My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Marlin_main.cpp 233KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402
  1. /**
  2. * Marlin Firmware
  3. *
  4. * Based on Sprinter and grbl.
  5. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. * About Marlin
  21. *
  22. * This firmware is a mashup between Sprinter and grbl.
  23. * - https://github.com/kliment/Sprinter
  24. * - https://github.com/simen/grbl/tree
  25. *
  26. * It has preliminary support for Matthew Roberts advance algorithm
  27. * - http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
  28. */
  29. #include "Marlin.h"
  30. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  31. #include "vector_3.h"
  32. #if ENABLED(AUTO_BED_LEVELING_GRID)
  33. #include "qr_solve.h"
  34. #endif
  35. #endif // AUTO_BED_LEVELING_FEATURE
  36. #if ENABLED(MESH_BED_LEVELING)
  37. #include "mesh_bed_leveling.h"
  38. #endif
  39. #include "ultralcd.h"
  40. #include "planner.h"
  41. #include "stepper.h"
  42. #include "temperature.h"
  43. #include "cardreader.h"
  44. #include "configuration_store.h"
  45. #include "language.h"
  46. #include "pins_arduino.h"
  47. #include "math.h"
  48. #include "buzzer.h"
  49. #if ENABLED(USE_WATCHDOG)
  50. #include "watchdog.h"
  51. #endif
  52. #if ENABLED(BLINKM)
  53. #include "blinkm.h"
  54. #include "Wire.h"
  55. #endif
  56. #if HAS_SERVOS
  57. #include "servo.h"
  58. #endif
  59. #if HAS_DIGIPOTSS
  60. #include <SPI.h>
  61. #endif
  62. /**
  63. * Look here for descriptions of G-codes:
  64. * - http://linuxcnc.org/handbook/gcode/g-code.html
  65. * - http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  66. *
  67. * Help us document these G-codes online:
  68. * - https://github.com/MarlinFirmware/Marlin/wiki/G-Code-in-Marlin
  69. * - http://reprap.org/wiki/G-code
  70. *
  71. * -----------------
  72. * Implemented Codes
  73. * -----------------
  74. *
  75. * "G" Codes
  76. *
  77. * G0 -> G1
  78. * G1 - Coordinated Movement X Y Z E
  79. * G2 - CW ARC
  80. * G3 - CCW ARC
  81. * G4 - Dwell S<seconds> or P<milliseconds>
  82. * G10 - retract filament according to settings of M207
  83. * G11 - retract recover filament according to settings of M208
  84. * G28 - Home one or more axes
  85. * G29 - Detailed Z probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  86. * G30 - Single Z probe, probes bed at current XY location.
  87. * G31 - Dock sled (Z_PROBE_SLED only)
  88. * G32 - Undock sled (Z_PROBE_SLED only)
  89. * G90 - Use Absolute Coordinates
  90. * G91 - Use Relative Coordinates
  91. * G92 - Set current position to coordinates given
  92. *
  93. * "M" Codes
  94. *
  95. * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  96. * M1 - Same as M0
  97. * M17 - Enable/Power all stepper motors
  98. * M18 - Disable all stepper motors; same as M84
  99. * M20 - List SD card
  100. * M21 - Init SD card
  101. * M22 - Release SD card
  102. * M23 - Select SD file (M23 filename.g)
  103. * M24 - Start/resume SD print
  104. * M25 - Pause SD print
  105. * M26 - Set SD position in bytes (M26 S12345)
  106. * M27 - Report SD print status
  107. * M28 - Start SD write (M28 filename.g)
  108. * M29 - Stop SD write
  109. * M30 - Delete file from SD (M30 filename.g)
  110. * M31 - Output time since last M109 or SD card start to serial
  111. * M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  112. * syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  113. * Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  114. * The '#' is necessary when calling from within sd files, as it stops buffer prereading
  115. * M33 - Get the longname version of a path
  116. * 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.
  117. * M48 - Measure Z_Probe repeatability. M48 [P # of points] [X position] [Y position] [V_erboseness #] [E_ngage Probe] [L # of legs of travel]
  118. * M80 - Turn on Power Supply
  119. * M81 - Turn off Power Supply
  120. * M82 - Set E codes absolute (default)
  121. * M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  122. * M84 - Disable steppers until next move,
  123. * or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  124. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  125. * M92 - Set axis_steps_per_unit - same syntax as G92
  126. * M104 - Set extruder target temp
  127. * M105 - Read current temp
  128. * M106 - Fan on
  129. * M107 - Fan off
  130. * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  131. * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  132. * IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  133. * M110 - Set the current line number
  134. * M111 - Set debug flags with S<mask>. See flag bits defined in Marlin.h.
  135. * M112 - Emergency stop
  136. * M114 - Output current position to serial port
  137. * M115 - Capabilities string
  138. * M117 - Display a message on the controller screen
  139. * M119 - Output Endstop status to serial port
  140. * M120 - Enable endstop detection
  141. * M121 - Disable endstop detection
  142. * M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  143. * M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  144. * M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  145. * M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  146. * M140 - Set bed target temp
  147. * M145 - Set the heatup state H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS)
  148. * 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.
  149. * M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  150. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  151. * M200 - set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).:D<millimeters>-
  152. * M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  153. * M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  154. * M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  155. * M204 - Set default acceleration: P for Printing moves, R for Retract only (no X, Y, Z) moves and T for Travel (non printing) moves (ex. M204 P800 T3000 R9000) in mm/sec^2
  156. * 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
  157. * M206 - Set additional homing offset
  158. * M207 - Set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  159. * M208 - Set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  160. * 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.
  161. * M218 - Set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  162. * M220 - Set speed factor override percentage: S<factor in percent>
  163. * M221 - Set extrude factor override percentage: S<factor in percent>
  164. * M226 - Wait until the specified pin reaches the state required: P<pin number> S<pin state>
  165. * M240 - Trigger a camera to take a photograph
  166. * M250 - Set LCD contrast C<contrast value> (value 0..63)
  167. * M280 - Set servo position absolute. P: servo index, S: angle or microseconds
  168. * M300 - Play beep sound S<frequency Hz> P<duration ms>
  169. * M301 - Set PID parameters P I and D
  170. * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  171. * M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  172. * M304 - Set bed PID parameters P I and D
  173. * M380 - Activate solenoid on active extruder
  174. * M381 - Disable all solenoids
  175. * M400 - Finish all moves
  176. * M401 - Lower Z probe if present
  177. * M402 - Raise Z probe if present
  178. * M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  179. * M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  180. * M406 - Turn off Filament Sensor extrusion control
  181. * M407 - Display measured filament diameter
  182. * M410 - Quickstop. Abort all the planned moves
  183. * M420 - Enable/Disable Mesh Leveling (with current values) S1=enable S0=disable
  184. * M421 - Set a single Z coordinate in the Mesh Leveling grid. X<mm> Y<mm> Z<mm>
  185. * M428 - Set the home_offset logically based on the current_position
  186. * M500 - Store parameters in EEPROM
  187. * M501 - Read parameters from EEPROM (if you need reset them after you changed them temporarily).
  188. * M502 - Revert to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  189. * M503 - Print the current settings (from memory not from EEPROM). Use S0 to leave off headings.
  190. * M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  191. * M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  192. * M665 - Set delta configurations: L<diagonal rod> R<delta radius> S<segments/s>
  193. * M666 - Set delta endstop adjustment
  194. * M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  195. * M907 - Set digital trimpot motor current using axis codes.
  196. * M908 - Control digital trimpot directly.
  197. * M350 - Set microstepping mode.
  198. * M351 - Toggle MS1 MS2 pins directly.
  199. *
  200. * ************ SCARA Specific - This can change to suit future G-code regulations
  201. * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  202. * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  203. * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  204. * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  205. * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  206. * M365 - SCARA calibration: Scaling factor, X, Y, Z axis
  207. * ************* SCARA End ***************
  208. *
  209. * ************ Custom codes - This can change to suit future G-code regulations
  210. * M100 - Watch Free Memory (For Debugging Only)
  211. * M851 - Set Z probe's Z offset (mm above extruder -- The value will always be negative)
  212. * M928 - Start SD logging (M928 filename.g) - ended by M29
  213. * M999 - Restart after being stopped by error
  214. *
  215. * "T" Codes
  216. *
  217. * T0-T3 - Select a tool by index (usually an extruder) [ F<mm/min> ]
  218. *
  219. */
  220. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  221. void gcode_M100();
  222. #endif
  223. #if ENABLED(SDSUPPORT)
  224. CardReader card;
  225. #endif
  226. bool Running = true;
  227. uint8_t marlin_debug_flags = DEBUG_INFO | DEBUG_ERRORS;
  228. static float feedrate = 1500.0, saved_feedrate;
  229. float current_position[NUM_AXIS] = { 0.0 };
  230. static float destination[NUM_AXIS] = { 0.0 };
  231. bool axis_known_position[3] = { false };
  232. bool axis_homed[3] = { false };
  233. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  234. static char* current_command, *current_command_args;
  235. static int cmd_queue_index_r = 0;
  236. static int cmd_queue_index_w = 0;
  237. static int commands_in_queue = 0;
  238. static char command_queue[BUFSIZE][MAX_CMD_SIZE];
  239. const float homing_feedrate[] = HOMING_FEEDRATE;
  240. bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
  241. int feedrate_multiplier = 100; //100->1 200->2
  242. int saved_feedrate_multiplier;
  243. int extruder_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100);
  244. bool volumetric_enabled = false;
  245. float filament_size[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(DEFAULT_NOMINAL_FILAMENT_DIA);
  246. float volumetric_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0);
  247. float home_offset[3] = { 0 };
  248. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  249. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  250. #if FAN_COUNT > 0
  251. int fanSpeeds[FAN_COUNT] = { 0 };
  252. #endif
  253. uint8_t active_extruder = 0;
  254. bool cancel_heatup = false;
  255. const char errormagic[] PROGMEM = "Error:";
  256. const char echomagic[] PROGMEM = "echo:";
  257. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  258. static bool relative_mode = false; //Determines Absolute or Relative Coordinates
  259. static int serial_count = 0;
  260. static char* seen_pointer; ///< A pointer to find chars in the command string (X, Y, Z, E, etc.)
  261. const char* queued_commands_P = NULL; /* pointer to the current line in the active sequence of commands, or NULL when none */
  262. const int sensitive_pins[] = SENSITIVE_PINS; ///< Sensitive pin list for M42
  263. // Inactivity shutdown
  264. millis_t previous_cmd_ms = 0;
  265. static millis_t max_inactive_time = 0;
  266. static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000L;
  267. millis_t print_job_start_ms = 0; ///< Print job start time
  268. millis_t print_job_stop_ms = 0; ///< Print job stop time
  269. static uint8_t target_extruder;
  270. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  271. int xy_travel_speed = XY_TRAVEL_SPEED;
  272. float zprobe_zoffset = Z_PROBE_OFFSET_FROM_EXTRUDER;
  273. #endif
  274. #if ENABLED(Z_DUAL_ENDSTOPS) && DISABLED(DELTA)
  275. float z_endstop_adj = 0;
  276. #endif
  277. // Extruder offsets
  278. #if EXTRUDERS > 1
  279. #ifndef EXTRUDER_OFFSET_X
  280. #define EXTRUDER_OFFSET_X { 0 }
  281. #endif
  282. #ifndef EXTRUDER_OFFSET_Y
  283. #define EXTRUDER_OFFSET_Y { 0 }
  284. #endif
  285. float extruder_offset[][EXTRUDERS] = {
  286. EXTRUDER_OFFSET_X,
  287. EXTRUDER_OFFSET_Y
  288. #if ENABLED(DUAL_X_CARRIAGE)
  289. , { 0 } // supports offsets in XYZ plane
  290. #endif
  291. };
  292. #endif
  293. #if HAS_SERVO_ENDSTOPS
  294. const int servo_endstop_id[] = SERVO_ENDSTOP_IDS;
  295. const int servo_endstop_angle[][2] = SERVO_ENDSTOP_ANGLES;
  296. #endif
  297. #if ENABLED(BARICUDA)
  298. int ValvePressure = 0;
  299. int EtoPPressure = 0;
  300. #endif
  301. #if ENABLED(FWRETRACT)
  302. bool autoretract_enabled = false;
  303. bool retracted[EXTRUDERS] = { false };
  304. bool retracted_swap[EXTRUDERS] = { false };
  305. float retract_length = RETRACT_LENGTH;
  306. float retract_length_swap = RETRACT_LENGTH_SWAP;
  307. float retract_feedrate = RETRACT_FEEDRATE;
  308. float retract_zlift = RETRACT_ZLIFT;
  309. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  310. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  311. float retract_recover_feedrate = RETRACT_RECOVER_FEEDRATE;
  312. #endif // FWRETRACT
  313. #if ENABLED(ULTIPANEL) && HAS_POWER_SWITCH
  314. bool powersupply =
  315. #if ENABLED(PS_DEFAULT_OFF)
  316. false
  317. #else
  318. true
  319. #endif
  320. ;
  321. #endif
  322. #if ENABLED(DELTA)
  323. #define TOWER_1 X_AXIS
  324. #define TOWER_2 Y_AXIS
  325. #define TOWER_3 Z_AXIS
  326. float delta[3] = { 0 };
  327. #define SIN_60 0.8660254037844386
  328. #define COS_60 0.5
  329. float endstop_adj[3] = { 0 };
  330. // these are the default values, can be overriden with M665
  331. float delta_radius = DELTA_RADIUS;
  332. float delta_tower1_x = -SIN_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_1); // front left tower
  333. float delta_tower1_y = -COS_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_1);
  334. float delta_tower2_x = SIN_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_2); // front right tower
  335. float delta_tower2_y = -COS_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_2);
  336. float delta_tower3_x = 0; // back middle tower
  337. float delta_tower3_y = (delta_radius + DELTA_RADIUS_TRIM_TOWER_3);
  338. float delta_diagonal_rod = DELTA_DIAGONAL_ROD;
  339. float delta_diagonal_rod_trim_tower_1 = DELTA_DIAGONAL_ROD_TRIM_TOWER_1;
  340. float delta_diagonal_rod_trim_tower_2 = DELTA_DIAGONAL_ROD_TRIM_TOWER_2;
  341. float delta_diagonal_rod_trim_tower_3 = DELTA_DIAGONAL_ROD_TRIM_TOWER_3;
  342. float delta_diagonal_rod_2_tower_1 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_1);
  343. float delta_diagonal_rod_2_tower_2 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_2);
  344. float delta_diagonal_rod_2_tower_3 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_3);
  345. //float delta_diagonal_rod_2 = sq(delta_diagonal_rod);
  346. float delta_segments_per_second = DELTA_SEGMENTS_PER_SECOND;
  347. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  348. int delta_grid_spacing[2] = { 0, 0 };
  349. float bed_level[AUTO_BED_LEVELING_GRID_POINTS][AUTO_BED_LEVELING_GRID_POINTS];
  350. #endif
  351. #else
  352. static bool home_all_axis = true;
  353. #endif
  354. #if ENABLED(SCARA)
  355. float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND;
  356. static float delta[3] = { 0 };
  357. float axis_scaling[3] = { 1, 1, 1 }; // Build size scaling, default to 1
  358. #endif
  359. #if ENABLED(FILAMENT_SENSOR)
  360. //Variables for Filament Sensor input
  361. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA; //Set nominal filament width, can be changed with M404
  362. bool filament_sensor = false; //M405 turns on filament_sensor control, M406 turns it off
  363. float filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; //Stores the measured filament diameter
  364. signed char measurement_delay[MAX_MEASUREMENT_DELAY + 1]; //ring buffer to delay measurement store extruder factor after subtracting 100
  365. int delay_index1 = 0; //index into ring buffer
  366. int delay_index2 = -1; //index into ring buffer - set to -1 on startup to indicate ring buffer needs to be initialized
  367. float delay_dist = 0; //delay distance counter
  368. int meas_delay_cm = MEASUREMENT_DELAY_CM; //distance delay setting
  369. #endif
  370. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  371. static bool filrunoutEnqueued = false;
  372. #endif
  373. static bool send_ok[BUFSIZE];
  374. #if HAS_SERVOS
  375. Servo servo[NUM_SERVOS];
  376. #endif
  377. #ifdef CHDK
  378. unsigned long chdkHigh = 0;
  379. boolean chdkActive = false;
  380. #endif
  381. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  382. int lpq_len = 20;
  383. #endif
  384. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  385. // States for managing Marlin and host communication
  386. // Marlin sends messages if blocked or busy
  387. enum MarlinBusyState {
  388. NOT_BUSY, // Not in a handler
  389. IN_HANDLER, // Processing a GCode
  390. IN_PROCESS, // Known to be blocking command input (as in G29)
  391. PAUSED_FOR_USER, // Blocking pending any input
  392. PAUSED_FOR_INPUT // Blocking pending text input (concept)
  393. };
  394. static MarlinBusyState busy_state = NOT_BUSY;
  395. static millis_t next_busy_signal_ms = -1;
  396. #define KEEPALIVE_STATE(n) do{ busy_state = n; }while(0)
  397. #else
  398. #define host_keepalive() ;
  399. #define KEEPALIVE_STATE(n) ;
  400. #endif // HOST_KEEPALIVE_FEATURE
  401. //===========================================================================
  402. //================================ Functions ================================
  403. //===========================================================================
  404. void process_next_command();
  405. void plan_arc(float target[NUM_AXIS], float* offset, uint8_t clockwise);
  406. bool setTargetedHotend(int code);
  407. void serial_echopair_P(const char* s_P, int v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  408. void serial_echopair_P(const char* s_P, long v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  409. void serial_echopair_P(const char* s_P, float v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  410. void serial_echopair_P(const char* s_P, double v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  411. void serial_echopair_P(const char* s_P, unsigned long v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  412. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  413. float extrude_min_temp = EXTRUDE_MINTEMP;
  414. #endif
  415. #if ENABLED(SDSUPPORT)
  416. #include "SdFatUtil.h"
  417. int freeMemory() { return SdFatUtil::FreeRam(); }
  418. #else
  419. extern "C" {
  420. extern unsigned int __bss_end;
  421. extern unsigned int __heap_start;
  422. extern void* __brkval;
  423. int freeMemory() {
  424. int free_memory;
  425. if ((int)__brkval == 0)
  426. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  427. else
  428. free_memory = ((int)&free_memory) - ((int)__brkval);
  429. return free_memory;
  430. }
  431. }
  432. #endif //!SDSUPPORT
  433. /**
  434. * Inject the next "immediate" command, when possible.
  435. * Return true if any immediate commands remain to inject.
  436. */
  437. static bool drain_queued_commands_P() {
  438. if (queued_commands_P != NULL) {
  439. // Get the next gcode to run
  440. size_t i = 0;
  441. char c;
  442. while ((c = queued_commands_P[i++]) && c != '\n') { };
  443. if (i > 1) {
  444. char cmd[i];
  445. strncpy_P(cmd, queued_commands_P, i - 1);
  446. cmd[i - 1] = '\0';
  447. if (enqueue_and_echo_command(cmd)) { // buffer was not full (else we will retry later)
  448. if (c)
  449. queued_commands_P += i; // move to next command
  450. else
  451. queued_commands_P = NULL; // no more commands in the sequence
  452. }
  453. }
  454. }
  455. return (queued_commands_P != NULL); // any more left to add?
  456. }
  457. /**
  458. * Record one or many commands to run from program memory.
  459. * Aborts the current queue, if any.
  460. * Note: drain_queued_commands_P() must be called repeatedly to drain the commands afterwards
  461. */
  462. void enqueue_and_echo_commands_P(const char* pgcode) {
  463. queued_commands_P = pgcode;
  464. drain_queued_commands_P(); // first command executed asap (when possible)
  465. }
  466. /**
  467. * Once a new command is in the ring buffer, call this to commit it
  468. */
  469. inline void _commit_command(bool say_ok) {
  470. send_ok[cmd_queue_index_w] = say_ok;
  471. cmd_queue_index_w = (cmd_queue_index_w + 1) % BUFSIZE;
  472. commands_in_queue++;
  473. }
  474. /**
  475. * Copy a command directly into the main command buffer, from RAM.
  476. * Returns true if successfully adds the command
  477. */
  478. inline bool _enqueuecommand(const char* cmd, bool say_ok=false) {
  479. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  480. strcpy(command_queue[cmd_queue_index_w], cmd);
  481. _commit_command(say_ok);
  482. return true;
  483. }
  484. /**
  485. * Enqueue with Serial Echo
  486. */
  487. bool enqueue_and_echo_command(const char* cmd, bool say_ok/*=false*/) {
  488. if (_enqueuecommand(cmd, say_ok)) {
  489. SERIAL_ECHO_START;
  490. SERIAL_ECHOPGM(MSG_Enqueueing);
  491. SERIAL_ECHO(cmd);
  492. SERIAL_ECHOLNPGM("\"");
  493. return true;
  494. }
  495. return false;
  496. }
  497. void setup_killpin() {
  498. #if HAS_KILL
  499. SET_INPUT(KILL_PIN);
  500. WRITE(KILL_PIN, HIGH);
  501. #endif
  502. }
  503. void setup_filrunoutpin() {
  504. #if HAS_FILRUNOUT
  505. pinMode(FILRUNOUT_PIN, INPUT);
  506. #if ENABLED(ENDSTOPPULLUP_FIL_RUNOUT)
  507. WRITE(FILRUNOUT_PIN, HIGH);
  508. #endif
  509. #endif
  510. }
  511. // Set home pin
  512. void setup_homepin(void) {
  513. #if HAS_HOME
  514. SET_INPUT(HOME_PIN);
  515. WRITE(HOME_PIN, HIGH);
  516. #endif
  517. }
  518. void setup_photpin() {
  519. #if HAS_PHOTOGRAPH
  520. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  521. #endif
  522. }
  523. void setup_powerhold() {
  524. #if HAS_SUICIDE
  525. OUT_WRITE(SUICIDE_PIN, HIGH);
  526. #endif
  527. #if HAS_POWER_SWITCH
  528. #if ENABLED(PS_DEFAULT_OFF)
  529. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  530. #else
  531. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE);
  532. #endif
  533. #endif
  534. }
  535. void suicide() {
  536. #if HAS_SUICIDE
  537. OUT_WRITE(SUICIDE_PIN, LOW);
  538. #endif
  539. }
  540. void servo_init() {
  541. #if NUM_SERVOS >= 1 && HAS_SERVO_0
  542. servo[0].attach(SERVO0_PIN);
  543. servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position.
  544. #endif
  545. #if NUM_SERVOS >= 2 && HAS_SERVO_1
  546. servo[1].attach(SERVO1_PIN);
  547. servo[1].detach();
  548. #endif
  549. #if NUM_SERVOS >= 3 && HAS_SERVO_2
  550. servo[2].attach(SERVO2_PIN);
  551. servo[2].detach();
  552. #endif
  553. #if NUM_SERVOS >= 4 && HAS_SERVO_3
  554. servo[3].attach(SERVO3_PIN);
  555. servo[3].detach();
  556. #endif
  557. // Set position of Servo Endstops that are defined
  558. #if HAS_SERVO_ENDSTOPS
  559. for (int i = 0; i < 3; i++)
  560. if (servo_endstop_id[i] >= 0)
  561. servo[servo_endstop_id[i]].move(servo_endstop_angle[i][1]);
  562. #endif
  563. }
  564. /**
  565. * Stepper Reset (RigidBoard, et.al.)
  566. */
  567. #if HAS_STEPPER_RESET
  568. void disableStepperDrivers() {
  569. pinMode(STEPPER_RESET_PIN, OUTPUT);
  570. digitalWrite(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips
  571. }
  572. void enableStepperDrivers() { pinMode(STEPPER_RESET_PIN, INPUT); } // set to input, which allows it to be pulled high by pullups
  573. #endif
  574. /**
  575. * Marlin entry-point: Set up before the program loop
  576. * - Set up the kill pin, filament runout, power hold
  577. * - Start the serial port
  578. * - Print startup messages and diagnostics
  579. * - Get EEPROM or default settings
  580. * - Initialize managers for:
  581. * • temperature
  582. * • planner
  583. * • watchdog
  584. * • stepper
  585. * • photo pin
  586. * • servos
  587. * • LCD controller
  588. * • Digipot I2C
  589. * • Z probe sled
  590. * • status LEDs
  591. */
  592. void setup() {
  593. #ifdef DISABLE_JTAG
  594. // Disable JTAG on AT90USB chips to free up pins for IO
  595. MCUCR = 0x80;
  596. MCUCR = 0x80;
  597. #endif
  598. setup_killpin();
  599. setup_filrunoutpin();
  600. setup_powerhold();
  601. #if HAS_STEPPER_RESET
  602. disableStepperDrivers();
  603. #endif
  604. MYSERIAL.begin(BAUDRATE);
  605. SERIAL_PROTOCOLLNPGM("start");
  606. SERIAL_ECHO_START;
  607. // Check startup - does nothing if bootloader sets MCUSR to 0
  608. byte mcu = MCUSR;
  609. if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  610. if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  611. if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  612. if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  613. if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  614. MCUSR = 0;
  615. SERIAL_ECHOPGM(MSG_MARLIN);
  616. SERIAL_ECHOLNPGM(" " SHORT_BUILD_VERSION);
  617. #ifdef STRING_DISTRIBUTION_DATE
  618. #ifdef STRING_CONFIG_H_AUTHOR
  619. SERIAL_ECHO_START;
  620. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  621. SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE);
  622. SERIAL_ECHOPGM(MSG_AUTHOR);
  623. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  624. SERIAL_ECHOPGM("Compiled: ");
  625. SERIAL_ECHOLNPGM(__DATE__);
  626. #endif // STRING_CONFIG_H_AUTHOR
  627. #endif // STRING_DISTRIBUTION_DATE
  628. SERIAL_ECHO_START;
  629. SERIAL_ECHOPGM(MSG_FREE_MEMORY);
  630. SERIAL_ECHO(freeMemory());
  631. SERIAL_ECHOPGM(MSG_PLANNER_BUFFER_BYTES);
  632. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  633. // Send "ok" after commands by default
  634. for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true;
  635. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  636. Config_RetrieveSettings();
  637. lcd_init();
  638. tp_init(); // Initialize temperature loop
  639. plan_init(); // Initialize planner;
  640. #if ENABLED(USE_WATCHDOG)
  641. watchdog_init();
  642. #endif
  643. st_init(); // Initialize stepper, this enables interrupts!
  644. setup_photpin();
  645. servo_init();
  646. #if HAS_CONTROLLERFAN
  647. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  648. #endif
  649. #if HAS_STEPPER_RESET
  650. enableStepperDrivers();
  651. #endif
  652. #if ENABLED(DIGIPOT_I2C)
  653. digipot_i2c_init();
  654. #endif
  655. #if ENABLED(Z_PROBE_SLED)
  656. pinMode(SLED_PIN, OUTPUT);
  657. digitalWrite(SLED_PIN, LOW); // turn it off
  658. #endif // Z_PROBE_SLED
  659. setup_homepin();
  660. #ifdef STAT_LED_RED
  661. pinMode(STAT_LED_RED, OUTPUT);
  662. digitalWrite(STAT_LED_RED, LOW); // turn it off
  663. #endif
  664. #ifdef STAT_LED_BLUE
  665. pinMode(STAT_LED_BLUE, OUTPUT);
  666. digitalWrite(STAT_LED_BLUE, LOW); // turn it off
  667. #endif
  668. }
  669. /**
  670. * The main Marlin program loop
  671. *
  672. * - Save or log commands to SD
  673. * - Process available commands (if not saving)
  674. * - Call heater manager
  675. * - Call inactivity manager
  676. * - Call endstop manager
  677. * - Call LCD update
  678. */
  679. void loop() {
  680. if (commands_in_queue < BUFSIZE) get_command();
  681. #if ENABLED(SDSUPPORT)
  682. card.checkautostart(false);
  683. #endif
  684. if (commands_in_queue) {
  685. #if ENABLED(SDSUPPORT)
  686. if (card.saving) {
  687. char* command = command_queue[cmd_queue_index_r];
  688. if (strstr_P(command, PSTR("M29"))) {
  689. // M29 closes the file
  690. card.closefile();
  691. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  692. ok_to_send();
  693. }
  694. else {
  695. // Write the string from the read buffer to SD
  696. card.write_command(command);
  697. if (card.logging)
  698. process_next_command(); // The card is saving because it's logging
  699. else
  700. ok_to_send();
  701. }
  702. }
  703. else
  704. process_next_command();
  705. #else
  706. process_next_command();
  707. #endif // SDSUPPORT
  708. commands_in_queue--;
  709. cmd_queue_index_r = (cmd_queue_index_r + 1) % BUFSIZE;
  710. }
  711. checkHitEndstops();
  712. idle();
  713. }
  714. void gcode_line_error(const char* err, bool doFlush = true) {
  715. SERIAL_ERROR_START;
  716. serialprintPGM(err);
  717. SERIAL_ERRORLN(gcode_LastN);
  718. //Serial.println(gcode_N);
  719. if (doFlush) FlushSerialRequestResend();
  720. serial_count = 0;
  721. }
  722. /**
  723. * Add to the circular command queue the next command from:
  724. * - The command-injection queue (queued_commands_P)
  725. * - The active serial input (usually USB)
  726. * - The SD card file being actively printed
  727. */
  728. void get_command() {
  729. static char serial_line_buffer[MAX_CMD_SIZE];
  730. static boolean serial_comment_mode = false;
  731. if (drain_queued_commands_P()) return; // priority is given to non-serial commands
  732. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  733. static millis_t last_command_time = 0;
  734. millis_t ms = millis();
  735. if (!MYSERIAL.available() && commands_in_queue == 0 && ms - last_command_time > NO_TIMEOUTS) {
  736. SERIAL_ECHOLNPGM(MSG_WAIT);
  737. last_command_time = ms;
  738. }
  739. #endif
  740. //
  741. // Loop while serial characters are incoming and the queue is not full
  742. //
  743. while (commands_in_queue < BUFSIZE && MYSERIAL.available() > 0) {
  744. char serial_char = MYSERIAL.read();
  745. //
  746. // If the character ends the line
  747. //
  748. if (serial_char == '\n' || serial_char == '\r') {
  749. serial_comment_mode = false; // end of line == end of comment
  750. if (!serial_count) return; // empty lines just exit
  751. serial_line_buffer[serial_count] = 0; // terminate string
  752. serial_count = 0; //reset buffer
  753. char* command = serial_line_buffer;
  754. while (*command == ' ') command++; // skip any leading spaces
  755. char* npos = (*command == 'N') ? command : NULL; // Require the N parameter to start the line
  756. char* apos = strchr(command, '*');
  757. if (npos) {
  758. boolean M110 = strstr_P(command, PSTR("M110")) != NULL;
  759. if (M110) {
  760. char* n2pos = strchr(command + 4, 'N');
  761. if (n2pos) npos = n2pos;
  762. }
  763. gcode_N = strtol(npos + 1, NULL, 10);
  764. if (gcode_N != gcode_LastN + 1 && !M110) {
  765. gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  766. return;
  767. }
  768. if (apos) {
  769. byte checksum = 0, count = 0;
  770. while (command[count] != '*') checksum ^= command[count++];
  771. if (strtol(apos + 1, NULL, 10) != checksum) {
  772. gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  773. return;
  774. }
  775. // if no errors, continue parsing
  776. }
  777. else {
  778. gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  779. return;
  780. }
  781. gcode_LastN = gcode_N;
  782. // if no errors, continue parsing
  783. }
  784. else if (apos) { // No '*' without 'N'
  785. gcode_line_error(PSTR(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM), false);
  786. return;
  787. }
  788. // Movement commands alert when stopped
  789. if (IsStopped()) {
  790. char* gpos = strchr(command, 'G');
  791. if (gpos) {
  792. int codenum = strtol(gpos + 1, NULL, 10);
  793. switch (codenum) {
  794. case 0:
  795. case 1:
  796. case 2:
  797. case 3:
  798. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  799. LCD_MESSAGEPGM(MSG_STOPPED);
  800. break;
  801. }
  802. }
  803. }
  804. // If command was e-stop process now
  805. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  806. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  807. last_command_time = ms;
  808. #endif
  809. // Add the command to the queue
  810. _enqueuecommand(serial_line_buffer, true);
  811. }
  812. else if (serial_count >= MAX_CMD_SIZE - 1) {
  813. // Keep fetching, but ignore normal characters beyond the max length
  814. // The command will be injected when EOL is reached
  815. }
  816. else if (serial_char == '\\') { // Handle escapes
  817. if (MYSERIAL.available() > 0) {
  818. // if we have one more character, copy it over
  819. serial_char = MYSERIAL.read();
  820. serial_line_buffer[serial_count++] = serial_char;
  821. }
  822. // otherwise do nothing
  823. }
  824. else { // it's not a newline, carriage return or escape char
  825. if (serial_char == ';') serial_comment_mode = true;
  826. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  827. }
  828. } // queue has space, serial has data
  829. #if ENABLED(SDSUPPORT)
  830. static bool stop_buffering = false,
  831. sd_comment_mode = false;
  832. if (!card.sdprinting) return;
  833. // '#' stops reading from SD to the buffer prematurely, so procedural macro calls are possible
  834. // if it occurs, stop_buffering is triggered and the buffer is run dry.
  835. // this character _can_ occur in serial com, due to checksums. however, no checksums are used in SD printing
  836. if (commands_in_queue == 0) stop_buffering = false;
  837. uint16_t sd_count = 0;
  838. bool card_eof = card.eof();
  839. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  840. int16_t n = card.get();
  841. char sd_char = (char)n;
  842. card_eof = card.eof();
  843. if (card_eof || n == -1
  844. || sd_char == '\n' || sd_char == '\r'
  845. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  846. ) {
  847. if (card_eof) {
  848. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  849. print_job_stop_ms = millis();
  850. char time[30];
  851. millis_t t = (print_job_stop_ms - print_job_start_ms) / 1000;
  852. int hours = t / 60 / 60, minutes = (t / 60) % 60;
  853. sprintf_P(time, PSTR("%i " MSG_END_HOUR " %i " MSG_END_MINUTE), hours, minutes);
  854. SERIAL_ECHO_START;
  855. SERIAL_ECHOLN(time);
  856. lcd_setstatus(time, true);
  857. card.printingHasFinished();
  858. card.checkautostart(true);
  859. }
  860. if (sd_char == '#') stop_buffering = true;
  861. sd_comment_mode = false; //for new command
  862. if (!sd_count) continue; //skip empty lines
  863. command_queue[cmd_queue_index_w][sd_count] = '\0'; //terminate string
  864. sd_count = 0; //clear buffer
  865. _commit_command(false);
  866. }
  867. else if (sd_count >= MAX_CMD_SIZE - 1) {
  868. // Keep fetching, but ignore normal characters beyond the max length
  869. // The command will be injected when EOL is reached
  870. }
  871. else {
  872. if (sd_char == ';') sd_comment_mode = true;
  873. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  874. }
  875. }
  876. #endif // SDSUPPORT
  877. }
  878. bool code_has_value() {
  879. int i = 1;
  880. char c = seen_pointer[i];
  881. while (c == ' ') c = seen_pointer[++i];
  882. if (c == '-' || c == '+') c = seen_pointer[++i];
  883. if (c == '.') c = seen_pointer[++i];
  884. return (c >= '0' && c <= '9');
  885. }
  886. float code_value() {
  887. float ret;
  888. char* e = strchr(seen_pointer, 'E');
  889. if (e) {
  890. *e = 0;
  891. ret = strtod(seen_pointer + 1, NULL);
  892. *e = 'E';
  893. }
  894. else
  895. ret = strtod(seen_pointer + 1, NULL);
  896. return ret;
  897. }
  898. long code_value_long() { return strtol(seen_pointer + 1, NULL, 10); }
  899. int16_t code_value_short() { return (int16_t)strtol(seen_pointer + 1, NULL, 10); }
  900. bool code_seen(char code) {
  901. seen_pointer = strchr(current_command_args, code);
  902. return (seen_pointer != NULL); // Return TRUE if the code-letter was found
  903. }
  904. #define DEFINE_PGM_READ_ANY(type, reader) \
  905. static inline type pgm_read_any(const type *p) \
  906. { return pgm_read_##reader##_near(p); }
  907. DEFINE_PGM_READ_ANY(float, float);
  908. DEFINE_PGM_READ_ANY(signed char, byte);
  909. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  910. static const PROGMEM type array##_P[3] = \
  911. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  912. static inline type array(int axis) \
  913. { return pgm_read_any(&array##_P[axis]); }
  914. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  915. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  916. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  917. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  918. XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM);
  919. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  920. #if ENABLED(DUAL_X_CARRIAGE)
  921. #define DXC_FULL_CONTROL_MODE 0
  922. #define DXC_AUTO_PARK_MODE 1
  923. #define DXC_DUPLICATION_MODE 2
  924. static int dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  925. static float x_home_pos(int extruder) {
  926. if (extruder == 0)
  927. return base_home_pos(X_AXIS) + home_offset[X_AXIS];
  928. else
  929. // In dual carriage mode the extruder offset provides an override of the
  930. // second X-carriage offset when homed - otherwise X2_HOME_POS is used.
  931. // This allow soft recalibration of the second extruder offset position without firmware reflash
  932. // (through the M218 command).
  933. return (extruder_offset[X_AXIS][1] > 0) ? extruder_offset[X_AXIS][1] : X2_HOME_POS;
  934. }
  935. static int x_home_dir(int extruder) {
  936. return (extruder == 0) ? X_HOME_DIR : X2_HOME_DIR;
  937. }
  938. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  939. static bool active_extruder_parked = false; // used in mode 1 & 2
  940. static float raised_parked_position[NUM_AXIS]; // used in mode 1
  941. static millis_t delayed_move_time = 0; // used in mode 1
  942. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  943. static float duplicate_extruder_temp_offset = 0; // used in mode 2
  944. bool extruder_duplication_enabled = false; // used in mode 2
  945. #endif //DUAL_X_CARRIAGE
  946. #if ENABLED(DEBUG_LEVELING_FEATURE)
  947. void print_xyz(const char* prefix, const float x, const float y, const float z) {
  948. SERIAL_ECHO(prefix);
  949. SERIAL_ECHOPAIR(": (", x);
  950. SERIAL_ECHOPAIR(", ", y);
  951. SERIAL_ECHOPAIR(", ", z);
  952. SERIAL_ECHOLNPGM(")");
  953. }
  954. void print_xyz(const char* prefix, const float xyz[]) {
  955. print_xyz(prefix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]);
  956. }
  957. #endif
  958. static void set_axis_is_at_home(AxisEnum axis) {
  959. #if ENABLED(DUAL_X_CARRIAGE)
  960. if (axis == X_AXIS) {
  961. if (active_extruder != 0) {
  962. current_position[X_AXIS] = x_home_pos(active_extruder);
  963. min_pos[X_AXIS] = X2_MIN_POS;
  964. max_pos[X_AXIS] = max(extruder_offset[X_AXIS][1], X2_MAX_POS);
  965. return;
  966. }
  967. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  968. float xoff = home_offset[X_AXIS];
  969. current_position[X_AXIS] = base_home_pos(X_AXIS) + xoff;
  970. min_pos[X_AXIS] = base_min_pos(X_AXIS) + xoff;
  971. max_pos[X_AXIS] = min(base_max_pos(X_AXIS) + xoff, max(extruder_offset[X_AXIS][1], X2_MAX_POS) - duplicate_extruder_x_offset);
  972. return;
  973. }
  974. }
  975. #endif
  976. #if ENABLED(SCARA)
  977. if (axis == X_AXIS || axis == Y_AXIS) {
  978. float homeposition[3];
  979. for (int i = 0; i < 3; i++) homeposition[i] = base_home_pos(i);
  980. // SERIAL_ECHOPGM("homeposition[x]= "); SERIAL_ECHO(homeposition[0]);
  981. // SERIAL_ECHOPGM("homeposition[y]= "); SERIAL_ECHOLN(homeposition[1]);
  982. // Works out real Homeposition angles using inverse kinematics,
  983. // and calculates homing offset using forward kinematics
  984. calculate_delta(homeposition);
  985. // SERIAL_ECHOPGM("base Theta= "); SERIAL_ECHO(delta[X_AXIS]);
  986. // SERIAL_ECHOPGM(" base Psi+Theta="); SERIAL_ECHOLN(delta[Y_AXIS]);
  987. for (int i = 0; i < 2; i++) delta[i] -= home_offset[i];
  988. // SERIAL_ECHOPGM("addhome X="); SERIAL_ECHO(home_offset[X_AXIS]);
  989. // SERIAL_ECHOPGM(" addhome Y="); SERIAL_ECHO(home_offset[Y_AXIS]);
  990. // SERIAL_ECHOPGM(" addhome Theta="); SERIAL_ECHO(delta[X_AXIS]);
  991. // SERIAL_ECHOPGM(" addhome Psi+Theta="); SERIAL_ECHOLN(delta[Y_AXIS]);
  992. calculate_SCARA_forward_Transform(delta);
  993. // SERIAL_ECHOPGM("Delta X="); SERIAL_ECHO(delta[X_AXIS]);
  994. // SERIAL_ECHOPGM(" Delta Y="); SERIAL_ECHOLN(delta[Y_AXIS]);
  995. current_position[axis] = delta[axis];
  996. // SCARA home positions are based on configuration since the actual limits are determined by the
  997. // inverse kinematic transform.
  998. min_pos[axis] = base_min_pos(axis); // + (delta[axis] - base_home_pos(axis));
  999. max_pos[axis] = base_max_pos(axis); // + (delta[axis] - base_home_pos(axis));
  1000. }
  1001. else
  1002. #endif
  1003. {
  1004. current_position[axis] = base_home_pos(axis) + home_offset[axis];
  1005. min_pos[axis] = base_min_pos(axis) + home_offset[axis];
  1006. max_pos[axis] = base_max_pos(axis) + home_offset[axis];
  1007. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && Z_HOME_DIR < 0
  1008. if (axis == Z_AXIS) current_position[Z_AXIS] -= zprobe_zoffset;
  1009. #endif
  1010. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1011. if (marlin_debug_flags & DEBUG_LEVELING) {
  1012. SERIAL_ECHOPAIR("set_axis_is_at_home ", (unsigned long)axis);
  1013. SERIAL_ECHOPAIR(" > (home_offset[axis]==", home_offset[axis]);
  1014. print_xyz(") > current_position", current_position);
  1015. }
  1016. #endif
  1017. }
  1018. }
  1019. /**
  1020. * Some planner shorthand inline functions
  1021. */
  1022. inline void set_homing_bump_feedrate(AxisEnum axis) {
  1023. const int homing_bump_divisor[] = HOMING_BUMP_DIVISOR;
  1024. int hbd = homing_bump_divisor[axis];
  1025. if (hbd < 1) {
  1026. hbd = 10;
  1027. SERIAL_ECHO_START;
  1028. SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1");
  1029. }
  1030. feedrate = homing_feedrate[axis] / hbd;
  1031. }
  1032. inline void line_to_current_position() {
  1033. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate / 60, active_extruder);
  1034. }
  1035. inline void line_to_z(float zPosition) {
  1036. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate / 60, active_extruder);
  1037. }
  1038. inline void line_to_destination(float mm_m) {
  1039. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], mm_m / 60, active_extruder);
  1040. }
  1041. inline void line_to_destination() {
  1042. line_to_destination(feedrate);
  1043. }
  1044. inline void sync_plan_position() {
  1045. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1046. }
  1047. #if ENABLED(DELTA) || ENABLED(SCARA)
  1048. inline void sync_plan_position_delta() {
  1049. calculate_delta(current_position);
  1050. plan_set_position(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], current_position[E_AXIS]);
  1051. }
  1052. #endif
  1053. inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); }
  1054. inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); }
  1055. static void setup_for_endstop_move() {
  1056. saved_feedrate = feedrate;
  1057. saved_feedrate_multiplier = feedrate_multiplier;
  1058. feedrate_multiplier = 100;
  1059. refresh_cmd_timeout();
  1060. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1061. if (marlin_debug_flags & DEBUG_LEVELING) {
  1062. SERIAL_ECHOLNPGM("setup_for_endstop_move > enable_endstops(true)");
  1063. }
  1064. #endif
  1065. enable_endstops(true);
  1066. }
  1067. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  1068. #if ENABLED(DELTA)
  1069. /**
  1070. * Calculate delta, start a line, and set current_position to destination
  1071. */
  1072. void prepare_move_raw() {
  1073. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1074. if (marlin_debug_flags & DEBUG_LEVELING) {
  1075. print_xyz("prepare_move_raw > destination", destination);
  1076. }
  1077. #endif
  1078. refresh_cmd_timeout();
  1079. calculate_delta(destination);
  1080. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], (feedrate / 60) * (feedrate_multiplier / 100.0), active_extruder);
  1081. set_current_to_destination();
  1082. }
  1083. #endif
  1084. #if ENABLED(AUTO_BED_LEVELING_GRID)
  1085. #if DISABLED(DELTA)
  1086. static void set_bed_level_equation_lsq(double* plane_equation_coefficients) {
  1087. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1088. planeNormal.debug("planeNormal");
  1089. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1090. //bedLevel.debug("bedLevel");
  1091. //plan_bed_level_matrix.debug("bed level before");
  1092. //vector_3 uncorrected_position = plan_get_position_mm();
  1093. //uncorrected_position.debug("position before");
  1094. vector_3 corrected_position = plan_get_position();
  1095. //corrected_position.debug("position after");
  1096. current_position[X_AXIS] = corrected_position.x;
  1097. current_position[Y_AXIS] = corrected_position.y;
  1098. current_position[Z_AXIS] = corrected_position.z;
  1099. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1100. if (marlin_debug_flags & DEBUG_LEVELING) {
  1101. print_xyz("set_bed_level_equation_lsq > current_position", current_position);
  1102. }
  1103. #endif
  1104. sync_plan_position();
  1105. }
  1106. #endif // !DELTA
  1107. #else // !AUTO_BED_LEVELING_GRID
  1108. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1109. plan_bed_level_matrix.set_to_identity();
  1110. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1111. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1112. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1113. vector_3 planeNormal = vector_3::cross(pt1 - pt2, pt3 - pt2).get_normal();
  1114. if (planeNormal.z < 0) {
  1115. planeNormal.x = -planeNormal.x;
  1116. planeNormal.y = -planeNormal.y;
  1117. planeNormal.z = -planeNormal.z;
  1118. }
  1119. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1120. vector_3 corrected_position = plan_get_position();
  1121. current_position[X_AXIS] = corrected_position.x;
  1122. current_position[Y_AXIS] = corrected_position.y;
  1123. current_position[Z_AXIS] = corrected_position.z;
  1124. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1125. if (marlin_debug_flags & DEBUG_LEVELING) {
  1126. print_xyz("set_bed_level_equation_3pts > current_position", current_position);
  1127. }
  1128. #endif
  1129. sync_plan_position();
  1130. }
  1131. #endif // !AUTO_BED_LEVELING_GRID
  1132. static void run_z_probe() {
  1133. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out and EXTRUDER_RUNOUT_PREVENT from extruding
  1134. #if ENABLED(DELTA)
  1135. float start_z = current_position[Z_AXIS];
  1136. long start_steps = st_get_position(Z_AXIS);
  1137. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1138. if (marlin_debug_flags & DEBUG_LEVELING) {
  1139. SERIAL_ECHOLNPGM("run_z_probe (DELTA) 1");
  1140. }
  1141. #endif
  1142. // move down slowly until you find the bed
  1143. feedrate = homing_feedrate[Z_AXIS] / 4;
  1144. destination[Z_AXIS] = -10;
  1145. prepare_move_raw(); // this will also set_current_to_destination
  1146. st_synchronize();
  1147. endstops_hit_on_purpose(); // clear endstop hit flags
  1148. // we have to let the planner know where we are right now as it is not where we said to go.
  1149. long stop_steps = st_get_position(Z_AXIS);
  1150. float mm = start_z - float(start_steps - stop_steps) / axis_steps_per_unit[Z_AXIS];
  1151. current_position[Z_AXIS] = mm;
  1152. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1153. if (marlin_debug_flags & DEBUG_LEVELING) {
  1154. print_xyz("run_z_probe (DELTA) 2 > current_position", current_position);
  1155. }
  1156. #endif
  1157. sync_plan_position_delta();
  1158. #else // !DELTA
  1159. plan_bed_level_matrix.set_to_identity();
  1160. feedrate = homing_feedrate[Z_AXIS];
  1161. // Move down until the Z probe (or endstop?) is triggered
  1162. float zPosition = -(Z_MAX_LENGTH + 10);
  1163. line_to_z(zPosition);
  1164. st_synchronize();
  1165. // Tell the planner where we ended up - Get this from the stepper handler
  1166. zPosition = st_get_axis_position_mm(Z_AXIS);
  1167. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1168. // move up the retract distance
  1169. zPosition += home_bump_mm(Z_AXIS);
  1170. line_to_z(zPosition);
  1171. st_synchronize();
  1172. endstops_hit_on_purpose(); // clear endstop hit flags
  1173. // move back down slowly to find bed
  1174. set_homing_bump_feedrate(Z_AXIS);
  1175. zPosition -= home_bump_mm(Z_AXIS) * 2;
  1176. line_to_z(zPosition);
  1177. st_synchronize();
  1178. endstops_hit_on_purpose(); // clear endstop hit flags
  1179. // Get the current stepper position after bumping an endstop
  1180. current_position[Z_AXIS] = st_get_axis_position_mm(Z_AXIS);
  1181. sync_plan_position();
  1182. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1183. if (marlin_debug_flags & DEBUG_LEVELING) {
  1184. print_xyz("run_z_probe > current_position", current_position);
  1185. }
  1186. #endif
  1187. #endif // !DELTA
  1188. }
  1189. /**
  1190. * Plan a move to (X, Y, Z) and set the current_position
  1191. * The final current_position may not be the one that was requested
  1192. */
  1193. static void do_blocking_move_to(float x, float y, float z) {
  1194. float oldFeedRate = feedrate;
  1195. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1196. if (marlin_debug_flags & DEBUG_LEVELING) {
  1197. print_xyz("do_blocking_move_to", x, y, z);
  1198. }
  1199. #endif
  1200. #if ENABLED(DELTA)
  1201. feedrate = XY_TRAVEL_SPEED;
  1202. destination[X_AXIS] = x;
  1203. destination[Y_AXIS] = y;
  1204. destination[Z_AXIS] = z;
  1205. prepare_move_raw(); // this will also set_current_to_destination
  1206. st_synchronize();
  1207. #else
  1208. feedrate = homing_feedrate[Z_AXIS];
  1209. current_position[Z_AXIS] = z;
  1210. line_to_current_position();
  1211. st_synchronize();
  1212. feedrate = xy_travel_speed;
  1213. current_position[X_AXIS] = x;
  1214. current_position[Y_AXIS] = y;
  1215. line_to_current_position();
  1216. st_synchronize();
  1217. #endif
  1218. feedrate = oldFeedRate;
  1219. }
  1220. inline void do_blocking_move_to_xy(float x, float y) { do_blocking_move_to(x, y, current_position[Z_AXIS]); }
  1221. inline void do_blocking_move_to_x(float x) { do_blocking_move_to(x, current_position[Y_AXIS], current_position[Z_AXIS]); }
  1222. inline void do_blocking_move_to_z(float z) { do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z); }
  1223. inline void raise_z_after_probing() { do_blocking_move_to_z(current_position[Z_AXIS] + Z_RAISE_AFTER_PROBING); }
  1224. static void clean_up_after_endstop_move() {
  1225. #if ENABLED(ENDSTOPS_ONLY_FOR_HOMING)
  1226. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1227. if (marlin_debug_flags & DEBUG_LEVELING) {
  1228. SERIAL_ECHOLNPGM("clean_up_after_endstop_move > ENDSTOPS_ONLY_FOR_HOMING > enable_endstops(false)");
  1229. }
  1230. #endif
  1231. enable_endstops(false);
  1232. #endif
  1233. feedrate = saved_feedrate;
  1234. feedrate_multiplier = saved_feedrate_multiplier;
  1235. refresh_cmd_timeout();
  1236. }
  1237. static void deploy_z_probe() {
  1238. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1239. if (marlin_debug_flags & DEBUG_LEVELING) {
  1240. print_xyz("deploy_z_probe > current_position", current_position);
  1241. }
  1242. #endif
  1243. #if HAS_SERVO_ENDSTOPS
  1244. // Engage Z Servo endstop if enabled
  1245. if (servo_endstop_id[Z_AXIS] >= 0) servo[servo_endstop_id[Z_AXIS]].move(servo_endstop_angle[Z_AXIS][0]);
  1246. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1247. feedrate = Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE;
  1248. // If endstop is already false, the Z probe is deployed
  1249. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1250. bool z_probe_endstop = (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING);
  1251. if (z_probe_endstop)
  1252. #else
  1253. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1254. if (z_min_endstop)
  1255. #endif
  1256. {
  1257. // Move to the start position to initiate deployment
  1258. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_1_X;
  1259. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_1_Y;
  1260. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_1_Z;
  1261. prepare_move_raw(); // this will also set_current_to_destination
  1262. // Move to engage deployment
  1263. if (Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE != Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE)
  1264. feedrate = Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE;
  1265. if (Z_PROBE_ALLEN_KEY_DEPLOY_2_X != Z_PROBE_ALLEN_KEY_DEPLOY_1_X)
  1266. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_2_X;
  1267. if (Z_PROBE_ALLEN_KEY_DEPLOY_2_Y != Z_PROBE_ALLEN_KEY_DEPLOY_1_Y)
  1268. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_2_Y;
  1269. if (Z_PROBE_ALLEN_KEY_DEPLOY_2_Z != Z_PROBE_ALLEN_KEY_DEPLOY_1_Z)
  1270. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_2_Z;
  1271. prepare_move_raw();
  1272. #ifdef Z_PROBE_ALLEN_KEY_DEPLOY_3_X
  1273. if (Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE != Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE)
  1274. feedrate = Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE;
  1275. // Move to trigger deployment
  1276. if (Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE != Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE)
  1277. feedrate = Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE;
  1278. if (Z_PROBE_ALLEN_KEY_DEPLOY_3_X != Z_PROBE_ALLEN_KEY_DEPLOY_2_X)
  1279. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_3_X;
  1280. if (Z_PROBE_ALLEN_KEY_DEPLOY_3_Y != Z_PROBE_ALLEN_KEY_DEPLOY_2_Y)
  1281. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_3_Y;
  1282. if (Z_PROBE_ALLEN_KEY_DEPLOY_3_Z != Z_PROBE_ALLEN_KEY_DEPLOY_2_Z)
  1283. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_3_Z;
  1284. prepare_move_raw();
  1285. #endif
  1286. }
  1287. // Partially Home X,Y for safety
  1288. destination[X_AXIS] = destination[X_AXIS] * 0.75;
  1289. destination[Y_AXIS] = destination[Y_AXIS] * 0.75;
  1290. prepare_move_raw(); // this will also set_current_to_destination
  1291. st_synchronize();
  1292. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1293. z_probe_endstop = (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING);
  1294. if (z_probe_endstop)
  1295. #else
  1296. z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1297. if (z_min_endstop)
  1298. #endif
  1299. {
  1300. if (IsRunning()) {
  1301. SERIAL_ERROR_START;
  1302. SERIAL_ERRORLNPGM("Z-Probe failed to engage!");
  1303. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1304. }
  1305. Stop();
  1306. }
  1307. #endif // Z_PROBE_ALLEN_KEY
  1308. }
  1309. static void stow_z_probe(bool doRaise = true) {
  1310. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1311. if (marlin_debug_flags & DEBUG_LEVELING) {
  1312. print_xyz("stow_z_probe > current_position", current_position);
  1313. }
  1314. #endif
  1315. #if HAS_SERVO_ENDSTOPS
  1316. // Retract Z Servo endstop if enabled
  1317. if (servo_endstop_id[Z_AXIS] >= 0) {
  1318. #if Z_RAISE_AFTER_PROBING > 0
  1319. if (doRaise) {
  1320. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1321. if (marlin_debug_flags & DEBUG_LEVELING) {
  1322. SERIAL_ECHOPAIR("Raise Z (after) by ", (float)Z_RAISE_AFTER_PROBING);
  1323. SERIAL_EOL;
  1324. SERIAL_ECHO("> SERVO_ENDSTOPS > raise_z_after_probing()");
  1325. SERIAL_EOL;
  1326. }
  1327. #endif
  1328. raise_z_after_probing(); // this also updates current_position
  1329. st_synchronize();
  1330. }
  1331. #endif
  1332. // Change the Z servo angle
  1333. servo[servo_endstop_id[Z_AXIS]].move(servo_endstop_angle[Z_AXIS][1]);
  1334. }
  1335. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1336. // Move up for safety
  1337. feedrate = Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE;
  1338. #if Z_RAISE_AFTER_PROBING > 0
  1339. destination[Z_AXIS] = current_position[Z_AXIS] + Z_RAISE_AFTER_PROBING;
  1340. prepare_move_raw(); // this will also set_current_to_destination
  1341. #endif
  1342. // Move to the start position to initiate retraction
  1343. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_STOW_1_X;
  1344. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_STOW_1_Y;
  1345. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_STOW_1_Z;
  1346. prepare_move_raw();
  1347. // Move the nozzle down to push the Z probe into retracted position
  1348. if (Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE != Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE)
  1349. feedrate = Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE;
  1350. if (Z_PROBE_ALLEN_KEY_STOW_2_X != Z_PROBE_ALLEN_KEY_STOW_1_X)
  1351. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_STOW_2_X;
  1352. if (Z_PROBE_ALLEN_KEY_STOW_2_Y != Z_PROBE_ALLEN_KEY_STOW_1_Y)
  1353. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_STOW_2_Y;
  1354. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_STOW_2_Z;
  1355. prepare_move_raw();
  1356. // Move up for safety
  1357. if (Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE != Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE)
  1358. feedrate = Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE;
  1359. if (Z_PROBE_ALLEN_KEY_STOW_3_X != Z_PROBE_ALLEN_KEY_STOW_2_X)
  1360. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_STOW_3_X;
  1361. if (Z_PROBE_ALLEN_KEY_STOW_3_Y != Z_PROBE_ALLEN_KEY_STOW_2_Y)
  1362. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_STOW_3_Y;
  1363. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_STOW_3_Z;
  1364. prepare_move_raw();
  1365. // Home XY for safety
  1366. feedrate = homing_feedrate[X_AXIS] / 2;
  1367. destination[X_AXIS] = 0;
  1368. destination[Y_AXIS] = 0;
  1369. prepare_move_raw(); // this will also set_current_to_destination
  1370. st_synchronize();
  1371. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1372. bool z_probe_endstop = (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING);
  1373. if (!z_probe_endstop)
  1374. #else
  1375. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1376. if (!z_min_endstop)
  1377. #endif
  1378. {
  1379. if (IsRunning()) {
  1380. SERIAL_ERROR_START;
  1381. SERIAL_ERRORLNPGM("Z-Probe failed to retract!");
  1382. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1383. }
  1384. Stop();
  1385. }
  1386. #endif // Z_PROBE_ALLEN_KEY
  1387. }
  1388. enum ProbeAction {
  1389. ProbeStay = 0,
  1390. ProbeDeploy = _BV(0),
  1391. ProbeStow = _BV(1),
  1392. ProbeDeployAndStow = (ProbeDeploy | ProbeStow)
  1393. };
  1394. // Probe bed height at position (x,y), returns the measured z value
  1395. static float probe_pt(float x, float y, float z_before, ProbeAction probe_action = ProbeDeployAndStow, int verbose_level = 1) {
  1396. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1397. if (marlin_debug_flags & DEBUG_LEVELING) {
  1398. SERIAL_ECHOLNPGM("probe_pt >>>");
  1399. SERIAL_ECHOPAIR("> ProbeAction:", (unsigned long)probe_action);
  1400. SERIAL_EOL;
  1401. print_xyz("> current_position", current_position);
  1402. }
  1403. #endif
  1404. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1405. if (marlin_debug_flags & DEBUG_LEVELING) {
  1406. SERIAL_ECHOPAIR("Z Raise to z_before ", z_before);
  1407. SERIAL_EOL;
  1408. SERIAL_ECHOPAIR("> do_blocking_move_to_z ", z_before);
  1409. SERIAL_EOL;
  1410. }
  1411. #endif
  1412. // Move Z up to the z_before height, then move the Z probe to the given XY
  1413. do_blocking_move_to_z(z_before); // this also updates current_position
  1414. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1415. if (marlin_debug_flags & DEBUG_LEVELING) {
  1416. SERIAL_ECHOPAIR("> do_blocking_move_to_xy ", x - (X_PROBE_OFFSET_FROM_EXTRUDER));
  1417. SERIAL_ECHOPAIR(", ", y - (Y_PROBE_OFFSET_FROM_EXTRUDER));
  1418. SERIAL_EOL;
  1419. }
  1420. #endif
  1421. do_blocking_move_to_xy(x - (X_PROBE_OFFSET_FROM_EXTRUDER), y - (Y_PROBE_OFFSET_FROM_EXTRUDER)); // this also updates current_position
  1422. #if DISABLED(Z_PROBE_SLED) && DISABLED(Z_PROBE_ALLEN_KEY)
  1423. if (probe_action & ProbeDeploy) {
  1424. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1425. if (marlin_debug_flags & DEBUG_LEVELING) {
  1426. SERIAL_ECHOLNPGM("> ProbeDeploy");
  1427. }
  1428. #endif
  1429. deploy_z_probe();
  1430. }
  1431. #endif
  1432. run_z_probe();
  1433. float measured_z = current_position[Z_AXIS];
  1434. #if DISABLED(Z_PROBE_SLED) && DISABLED(Z_PROBE_ALLEN_KEY)
  1435. if (probe_action & ProbeStow) {
  1436. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1437. if (marlin_debug_flags & DEBUG_LEVELING) {
  1438. SERIAL_ECHOLNPGM("> ProbeStow (stow_z_probe will do Z Raise)");
  1439. }
  1440. #endif
  1441. stow_z_probe();
  1442. }
  1443. #endif
  1444. if (verbose_level > 2) {
  1445. SERIAL_PROTOCOLPGM("Bed X: ");
  1446. SERIAL_PROTOCOL_F(x, 3);
  1447. SERIAL_PROTOCOLPGM(" Y: ");
  1448. SERIAL_PROTOCOL_F(y, 3);
  1449. SERIAL_PROTOCOLPGM(" Z: ");
  1450. SERIAL_PROTOCOL_F(measured_z, 3);
  1451. SERIAL_EOL;
  1452. }
  1453. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1454. if (marlin_debug_flags & DEBUG_LEVELING) {
  1455. SERIAL_ECHOLNPGM("<<< probe_pt");
  1456. }
  1457. #endif
  1458. return measured_z;
  1459. }
  1460. #if ENABLED(DELTA)
  1461. /**
  1462. * All DELTA leveling in the Marlin uses NONLINEAR_BED_LEVELING
  1463. */
  1464. static void extrapolate_one_point(int x, int y, int xdir, int ydir) {
  1465. if (bed_level[x][y] != 0.0) {
  1466. return; // Don't overwrite good values.
  1467. }
  1468. float a = 2 * bed_level[x + xdir][y] - bed_level[x + xdir * 2][y]; // Left to right.
  1469. float b = 2 * bed_level[x][y + ydir] - bed_level[x][y + ydir * 2]; // Front to back.
  1470. float c = 2 * bed_level[x + xdir][y + ydir] - bed_level[x + xdir * 2][y + ydir * 2]; // Diagonal.
  1471. float median = c; // Median is robust (ignores outliers).
  1472. if (a < b) {
  1473. if (b < c) median = b;
  1474. if (c < a) median = a;
  1475. }
  1476. else { // b <= a
  1477. if (c < b) median = b;
  1478. if (a < c) median = a;
  1479. }
  1480. bed_level[x][y] = median;
  1481. }
  1482. // Fill in the unprobed points (corners of circular print surface)
  1483. // using linear extrapolation, away from the center.
  1484. static void extrapolate_unprobed_bed_level() {
  1485. int half = (AUTO_BED_LEVELING_GRID_POINTS - 1) / 2;
  1486. for (int y = 0; y <= half; y++) {
  1487. for (int x = 0; x <= half; x++) {
  1488. if (x + y < 3) continue;
  1489. extrapolate_one_point(half - x, half - y, x > 1 ? +1 : 0, y > 1 ? +1 : 0);
  1490. extrapolate_one_point(half + x, half - y, x > 1 ? -1 : 0, y > 1 ? +1 : 0);
  1491. extrapolate_one_point(half - x, half + y, x > 1 ? +1 : 0, y > 1 ? -1 : 0);
  1492. extrapolate_one_point(half + x, half + y, x > 1 ? -1 : 0, y > 1 ? -1 : 0);
  1493. }
  1494. }
  1495. }
  1496. // Print calibration results for plotting or manual frame adjustment.
  1497. static void print_bed_level() {
  1498. for (int y = 0; y < AUTO_BED_LEVELING_GRID_POINTS; y++) {
  1499. for (int x = 0; x < AUTO_BED_LEVELING_GRID_POINTS; x++) {
  1500. SERIAL_PROTOCOL_F(bed_level[x][y], 2);
  1501. SERIAL_PROTOCOLCHAR(' ');
  1502. }
  1503. SERIAL_EOL;
  1504. }
  1505. }
  1506. // Reset calibration results to zero.
  1507. void reset_bed_level() {
  1508. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1509. if (marlin_debug_flags & DEBUG_LEVELING) {
  1510. SERIAL_ECHOLNPGM("reset_bed_level");
  1511. }
  1512. #endif
  1513. for (int y = 0; y < AUTO_BED_LEVELING_GRID_POINTS; y++) {
  1514. for (int x = 0; x < AUTO_BED_LEVELING_GRID_POINTS; x++) {
  1515. bed_level[x][y] = 0.0;
  1516. }
  1517. }
  1518. }
  1519. #endif // DELTA
  1520. #if HAS_SERVO_ENDSTOPS && DISABLED(Z_PROBE_SLED)
  1521. void raise_z_for_servo() {
  1522. float zpos = current_position[Z_AXIS], z_dest = Z_RAISE_BEFORE_PROBING;
  1523. // The zprobe_zoffset is negative any switch below the nozzle, so
  1524. // multiply by Z_HOME_DIR (-1) to move enough away from bed for the probe
  1525. z_dest += axis_known_position[Z_AXIS] ? zprobe_zoffset * Z_HOME_DIR : zpos;
  1526. if (zpos < z_dest) do_blocking_move_to_z(z_dest); // also updates current_position
  1527. }
  1528. #endif
  1529. #endif // AUTO_BED_LEVELING_FEATURE
  1530. #if ENABLED(Z_PROBE_SLED)
  1531. #ifndef SLED_DOCKING_OFFSET
  1532. #define SLED_DOCKING_OFFSET 0
  1533. #endif
  1534. /**
  1535. * Method to dock/undock a sled designed by Charles Bell.
  1536. *
  1537. * dock[in] If true, move to MAX_X and engage the electromagnet
  1538. * offset[in] The additional distance to move to adjust docking location
  1539. */
  1540. static void dock_sled(bool dock, int offset = 0) {
  1541. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1542. if (marlin_debug_flags & DEBUG_LEVELING) {
  1543. SERIAL_ECHOPAIR("dock_sled", dock);
  1544. SERIAL_EOL;
  1545. }
  1546. #endif
  1547. if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) {
  1548. LCD_MESSAGEPGM(MSG_POSITION_UNKNOWN);
  1549. SERIAL_ECHO_START;
  1550. SERIAL_ECHOLNPGM(MSG_POSITION_UNKNOWN);
  1551. return;
  1552. }
  1553. float oldXpos = current_position[X_AXIS]; // save x position
  1554. if (dock) {
  1555. #if Z_RAISE_AFTER_PROBING > 0
  1556. raise_z_after_probing(); // raise Z
  1557. #endif
  1558. do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET + offset - 1); // Dock sled a bit closer to ensure proper capturing
  1559. digitalWrite(SLED_PIN, LOW); // turn off magnet
  1560. }
  1561. else {
  1562. float z_loc = current_position[Z_AXIS];
  1563. if (z_loc < Z_RAISE_BEFORE_PROBING + 5) z_loc = Z_RAISE_BEFORE_PROBING;
  1564. do_blocking_move_to(X_MAX_POS + SLED_DOCKING_OFFSET + offset, current_position[Y_AXIS], z_loc); // this also updates current_position
  1565. digitalWrite(SLED_PIN, HIGH); // turn on magnet
  1566. }
  1567. do_blocking_move_to_x(oldXpos); // return to position before docking
  1568. }
  1569. #endif // Z_PROBE_SLED
  1570. /**
  1571. * Home an individual axis
  1572. */
  1573. #define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS)
  1574. static void homeaxis(AxisEnum axis) {
  1575. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1576. if (marlin_debug_flags & DEBUG_LEVELING) {
  1577. SERIAL_ECHOPAIR(">>> homeaxis(", (unsigned long)axis);
  1578. SERIAL_CHAR(')');
  1579. SERIAL_EOL;
  1580. }
  1581. #endif
  1582. #define HOMEAXIS_DO(LETTER) \
  1583. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1584. if (axis == X_AXIS ? HOMEAXIS_DO(X) : axis == Y_AXIS ? HOMEAXIS_DO(Y) : axis == Z_AXIS ? HOMEAXIS_DO(Z) : 0) {
  1585. int axis_home_dir =
  1586. #if ENABLED(DUAL_X_CARRIAGE)
  1587. (axis == X_AXIS) ? x_home_dir(active_extruder) :
  1588. #endif
  1589. home_dir(axis);
  1590. // Set the axis position as setup for the move
  1591. current_position[axis] = 0;
  1592. sync_plan_position();
  1593. #if ENABLED(Z_PROBE_SLED)
  1594. // Get Probe
  1595. if (axis == Z_AXIS) {
  1596. if (axis_home_dir < 0) dock_sled(false);
  1597. }
  1598. #endif
  1599. #if SERVO_LEVELING && DISABLED(Z_PROBE_SLED)
  1600. // Deploy a Z probe if there is one, and homing towards the bed
  1601. if (axis == Z_AXIS) {
  1602. if (axis_home_dir < 0) deploy_z_probe();
  1603. }
  1604. #endif
  1605. #if HAS_SERVO_ENDSTOPS
  1606. // Engage Servo endstop if enabled
  1607. if (axis != Z_AXIS && servo_endstop_id[axis] >= 0)
  1608. servo[servo_endstop_id[axis]].move(servo_endstop_angle[axis][0]);
  1609. #endif
  1610. // Set a flag for Z motor locking
  1611. #if ENABLED(Z_DUAL_ENDSTOPS)
  1612. if (axis == Z_AXIS) In_Homing_Process(true);
  1613. #endif
  1614. // Move towards the endstop until an endstop is triggered
  1615. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1616. feedrate = homing_feedrate[axis];
  1617. line_to_destination();
  1618. st_synchronize();
  1619. // Set the axis position as setup for the move
  1620. current_position[axis] = 0;
  1621. sync_plan_position();
  1622. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1623. if (marlin_debug_flags & DEBUG_LEVELING) {
  1624. SERIAL_ECHOLNPGM("> enable_endstops(false)");
  1625. }
  1626. #endif
  1627. enable_endstops(false); // Disable endstops while moving away
  1628. // Move away from the endstop by the axis HOME_BUMP_MM
  1629. destination[axis] = -home_bump_mm(axis) * axis_home_dir;
  1630. line_to_destination();
  1631. st_synchronize();
  1632. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1633. if (marlin_debug_flags & DEBUG_LEVELING) {
  1634. SERIAL_ECHOLNPGM("> enable_endstops(true)");
  1635. }
  1636. #endif
  1637. enable_endstops(true); // Enable endstops for next homing move
  1638. // Slow down the feedrate for the next move
  1639. set_homing_bump_feedrate(axis);
  1640. // Move slowly towards the endstop until triggered
  1641. destination[axis] = 2 * home_bump_mm(axis) * axis_home_dir;
  1642. line_to_destination();
  1643. st_synchronize();
  1644. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1645. if (marlin_debug_flags & DEBUG_LEVELING) {
  1646. print_xyz("> TRIGGER ENDSTOP > current_position", current_position);
  1647. }
  1648. #endif
  1649. #if ENABLED(Z_DUAL_ENDSTOPS)
  1650. if (axis == Z_AXIS) {
  1651. float adj = fabs(z_endstop_adj);
  1652. bool lockZ1;
  1653. if (axis_home_dir > 0) {
  1654. adj = -adj;
  1655. lockZ1 = (z_endstop_adj > 0);
  1656. }
  1657. else
  1658. lockZ1 = (z_endstop_adj < 0);
  1659. if (lockZ1) Lock_z_motor(true); else Lock_z2_motor(true);
  1660. sync_plan_position();
  1661. // Move to the adjusted endstop height
  1662. feedrate = homing_feedrate[axis];
  1663. destination[Z_AXIS] = adj;
  1664. line_to_destination();
  1665. st_synchronize();
  1666. if (lockZ1) Lock_z_motor(false); else Lock_z2_motor(false);
  1667. In_Homing_Process(false);
  1668. } // Z_AXIS
  1669. #endif
  1670. #if ENABLED(DELTA)
  1671. // retrace by the amount specified in endstop_adj
  1672. if (endstop_adj[axis] * axis_home_dir < 0) {
  1673. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1674. if (marlin_debug_flags & DEBUG_LEVELING) {
  1675. SERIAL_ECHOLNPGM("> enable_endstops(false)");
  1676. }
  1677. #endif
  1678. enable_endstops(false); // Disable endstops while moving away
  1679. sync_plan_position();
  1680. destination[axis] = endstop_adj[axis];
  1681. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1682. if (marlin_debug_flags & DEBUG_LEVELING) {
  1683. SERIAL_ECHOPAIR("> endstop_adj = ", endstop_adj[axis]);
  1684. print_xyz(" > destination", destination);
  1685. }
  1686. #endif
  1687. line_to_destination();
  1688. st_synchronize();
  1689. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1690. if (marlin_debug_flags & DEBUG_LEVELING) {
  1691. SERIAL_ECHOLNPGM("> enable_endstops(true)");
  1692. }
  1693. #endif
  1694. enable_endstops(true); // Enable endstops for next homing move
  1695. }
  1696. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1697. else {
  1698. if (marlin_debug_flags & DEBUG_LEVELING) {
  1699. SERIAL_ECHOPAIR("> endstop_adj * axis_home_dir = ", endstop_adj[axis] * axis_home_dir);
  1700. SERIAL_EOL;
  1701. }
  1702. }
  1703. #endif
  1704. #endif
  1705. // Set the axis position to its home position (plus home offsets)
  1706. set_axis_is_at_home(axis);
  1707. sync_plan_position();
  1708. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1709. if (marlin_debug_flags & DEBUG_LEVELING) {
  1710. print_xyz("> AFTER set_axis_is_at_home > current_position", current_position);
  1711. }
  1712. #endif
  1713. destination[axis] = current_position[axis];
  1714. feedrate = 0.0;
  1715. endstops_hit_on_purpose(); // clear endstop hit flags
  1716. axis_known_position[axis] = true;
  1717. axis_homed[axis] = true;
  1718. #if ENABLED(Z_PROBE_SLED)
  1719. // bring Z probe back
  1720. if (axis == Z_AXIS) {
  1721. if (axis_home_dir < 0) dock_sled(true);
  1722. }
  1723. #endif
  1724. #if SERVO_LEVELING && DISABLED(Z_PROBE_SLED)
  1725. // Deploy a Z probe if there is one, and homing towards the bed
  1726. if (axis == Z_AXIS) {
  1727. if (axis_home_dir < 0) {
  1728. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1729. if (marlin_debug_flags & DEBUG_LEVELING) {
  1730. SERIAL_ECHOLNPGM("> SERVO_LEVELING > stow_z_probe");
  1731. }
  1732. #endif
  1733. stow_z_probe();
  1734. }
  1735. }
  1736. else
  1737. #endif
  1738. {
  1739. #if HAS_SERVO_ENDSTOPS
  1740. // Retract Servo endstop if enabled
  1741. if (servo_endstop_id[axis] >= 0) {
  1742. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1743. if (marlin_debug_flags & DEBUG_LEVELING) {
  1744. SERIAL_ECHOLNPGM("> SERVO_ENDSTOPS > Stow with servo.move()");
  1745. }
  1746. #endif
  1747. servo[servo_endstop_id[axis]].move(servo_endstop_angle[axis][1]);
  1748. }
  1749. #endif
  1750. }
  1751. }
  1752. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1753. if (marlin_debug_flags & DEBUG_LEVELING) {
  1754. SERIAL_ECHOPAIR("<<< homeaxis(", (unsigned long)axis);
  1755. SERIAL_CHAR(')');
  1756. SERIAL_EOL;
  1757. }
  1758. #endif
  1759. }
  1760. #if ENABLED(FWRETRACT)
  1761. void retract(bool retracting, bool swapping = false) {
  1762. if (retracting == retracted[active_extruder]) return;
  1763. float oldFeedrate = feedrate;
  1764. set_destination_to_current();
  1765. if (retracting) {
  1766. feedrate = retract_feedrate * 60;
  1767. current_position[E_AXIS] += (swapping ? retract_length_swap : retract_length) / volumetric_multiplier[active_extruder];
  1768. plan_set_e_position(current_position[E_AXIS]);
  1769. prepare_move();
  1770. if (retract_zlift > 0.01) {
  1771. current_position[Z_AXIS] -= retract_zlift;
  1772. #if ENABLED(DELTA)
  1773. sync_plan_position_delta();
  1774. #else
  1775. sync_plan_position();
  1776. #endif
  1777. prepare_move();
  1778. }
  1779. }
  1780. else {
  1781. if (retract_zlift > 0.01) {
  1782. current_position[Z_AXIS] += retract_zlift;
  1783. #if ENABLED(DELTA)
  1784. sync_plan_position_delta();
  1785. #else
  1786. sync_plan_position();
  1787. #endif
  1788. //prepare_move();
  1789. }
  1790. feedrate = retract_recover_feedrate * 60;
  1791. float move_e = swapping ? retract_length_swap + retract_recover_length_swap : retract_length + retract_recover_length;
  1792. current_position[E_AXIS] -= move_e / volumetric_multiplier[active_extruder];
  1793. plan_set_e_position(current_position[E_AXIS]);
  1794. prepare_move();
  1795. }
  1796. feedrate = oldFeedrate;
  1797. retracted[active_extruder] = retracting;
  1798. } // retract()
  1799. #endif // FWRETRACT
  1800. /**
  1801. *
  1802. * G-Code Handler functions
  1803. *
  1804. */
  1805. /**
  1806. * Set XYZE destination and feedrate from the current GCode command
  1807. *
  1808. * - Set destination from included axis codes
  1809. * - Set to current for missing axis codes
  1810. * - Set the feedrate, if included
  1811. */
  1812. void gcode_get_destination() {
  1813. for (int i = 0; i < NUM_AXIS; i++) {
  1814. if (code_seen(axis_codes[i]))
  1815. destination[i] = code_value() + (axis_relative_modes[i] || relative_mode ? current_position[i] : 0);
  1816. else
  1817. destination[i] = current_position[i];
  1818. }
  1819. if (code_seen('F')) {
  1820. float next_feedrate = code_value();
  1821. if (next_feedrate > 0.0) feedrate = next_feedrate;
  1822. }
  1823. }
  1824. void unknown_command_error() {
  1825. SERIAL_ECHO_START;
  1826. SERIAL_ECHOPGM(MSG_UNKNOWN_COMMAND);
  1827. SERIAL_ECHO(current_command);
  1828. SERIAL_ECHOPGM("\"\n");
  1829. }
  1830. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  1831. void host_keepalive() {
  1832. millis_t ms = millis();
  1833. if (busy_state != NOT_BUSY) {
  1834. if (ms < next_busy_signal_ms) return;
  1835. switch (busy_state) {
  1836. case NOT_BUSY:
  1837. break;
  1838. case IN_HANDLER:
  1839. case IN_PROCESS:
  1840. SERIAL_ECHO_START;
  1841. SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING);
  1842. break;
  1843. case PAUSED_FOR_USER:
  1844. SERIAL_ECHO_START;
  1845. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER);
  1846. break;
  1847. case PAUSED_FOR_INPUT:
  1848. SERIAL_ECHO_START;
  1849. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT);
  1850. break;
  1851. }
  1852. }
  1853. next_busy_signal_ms = ms + 2000UL;
  1854. }
  1855. #endif //HOST_KEEPALIVE_FEATURE
  1856. /**
  1857. * G0, G1: Coordinated movement of X Y Z E axes
  1858. */
  1859. inline void gcode_G0_G1() {
  1860. if (IsRunning()) {
  1861. gcode_get_destination(); // For X Y Z E F
  1862. #if ENABLED(FWRETRACT)
  1863. if (autoretract_enabled && !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  1864. float echange = destination[E_AXIS] - current_position[E_AXIS];
  1865. // Is this move an attempt to retract or recover?
  1866. if ((echange < -MIN_RETRACT && !retracted[active_extruder]) || (echange > MIN_RETRACT && retracted[active_extruder])) {
  1867. current_position[E_AXIS] = destination[E_AXIS]; // hide the slicer-generated retract/recover from calculations
  1868. plan_set_e_position(current_position[E_AXIS]); // AND from the planner
  1869. retract(!retracted[active_extruder]);
  1870. return;
  1871. }
  1872. }
  1873. #endif //FWRETRACT
  1874. prepare_move();
  1875. }
  1876. }
  1877. /**
  1878. * G2: Clockwise Arc
  1879. * G3: Counterclockwise Arc
  1880. */
  1881. inline void gcode_G2_G3(bool clockwise) {
  1882. if (IsRunning()) {
  1883. #if ENABLED(SF_ARC_FIX)
  1884. bool relative_mode_backup = relative_mode;
  1885. relative_mode = true;
  1886. #endif
  1887. gcode_get_destination();
  1888. #if ENABLED(SF_ARC_FIX)
  1889. relative_mode = relative_mode_backup;
  1890. #endif
  1891. // Center of arc as offset from current_position
  1892. float arc_offset[2] = {
  1893. code_seen('I') ? code_value() : 0,
  1894. code_seen('J') ? code_value() : 0
  1895. };
  1896. // Send an arc to the planner
  1897. plan_arc(destination, arc_offset, clockwise);
  1898. refresh_cmd_timeout();
  1899. }
  1900. }
  1901. /**
  1902. * G4: Dwell S<seconds> or P<milliseconds>
  1903. */
  1904. inline void gcode_G4() {
  1905. millis_t codenum = 0;
  1906. if (code_seen('P')) codenum = code_value_long(); // milliseconds to wait
  1907. if (code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  1908. st_synchronize();
  1909. refresh_cmd_timeout();
  1910. codenum += previous_cmd_ms; // keep track of when we started waiting
  1911. if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL);
  1912. while (millis() < codenum) idle();
  1913. }
  1914. #if ENABLED(FWRETRACT)
  1915. /**
  1916. * G10 - Retract filament according to settings of M207
  1917. * G11 - Recover filament according to settings of M208
  1918. */
  1919. inline void gcode_G10_G11(bool doRetract=false) {
  1920. #if EXTRUDERS > 1
  1921. if (doRetract) {
  1922. retracted_swap[active_extruder] = (code_seen('S') && code_value_short() == 1); // checks for swap retract argument
  1923. }
  1924. #endif
  1925. retract(doRetract
  1926. #if EXTRUDERS > 1
  1927. , retracted_swap[active_extruder]
  1928. #endif
  1929. );
  1930. }
  1931. #endif //FWRETRACT
  1932. /**
  1933. * G28: Home all axes according to settings
  1934. *
  1935. * Parameters
  1936. *
  1937. * None Home to all axes with no parameters.
  1938. * With QUICK_HOME enabled XY will home together, then Z.
  1939. *
  1940. * Cartesian parameters
  1941. *
  1942. * X Home to the X endstop
  1943. * Y Home to the Y endstop
  1944. * Z Home to the Z endstop
  1945. *
  1946. */
  1947. inline void gcode_G28() {
  1948. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1949. if (marlin_debug_flags & DEBUG_LEVELING) {
  1950. SERIAL_ECHOLNPGM("gcode_G28 >>>");
  1951. }
  1952. #endif
  1953. // Wait for planner moves to finish!
  1954. st_synchronize();
  1955. // For auto bed leveling, clear the level matrix
  1956. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  1957. plan_bed_level_matrix.set_to_identity();
  1958. #if ENABLED(DELTA)
  1959. reset_bed_level();
  1960. #endif
  1961. #endif
  1962. // For manual bed leveling deactivate the matrix temporarily
  1963. #if ENABLED(MESH_BED_LEVELING)
  1964. uint8_t mbl_was_active = mbl.active;
  1965. mbl.active = 0;
  1966. #endif
  1967. setup_for_endstop_move();
  1968. set_destination_to_current(); // Directly after a reset this is all 0. Later we get a hint if we have to raise z or not.
  1969. feedrate = 0.0;
  1970. #if ENABLED(DELTA)
  1971. // A delta can only safely home all axis at the same time
  1972. // all axis have to home at the same time
  1973. // Pretend the current position is 0,0,0
  1974. for (int i = X_AXIS; i <= Z_AXIS; i++) current_position[i] = 0;
  1975. sync_plan_position();
  1976. // Move all carriages up together until the first endstop is hit.
  1977. for (int i = X_AXIS; i <= Z_AXIS; i++) destination[i] = 3 * (Z_MAX_LENGTH);
  1978. feedrate = 1.732 * homing_feedrate[X_AXIS];
  1979. line_to_destination();
  1980. st_synchronize();
  1981. endstops_hit_on_purpose(); // clear endstop hit flags
  1982. // Destination reached
  1983. for (int i = X_AXIS; i <= Z_AXIS; i++) current_position[i] = destination[i];
  1984. // take care of back off and rehome now we are all at the top
  1985. HOMEAXIS(X);
  1986. HOMEAXIS(Y);
  1987. HOMEAXIS(Z);
  1988. sync_plan_position_delta();
  1989. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1990. if (marlin_debug_flags & DEBUG_LEVELING) {
  1991. print_xyz("(DELTA) > current_position", current_position);
  1992. }
  1993. #endif
  1994. #else // NOT DELTA
  1995. bool homeX = code_seen(axis_codes[X_AXIS]),
  1996. homeY = code_seen(axis_codes[Y_AXIS]),
  1997. homeZ = code_seen(axis_codes[Z_AXIS]);
  1998. home_all_axis = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ);
  1999. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2000. if (home_all_axis || homeZ) {
  2001. HOMEAXIS(Z);
  2002. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2003. if (marlin_debug_flags & DEBUG_LEVELING) {
  2004. print_xyz("> HOMEAXIS(Z) > current_position", current_position);
  2005. }
  2006. #endif
  2007. }
  2008. #elif defined(MIN_Z_HEIGHT_FOR_HOMING) && MIN_Z_HEIGHT_FOR_HOMING > 0
  2009. // Raise Z before homing any other axes and z is not already high enough (never lower z)
  2010. if (current_position[Z_AXIS] <= MIN_Z_HEIGHT_FOR_HOMING) {
  2011. destination[Z_AXIS] = MIN_Z_HEIGHT_FOR_HOMING;
  2012. feedrate = max_feedrate[Z_AXIS] * 60; // feedrate (mm/m) = max_feedrate (mm/s)
  2013. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2014. if (marlin_debug_flags & DEBUG_LEVELING) {
  2015. SERIAL_ECHOPAIR("Raise Z (before homing) to ", (float)(MIN_Z_HEIGHT_FOR_HOMING));
  2016. SERIAL_EOL;
  2017. print_xyz("> (home_all_axis || homeZ) > current_position", current_position);
  2018. print_xyz("> (home_all_axis || homeZ) > destination", destination);
  2019. }
  2020. #endif
  2021. line_to_destination();
  2022. st_synchronize();
  2023. // Update the current Z position even if it currently not real from Z-home
  2024. // otherwise each call to line_to_destination() will want to move Z-axis
  2025. // by MIN_Z_HEIGHT_FOR_HOMING.
  2026. current_position[Z_AXIS] = destination[Z_AXIS];
  2027. }
  2028. #endif
  2029. #if ENABLED(QUICK_HOME)
  2030. if (home_all_axis || (homeX && homeY)) { // First diagonal move
  2031. current_position[X_AXIS] = current_position[Y_AXIS] = 0;
  2032. #if ENABLED(DUAL_X_CARRIAGE)
  2033. int x_axis_home_dir = x_home_dir(active_extruder);
  2034. extruder_duplication_enabled = false;
  2035. #else
  2036. int x_axis_home_dir = home_dir(X_AXIS);
  2037. #endif
  2038. sync_plan_position();
  2039. float mlx = max_length(X_AXIS), mly = max_length(Y_AXIS),
  2040. mlratio = mlx > mly ? mly / mlx : mlx / mly;
  2041. destination[X_AXIS] = 1.5 * mlx * x_axis_home_dir;
  2042. destination[Y_AXIS] = 1.5 * mly * home_dir(Y_AXIS);
  2043. feedrate = min(homing_feedrate[X_AXIS], homing_feedrate[Y_AXIS]) * sqrt(mlratio * mlratio + 1);
  2044. line_to_destination();
  2045. st_synchronize();
  2046. set_axis_is_at_home(X_AXIS);
  2047. set_axis_is_at_home(Y_AXIS);
  2048. sync_plan_position();
  2049. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2050. if (marlin_debug_flags & DEBUG_LEVELING) {
  2051. print_xyz("> QUICK_HOME > current_position 1", current_position);
  2052. }
  2053. #endif
  2054. destination[X_AXIS] = current_position[X_AXIS];
  2055. destination[Y_AXIS] = current_position[Y_AXIS];
  2056. line_to_destination();
  2057. feedrate = 0.0;
  2058. st_synchronize();
  2059. endstops_hit_on_purpose(); // clear endstop hit flags
  2060. current_position[X_AXIS] = destination[X_AXIS];
  2061. current_position[Y_AXIS] = destination[Y_AXIS];
  2062. #if DISABLED(SCARA)
  2063. current_position[Z_AXIS] = destination[Z_AXIS];
  2064. #endif
  2065. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2066. if (marlin_debug_flags & DEBUG_LEVELING) {
  2067. print_xyz("> QUICK_HOME > current_position 2", current_position);
  2068. }
  2069. #endif
  2070. }
  2071. #endif // QUICK_HOME
  2072. #if ENABLED(HOME_Y_BEFORE_X)
  2073. // Home Y
  2074. if (home_all_axis || homeY) HOMEAXIS(Y);
  2075. #endif
  2076. // Home X
  2077. if (home_all_axis || homeX) {
  2078. #if ENABLED(DUAL_X_CARRIAGE)
  2079. int tmp_extruder = active_extruder;
  2080. extruder_duplication_enabled = false;
  2081. active_extruder = !active_extruder;
  2082. HOMEAXIS(X);
  2083. inactive_extruder_x_pos = current_position[X_AXIS];
  2084. active_extruder = tmp_extruder;
  2085. HOMEAXIS(X);
  2086. // reset state used by the different modes
  2087. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  2088. delayed_move_time = 0;
  2089. active_extruder_parked = true;
  2090. #else
  2091. HOMEAXIS(X);
  2092. #endif
  2093. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2094. if (marlin_debug_flags & DEBUG_LEVELING) {
  2095. print_xyz("> homeX", current_position);
  2096. }
  2097. #endif
  2098. }
  2099. #if DISABLED(HOME_Y_BEFORE_X)
  2100. // Home Y
  2101. if (home_all_axis || homeY) {
  2102. HOMEAXIS(Y);
  2103. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2104. if (marlin_debug_flags & DEBUG_LEVELING) {
  2105. print_xyz("> homeY", current_position);
  2106. }
  2107. #endif
  2108. }
  2109. #endif
  2110. // Home Z last if homing towards the bed
  2111. #if Z_HOME_DIR < 0
  2112. if (home_all_axis || homeZ) {
  2113. #if ENABLED(Z_SAFE_HOMING)
  2114. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2115. if (marlin_debug_flags & DEBUG_LEVELING) {
  2116. SERIAL_ECHOLNPGM("> Z_SAFE_HOMING >>>");
  2117. }
  2118. #endif
  2119. if (home_all_axis) {
  2120. // At this point we already have Z at MIN_Z_HEIGHT_FOR_HOMING height
  2121. // No need to move Z any more as this height should already be safe
  2122. // enough to reach Z_SAFE_HOMING XY positions.
  2123. // Just make sure the planner is in sync.
  2124. sync_plan_position();
  2125. //
  2126. // Set the Z probe (or just the nozzle) destination to the safe homing point
  2127. //
  2128. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - (X_PROBE_OFFSET_FROM_EXTRUDER));
  2129. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - (Y_PROBE_OFFSET_FROM_EXTRUDER));
  2130. destination[Z_AXIS] = current_position[Z_AXIS]; //z is already at the right height
  2131. feedrate = XY_TRAVEL_SPEED;
  2132. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2133. if (marlin_debug_flags & DEBUG_LEVELING) {
  2134. print_xyz("> Z_SAFE_HOMING > home_all_axis > current_position", current_position);
  2135. print_xyz("> Z_SAFE_HOMING > home_all_axis > destination", destination);
  2136. }
  2137. #endif
  2138. // Move in the XY plane
  2139. line_to_destination();
  2140. st_synchronize();
  2141. // Update the current positions for XY, Z is still at least at
  2142. // MIN_Z_HEIGHT_FOR_HOMING height, no changes there.
  2143. current_position[X_AXIS] = destination[X_AXIS];
  2144. current_position[Y_AXIS] = destination[Y_AXIS];
  2145. // Home the Z axis
  2146. HOMEAXIS(Z);
  2147. }
  2148. else if (homeZ) { // Don't need to Home Z twice
  2149. // Let's see if X and Y are homed
  2150. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) {
  2151. // Make sure the Z probe is within the physical limits
  2152. // NOTE: This doesn't necessarily ensure the Z probe is also within the bed!
  2153. float cpx = current_position[X_AXIS], cpy = current_position[Y_AXIS];
  2154. if ( cpx >= X_MIN_POS - (X_PROBE_OFFSET_FROM_EXTRUDER)
  2155. && cpx <= X_MAX_POS - (X_PROBE_OFFSET_FROM_EXTRUDER)
  2156. && cpy >= Y_MIN_POS - (Y_PROBE_OFFSET_FROM_EXTRUDER)
  2157. && cpy <= Y_MAX_POS - (Y_PROBE_OFFSET_FROM_EXTRUDER)) {
  2158. // Home the Z axis
  2159. HOMEAXIS(Z);
  2160. }
  2161. else {
  2162. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  2163. SERIAL_ECHO_START;
  2164. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  2165. }
  2166. }
  2167. else {
  2168. LCD_MESSAGEPGM(MSG_POSITION_UNKNOWN);
  2169. SERIAL_ECHO_START;
  2170. SERIAL_ECHOLNPGM(MSG_POSITION_UNKNOWN);
  2171. }
  2172. } // !home_all_axes && homeZ
  2173. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2174. if (marlin_debug_flags & DEBUG_LEVELING) {
  2175. SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING");
  2176. }
  2177. #endif
  2178. #else // !Z_SAFE_HOMING
  2179. HOMEAXIS(Z);
  2180. #endif // !Z_SAFE_HOMING
  2181. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2182. if (marlin_debug_flags & DEBUG_LEVELING) {
  2183. print_xyz("> (home_all_axis || homeZ) > final", current_position);
  2184. }
  2185. #endif
  2186. } // home_all_axis || homeZ
  2187. #endif // Z_HOME_DIR < 0
  2188. sync_plan_position();
  2189. #endif // else DELTA
  2190. #if ENABLED(SCARA)
  2191. sync_plan_position_delta();
  2192. #endif
  2193. #if ENABLED(ENDSTOPS_ONLY_FOR_HOMING)
  2194. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2195. if (marlin_debug_flags & DEBUG_LEVELING) {
  2196. SERIAL_ECHOLNPGM("ENDSTOPS_ONLY_FOR_HOMING enable_endstops(false)");
  2197. }
  2198. #endif
  2199. enable_endstops(false);
  2200. #endif
  2201. // For manual leveling move back to 0,0
  2202. #if ENABLED(MESH_BED_LEVELING)
  2203. if (mbl_was_active) {
  2204. current_position[X_AXIS] = mbl.get_x(0);
  2205. current_position[Y_AXIS] = mbl.get_y(0);
  2206. set_destination_to_current();
  2207. feedrate = homing_feedrate[X_AXIS];
  2208. line_to_destination();
  2209. st_synchronize();
  2210. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z;
  2211. sync_plan_position();
  2212. mbl.active = 1;
  2213. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2214. if (marlin_debug_flags & DEBUG_LEVELING) {
  2215. print_xyz("mbl_was_active > current_position", current_position);
  2216. }
  2217. #endif
  2218. }
  2219. #endif
  2220. feedrate = saved_feedrate;
  2221. feedrate_multiplier = saved_feedrate_multiplier;
  2222. refresh_cmd_timeout();
  2223. endstops_hit_on_purpose(); // clear endstop hit flags
  2224. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2225. if (marlin_debug_flags & DEBUG_LEVELING) {
  2226. SERIAL_ECHOLNPGM("<<< gcode_G28");
  2227. }
  2228. #endif
  2229. }
  2230. #if ENABLED(MESH_BED_LEVELING)
  2231. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  2232. /**
  2233. * G29: Mesh-based Z probe, probes a grid and produces a
  2234. * mesh to compensate for variable bed height
  2235. *
  2236. * Parameters With MESH_BED_LEVELING:
  2237. *
  2238. * S0 Produce a mesh report
  2239. * S1 Start probing mesh points
  2240. * S2 Probe the next mesh point
  2241. * S3 Xn Yn Zn.nn Manually modify a single point
  2242. *
  2243. * The S0 report the points as below
  2244. *
  2245. * +----> X-axis
  2246. * |
  2247. * |
  2248. * v Y-axis
  2249. *
  2250. */
  2251. inline void gcode_G29() {
  2252. static int probe_point = -1;
  2253. MeshLevelingState state = code_seen('S') ? (MeshLevelingState)code_value_short() : MeshReport;
  2254. if (state < 0 || state > 3) {
  2255. SERIAL_PROTOCOLLNPGM("S out of range (0-3).");
  2256. return;
  2257. }
  2258. int ix, iy;
  2259. float z;
  2260. switch (state) {
  2261. case MeshReport:
  2262. if (mbl.active) {
  2263. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2264. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2265. SERIAL_PROTOCOLCHAR(',');
  2266. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2267. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2268. SERIAL_PROTOCOL(MESH_HOME_SEARCH_Z);
  2269. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2270. for (int y = 0; y < MESH_NUM_Y_POINTS; y++) {
  2271. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2272. SERIAL_PROTOCOLPGM(" ");
  2273. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2274. }
  2275. SERIAL_EOL;
  2276. }
  2277. }
  2278. else
  2279. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  2280. break;
  2281. case MeshStart:
  2282. mbl.reset();
  2283. probe_point = 0;
  2284. enqueue_and_echo_commands_P(PSTR("G28\nG29 S2"));
  2285. break;
  2286. case MeshNext:
  2287. if (probe_point < 0) {
  2288. SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first.");
  2289. return;
  2290. }
  2291. if (probe_point == 0) {
  2292. // Set Z to a positive value before recording the first Z.
  2293. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z;
  2294. sync_plan_position();
  2295. }
  2296. else {
  2297. // For others, save the Z of the previous point, then raise Z again.
  2298. ix = (probe_point - 1) % (MESH_NUM_X_POINTS);
  2299. iy = (probe_point - 1) / (MESH_NUM_X_POINTS);
  2300. if (iy & 1) ix = (MESH_NUM_X_POINTS - 1) - ix; // zig-zag
  2301. mbl.set_z(ix, iy, current_position[Z_AXIS]);
  2302. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z;
  2303. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[X_AXIS] / 60, active_extruder);
  2304. st_synchronize();
  2305. }
  2306. // Is there another point to sample? Move there.
  2307. if (probe_point < (MESH_NUM_X_POINTS) * (MESH_NUM_Y_POINTS)) {
  2308. ix = probe_point % (MESH_NUM_X_POINTS);
  2309. iy = probe_point / (MESH_NUM_X_POINTS);
  2310. if (iy & 1) ix = (MESH_NUM_X_POINTS - 1) - ix; // zig-zag
  2311. current_position[X_AXIS] = mbl.get_x(ix);
  2312. current_position[Y_AXIS] = mbl.get_y(iy);
  2313. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[X_AXIS] / 60, active_extruder);
  2314. st_synchronize();
  2315. probe_point++;
  2316. }
  2317. else {
  2318. // After recording the last point, activate the mbl and home
  2319. SERIAL_PROTOCOLLNPGM("Mesh probing done.");
  2320. probe_point = -1;
  2321. mbl.active = 1;
  2322. enqueue_and_echo_commands_P(PSTR("G28"));
  2323. }
  2324. break;
  2325. case MeshSet:
  2326. if (code_seen('X')) {
  2327. ix = code_value_long() - 1;
  2328. if (ix < 0 || ix >= MESH_NUM_X_POINTS) {
  2329. SERIAL_PROTOCOLPGM("X out of range (1-" STRINGIFY(MESH_NUM_X_POINTS) ").\n");
  2330. return;
  2331. }
  2332. }
  2333. else {
  2334. SERIAL_PROTOCOLPGM("X not entered.\n");
  2335. return;
  2336. }
  2337. if (code_seen('Y')) {
  2338. iy = code_value_long() - 1;
  2339. if (iy < 0 || iy >= MESH_NUM_Y_POINTS) {
  2340. SERIAL_PROTOCOLPGM("Y out of range (1-" STRINGIFY(MESH_NUM_Y_POINTS) ").\n");
  2341. return;
  2342. }
  2343. }
  2344. else {
  2345. SERIAL_PROTOCOLPGM("Y not entered.\n");
  2346. return;
  2347. }
  2348. if (code_seen('Z')) {
  2349. z = code_value();
  2350. }
  2351. else {
  2352. SERIAL_PROTOCOLPGM("Z not entered.\n");
  2353. return;
  2354. }
  2355. mbl.z_values[iy][ix] = z;
  2356. } // switch(state)
  2357. }
  2358. #elif ENABLED(AUTO_BED_LEVELING_FEATURE)
  2359. void out_of_range_error(const char* p_edge) {
  2360. SERIAL_PROTOCOLPGM("?Probe ");
  2361. serialprintPGM(p_edge);
  2362. SERIAL_PROTOCOLLNPGM(" position out of range.");
  2363. }
  2364. /**
  2365. * G29: Detailed Z probe, probes the bed at 3 or more points.
  2366. * Will fail if the printer has not been homed with G28.
  2367. *
  2368. * Enhanced G29 Auto Bed Leveling Probe Routine
  2369. *
  2370. * Parameters With AUTO_BED_LEVELING_GRID:
  2371. *
  2372. * P Set the size of the grid that will be probed (P x P points).
  2373. * Not supported by non-linear delta printer bed leveling.
  2374. * Example: "G29 P4"
  2375. *
  2376. * S Set the XY travel speed between probe points (in mm/min)
  2377. *
  2378. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  2379. * or clean the rotation Matrix. Useful to check the topology
  2380. * after a first run of G29.
  2381. *
  2382. * V Set the verbose level (0-4). Example: "G29 V3"
  2383. *
  2384. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  2385. * This is useful for manual bed leveling and finding flaws in the bed (to
  2386. * assist with part placement).
  2387. * Not supported by non-linear delta printer bed leveling.
  2388. *
  2389. * F Set the Front limit of the probing grid
  2390. * B Set the Back limit of the probing grid
  2391. * L Set the Left limit of the probing grid
  2392. * R Set the Right limit of the probing grid
  2393. *
  2394. * Global Parameters:
  2395. *
  2396. * E/e By default G29 will engage the Z probe, test the bed, then disengage.
  2397. * Include "E" to engage/disengage the Z probe for each sample.
  2398. * There's no extra effect if you have a fixed Z probe.
  2399. * Usage: "G29 E" or "G29 e"
  2400. *
  2401. */
  2402. inline void gcode_G29() {
  2403. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2404. if (marlin_debug_flags & DEBUG_LEVELING) {
  2405. SERIAL_ECHOLNPGM("gcode_G29 >>>");
  2406. }
  2407. #endif
  2408. // Don't allow auto-leveling without homing first
  2409. if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) {
  2410. LCD_MESSAGEPGM(MSG_POSITION_UNKNOWN);
  2411. SERIAL_ECHO_START;
  2412. SERIAL_ECHOLNPGM(MSG_POSITION_UNKNOWN);
  2413. return;
  2414. }
  2415. int verbose_level = code_seen('V') ? code_value_short() : 1;
  2416. if (verbose_level < 0 || verbose_level > 4) {
  2417. SERIAL_ECHOLNPGM("?(V)erbose Level is implausible (0-4).");
  2418. return;
  2419. }
  2420. bool dryrun = code_seen('D'),
  2421. deploy_probe_for_each_reading = code_seen('E');
  2422. #if ENABLED(AUTO_BED_LEVELING_GRID)
  2423. #if DISABLED(DELTA)
  2424. bool do_topography_map = verbose_level > 2 || code_seen('T');
  2425. #endif
  2426. if (verbose_level > 0) {
  2427. SERIAL_PROTOCOLPGM("G29 Auto Bed Leveling\n");
  2428. if (dryrun) SERIAL_ECHOLNPGM("Running in DRY-RUN mode");
  2429. }
  2430. int auto_bed_leveling_grid_points = AUTO_BED_LEVELING_GRID_POINTS;
  2431. #if DISABLED(DELTA)
  2432. if (code_seen('P')) auto_bed_leveling_grid_points = code_value_short();
  2433. if (auto_bed_leveling_grid_points < 2) {
  2434. SERIAL_PROTOCOLPGM("?Number of probed (P)oints is implausible (2 minimum).\n");
  2435. return;
  2436. }
  2437. #endif
  2438. xy_travel_speed = code_seen('S') ? code_value_short() : XY_TRAVEL_SPEED;
  2439. int left_probe_bed_position = code_seen('L') ? code_value_short() : LEFT_PROBE_BED_POSITION,
  2440. right_probe_bed_position = code_seen('R') ? code_value_short() : RIGHT_PROBE_BED_POSITION,
  2441. front_probe_bed_position = code_seen('F') ? code_value_short() : FRONT_PROBE_BED_POSITION,
  2442. back_probe_bed_position = code_seen('B') ? code_value_short() : BACK_PROBE_BED_POSITION;
  2443. bool left_out_l = left_probe_bed_position < MIN_PROBE_X,
  2444. left_out = left_out_l || left_probe_bed_position > right_probe_bed_position - (MIN_PROBE_EDGE),
  2445. right_out_r = right_probe_bed_position > MAX_PROBE_X,
  2446. right_out = right_out_r || right_probe_bed_position < left_probe_bed_position + MIN_PROBE_EDGE,
  2447. front_out_f = front_probe_bed_position < MIN_PROBE_Y,
  2448. front_out = front_out_f || front_probe_bed_position > back_probe_bed_position - (MIN_PROBE_EDGE),
  2449. back_out_b = back_probe_bed_position > MAX_PROBE_Y,
  2450. back_out = back_out_b || back_probe_bed_position < front_probe_bed_position + MIN_PROBE_EDGE;
  2451. if (left_out || right_out || front_out || back_out) {
  2452. if (left_out) {
  2453. out_of_range_error(PSTR("(L)eft"));
  2454. left_probe_bed_position = left_out_l ? MIN_PROBE_X : right_probe_bed_position - (MIN_PROBE_EDGE);
  2455. }
  2456. if (right_out) {
  2457. out_of_range_error(PSTR("(R)ight"));
  2458. right_probe_bed_position = right_out_r ? MAX_PROBE_X : left_probe_bed_position + MIN_PROBE_EDGE;
  2459. }
  2460. if (front_out) {
  2461. out_of_range_error(PSTR("(F)ront"));
  2462. front_probe_bed_position = front_out_f ? MIN_PROBE_Y : back_probe_bed_position - (MIN_PROBE_EDGE);
  2463. }
  2464. if (back_out) {
  2465. out_of_range_error(PSTR("(B)ack"));
  2466. back_probe_bed_position = back_out_b ? MAX_PROBE_Y : front_probe_bed_position + MIN_PROBE_EDGE;
  2467. }
  2468. return;
  2469. }
  2470. #endif // AUTO_BED_LEVELING_GRID
  2471. #if ENABLED(Z_PROBE_SLED)
  2472. dock_sled(false); // engage (un-dock) the Z probe
  2473. #elif ENABLED(Z_PROBE_ALLEN_KEY) //|| SERVO_LEVELING
  2474. deploy_z_probe();
  2475. #endif
  2476. st_synchronize();
  2477. if (!dryrun) {
  2478. // make sure the bed_level_rotation_matrix is identity or the planner will get it wrong
  2479. plan_bed_level_matrix.set_to_identity();
  2480. #if ENABLED(DELTA)
  2481. reset_bed_level();
  2482. #else //!DELTA
  2483. //vector_3 corrected_position = plan_get_position_mm();
  2484. //corrected_position.debug("position before G29");
  2485. vector_3 uncorrected_position = plan_get_position();
  2486. //uncorrected_position.debug("position during G29");
  2487. current_position[X_AXIS] = uncorrected_position.x;
  2488. current_position[Y_AXIS] = uncorrected_position.y;
  2489. current_position[Z_AXIS] = uncorrected_position.z;
  2490. sync_plan_position();
  2491. #endif // !DELTA
  2492. }
  2493. setup_for_endstop_move();
  2494. feedrate = homing_feedrate[Z_AXIS];
  2495. #if ENABLED(AUTO_BED_LEVELING_GRID)
  2496. // probe at the points of a lattice grid
  2497. const int xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (auto_bed_leveling_grid_points - 1),
  2498. yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (auto_bed_leveling_grid_points - 1);
  2499. #if ENABLED(DELTA)
  2500. delta_grid_spacing[0] = xGridSpacing;
  2501. delta_grid_spacing[1] = yGridSpacing;
  2502. float z_offset = zprobe_zoffset;
  2503. if (code_seen(axis_codes[Z_AXIS])) z_offset += code_value();
  2504. #else // !DELTA
  2505. // solve the plane equation ax + by + d = z
  2506. // A is the matrix with rows [x y 1] for all the probed points
  2507. // B is the vector of the Z positions
  2508. // 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
  2509. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  2510. int abl2 = auto_bed_leveling_grid_points * auto_bed_leveling_grid_points;
  2511. double eqnAMatrix[abl2 * 3], // "A" matrix of the linear system of equations
  2512. eqnBVector[abl2], // "B" vector of Z points
  2513. mean = 0.0;
  2514. int8_t indexIntoAB[auto_bed_leveling_grid_points][auto_bed_leveling_grid_points];
  2515. #endif // !DELTA
  2516. int probePointCounter = 0;
  2517. bool zig = (auto_bed_leveling_grid_points & 1) ? true : false; //always end at [RIGHT_PROBE_BED_POSITION, BACK_PROBE_BED_POSITION]
  2518. for (int yCount = 0; yCount < auto_bed_leveling_grid_points; yCount++) {
  2519. double yProbe = front_probe_bed_position + yGridSpacing * yCount;
  2520. int xStart, xStop, xInc;
  2521. if (zig) {
  2522. xStart = 0;
  2523. xStop = auto_bed_leveling_grid_points;
  2524. xInc = 1;
  2525. }
  2526. else {
  2527. xStart = auto_bed_leveling_grid_points - 1;
  2528. xStop = -1;
  2529. xInc = -1;
  2530. }
  2531. zig = !zig;
  2532. for (int xCount = xStart; xCount != xStop; xCount += xInc) {
  2533. double xProbe = left_probe_bed_position + xGridSpacing * xCount;
  2534. // raise extruder
  2535. float measured_z,
  2536. z_before = probePointCounter ? Z_RAISE_BETWEEN_PROBINGS + current_position[Z_AXIS] : Z_RAISE_BEFORE_PROBING;
  2537. if (probePointCounter) {
  2538. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2539. if (marlin_debug_flags & DEBUG_LEVELING) {
  2540. SERIAL_ECHOPAIR("z_before = (between) ", (float)(Z_RAISE_BETWEEN_PROBINGS + current_position[Z_AXIS]));
  2541. SERIAL_EOL;
  2542. }
  2543. #endif
  2544. }
  2545. else {
  2546. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2547. if (marlin_debug_flags & DEBUG_LEVELING) {
  2548. SERIAL_ECHOPAIR("z_before = (before) ", (float)Z_RAISE_BEFORE_PROBING);
  2549. SERIAL_EOL;
  2550. }
  2551. #endif
  2552. }
  2553. #if ENABLED(DELTA)
  2554. // Avoid probing the corners (outside the round or hexagon print surface) on a delta printer.
  2555. float distance_from_center = sqrt(xProbe * xProbe + yProbe * yProbe);
  2556. if (distance_from_center > DELTA_PROBABLE_RADIUS) continue;
  2557. #endif //DELTA
  2558. ProbeAction act;
  2559. if (deploy_probe_for_each_reading) // G29 E - Stow between probes
  2560. act = ProbeDeployAndStow;
  2561. else if (yCount == 0 && xCount == xStart)
  2562. act = ProbeDeploy;
  2563. else if (yCount == auto_bed_leveling_grid_points - 1 && xCount == xStop - xInc)
  2564. act = ProbeStow;
  2565. else
  2566. act = ProbeStay;
  2567. measured_z = probe_pt(xProbe, yProbe, z_before, act, verbose_level);
  2568. #if DISABLED(DELTA)
  2569. mean += measured_z;
  2570. eqnBVector[probePointCounter] = measured_z;
  2571. eqnAMatrix[probePointCounter + 0 * abl2] = xProbe;
  2572. eqnAMatrix[probePointCounter + 1 * abl2] = yProbe;
  2573. eqnAMatrix[probePointCounter + 2 * abl2] = 1;
  2574. indexIntoAB[xCount][yCount] = probePointCounter;
  2575. #else
  2576. bed_level[xCount][yCount] = measured_z + z_offset;
  2577. #endif
  2578. probePointCounter++;
  2579. idle();
  2580. } //xProbe
  2581. } //yProbe
  2582. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2583. if (marlin_debug_flags & DEBUG_LEVELING) {
  2584. print_xyz("> probing complete > current_position", current_position);
  2585. }
  2586. #endif
  2587. clean_up_after_endstop_move();
  2588. #if ENABLED(DELTA)
  2589. if (!dryrun) extrapolate_unprobed_bed_level();
  2590. print_bed_level();
  2591. #else // !DELTA
  2592. // solve lsq problem
  2593. double plane_equation_coefficients[3];
  2594. qr_solve(plane_equation_coefficients, abl2, 3, eqnAMatrix, eqnBVector);
  2595. mean /= abl2;
  2596. if (verbose_level) {
  2597. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  2598. SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8);
  2599. SERIAL_PROTOCOLPGM(" b: ");
  2600. SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8);
  2601. SERIAL_PROTOCOLPGM(" d: ");
  2602. SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8);
  2603. SERIAL_EOL;
  2604. if (verbose_level > 2) {
  2605. SERIAL_PROTOCOLPGM("Mean of sampled points: ");
  2606. SERIAL_PROTOCOL_F(mean, 8);
  2607. SERIAL_EOL;
  2608. }
  2609. }
  2610. if (!dryrun) set_bed_level_equation_lsq(plane_equation_coefficients);
  2611. // Show the Topography map if enabled
  2612. if (do_topography_map) {
  2613. SERIAL_PROTOCOLPGM(" \nBed Height Topography: \n");
  2614. SERIAL_PROTOCOLPGM(" +--- BACK --+\n");
  2615. SERIAL_PROTOCOLPGM(" | |\n");
  2616. SERIAL_PROTOCOLPGM(" L | (+) | R\n");
  2617. SERIAL_PROTOCOLPGM(" E | | I\n");
  2618. SERIAL_PROTOCOLPGM(" F | (-) N (+) | G\n");
  2619. SERIAL_PROTOCOLPGM(" T | | H\n");
  2620. SERIAL_PROTOCOLPGM(" | (-) | T\n");
  2621. SERIAL_PROTOCOLPGM(" | |\n");
  2622. SERIAL_PROTOCOLPGM(" O-- FRONT --+\n");
  2623. SERIAL_PROTOCOLPGM(" (0,0)\n");
  2624. float min_diff = 999;
  2625. for (int yy = auto_bed_leveling_grid_points - 1; yy >= 0; yy--) {
  2626. for (int xx = 0; xx < auto_bed_leveling_grid_points; xx++) {
  2627. int ind = indexIntoAB[xx][yy];
  2628. float diff = eqnBVector[ind] - mean;
  2629. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  2630. y_tmp = eqnAMatrix[ind + 1 * abl2],
  2631. z_tmp = 0;
  2632. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp);
  2633. NOMORE(min_diff, eqnBVector[ind] - z_tmp);
  2634. if (diff >= 0.0)
  2635. SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment
  2636. else
  2637. SERIAL_PROTOCOLCHAR(' ');
  2638. SERIAL_PROTOCOL_F(diff, 5);
  2639. } // xx
  2640. SERIAL_EOL;
  2641. } // yy
  2642. SERIAL_EOL;
  2643. if (verbose_level > 3) {
  2644. SERIAL_PROTOCOLPGM(" \nCorrected Bed Height vs. Bed Topology: \n");
  2645. for (int yy = auto_bed_leveling_grid_points - 1; yy >= 0; yy--) {
  2646. for (int xx = 0; xx < auto_bed_leveling_grid_points; xx++) {
  2647. int ind = indexIntoAB[xx][yy];
  2648. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  2649. y_tmp = eqnAMatrix[ind + 1 * abl2],
  2650. z_tmp = 0;
  2651. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp);
  2652. float diff = eqnBVector[ind] - z_tmp - min_diff;
  2653. if (diff >= 0.0)
  2654. SERIAL_PROTOCOLPGM(" +");
  2655. // Include + for column alignment
  2656. else
  2657. SERIAL_PROTOCOLCHAR(' ');
  2658. SERIAL_PROTOCOL_F(diff, 5);
  2659. } // xx
  2660. SERIAL_EOL;
  2661. } // yy
  2662. SERIAL_EOL;
  2663. }
  2664. } //do_topography_map
  2665. #endif //!DELTA
  2666. #else // !AUTO_BED_LEVELING_GRID
  2667. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2668. if (marlin_debug_flags & DEBUG_LEVELING) {
  2669. SERIAL_ECHOLNPGM("> 3-point Leveling");
  2670. }
  2671. #endif
  2672. // Actions for each probe
  2673. ProbeAction p1, p2, p3;
  2674. if (deploy_probe_for_each_reading)
  2675. p1 = p2 = p3 = ProbeDeployAndStow;
  2676. else
  2677. p1 = ProbeDeploy, p2 = ProbeStay, p3 = ProbeStow;
  2678. // Probe at 3 arbitrary points
  2679. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING, p1, verbose_level),
  2680. z_at_pt_2 = probe_pt(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS, p2, verbose_level),
  2681. z_at_pt_3 = probe_pt(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS, p3, verbose_level);
  2682. clean_up_after_endstop_move();
  2683. if (!dryrun) set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  2684. #endif // !AUTO_BED_LEVELING_GRID
  2685. #if ENABLED(DELTA)
  2686. // Allen Key Probe for Delta
  2687. #if ENABLED(Z_PROBE_ALLEN_KEY)
  2688. stow_z_probe();
  2689. #elif Z_RAISE_AFTER_PROBING > 0
  2690. raise_z_after_probing();
  2691. #endif
  2692. #else // !DELTA
  2693. if (verbose_level > 0)
  2694. plan_bed_level_matrix.debug(" \n\nBed Level Correction Matrix:");
  2695. if (!dryrun) {
  2696. // Correct the Z height difference from Z probe position and nozzle tip position.
  2697. // The Z height on homing is measured by Z probe, but the Z probe is quite far from the nozzle.
  2698. // When the bed is uneven, this height must be corrected.
  2699. float x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER,
  2700. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER,
  2701. z_tmp = current_position[Z_AXIS],
  2702. real_z = st_get_axis_position_mm(Z_AXIS); //get the real Z (since plan_get_position is now correcting the plane)
  2703. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2704. if (marlin_debug_flags & DEBUG_LEVELING) {
  2705. SERIAL_ECHOPAIR("> BEFORE apply_rotation_xyz > z_tmp = ", z_tmp);
  2706. SERIAL_EOL;
  2707. SERIAL_ECHOPAIR("> BEFORE apply_rotation_xyz > real_z = ", real_z);
  2708. SERIAL_EOL;
  2709. }
  2710. #endif
  2711. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); // Apply the correction sending the Z probe offset
  2712. // Get the current Z position and send it to the planner.
  2713. //
  2714. // >> (z_tmp - real_z) : The rotated current Z minus the uncorrected Z (most recent plan_set_position/sync_plan_position)
  2715. //
  2716. // >> zprobe_zoffset : Z distance from nozzle to Z probe (set by default, M851, EEPROM, or Menu)
  2717. //
  2718. // >> Z_RAISE_AFTER_PROBING : The distance the Z probe will have lifted after the last probe
  2719. //
  2720. // >> Should home_offset[Z_AXIS] be included?
  2721. //
  2722. // Discussion: home_offset[Z_AXIS] was applied in G28 to set the starting Z.
  2723. // If Z is not tweaked in G29 -and- the Z probe in G29 is not actually "homing" Z...
  2724. // then perhaps it should not be included here. The purpose of home_offset[] is to
  2725. // adjust for inaccurate endstops, not for reasonably accurate probes. If it were
  2726. // added here, it could be seen as a compensating factor for the Z probe.
  2727. //
  2728. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2729. if (marlin_debug_flags & DEBUG_LEVELING) {
  2730. SERIAL_ECHOPAIR("> AFTER apply_rotation_xyz > z_tmp = ", z_tmp);
  2731. SERIAL_EOL;
  2732. }
  2733. #endif
  2734. current_position[Z_AXIS] = -zprobe_zoffset + (z_tmp - real_z)
  2735. #if HAS_SERVO_ENDSTOPS || ENABLED(Z_PROBE_ALLEN_KEY) || ENABLED(Z_PROBE_SLED)
  2736. + Z_RAISE_AFTER_PROBING
  2737. #endif
  2738. ;
  2739. // current_position[Z_AXIS] += home_offset[Z_AXIS]; // The Z probe determines Z=0, not "Z home"
  2740. sync_plan_position();
  2741. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2742. if (marlin_debug_flags & DEBUG_LEVELING) {
  2743. print_xyz("> corrected Z in G29", current_position);
  2744. }
  2745. #endif
  2746. }
  2747. // Sled assembly for Cartesian bots
  2748. #if ENABLED(Z_PROBE_SLED)
  2749. dock_sled(true); // dock the sled
  2750. #elif Z_RAISE_AFTER_PROBING > 0
  2751. // Raise Z axis for non-delta and non servo based probes
  2752. #if !defined(HAS_SERVO_ENDSTOPS) && DISABLED(Z_PROBE_ALLEN_KEY) && DISABLED(Z_PROBE_SLED)
  2753. raise_z_after_probing();
  2754. #endif
  2755. #endif
  2756. #endif // !DELTA
  2757. #ifdef Z_PROBE_END_SCRIPT
  2758. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2759. if (marlin_debug_flags & DEBUG_LEVELING) {
  2760. SERIAL_ECHO("Z Probe End Script: ");
  2761. SERIAL_ECHOLNPGM(Z_PROBE_END_SCRIPT);
  2762. }
  2763. #endif
  2764. enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT));
  2765. st_synchronize();
  2766. #endif
  2767. KEEPALIVE_STATE(IN_HANDLER);
  2768. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2769. if (marlin_debug_flags & DEBUG_LEVELING) {
  2770. SERIAL_ECHOLNPGM("<<< gcode_G29");
  2771. }
  2772. #endif
  2773. }
  2774. #if DISABLED(Z_PROBE_SLED)
  2775. /**
  2776. * G30: Do a single Z probe at the current XY
  2777. */
  2778. inline void gcode_G30() {
  2779. #if HAS_SERVO_ENDSTOPS
  2780. raise_z_for_servo();
  2781. #endif
  2782. deploy_z_probe(); // Engage Z Servo endstop if available
  2783. st_synchronize();
  2784. // TODO: clear the leveling matrix or the planner will be set incorrectly
  2785. setup_for_endstop_move();
  2786. feedrate = homing_feedrate[Z_AXIS];
  2787. run_z_probe();
  2788. SERIAL_PROTOCOLPGM("Bed X: ");
  2789. SERIAL_PROTOCOL(current_position[X_AXIS] + 0.0001);
  2790. SERIAL_PROTOCOLPGM(" Y: ");
  2791. SERIAL_PROTOCOL(current_position[Y_AXIS] + 0.0001);
  2792. SERIAL_PROTOCOLPGM(" Z: ");
  2793. SERIAL_PROTOCOL(current_position[Z_AXIS] + 0.0001);
  2794. SERIAL_EOL;
  2795. clean_up_after_endstop_move();
  2796. #if HAS_SERVO_ENDSTOPS
  2797. raise_z_for_servo();
  2798. #endif
  2799. stow_z_probe(false); // Retract Z Servo endstop if available
  2800. }
  2801. #endif //!Z_PROBE_SLED
  2802. #endif //AUTO_BED_LEVELING_FEATURE
  2803. /**
  2804. * G92: Set current position to given X Y Z E
  2805. */
  2806. inline void gcode_G92() {
  2807. if (!code_seen(axis_codes[E_AXIS]))
  2808. st_synchronize();
  2809. bool didXYZ = false;
  2810. for (int i = 0; i < NUM_AXIS; i++) {
  2811. if (code_seen(axis_codes[i])) {
  2812. float v = current_position[i] = code_value();
  2813. if (i == E_AXIS)
  2814. plan_set_e_position(v);
  2815. else
  2816. didXYZ = true;
  2817. }
  2818. }
  2819. if (didXYZ) {
  2820. #if ENABLED(DELTA) || ENABLED(SCARA)
  2821. sync_plan_position_delta();
  2822. #else
  2823. sync_plan_position();
  2824. #endif
  2825. }
  2826. }
  2827. #if ENABLED(ULTIPANEL)
  2828. /**
  2829. * M0: // M0 - Unconditional stop - Wait for user button press on LCD
  2830. * M1: // M1 - Conditional stop - Wait for user button press on LCD
  2831. */
  2832. inline void gcode_M0_M1() {
  2833. char* args = current_command_args;
  2834. millis_t codenum = 0;
  2835. bool hasP = false, hasS = false;
  2836. if (code_seen('P')) {
  2837. codenum = code_value_short(); // milliseconds to wait
  2838. hasP = codenum > 0;
  2839. }
  2840. if (code_seen('S')) {
  2841. codenum = code_value() * 1000; // seconds to wait
  2842. hasS = codenum > 0;
  2843. }
  2844. if (!hasP && !hasS && *args != '\0')
  2845. lcd_setstatus(args, true);
  2846. else {
  2847. LCD_MESSAGEPGM(MSG_USERWAIT);
  2848. #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0
  2849. dontExpireStatus();
  2850. #endif
  2851. }
  2852. lcd_ignore_click();
  2853. st_synchronize();
  2854. refresh_cmd_timeout();
  2855. if (codenum > 0) {
  2856. codenum += previous_cmd_ms; // wait until this time for a click
  2857. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2858. while (millis() < codenum && !lcd_clicked()) idle();
  2859. KEEPALIVE_STATE(IN_HANDLER);
  2860. lcd_ignore_click(false);
  2861. }
  2862. else {
  2863. if (!lcd_detected()) return;
  2864. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2865. while (!lcd_clicked()) idle();
  2866. KEEPALIVE_STATE(IN_HANDLER);
  2867. }
  2868. if (IS_SD_PRINTING)
  2869. LCD_MESSAGEPGM(MSG_RESUMING);
  2870. else
  2871. LCD_MESSAGEPGM(WELCOME_MSG);
  2872. }
  2873. #endif // ULTIPANEL
  2874. /**
  2875. * M17: Enable power on all stepper motors
  2876. */
  2877. inline void gcode_M17() {
  2878. LCD_MESSAGEPGM(MSG_NO_MOVE);
  2879. enable_all_steppers();
  2880. }
  2881. #if ENABLED(SDSUPPORT)
  2882. /**
  2883. * M20: List SD card to serial output
  2884. */
  2885. inline void gcode_M20() {
  2886. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  2887. card.ls();
  2888. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  2889. }
  2890. /**
  2891. * M21: Init SD Card
  2892. */
  2893. inline void gcode_M21() {
  2894. card.initsd();
  2895. }
  2896. /**
  2897. * M22: Release SD Card
  2898. */
  2899. inline void gcode_M22() {
  2900. card.release();
  2901. }
  2902. /**
  2903. * M23: Open a file
  2904. */
  2905. inline void gcode_M23() {
  2906. card.openFile(current_command_args, true);
  2907. }
  2908. /**
  2909. * M24: Start SD Print
  2910. */
  2911. inline void gcode_M24() {
  2912. card.startFileprint();
  2913. print_job_start_ms = millis();
  2914. }
  2915. /**
  2916. * M25: Pause SD Print
  2917. */
  2918. inline void gcode_M25() {
  2919. card.pauseSDPrint();
  2920. }
  2921. /**
  2922. * M26: Set SD Card file index
  2923. */
  2924. inline void gcode_M26() {
  2925. if (card.cardOK && code_seen('S'))
  2926. card.setIndex(code_value_short());
  2927. }
  2928. /**
  2929. * M27: Get SD Card status
  2930. */
  2931. inline void gcode_M27() {
  2932. card.getStatus();
  2933. }
  2934. /**
  2935. * M28: Start SD Write
  2936. */
  2937. inline void gcode_M28() {
  2938. card.openFile(current_command_args, false);
  2939. }
  2940. /**
  2941. * M29: Stop SD Write
  2942. * Processed in write to file routine above
  2943. */
  2944. inline void gcode_M29() {
  2945. // card.saving = false;
  2946. }
  2947. /**
  2948. * M30 <filename>: Delete SD Card file
  2949. */
  2950. inline void gcode_M30() {
  2951. if (card.cardOK) {
  2952. card.closefile();
  2953. card.removeFile(current_command_args);
  2954. }
  2955. }
  2956. #endif //SDSUPPORT
  2957. /**
  2958. * M31: Get the time since the start of SD Print (or last M109)
  2959. */
  2960. inline void gcode_M31() {
  2961. print_job_stop_ms = millis();
  2962. millis_t t = (print_job_stop_ms - print_job_start_ms) / 1000;
  2963. int min = t / 60, sec = t % 60;
  2964. char time[30];
  2965. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  2966. SERIAL_ECHO_START;
  2967. SERIAL_ECHOLN(time);
  2968. lcd_setstatus(time);
  2969. autotempShutdown();
  2970. }
  2971. #if ENABLED(SDSUPPORT)
  2972. /**
  2973. * M32: Select file and start SD Print
  2974. */
  2975. inline void gcode_M32() {
  2976. if (card.sdprinting)
  2977. st_synchronize();
  2978. char* namestartpos = strchr(current_command_args, '!'); // Find ! to indicate filename string start.
  2979. if (!namestartpos)
  2980. namestartpos = current_command_args; // Default name position, 4 letters after the M
  2981. else
  2982. namestartpos++; //to skip the '!'
  2983. bool call_procedure = code_seen('P') && (seen_pointer < namestartpos);
  2984. if (card.cardOK) {
  2985. card.openFile(namestartpos, true, !call_procedure);
  2986. if (code_seen('S') && seen_pointer < namestartpos) // "S" (must occur _before_ the filename!)
  2987. card.setIndex(code_value_short());
  2988. card.startFileprint();
  2989. if (!call_procedure)
  2990. print_job_start_ms = millis(); //procedure calls count as normal print time.
  2991. }
  2992. }
  2993. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  2994. /**
  2995. * M33: Get the long full path of a file or folder
  2996. *
  2997. * Parameters:
  2998. * <dospath> Case-insensitive DOS-style path to a file or folder
  2999. *
  3000. * Example:
  3001. * M33 miscel~1/armchair/armcha~1.gco
  3002. *
  3003. * Output:
  3004. * /Miscellaneous/Armchair/Armchair.gcode
  3005. */
  3006. inline void gcode_M33() {
  3007. card.printLongPath(current_command_args);
  3008. }
  3009. #endif
  3010. /**
  3011. * M928: Start SD Write
  3012. */
  3013. inline void gcode_M928() {
  3014. card.openLogFile(current_command_args);
  3015. }
  3016. #endif // SDSUPPORT
  3017. /**
  3018. * M42: Change pin status via GCode
  3019. *
  3020. * P<pin> Pin number (LED if omitted)
  3021. * S<byte> Pin status from 0 - 255
  3022. */
  3023. inline void gcode_M42() {
  3024. if (code_seen('S')) {
  3025. int pin_status = code_value_short();
  3026. if (pin_status < 0 || pin_status > 255) return;
  3027. int pin_number = code_seen('P') ? code_value_short() : LED_PIN;
  3028. if (pin_number < 0) return;
  3029. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++)
  3030. if (pin_number == sensitive_pins[i]) return;
  3031. pinMode(pin_number, OUTPUT);
  3032. digitalWrite(pin_number, pin_status);
  3033. analogWrite(pin_number, pin_status);
  3034. #if FAN_COUNT > 0
  3035. switch (pin_number) {
  3036. #if HAS_FAN0
  3037. case FAN_PIN: fanSpeeds[0] = pin_status; break;
  3038. #endif
  3039. #if HAS_FAN1
  3040. case FAN1_PIN: fanSpeeds[1] = pin_status; break;
  3041. #endif
  3042. #if HAS_FAN2
  3043. case FAN2_PIN: fanSpeeds[2] = pin_status; break;
  3044. #endif
  3045. }
  3046. #endif
  3047. } // code_seen('S')
  3048. }
  3049. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  3050. // This is redundant since the SanityCheck.h already checks for a valid Z_MIN_PROBE_PIN, but here for clarity.
  3051. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  3052. #if !HAS_Z_PROBE
  3053. #error You must define Z_MIN_PROBE_PIN to enable Z probe repeatability calculation.
  3054. #endif
  3055. #elif !HAS_Z_MIN
  3056. #error You must define Z_MIN_PIN to enable Z probe repeatability calculation.
  3057. #endif
  3058. /**
  3059. * M48: Z probe repeatability measurement function.
  3060. *
  3061. * Usage:
  3062. * M48 <P#> <X#> <Y#> <V#> <E> <L#>
  3063. * P = Number of sampled points (4-50, default 10)
  3064. * X = Sample X position
  3065. * Y = Sample Y position
  3066. * V = Verbose level (0-4, default=1)
  3067. * E = Engage Z probe for each reading
  3068. * L = Number of legs of movement before probe
  3069. *
  3070. * This function assumes the bed has been homed. Specifically, that a G28 command
  3071. * as been issued prior to invoking the M48 Z probe repeatability measurement function.
  3072. * Any information generated by a prior G29 Bed leveling command will be lost and need to be
  3073. * regenerated.
  3074. */
  3075. inline void gcode_M48() {
  3076. double sum = 0.0, mean = 0.0, sigma = 0.0, sample_set[50];
  3077. uint8_t verbose_level = 1, n_samples = 10, n_legs = 0;
  3078. if (code_seen('V')) {
  3079. verbose_level = code_value_short();
  3080. if (verbose_level < 0 || verbose_level > 4) {
  3081. SERIAL_PROTOCOLPGM("?Verbose Level not plausible (0-4).\n");
  3082. return;
  3083. }
  3084. }
  3085. if (verbose_level > 0)
  3086. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test\n");
  3087. if (code_seen('P')) {
  3088. n_samples = code_value_short();
  3089. if (n_samples < 4 || n_samples > 50) {
  3090. SERIAL_PROTOCOLPGM("?Sample size not plausible (4-50).\n");
  3091. return;
  3092. }
  3093. }
  3094. double X_current = st_get_axis_position_mm(X_AXIS),
  3095. Y_current = st_get_axis_position_mm(Y_AXIS),
  3096. Z_current = st_get_axis_position_mm(Z_AXIS),
  3097. E_current = st_get_axis_position_mm(E_AXIS),
  3098. X_probe_location = X_current, Y_probe_location = Y_current,
  3099. Z_start_location = Z_current + Z_RAISE_BEFORE_PROBING;
  3100. bool deploy_probe_for_each_reading = code_seen('E');
  3101. if (code_seen('X')) {
  3102. X_probe_location = code_value() - (X_PROBE_OFFSET_FROM_EXTRUDER);
  3103. if (X_probe_location < X_MIN_POS || X_probe_location > X_MAX_POS) {
  3104. out_of_range_error(PSTR("X"));
  3105. return;
  3106. }
  3107. }
  3108. if (code_seen('Y')) {
  3109. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  3110. if (Y_probe_location < Y_MIN_POS || Y_probe_location > Y_MAX_POS) {
  3111. out_of_range_error(PSTR("Y"));
  3112. return;
  3113. }
  3114. }
  3115. if (code_seen('L')) {
  3116. n_legs = code_value_short();
  3117. if (n_legs == 1) n_legs = 2;
  3118. if (n_legs < 0 || n_legs > 15) {
  3119. SERIAL_PROTOCOLPGM("?Number of legs in movement not plausible (0-15).\n");
  3120. return;
  3121. }
  3122. }
  3123. //
  3124. // Do all the preliminary setup work. First raise the Z probe.
  3125. //
  3126. st_synchronize();
  3127. plan_bed_level_matrix.set_to_identity();
  3128. plan_buffer_line(X_current, Y_current, Z_start_location, E_current, homing_feedrate[Z_AXIS] / 60, active_extruder);
  3129. st_synchronize();
  3130. //
  3131. // Now get everything to the specified probe point So we can safely do a probe to
  3132. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  3133. // use that as a starting point for each probe.
  3134. //
  3135. if (verbose_level > 2)
  3136. SERIAL_PROTOCOLPGM("Positioning the probe...\n");
  3137. plan_buffer_line(X_probe_location, Y_probe_location, Z_start_location,
  3138. E_current,
  3139. homing_feedrate[X_AXIS] / 60,
  3140. active_extruder);
  3141. st_synchronize();
  3142. current_position[X_AXIS] = X_current = st_get_axis_position_mm(X_AXIS);
  3143. current_position[Y_AXIS] = Y_current = st_get_axis_position_mm(Y_AXIS);
  3144. current_position[Z_AXIS] = Z_current = st_get_axis_position_mm(Z_AXIS);
  3145. current_position[E_AXIS] = E_current = st_get_axis_position_mm(E_AXIS);
  3146. //
  3147. // OK, do the initial probe to get us close to the bed.
  3148. // Then retrace the right amount and use that in subsequent probes
  3149. //
  3150. deploy_z_probe();
  3151. setup_for_endstop_move();
  3152. run_z_probe();
  3153. Z_current = current_position[Z_AXIS] = st_get_axis_position_mm(Z_AXIS);
  3154. Z_start_location = Z_current + Z_RAISE_BEFORE_PROBING;
  3155. plan_buffer_line(X_probe_location, Y_probe_location, Z_start_location,
  3156. E_current,
  3157. homing_feedrate[X_AXIS] / 60,
  3158. active_extruder);
  3159. st_synchronize();
  3160. Z_current = current_position[Z_AXIS] = st_get_axis_position_mm(Z_AXIS);
  3161. if (deploy_probe_for_each_reading) stow_z_probe();
  3162. for (uint8_t n = 0; n < n_samples; n++) {
  3163. // Make sure we are at the probe location
  3164. do_blocking_move_to(X_probe_location, Y_probe_location, Z_start_location); // this also updates current_position
  3165. if (n_legs) {
  3166. millis_t ms = millis();
  3167. double radius = ms % ((X_MAX_LENGTH) / 4), // limit how far out to go
  3168. theta = RADIANS(ms % 360L);
  3169. float dir = (ms & 0x0001) ? 1 : -1; // clockwise or counter clockwise
  3170. //SERIAL_ECHOPAIR("starting radius: ",radius);
  3171. //SERIAL_ECHOPAIR(" theta: ",theta);
  3172. //SERIAL_ECHOPAIR(" direction: ",dir);
  3173. //SERIAL_EOL;
  3174. for (uint8_t l = 0; l < n_legs - 1; l++) {
  3175. ms = millis();
  3176. theta += RADIANS(dir * (ms % 20L));
  3177. radius += (ms % 10L) - 5L;
  3178. if (radius < 0.0) radius = -radius;
  3179. X_current = X_probe_location + cos(theta) * radius;
  3180. X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
  3181. Y_current = Y_probe_location + sin(theta) * radius;
  3182. Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
  3183. if (verbose_level > 3) {
  3184. SERIAL_ECHOPAIR("x: ", X_current);
  3185. SERIAL_ECHOPAIR("y: ", Y_current);
  3186. SERIAL_EOL;
  3187. }
  3188. do_blocking_move_to(X_current, Y_current, Z_current); // this also updates current_position
  3189. } // n_legs loop
  3190. // Go back to the probe location
  3191. do_blocking_move_to(X_probe_location, Y_probe_location, Z_start_location); // this also updates current_position
  3192. } // n_legs
  3193. if (deploy_probe_for_each_reading) {
  3194. deploy_z_probe();
  3195. delay(1000);
  3196. }
  3197. setup_for_endstop_move();
  3198. run_z_probe();
  3199. sample_set[n] = current_position[Z_AXIS];
  3200. //
  3201. // Get the current mean for the data points we have so far
  3202. //
  3203. sum = 0.0;
  3204. for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
  3205. mean = sum / (n + 1);
  3206. //
  3207. // Now, use that mean to calculate the standard deviation for the
  3208. // data points we have so far
  3209. //
  3210. sum = 0.0;
  3211. for (uint8_t j = 0; j <= n; j++) {
  3212. float ss = sample_set[j] - mean;
  3213. sum += ss * ss;
  3214. }
  3215. sigma = sqrt(sum / (n + 1));
  3216. if (verbose_level > 1) {
  3217. SERIAL_PROTOCOL(n + 1);
  3218. SERIAL_PROTOCOLPGM(" of ");
  3219. SERIAL_PROTOCOL((int)n_samples);
  3220. SERIAL_PROTOCOLPGM(" z: ");
  3221. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  3222. if (verbose_level > 2) {
  3223. SERIAL_PROTOCOLPGM(" mean: ");
  3224. SERIAL_PROTOCOL_F(mean, 6);
  3225. SERIAL_PROTOCOLPGM(" sigma: ");
  3226. SERIAL_PROTOCOL_F(sigma, 6);
  3227. }
  3228. }
  3229. if (verbose_level > 0) SERIAL_EOL;
  3230. plan_buffer_line(X_probe_location, Y_probe_location, Z_start_location, current_position[E_AXIS], homing_feedrate[Z_AXIS] / 60, active_extruder);
  3231. st_synchronize();
  3232. // Stow between
  3233. if (deploy_probe_for_each_reading) {
  3234. stow_z_probe();
  3235. delay(1000);
  3236. }
  3237. }
  3238. // Stow after
  3239. if (!deploy_probe_for_each_reading) {
  3240. stow_z_probe();
  3241. delay(1000);
  3242. }
  3243. clean_up_after_endstop_move();
  3244. if (verbose_level > 0) {
  3245. SERIAL_PROTOCOLPGM("Mean: ");
  3246. SERIAL_PROTOCOL_F(mean, 6);
  3247. SERIAL_EOL;
  3248. }
  3249. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  3250. SERIAL_PROTOCOL_F(sigma, 6);
  3251. SERIAL_EOL; SERIAL_EOL;
  3252. }
  3253. #endif // AUTO_BED_LEVELING_FEATURE && Z_MIN_PROBE_REPEATABILITY_TEST
  3254. /**
  3255. * M104: Set hot end temperature
  3256. */
  3257. inline void gcode_M104() {
  3258. if (setTargetedHotend(104)) return;
  3259. if (marlin_debug_flags & DEBUG_DRYRUN) return;
  3260. if (code_seen('S')) {
  3261. float temp = code_value();
  3262. setTargetHotend(temp, target_extruder);
  3263. #if ENABLED(DUAL_X_CARRIAGE)
  3264. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  3265. setTargetHotend1(temp == 0.0 ? 0.0 : temp + duplicate_extruder_temp_offset);
  3266. #endif
  3267. }
  3268. }
  3269. #if HAS_TEMP_0 || HAS_TEMP_BED || ENABLED(HEATER_0_USES_MAX6675)
  3270. void print_heaterstates() {
  3271. #if HAS_TEMP_0 || ENABLED(HEATER_0_USES_MAX6675)
  3272. SERIAL_PROTOCOLPGM(" T:");
  3273. SERIAL_PROTOCOL_F(degHotend(target_extruder), 1);
  3274. SERIAL_PROTOCOLPGM(" /");
  3275. SERIAL_PROTOCOL_F(degTargetHotend(target_extruder), 1);
  3276. #endif
  3277. #if HAS_TEMP_BED
  3278. SERIAL_PROTOCOLPGM(" B:");
  3279. SERIAL_PROTOCOL_F(degBed(), 1);
  3280. SERIAL_PROTOCOLPGM(" /");
  3281. SERIAL_PROTOCOL_F(degTargetBed(), 1);
  3282. #endif
  3283. #if EXTRUDERS > 1
  3284. for (int8_t e = 0; e < EXTRUDERS; ++e) {
  3285. SERIAL_PROTOCOLPGM(" T");
  3286. SERIAL_PROTOCOL(e);
  3287. SERIAL_PROTOCOLCHAR(':');
  3288. SERIAL_PROTOCOL_F(degHotend(e), 1);
  3289. SERIAL_PROTOCOLPGM(" /");
  3290. SERIAL_PROTOCOL_F(degTargetHotend(e), 1);
  3291. }
  3292. #endif
  3293. #if HAS_TEMP_BED
  3294. SERIAL_PROTOCOLPGM(" B@:");
  3295. #ifdef BED_WATTS
  3296. SERIAL_PROTOCOL(((BED_WATTS) * getHeaterPower(-1)) / 127);
  3297. SERIAL_PROTOCOLCHAR('W');
  3298. #else
  3299. SERIAL_PROTOCOL(getHeaterPower(-1));
  3300. #endif
  3301. #endif
  3302. SERIAL_PROTOCOLPGM(" @:");
  3303. #ifdef EXTRUDER_WATTS
  3304. SERIAL_PROTOCOL(((EXTRUDER_WATTS) * getHeaterPower(target_extruder)) / 127);
  3305. SERIAL_PROTOCOLCHAR('W');
  3306. #else
  3307. SERIAL_PROTOCOL(getHeaterPower(target_extruder));
  3308. #endif
  3309. #if EXTRUDERS > 1
  3310. for (int8_t e = 0; e < EXTRUDERS; ++e) {
  3311. SERIAL_PROTOCOLPGM(" @");
  3312. SERIAL_PROTOCOL(e);
  3313. SERIAL_PROTOCOLCHAR(':');
  3314. #ifdef EXTRUDER_WATTS
  3315. SERIAL_PROTOCOL(((EXTRUDER_WATTS) * getHeaterPower(e)) / 127);
  3316. SERIAL_PROTOCOLCHAR('W');
  3317. #else
  3318. SERIAL_PROTOCOL(getHeaterPower(e));
  3319. #endif
  3320. }
  3321. #endif
  3322. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  3323. #if HAS_TEMP_BED
  3324. SERIAL_PROTOCOLPGM(" ADC B:");
  3325. SERIAL_PROTOCOL_F(degBed(), 1);
  3326. SERIAL_PROTOCOLPGM("C->");
  3327. SERIAL_PROTOCOL_F(rawBedTemp() / OVERSAMPLENR, 0);
  3328. #endif
  3329. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  3330. SERIAL_PROTOCOLPGM(" T");
  3331. SERIAL_PROTOCOL(cur_extruder);
  3332. SERIAL_PROTOCOLCHAR(':');
  3333. SERIAL_PROTOCOL_F(degHotend(cur_extruder), 1);
  3334. SERIAL_PROTOCOLPGM("C->");
  3335. SERIAL_PROTOCOL_F(rawHotendTemp(cur_extruder) / OVERSAMPLENR, 0);
  3336. }
  3337. #endif
  3338. }
  3339. #endif
  3340. /**
  3341. * M105: Read hot end and bed temperature
  3342. */
  3343. inline void gcode_M105() {
  3344. if (setTargetedHotend(105)) return;
  3345. #if HAS_TEMP_0 || HAS_TEMP_BED || ENABLED(HEATER_0_USES_MAX6675)
  3346. SERIAL_PROTOCOLPGM(MSG_OK);
  3347. print_heaterstates();
  3348. #else // !HAS_TEMP_0 && !HAS_TEMP_BED
  3349. SERIAL_ERROR_START;
  3350. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  3351. #endif
  3352. SERIAL_EOL;
  3353. }
  3354. #if FAN_COUNT > 0
  3355. /**
  3356. * M106: Set Fan Speed
  3357. *
  3358. * S<int> Speed between 0-255
  3359. * P<index> Fan index, if more than one fan
  3360. */
  3361. inline void gcode_M106() {
  3362. uint16_t s = code_seen('S') ? code_value_short() : 255,
  3363. p = code_seen('P') ? code_value_short() : 0;
  3364. NOMORE(s, 255);
  3365. if (p < FAN_COUNT) fanSpeeds[p] = s;
  3366. }
  3367. /**
  3368. * M107: Fan Off
  3369. */
  3370. inline void gcode_M107() {
  3371. uint16_t p = code_seen('P') ? code_value_short() : 0;
  3372. if (p < FAN_COUNT) fanSpeeds[p] = 0;
  3373. }
  3374. #endif // FAN_COUNT > 0
  3375. /**
  3376. * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating.
  3377. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling.
  3378. */
  3379. inline void gcode_M109() {
  3380. bool no_wait_for_cooling = true;
  3381. if (setTargetedHotend(109)) return;
  3382. if (marlin_debug_flags & DEBUG_DRYRUN) return;
  3383. LCD_MESSAGEPGM(MSG_HEATING);
  3384. no_wait_for_cooling = code_seen('S');
  3385. if (no_wait_for_cooling || code_seen('R')) {
  3386. float temp = code_value();
  3387. setTargetHotend(temp, target_extruder);
  3388. #if ENABLED(DUAL_X_CARRIAGE)
  3389. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  3390. setTargetHotend1(temp == 0.0 ? 0.0 : temp + duplicate_extruder_temp_offset);
  3391. #endif
  3392. }
  3393. #if ENABLED(AUTOTEMP)
  3394. autotemp_enabled = code_seen('F');
  3395. if (autotemp_enabled) autotemp_factor = code_value();
  3396. if (code_seen('S')) autotemp_min = code_value();
  3397. if (code_seen('B')) autotemp_max = code_value();
  3398. #endif
  3399. // Exit if the temperature is above target and not waiting for cooling
  3400. if (no_wait_for_cooling && !isHeatingHotend(target_extruder)) return;
  3401. // Prevents a wait-forever situation if R is misused i.e. M109 R0
  3402. // Try to calculate a ballpark safe margin by halving EXTRUDE_MINTEMP
  3403. if (degTargetHotend(target_extruder) < (EXTRUDE_MINTEMP/2)) return;
  3404. #ifdef TEMP_RESIDENCY_TIME
  3405. long residency_start_ms = -1;
  3406. // Loop until the temperature has stabilized
  3407. #define TEMP_CONDITIONS (residency_start_ms < 0 || now < residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL)
  3408. #else
  3409. // Loop until the temperature is very close target
  3410. #define TEMP_CONDITIONS (fabs(degHotend(target_extruder) - degTargetHotend(target_extruder)) < 0.75f)
  3411. #endif //TEMP_RESIDENCY_TIME
  3412. cancel_heatup = false;
  3413. millis_t now = millis(), next_temp_ms = now + 1000UL;
  3414. while (!cancel_heatup && TEMP_CONDITIONS) {
  3415. now = millis();
  3416. if (now > next_temp_ms) { //Print temp & remaining time every 1s while waiting
  3417. next_temp_ms = now + 1000UL;
  3418. #if HAS_TEMP_0 || HAS_TEMP_BED || ENABLED(HEATER_0_USES_MAX6675)
  3419. print_heaterstates();
  3420. #endif
  3421. #ifdef TEMP_RESIDENCY_TIME
  3422. SERIAL_PROTOCOLPGM(" W:");
  3423. if (residency_start_ms >= 0) {
  3424. long rem = (((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL;
  3425. SERIAL_PROTOCOLLN(rem);
  3426. }
  3427. else {
  3428. SERIAL_PROTOCOLLNPGM("?");
  3429. }
  3430. #else
  3431. SERIAL_EOL;
  3432. #endif
  3433. }
  3434. idle();
  3435. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  3436. #ifdef TEMP_RESIDENCY_TIME
  3437. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  3438. // Restart the timer whenever the temperature falls outside the hysteresis.
  3439. if (labs(degHotend(target_extruder) - degTargetHotend(target_extruder)) > ((residency_start_ms < 0) ? TEMP_WINDOW : TEMP_HYSTERESIS))
  3440. residency_start_ms = millis();
  3441. #endif //TEMP_RESIDENCY_TIME
  3442. } // while(!cancel_heatup && TEMP_CONDITIONS)
  3443. LCD_MESSAGEPGM(MSG_HEATING_COMPLETE);
  3444. print_job_start_ms = previous_cmd_ms;
  3445. }
  3446. #if HAS_TEMP_BED
  3447. /**
  3448. * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3449. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3450. */
  3451. inline void gcode_M190() {
  3452. if (marlin_debug_flags & DEBUG_DRYRUN) return;
  3453. LCD_MESSAGEPGM(MSG_BED_HEATING);
  3454. bool no_wait_for_cooling = code_seen('S');
  3455. if (no_wait_for_cooling || code_seen('R'))
  3456. setTargetBed(code_value());
  3457. // Exit if the temperature is above target and not waiting for cooling
  3458. if (no_wait_for_cooling && !isHeatingBed()) return;
  3459. cancel_heatup = false;
  3460. millis_t now = millis(), next_temp_ms = now + 1000UL;
  3461. while (!cancel_heatup && degTargetBed() != degBed()) {
  3462. millis_t now = millis();
  3463. if (now > next_temp_ms) { //Print Temp Reading every 1 second while heating up.
  3464. next_temp_ms = now + 1000UL;
  3465. print_heaterstates();
  3466. SERIAL_EOL;
  3467. }
  3468. idle();
  3469. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  3470. }
  3471. LCD_MESSAGEPGM(MSG_BED_DONE);
  3472. }
  3473. #endif // HAS_TEMP_BED
  3474. /**
  3475. * M110: Set Current Line Number
  3476. */
  3477. inline void gcode_M110() {
  3478. if (code_seen('N')) gcode_N = code_value_long();
  3479. }
  3480. /**
  3481. * M111: Set the debug level
  3482. */
  3483. inline void gcode_M111() {
  3484. marlin_debug_flags = code_seen('S') ? code_value_short() : DEBUG_INFO | DEBUG_COMMUNICATION;
  3485. if (marlin_debug_flags & DEBUG_ECHO) {
  3486. SERIAL_ECHO_START;
  3487. SERIAL_ECHOLNPGM(MSG_DEBUG_ECHO);
  3488. }
  3489. // FOR MOMENT NOT ACTIVE
  3490. //if (marlin_debug_flags & DEBUG_INFO) SERIAL_ECHOLNPGM(MSG_DEBUG_INFO);
  3491. //if (marlin_debug_flags & DEBUG_ERRORS) SERIAL_ECHOLNPGM(MSG_DEBUG_ERRORS);
  3492. if (marlin_debug_flags & DEBUG_DRYRUN) {
  3493. SERIAL_ECHO_START;
  3494. SERIAL_ECHOLNPGM(MSG_DEBUG_DRYRUN);
  3495. disable_all_heaters();
  3496. }
  3497. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3498. if (marlin_debug_flags & DEBUG_LEVELING) {
  3499. SERIAL_ECHO_START;
  3500. SERIAL_ECHOLNPGM(MSG_DEBUG_LEVELING);
  3501. }
  3502. #endif
  3503. }
  3504. /**
  3505. * M112: Emergency Stop
  3506. */
  3507. inline void gcode_M112() { kill(PSTR(MSG_KILLED)); }
  3508. #if ENABLED(BARICUDA)
  3509. #if HAS_HEATER_1
  3510. /**
  3511. * M126: Heater 1 valve open
  3512. */
  3513. inline void gcode_M126() { ValvePressure = code_seen('S') ? constrain(code_value(), 0, 255) : 255; }
  3514. /**
  3515. * M127: Heater 1 valve close
  3516. */
  3517. inline void gcode_M127() { ValvePressure = 0; }
  3518. #endif
  3519. #if HAS_HEATER_2
  3520. /**
  3521. * M128: Heater 2 valve open
  3522. */
  3523. inline void gcode_M128() { EtoPPressure = code_seen('S') ? constrain(code_value(), 0, 255) : 255; }
  3524. /**
  3525. * M129: Heater 2 valve close
  3526. */
  3527. inline void gcode_M129() { EtoPPressure = 0; }
  3528. #endif
  3529. #endif //BARICUDA
  3530. /**
  3531. * M140: Set bed temperature
  3532. */
  3533. inline void gcode_M140() {
  3534. if (marlin_debug_flags & DEBUG_DRYRUN) return;
  3535. if (code_seen('S')) setTargetBed(code_value());
  3536. }
  3537. #if ENABLED(ULTIPANEL)
  3538. /**
  3539. * M145: Set the heatup state for a material in the LCD menu
  3540. * S<material> (0=PLA, 1=ABS)
  3541. * H<hotend temp>
  3542. * B<bed temp>
  3543. * F<fan speed>
  3544. */
  3545. inline void gcode_M145() {
  3546. int8_t material = code_seen('S') ? code_value_short() : 0;
  3547. if (material < 0 || material > 1) {
  3548. SERIAL_ERROR_START;
  3549. SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX);
  3550. }
  3551. else {
  3552. int v;
  3553. switch (material) {
  3554. case 0:
  3555. if (code_seen('H')) {
  3556. v = code_value_short();
  3557. plaPreheatHotendTemp = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  3558. }
  3559. if (code_seen('F')) {
  3560. v = code_value_short();
  3561. plaPreheatFanSpeed = constrain(v, 0, 255);
  3562. }
  3563. #if TEMP_SENSOR_BED != 0
  3564. if (code_seen('B')) {
  3565. v = code_value_short();
  3566. plaPreheatHPBTemp = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  3567. }
  3568. #endif
  3569. break;
  3570. case 1:
  3571. if (code_seen('H')) {
  3572. v = code_value_short();
  3573. absPreheatHotendTemp = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  3574. }
  3575. if (code_seen('F')) {
  3576. v = code_value_short();
  3577. absPreheatFanSpeed = constrain(v, 0, 255);
  3578. }
  3579. #if TEMP_SENSOR_BED != 0
  3580. if (code_seen('B')) {
  3581. v = code_value_short();
  3582. absPreheatHPBTemp = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  3583. }
  3584. #endif
  3585. break;
  3586. }
  3587. }
  3588. }
  3589. #endif
  3590. #if HAS_POWER_SWITCH
  3591. /**
  3592. * M80: Turn on Power Supply
  3593. */
  3594. inline void gcode_M80() {
  3595. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); //GND
  3596. // If you have a switch on suicide pin, this is useful
  3597. // if you want to start another print with suicide feature after
  3598. // a print without suicide...
  3599. #if HAS_SUICIDE
  3600. OUT_WRITE(SUICIDE_PIN, HIGH);
  3601. #endif
  3602. #if ENABLED(ULTIPANEL)
  3603. powersupply = true;
  3604. LCD_MESSAGEPGM(WELCOME_MSG);
  3605. lcd_update();
  3606. #endif
  3607. }
  3608. #endif // HAS_POWER_SWITCH
  3609. /**
  3610. * M81: Turn off Power, including Power Supply, if there is one.
  3611. *
  3612. * This code should ALWAYS be available for EMERGENCY SHUTDOWN!
  3613. */
  3614. inline void gcode_M81() {
  3615. disable_all_heaters();
  3616. finishAndDisableSteppers();
  3617. #if FAN_COUNT > 0
  3618. #if FAN_COUNT > 1
  3619. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  3620. #else
  3621. fanSpeeds[0] = 0;
  3622. #endif
  3623. #endif
  3624. delay(1000); // Wait 1 second before switching off
  3625. #if HAS_SUICIDE
  3626. st_synchronize();
  3627. suicide();
  3628. #elif HAS_POWER_SWITCH
  3629. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  3630. #endif
  3631. #if ENABLED(ULTIPANEL)
  3632. #if HAS_POWER_SWITCH
  3633. powersupply = false;
  3634. #endif
  3635. LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF ".");
  3636. lcd_update();
  3637. #endif
  3638. }
  3639. /**
  3640. * M82: Set E codes absolute (default)
  3641. */
  3642. inline void gcode_M82() { axis_relative_modes[E_AXIS] = false; }
  3643. /**
  3644. * M83: Set E codes relative while in Absolute Coordinates (G90) mode
  3645. */
  3646. inline void gcode_M83() { axis_relative_modes[E_AXIS] = true; }
  3647. /**
  3648. * M18, M84: Disable all stepper motors
  3649. */
  3650. inline void gcode_M18_M84() {
  3651. if (code_seen('S')) {
  3652. stepper_inactive_time = code_value() * 1000;
  3653. }
  3654. else {
  3655. 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])));
  3656. if (all_axis) {
  3657. finishAndDisableSteppers();
  3658. }
  3659. else {
  3660. st_synchronize();
  3661. if (code_seen('X')) disable_x();
  3662. if (code_seen('Y')) disable_y();
  3663. if (code_seen('Z')) disable_z();
  3664. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  3665. if (code_seen('E')) {
  3666. disable_e0();
  3667. disable_e1();
  3668. disable_e2();
  3669. disable_e3();
  3670. }
  3671. #endif
  3672. }
  3673. }
  3674. }
  3675. /**
  3676. * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3677. */
  3678. inline void gcode_M85() {
  3679. if (code_seen('S')) max_inactive_time = code_value() * 1000;
  3680. }
  3681. /**
  3682. * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E.
  3683. * (Follows the same syntax as G92)
  3684. */
  3685. inline void gcode_M92() {
  3686. for (int8_t i = 0; i < NUM_AXIS; i++) {
  3687. if (code_seen(axis_codes[i])) {
  3688. if (i == E_AXIS) {
  3689. float value = code_value();
  3690. if (value < 20.0) {
  3691. float factor = axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  3692. max_e_jerk *= factor;
  3693. max_feedrate[i] *= factor;
  3694. axis_steps_per_sqr_second[i] *= factor;
  3695. }
  3696. axis_steps_per_unit[i] = value;
  3697. }
  3698. else {
  3699. axis_steps_per_unit[i] = code_value();
  3700. }
  3701. }
  3702. }
  3703. }
  3704. /**
  3705. * M114: Output current position to serial port
  3706. */
  3707. inline void gcode_M114() {
  3708. SERIAL_PROTOCOLPGM("X:");
  3709. SERIAL_PROTOCOL(current_position[X_AXIS]);
  3710. SERIAL_PROTOCOLPGM(" Y:");
  3711. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3712. SERIAL_PROTOCOLPGM(" Z:");
  3713. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3714. SERIAL_PROTOCOLPGM(" E:");
  3715. SERIAL_PROTOCOL(current_position[E_AXIS]);
  3716. CRITICAL_SECTION_START;
  3717. extern volatile long count_position[NUM_AXIS];
  3718. long xpos = count_position[X_AXIS],
  3719. ypos = count_position[Y_AXIS],
  3720. zpos = count_position[Z_AXIS];
  3721. CRITICAL_SECTION_END;
  3722. #if ENABLED(COREXY) || ENABLED(COREXZ)
  3723. SERIAL_PROTOCOLPGM(MSG_COUNT_A);
  3724. #else
  3725. SERIAL_PROTOCOLPGM(MSG_COUNT_X);
  3726. #endif
  3727. SERIAL_PROTOCOL(xpos);
  3728. #if ENABLED(COREXY)
  3729. SERIAL_PROTOCOLPGM(" B:");
  3730. #else
  3731. SERIAL_PROTOCOLPGM(" Y:");
  3732. #endif
  3733. SERIAL_PROTOCOL(ypos);
  3734. #if ENABLED(COREXZ)
  3735. SERIAL_PROTOCOLPGM(" C:");
  3736. #else
  3737. SERIAL_PROTOCOLPGM(" Z:");
  3738. #endif
  3739. SERIAL_PROTOCOL(zpos);
  3740. SERIAL_EOL;
  3741. #if ENABLED(SCARA)
  3742. SERIAL_PROTOCOLPGM("SCARA Theta:");
  3743. SERIAL_PROTOCOL(delta[X_AXIS]);
  3744. SERIAL_PROTOCOLPGM(" Psi+Theta:");
  3745. SERIAL_PROTOCOL(delta[Y_AXIS]);
  3746. SERIAL_EOL;
  3747. SERIAL_PROTOCOLPGM("SCARA Cal - Theta:");
  3748. SERIAL_PROTOCOL(delta[X_AXIS] + home_offset[X_AXIS]);
  3749. SERIAL_PROTOCOLPGM(" Psi+Theta (90):");
  3750. SERIAL_PROTOCOL(delta[Y_AXIS] - delta[X_AXIS] - 90 + home_offset[Y_AXIS]);
  3751. SERIAL_EOL;
  3752. SERIAL_PROTOCOLPGM("SCARA step Cal - Theta:");
  3753. SERIAL_PROTOCOL(delta[X_AXIS] / 90 * axis_steps_per_unit[X_AXIS]);
  3754. SERIAL_PROTOCOLPGM(" Psi+Theta:");
  3755. SERIAL_PROTOCOL((delta[Y_AXIS] - delta[X_AXIS]) / 90 * axis_steps_per_unit[Y_AXIS]);
  3756. SERIAL_EOL; SERIAL_EOL;
  3757. #endif
  3758. }
  3759. /**
  3760. * M115: Capabilities string
  3761. */
  3762. inline void gcode_M115() {
  3763. SERIAL_PROTOCOLPGM(MSG_M115_REPORT);
  3764. }
  3765. /**
  3766. * M117: Set LCD Status Message
  3767. */
  3768. inline void gcode_M117() {
  3769. lcd_setstatus(current_command_args);
  3770. }
  3771. /**
  3772. * M119: Output endstop states to serial output
  3773. */
  3774. inline void gcode_M119() {
  3775. SERIAL_PROTOCOLLN(MSG_M119_REPORT);
  3776. #if HAS_X_MIN
  3777. SERIAL_PROTOCOLPGM(MSG_X_MIN);
  3778. SERIAL_PROTOCOLLN(((READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3779. #endif
  3780. #if HAS_X_MAX
  3781. SERIAL_PROTOCOLPGM(MSG_X_MAX);
  3782. SERIAL_PROTOCOLLN(((READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3783. #endif
  3784. #if HAS_Y_MIN
  3785. SERIAL_PROTOCOLPGM(MSG_Y_MIN);
  3786. SERIAL_PROTOCOLLN(((READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3787. #endif
  3788. #if HAS_Y_MAX
  3789. SERIAL_PROTOCOLPGM(MSG_Y_MAX);
  3790. SERIAL_PROTOCOLLN(((READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3791. #endif
  3792. #if HAS_Z_MIN
  3793. SERIAL_PROTOCOLPGM(MSG_Z_MIN);
  3794. SERIAL_PROTOCOLLN(((READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3795. #endif
  3796. #if HAS_Z_MAX
  3797. SERIAL_PROTOCOLPGM(MSG_Z_MAX);
  3798. SERIAL_PROTOCOLLN(((READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3799. #endif
  3800. #if HAS_Z2_MAX
  3801. SERIAL_PROTOCOLPGM(MSG_Z2_MAX);
  3802. SERIAL_PROTOCOLLN(((READ(Z2_MAX_PIN)^Z2_MAX_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3803. #endif
  3804. #if HAS_Z_PROBE
  3805. SERIAL_PROTOCOLPGM(MSG_Z_PROBE);
  3806. SERIAL_PROTOCOLLN(((READ(Z_MIN_PROBE_PIN)^Z_MIN_PROBE_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3807. #endif
  3808. }
  3809. /**
  3810. * M120: Enable endstops
  3811. */
  3812. inline void gcode_M120() { enable_endstops(true); }
  3813. /**
  3814. * M121: Disable endstops
  3815. */
  3816. inline void gcode_M121() { enable_endstops(false); }
  3817. #if ENABLED(BLINKM)
  3818. /**
  3819. * M150: Set Status LED Color - Use R-U-B for R-G-B
  3820. */
  3821. inline void gcode_M150() {
  3822. SendColors(
  3823. code_seen('R') ? (byte)code_value_short() : 0,
  3824. code_seen('U') ? (byte)code_value_short() : 0,
  3825. code_seen('B') ? (byte)code_value_short() : 0
  3826. );
  3827. }
  3828. #endif // BLINKM
  3829. /**
  3830. * M200: Set filament diameter and set E axis units to cubic millimeters
  3831. *
  3832. * T<extruder> - Optional extruder number. Current extruder if omitted.
  3833. * D<mm> - Diameter of the filament. Use "D0" to set units back to millimeters.
  3834. */
  3835. inline void gcode_M200() {
  3836. if (setTargetedHotend(200)) return;
  3837. if (code_seen('D')) {
  3838. float diameter = code_value();
  3839. // setting any extruder filament size disables volumetric on the assumption that
  3840. // slicers either generate in extruder values as cubic mm or as as filament feeds
  3841. // for all extruders
  3842. volumetric_enabled = (diameter != 0.0);
  3843. if (volumetric_enabled) {
  3844. filament_size[target_extruder] = diameter;
  3845. // make sure all extruders have some sane value for the filament size
  3846. for (int i = 0; i < EXTRUDERS; i++)
  3847. if (! filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  3848. }
  3849. }
  3850. else {
  3851. //reserved for setting filament diameter via UFID or filament measuring device
  3852. return;
  3853. }
  3854. calculate_volumetric_multipliers();
  3855. }
  3856. /**
  3857. * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3858. */
  3859. inline void gcode_M201() {
  3860. for (int8_t i = 0; i < NUM_AXIS; i++) {
  3861. if (code_seen(axis_codes[i])) {
  3862. max_acceleration_units_per_sq_second[i] = code_value();
  3863. }
  3864. }
  3865. // 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)
  3866. reset_acceleration_rates();
  3867. }
  3868. #if 0 // Not used for Sprinter/grbl gen6
  3869. inline void gcode_M202() {
  3870. for (int8_t i = 0; i < NUM_AXIS; i++) {
  3871. if (code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * axis_steps_per_unit[i];
  3872. }
  3873. }
  3874. #endif
  3875. /**
  3876. * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3877. */
  3878. inline void gcode_M203() {
  3879. for (int8_t i = 0; i < NUM_AXIS; i++) {
  3880. if (code_seen(axis_codes[i])) {
  3881. max_feedrate[i] = code_value();
  3882. }
  3883. }
  3884. }
  3885. /**
  3886. * M204: Set Accelerations in mm/sec^2 (M204 P1200 R3000 T3000)
  3887. *
  3888. * P = Printing moves
  3889. * R = Retract only (no X, Y, Z) moves
  3890. * T = Travel (non printing) moves
  3891. *
  3892. * Also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  3893. */
  3894. inline void gcode_M204() {
  3895. if (code_seen('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments.
  3896. travel_acceleration = acceleration = code_value();
  3897. SERIAL_ECHOPAIR("Setting Print and Travel Acceleration: ", acceleration);
  3898. SERIAL_EOL;
  3899. }
  3900. if (code_seen('P')) {
  3901. acceleration = code_value();
  3902. SERIAL_ECHOPAIR("Setting Print Acceleration: ", acceleration);
  3903. SERIAL_EOL;
  3904. }
  3905. if (code_seen('R')) {
  3906. retract_acceleration = code_value();
  3907. SERIAL_ECHOPAIR("Setting Retract Acceleration: ", retract_acceleration);
  3908. SERIAL_EOL;
  3909. }
  3910. if (code_seen('T')) {
  3911. travel_acceleration = code_value();
  3912. SERIAL_ECHOPAIR("Setting Travel Acceleration: ", travel_acceleration);
  3913. SERIAL_EOL;
  3914. }
  3915. }
  3916. /**
  3917. * M205: Set Advanced Settings
  3918. *
  3919. * S = Min Feed Rate (mm/s)
  3920. * T = Min Travel Feed Rate (mm/s)
  3921. * B = Min Segment Time (µs)
  3922. * X = Max XY Jerk (mm/s/s)
  3923. * Z = Max Z Jerk (mm/s/s)
  3924. * E = Max E Jerk (mm/s/s)
  3925. */
  3926. inline void gcode_M205() {
  3927. if (code_seen('S')) minimumfeedrate = code_value();
  3928. if (code_seen('T')) mintravelfeedrate = code_value();
  3929. if (code_seen('B')) minsegmenttime = code_value();
  3930. if (code_seen('X')) max_xy_jerk = code_value();
  3931. if (code_seen('Z')) max_z_jerk = code_value();
  3932. if (code_seen('E')) max_e_jerk = code_value();
  3933. }
  3934. /**
  3935. * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y
  3936. */
  3937. inline void gcode_M206() {
  3938. for (int8_t i = X_AXIS; i <= Z_AXIS; i++) {
  3939. if (code_seen(axis_codes[i])) {
  3940. home_offset[i] = code_value();
  3941. }
  3942. }
  3943. #if ENABLED(SCARA)
  3944. if (code_seen('T')) home_offset[X_AXIS] = code_value(); // Theta
  3945. if (code_seen('P')) home_offset[Y_AXIS] = code_value(); // Psi
  3946. #endif
  3947. }
  3948. #if ENABLED(DELTA)
  3949. /**
  3950. * M665: Set delta configurations
  3951. *
  3952. * L = diagonal rod
  3953. * R = delta radius
  3954. * S = segments per second
  3955. * A = Alpha (Tower 1) diagonal rod trim
  3956. * B = Beta (Tower 2) diagonal rod trim
  3957. * C = Gamma (Tower 3) diagonal rod trim
  3958. */
  3959. inline void gcode_M665() {
  3960. if (code_seen('L')) delta_diagonal_rod = code_value();
  3961. if (code_seen('R')) delta_radius = code_value();
  3962. if (code_seen('S')) delta_segments_per_second = code_value();
  3963. if (code_seen('A')) delta_diagonal_rod_trim_tower_1 = code_value();
  3964. if (code_seen('B')) delta_diagonal_rod_trim_tower_2 = code_value();
  3965. if (code_seen('C')) delta_diagonal_rod_trim_tower_3 = code_value();
  3966. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  3967. }
  3968. /**
  3969. * M666: Set delta endstop adjustment
  3970. */
  3971. inline void gcode_M666() {
  3972. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3973. if (marlin_debug_flags & DEBUG_LEVELING) {
  3974. SERIAL_ECHOLNPGM(">>> gcode_M666");
  3975. }
  3976. #endif
  3977. for (int8_t i = X_AXIS; i <= Z_AXIS; i++) {
  3978. if (code_seen(axis_codes[i])) {
  3979. endstop_adj[i] = code_value();
  3980. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3981. if (marlin_debug_flags & DEBUG_LEVELING) {
  3982. SERIAL_ECHOPGM("endstop_adj[");
  3983. SERIAL_ECHO(axis_codes[i]);
  3984. SERIAL_ECHOPAIR("] = ", endstop_adj[i]);
  3985. SERIAL_EOL;
  3986. }
  3987. #endif
  3988. }
  3989. }
  3990. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3991. if (marlin_debug_flags & DEBUG_LEVELING) {
  3992. SERIAL_ECHOLNPGM("<<< gcode_M666");
  3993. }
  3994. #endif
  3995. }
  3996. #elif ENABLED(Z_DUAL_ENDSTOPS) // !DELTA && ENABLED(Z_DUAL_ENDSTOPS)
  3997. /**
  3998. * M666: For Z Dual Endstop setup, set z axis offset to the z2 axis.
  3999. */
  4000. inline void gcode_M666() {
  4001. if (code_seen('Z')) z_endstop_adj = code_value();
  4002. SERIAL_ECHOPAIR("Z Endstop Adjustment set to (mm):", z_endstop_adj);
  4003. SERIAL_EOL;
  4004. }
  4005. #endif // !DELTA && Z_DUAL_ENDSTOPS
  4006. #if ENABLED(FWRETRACT)
  4007. /**
  4008. * M207: Set firmware retraction values
  4009. *
  4010. * S[+mm] retract_length
  4011. * W[+mm] retract_length_swap (multi-extruder)
  4012. * F[mm/min] retract_feedrate
  4013. * Z[mm] retract_zlift
  4014. */
  4015. inline void gcode_M207() {
  4016. if (code_seen('S')) retract_length = code_value();
  4017. if (code_seen('F')) retract_feedrate = code_value() / 60;
  4018. if (code_seen('Z')) retract_zlift = code_value();
  4019. #if EXTRUDERS > 1
  4020. if (code_seen('W')) retract_length_swap = code_value();
  4021. #endif
  4022. }
  4023. /**
  4024. * M208: Set firmware un-retraction values
  4025. *
  4026. * S[+mm] retract_recover_length (in addition to M207 S*)
  4027. * W[+mm] retract_recover_length_swap (multi-extruder)
  4028. * F[mm/min] retract_recover_feedrate
  4029. */
  4030. inline void gcode_M208() {
  4031. if (code_seen('S')) retract_recover_length = code_value();
  4032. if (code_seen('F')) retract_recover_feedrate = code_value() / 60;
  4033. #if EXTRUDERS > 1
  4034. if (code_seen('W')) retract_recover_length_swap = code_value();
  4035. #endif
  4036. }
  4037. /**
  4038. * M209: Enable automatic retract (M209 S1)
  4039. * detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction.
  4040. */
  4041. inline void gcode_M209() {
  4042. if (code_seen('S')) {
  4043. int t = code_value_short();
  4044. switch (t) {
  4045. case 0:
  4046. autoretract_enabled = false;
  4047. break;
  4048. case 1:
  4049. autoretract_enabled = true;
  4050. break;
  4051. default:
  4052. unknown_command_error();
  4053. return;
  4054. }
  4055. for (int i = 0; i < EXTRUDERS; i++) retracted[i] = false;
  4056. }
  4057. }
  4058. #endif // FWRETRACT
  4059. #if EXTRUDERS > 1
  4060. /**
  4061. * M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  4062. */
  4063. inline void gcode_M218() {
  4064. if (setTargetedHotend(218)) return;
  4065. if (code_seen('X')) extruder_offset[X_AXIS][target_extruder] = code_value();
  4066. if (code_seen('Y')) extruder_offset[Y_AXIS][target_extruder] = code_value();
  4067. #if ENABLED(DUAL_X_CARRIAGE)
  4068. if (code_seen('Z')) extruder_offset[Z_AXIS][target_extruder] = code_value();
  4069. #endif
  4070. SERIAL_ECHO_START;
  4071. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  4072. for (int e = 0; e < EXTRUDERS; e++) {
  4073. SERIAL_CHAR(' ');
  4074. SERIAL_ECHO(extruder_offset[X_AXIS][e]);
  4075. SERIAL_CHAR(',');
  4076. SERIAL_ECHO(extruder_offset[Y_AXIS][e]);
  4077. #if ENABLED(DUAL_X_CARRIAGE)
  4078. SERIAL_CHAR(',');
  4079. SERIAL_ECHO(extruder_offset[Z_AXIS][e]);
  4080. #endif
  4081. }
  4082. SERIAL_EOL;
  4083. }
  4084. #endif // EXTRUDERS > 1
  4085. /**
  4086. * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95)
  4087. */
  4088. inline void gcode_M220() {
  4089. if (code_seen('S')) feedrate_multiplier = code_value();
  4090. }
  4091. /**
  4092. * M221: Set extrusion percentage (M221 T0 S95)
  4093. */
  4094. inline void gcode_M221() {
  4095. if (code_seen('S')) {
  4096. int sval = code_value();
  4097. if (setTargetedHotend(221)) return;
  4098. extruder_multiplier[target_extruder] = sval;
  4099. }
  4100. }
  4101. /**
  4102. * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>)
  4103. */
  4104. inline void gcode_M226() {
  4105. if (code_seen('P')) {
  4106. int pin_number = code_value();
  4107. int pin_state = code_seen('S') ? code_value() : -1; // required pin state - default is inverted
  4108. if (pin_state >= -1 && pin_state <= 1) {
  4109. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++) {
  4110. if (sensitive_pins[i] == pin_number) {
  4111. pin_number = -1;
  4112. break;
  4113. }
  4114. }
  4115. if (pin_number > -1) {
  4116. int target = LOW;
  4117. st_synchronize();
  4118. pinMode(pin_number, INPUT);
  4119. switch (pin_state) {
  4120. case 1:
  4121. target = HIGH;
  4122. break;
  4123. case 0:
  4124. target = LOW;
  4125. break;
  4126. case -1:
  4127. target = !digitalRead(pin_number);
  4128. break;
  4129. }
  4130. while (digitalRead(pin_number) != target) idle();
  4131. } // pin_number > -1
  4132. } // pin_state -1 0 1
  4133. } // code_seen('P')
  4134. }
  4135. #if HAS_SERVOS
  4136. /**
  4137. * M280: Get or set servo position. P<index> S<angle>
  4138. */
  4139. inline void gcode_M280() {
  4140. int servo_index = code_seen('P') ? code_value_short() : -1;
  4141. int servo_position = 0;
  4142. if (code_seen('S')) {
  4143. servo_position = code_value_short();
  4144. if (servo_index >= 0 && servo_index < NUM_SERVOS)
  4145. servo[servo_index].move(servo_position);
  4146. else {
  4147. SERIAL_ERROR_START;
  4148. SERIAL_ERROR("Servo ");
  4149. SERIAL_ERROR(servo_index);
  4150. SERIAL_ERRORLN(" out of range");
  4151. }
  4152. }
  4153. else if (servo_index >= 0) {
  4154. SERIAL_ECHO_START;
  4155. SERIAL_ECHO(" Servo ");
  4156. SERIAL_ECHO(servo_index);
  4157. SERIAL_ECHO(": ");
  4158. SERIAL_ECHOLN(servo[servo_index].read());
  4159. }
  4160. }
  4161. #endif // HAS_SERVOS
  4162. #if HAS_BUZZER
  4163. /**
  4164. * M300: Play beep sound S<frequency Hz> P<duration ms>
  4165. */
  4166. inline void gcode_M300() {
  4167. uint16_t beepS = code_seen('S') ? code_value_short() : 110;
  4168. uint32_t beepP = code_seen('P') ? code_value_long() : 1000;
  4169. if (beepP > 5000) beepP = 5000; // limit to 5 seconds
  4170. buzz(beepP, beepS);
  4171. }
  4172. #endif // HAS_BUZZER
  4173. #if ENABLED(PIDTEMP)
  4174. /**
  4175. * M301: Set PID parameters P I D (and optionally C, L)
  4176. *
  4177. * P[float] Kp term
  4178. * I[float] Ki term (unscaled)
  4179. * D[float] Kd term (unscaled)
  4180. *
  4181. * With PID_ADD_EXTRUSION_RATE:
  4182. *
  4183. * C[float] Kc term
  4184. * L[float] LPQ length
  4185. */
  4186. inline void gcode_M301() {
  4187. // multi-extruder PID patch: M301 updates or prints a single extruder's PID values
  4188. // default behaviour (omitting E parameter) is to update for extruder 0 only
  4189. int e = code_seen('E') ? code_value() : 0; // extruder being updated
  4190. if (e < EXTRUDERS) { // catch bad input value
  4191. if (code_seen('P')) PID_PARAM(Kp, e) = code_value();
  4192. if (code_seen('I')) PID_PARAM(Ki, e) = scalePID_i(code_value());
  4193. if (code_seen('D')) PID_PARAM(Kd, e) = scalePID_d(code_value());
  4194. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  4195. if (code_seen('C')) PID_PARAM(Kc, e) = code_value();
  4196. if (code_seen('L')) lpq_len = code_value();
  4197. NOMORE(lpq_len, LPQ_MAX_LEN);
  4198. #endif
  4199. updatePID();
  4200. SERIAL_ECHO_START;
  4201. #if ENABLED(PID_PARAMS_PER_EXTRUDER)
  4202. SERIAL_ECHO(" e:"); // specify extruder in serial output
  4203. SERIAL_ECHO(e);
  4204. #endif // PID_PARAMS_PER_EXTRUDER
  4205. SERIAL_ECHO(" p:");
  4206. SERIAL_ECHO(PID_PARAM(Kp, e));
  4207. SERIAL_ECHO(" i:");
  4208. SERIAL_ECHO(unscalePID_i(PID_PARAM(Ki, e)));
  4209. SERIAL_ECHO(" d:");
  4210. SERIAL_ECHO(unscalePID_d(PID_PARAM(Kd, e)));
  4211. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  4212. SERIAL_ECHO(" c:");
  4213. //Kc does not have scaling applied above, or in resetting defaults
  4214. SERIAL_ECHO(PID_PARAM(Kc, e));
  4215. #endif
  4216. SERIAL_EOL;
  4217. }
  4218. else {
  4219. SERIAL_ERROR_START;
  4220. SERIAL_ERRORLN(MSG_INVALID_EXTRUDER);
  4221. }
  4222. }
  4223. #endif // PIDTEMP
  4224. #if ENABLED(PIDTEMPBED)
  4225. inline void gcode_M304() {
  4226. if (code_seen('P')) bedKp = code_value();
  4227. if (code_seen('I')) bedKi = scalePID_i(code_value());
  4228. if (code_seen('D')) bedKd = scalePID_d(code_value());
  4229. updatePID();
  4230. SERIAL_ECHO_START;
  4231. SERIAL_ECHO(" p:");
  4232. SERIAL_ECHO(bedKp);
  4233. SERIAL_ECHO(" i:");
  4234. SERIAL_ECHO(unscalePID_i(bedKi));
  4235. SERIAL_ECHO(" d:");
  4236. SERIAL_ECHOLN(unscalePID_d(bedKd));
  4237. }
  4238. #endif // PIDTEMPBED
  4239. #if defined(CHDK) || HAS_PHOTOGRAPH
  4240. /**
  4241. * M240: Trigger a camera by emulating a Canon RC-1
  4242. * See http://www.doc-diy.net/photo/rc-1_hacked/
  4243. */
  4244. inline void gcode_M240() {
  4245. #ifdef CHDK
  4246. OUT_WRITE(CHDK, HIGH);
  4247. chdkHigh = millis();
  4248. chdkActive = true;
  4249. #elif HAS_PHOTOGRAPH
  4250. const uint8_t NUM_PULSES = 16;
  4251. const float PULSE_LENGTH = 0.01524;
  4252. for (int i = 0; i < NUM_PULSES; i++) {
  4253. WRITE(PHOTOGRAPH_PIN, HIGH);
  4254. _delay_ms(PULSE_LENGTH);
  4255. WRITE(PHOTOGRAPH_PIN, LOW);
  4256. _delay_ms(PULSE_LENGTH);
  4257. }
  4258. delay(7.33);
  4259. for (int i = 0; i < NUM_PULSES; i++) {
  4260. WRITE(PHOTOGRAPH_PIN, HIGH);
  4261. _delay_ms(PULSE_LENGTH);
  4262. WRITE(PHOTOGRAPH_PIN, LOW);
  4263. _delay_ms(PULSE_LENGTH);
  4264. }
  4265. #endif // !CHDK && HAS_PHOTOGRAPH
  4266. }
  4267. #endif // CHDK || PHOTOGRAPH_PIN
  4268. #if ENABLED(HAS_LCD_CONTRAST)
  4269. /**
  4270. * M250: Read and optionally set the LCD contrast
  4271. */
  4272. inline void gcode_M250() {
  4273. if (code_seen('C')) lcd_setcontrast(code_value_short() & 0x3F);
  4274. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  4275. SERIAL_PROTOCOL(lcd_contrast);
  4276. SERIAL_EOL;
  4277. }
  4278. #endif // HAS_LCD_CONTRAST
  4279. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  4280. void set_extrude_min_temp(float temp) { extrude_min_temp = temp; }
  4281. /**
  4282. * M302: Allow cold extrudes, or set the minimum extrude S<temperature>.
  4283. */
  4284. inline void gcode_M302() {
  4285. set_extrude_min_temp(code_seen('S') ? code_value() : 0);
  4286. }
  4287. #endif // PREVENT_DANGEROUS_EXTRUDE
  4288. /**
  4289. * M303: PID relay autotune
  4290. * S<temperature> sets the target temperature. (default target temperature = 150C)
  4291. * E<extruder> (-1 for the bed)
  4292. * C<cycles>
  4293. */
  4294. inline void gcode_M303() {
  4295. int e = code_seen('E') ? code_value_short() : 0;
  4296. int c = code_seen('C') ? code_value_short() : 5;
  4297. float temp = code_seen('S') ? code_value() : (e < 0 ? 70.0 : 150.0);
  4298. if (e >=0 && e < EXTRUDERS)
  4299. target_extruder = e;
  4300. KEEPALIVE_STATE(NOT_BUSY);
  4301. PID_autotune(temp, e, c);
  4302. }
  4303. #if ENABLED(SCARA)
  4304. bool SCARA_move_to_cal(uint8_t delta_x, uint8_t delta_y) {
  4305. //SoftEndsEnabled = false; // Ignore soft endstops during calibration
  4306. //SERIAL_ECHOLN(" Soft endstops disabled ");
  4307. if (IsRunning()) {
  4308. //gcode_get_destination(); // For X Y Z E F
  4309. delta[X_AXIS] = delta_x;
  4310. delta[Y_AXIS] = delta_y;
  4311. calculate_SCARA_forward_Transform(delta);
  4312. destination[X_AXIS] = delta[X_AXIS] / axis_scaling[X_AXIS];
  4313. destination[Y_AXIS] = delta[Y_AXIS] / axis_scaling[Y_AXIS];
  4314. prepare_move();
  4315. //ok_to_send();
  4316. return true;
  4317. }
  4318. return false;
  4319. }
  4320. /**
  4321. * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  4322. */
  4323. inline bool gcode_M360() {
  4324. SERIAL_ECHOLN(" Cal: Theta 0 ");
  4325. return SCARA_move_to_cal(0, 120);
  4326. }
  4327. /**
  4328. * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  4329. */
  4330. inline bool gcode_M361() {
  4331. SERIAL_ECHOLN(" Cal: Theta 90 ");
  4332. return SCARA_move_to_cal(90, 130);
  4333. }
  4334. /**
  4335. * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  4336. */
  4337. inline bool gcode_M362() {
  4338. SERIAL_ECHOLN(" Cal: Psi 0 ");
  4339. return SCARA_move_to_cal(60, 180);
  4340. }
  4341. /**
  4342. * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  4343. */
  4344. inline bool gcode_M363() {
  4345. SERIAL_ECHOLN(" Cal: Psi 90 ");
  4346. return SCARA_move_to_cal(50, 90);
  4347. }
  4348. /**
  4349. * M364: SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  4350. */
  4351. inline bool gcode_M364() {
  4352. SERIAL_ECHOLN(" Cal: Theta-Psi 90 ");
  4353. return SCARA_move_to_cal(45, 135);
  4354. }
  4355. /**
  4356. * M365: SCARA calibration: Scaling factor, X, Y, Z axis
  4357. */
  4358. inline void gcode_M365() {
  4359. for (int8_t i = X_AXIS; i <= Z_AXIS; i++) {
  4360. if (code_seen(axis_codes[i])) {
  4361. axis_scaling[i] = code_value();
  4362. }
  4363. }
  4364. }
  4365. #endif // SCARA
  4366. #if ENABLED(EXT_SOLENOID)
  4367. void enable_solenoid(uint8_t num) {
  4368. switch (num) {
  4369. case 0:
  4370. OUT_WRITE(SOL0_PIN, HIGH);
  4371. break;
  4372. #if HAS_SOLENOID_1
  4373. case 1:
  4374. OUT_WRITE(SOL1_PIN, HIGH);
  4375. break;
  4376. #endif
  4377. #if HAS_SOLENOID_2
  4378. case 2:
  4379. OUT_WRITE(SOL2_PIN, HIGH);
  4380. break;
  4381. #endif
  4382. #if HAS_SOLENOID_3
  4383. case 3:
  4384. OUT_WRITE(SOL3_PIN, HIGH);
  4385. break;
  4386. #endif
  4387. default:
  4388. SERIAL_ECHO_START;
  4389. SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID);
  4390. break;
  4391. }
  4392. }
  4393. void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); }
  4394. void disable_all_solenoids() {
  4395. OUT_WRITE(SOL0_PIN, LOW);
  4396. OUT_WRITE(SOL1_PIN, LOW);
  4397. OUT_WRITE(SOL2_PIN, LOW);
  4398. OUT_WRITE(SOL3_PIN, LOW);
  4399. }
  4400. /**
  4401. * M380: Enable solenoid on the active extruder
  4402. */
  4403. inline void gcode_M380() { enable_solenoid_on_active_extruder(); }
  4404. /**
  4405. * M381: Disable all solenoids
  4406. */
  4407. inline void gcode_M381() { disable_all_solenoids(); }
  4408. #endif // EXT_SOLENOID
  4409. /**
  4410. * M400: Finish all moves
  4411. */
  4412. inline void gcode_M400() { st_synchronize(); }
  4413. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && DISABLED(Z_PROBE_SLED) && (HAS_SERVO_ENDSTOPS || ENABLED(Z_PROBE_ALLEN_KEY))
  4414. /**
  4415. * M401: Engage Z Servo endstop if available
  4416. */
  4417. inline void gcode_M401() {
  4418. #if HAS_SERVO_ENDSTOPS
  4419. raise_z_for_servo();
  4420. #endif
  4421. deploy_z_probe();
  4422. }
  4423. /**
  4424. * M402: Retract Z Servo endstop if enabled
  4425. */
  4426. inline void gcode_M402() {
  4427. #if HAS_SERVO_ENDSTOPS
  4428. raise_z_for_servo();
  4429. #endif
  4430. stow_z_probe(false);
  4431. }
  4432. #endif // AUTO_BED_LEVELING_FEATURE && (HAS_SERVO_ENDSTOPS || Z_PROBE_ALLEN_KEY) && !Z_PROBE_SLED
  4433. #if ENABLED(FILAMENT_SENSOR)
  4434. /**
  4435. * M404: Display or set the nominal filament width (3mm, 1.75mm ) W<3.0>
  4436. */
  4437. inline void gcode_M404() {
  4438. #if HAS_FILWIDTH
  4439. if (code_seen('W')) {
  4440. filament_width_nominal = code_value();
  4441. }
  4442. else {
  4443. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  4444. SERIAL_PROTOCOLLN(filament_width_nominal);
  4445. }
  4446. #endif
  4447. }
  4448. /**
  4449. * M405: Turn on filament sensor for control
  4450. */
  4451. inline void gcode_M405() {
  4452. if (code_seen('D')) meas_delay_cm = code_value();
  4453. NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY);
  4454. if (delay_index2 == -1) { //initialize the ring buffer if it has not been done since startup
  4455. int temp_ratio = widthFil_to_size_ratio();
  4456. for (delay_index1 = 0; delay_index1 < MAX_MEASUREMENT_DELAY + 1; ++delay_index1)
  4457. measurement_delay[delay_index1] = temp_ratio - 100; //subtract 100 to scale within a signed byte
  4458. delay_index1 = delay_index2 = 0;
  4459. }
  4460. filament_sensor = true;
  4461. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  4462. //SERIAL_PROTOCOL(filament_width_meas);
  4463. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  4464. //SERIAL_PROTOCOL(extruder_multiplier[active_extruder]);
  4465. }
  4466. /**
  4467. * M406: Turn off filament sensor for control
  4468. */
  4469. inline void gcode_M406() { filament_sensor = false; }
  4470. /**
  4471. * M407: Get measured filament diameter on serial output
  4472. */
  4473. inline void gcode_M407() {
  4474. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  4475. SERIAL_PROTOCOLLN(filament_width_meas);
  4476. }
  4477. #endif // FILAMENT_SENSOR
  4478. /**
  4479. * M410: Quickstop - Abort all planned moves
  4480. *
  4481. * This will stop the carriages mid-move, so most likely they
  4482. * will be out of sync with the stepper position after this.
  4483. */
  4484. inline void gcode_M410() { quickStop(); }
  4485. #if ENABLED(MESH_BED_LEVELING)
  4486. /**
  4487. * M420: Enable/Disable Mesh Bed Leveling
  4488. */
  4489. inline void gcode_M420() { if (code_seen('S') && code_has_value()) mbl.active = !!code_value_short(); }
  4490. /**
  4491. * M421: Set a single Mesh Bed Leveling Z coordinate
  4492. */
  4493. inline void gcode_M421() {
  4494. float x, y, z;
  4495. bool err = false, hasX, hasY, hasZ;
  4496. if ((hasX = code_seen('X'))) x = code_value();
  4497. if ((hasY = code_seen('Y'))) y = code_value();
  4498. if ((hasZ = code_seen('Z'))) z = code_value();
  4499. if (!hasX || !hasY || !hasZ) {
  4500. SERIAL_ERROR_START;
  4501. SERIAL_ERRORLNPGM(MSG_ERR_M421_REQUIRES_XYZ);
  4502. err = true;
  4503. }
  4504. if (x >= MESH_NUM_X_POINTS || y >= MESH_NUM_Y_POINTS) {
  4505. SERIAL_ERROR_START;
  4506. SERIAL_ERRORLNPGM(MSG_ERR_MESH_INDEX_OOB);
  4507. err = true;
  4508. }
  4509. if (!err) mbl.set_z(mbl.select_x_index(x), mbl.select_y_index(y), z);
  4510. }
  4511. #endif
  4512. /**
  4513. * M428: Set home_offset based on the distance between the
  4514. * current_position and the nearest "reference point."
  4515. * If an axis is past center its endstop position
  4516. * is the reference-point. Otherwise it uses 0. This allows
  4517. * the Z offset to be set near the bed when using a max endstop.
  4518. *
  4519. * M428 can't be used more than 2cm away from 0 or an endstop.
  4520. *
  4521. * Use M206 to set these values directly.
  4522. */
  4523. inline void gcode_M428() {
  4524. bool err = false;
  4525. float new_offs[3], new_pos[3];
  4526. memcpy(new_pos, current_position, sizeof(new_pos));
  4527. memcpy(new_offs, home_offset, sizeof(new_offs));
  4528. for (int8_t i = X_AXIS; i <= Z_AXIS; i++) {
  4529. if (axis_known_position[i]) {
  4530. float base = (new_pos[i] > (min_pos[i] + max_pos[i]) / 2) ? base_home_pos(i) : 0,
  4531. diff = new_pos[i] - base;
  4532. if (diff > -20 && diff < 20) {
  4533. new_offs[i] -= diff;
  4534. new_pos[i] = base;
  4535. }
  4536. else {
  4537. SERIAL_ERROR_START;
  4538. SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR);
  4539. LCD_ALERTMESSAGEPGM("Err: Too far!");
  4540. #if HAS_BUZZER
  4541. enqueue_and_echo_commands_P(PSTR("M300 S40 P200"));
  4542. #endif
  4543. err = true;
  4544. break;
  4545. }
  4546. }
  4547. }
  4548. if (!err) {
  4549. memcpy(current_position, new_pos, sizeof(new_pos));
  4550. memcpy(home_offset, new_offs, sizeof(new_offs));
  4551. sync_plan_position();
  4552. LCD_ALERTMESSAGEPGM("Offset applied.");
  4553. #if HAS_BUZZER
  4554. enqueue_and_echo_commands_P(PSTR("M300 S659 P200\nM300 S698 P200"));
  4555. #endif
  4556. }
  4557. }
  4558. /**
  4559. * M500: Store settings in EEPROM
  4560. */
  4561. inline void gcode_M500() {
  4562. Config_StoreSettings();
  4563. }
  4564. /**
  4565. * M501: Read settings from EEPROM
  4566. */
  4567. inline void gcode_M501() {
  4568. Config_RetrieveSettings();
  4569. }
  4570. /**
  4571. * M502: Revert to default settings
  4572. */
  4573. inline void gcode_M502() {
  4574. Config_ResetDefault();
  4575. }
  4576. /**
  4577. * M503: print settings currently in memory
  4578. */
  4579. inline void gcode_M503() {
  4580. Config_PrintSettings(code_seen('S') && code_value() == 0);
  4581. }
  4582. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  4583. /**
  4584. * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>)
  4585. */
  4586. inline void gcode_M540() {
  4587. if (code_seen('S')) abort_on_endstop_hit = (code_value() > 0);
  4588. }
  4589. #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  4590. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  4591. inline void gcode_SET_Z_PROBE_OFFSET() {
  4592. SERIAL_ECHO_START;
  4593. SERIAL_ECHOPGM(MSG_ZPROBE_ZOFFSET);
  4594. SERIAL_CHAR(' ');
  4595. if (code_seen('Z')) {
  4596. float value = code_value();
  4597. if (Z_PROBE_OFFSET_RANGE_MIN <= value && value <= Z_PROBE_OFFSET_RANGE_MAX) {
  4598. zprobe_zoffset = value;
  4599. SERIAL_ECHO(zprobe_zoffset);
  4600. }
  4601. else {
  4602. SERIAL_ECHOPGM(MSG_Z_MIN);
  4603. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  4604. SERIAL_ECHOPGM(MSG_Z_MAX);
  4605. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  4606. }
  4607. }
  4608. else {
  4609. SERIAL_ECHOPAIR(": ", zprobe_zoffset);
  4610. }
  4611. SERIAL_EOL;
  4612. }
  4613. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  4614. #if ENABLED(FILAMENTCHANGEENABLE)
  4615. /**
  4616. * M600: Pause for filament change
  4617. *
  4618. * E[distance] - Retract the filament this far (negative value)
  4619. * Z[distance] - Move the Z axis by this distance
  4620. * X[position] - Move to this X position, with Y
  4621. * Y[position] - Move to this Y position, with X
  4622. * L[distance] - Retract distance for removal (manual reload)
  4623. *
  4624. * Default values are used for omitted arguments.
  4625. *
  4626. */
  4627. inline void gcode_M600() {
  4628. if (degHotend(active_extruder) < extrude_min_temp) {
  4629. SERIAL_ERROR_START;
  4630. SERIAL_ERRORLNPGM(MSG_TOO_COLD_FOR_M600);
  4631. return;
  4632. }
  4633. float lastpos[NUM_AXIS], fr60 = feedrate / 60;
  4634. for (int i = 0; i < NUM_AXIS; i++)
  4635. lastpos[i] = destination[i] = current_position[i];
  4636. #if ENABLED(DELTA)
  4637. #define RUNPLAN calculate_delta(destination); \
  4638. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], fr60, active_extruder);
  4639. #else
  4640. #define RUNPLAN line_to_destination();
  4641. #endif
  4642. //retract by E
  4643. if (code_seen('E')) destination[E_AXIS] += code_value();
  4644. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  4645. else destination[E_AXIS] += FILAMENTCHANGE_FIRSTRETRACT;
  4646. #endif
  4647. RUNPLAN;
  4648. //lift Z
  4649. if (code_seen('Z')) destination[Z_AXIS] += code_value();
  4650. #ifdef FILAMENTCHANGE_ZADD
  4651. else destination[Z_AXIS] += FILAMENTCHANGE_ZADD;
  4652. #endif
  4653. RUNPLAN;
  4654. //move xy
  4655. if (code_seen('X')) destination[X_AXIS] = code_value();
  4656. #ifdef FILAMENTCHANGE_XPOS
  4657. else destination[X_AXIS] = FILAMENTCHANGE_XPOS;
  4658. #endif
  4659. if (code_seen('Y')) destination[Y_AXIS] = code_value();
  4660. #ifdef FILAMENTCHANGE_YPOS
  4661. else destination[Y_AXIS] = FILAMENTCHANGE_YPOS;
  4662. #endif
  4663. RUNPLAN;
  4664. if (code_seen('L')) destination[E_AXIS] += code_value();
  4665. #ifdef FILAMENTCHANGE_FINALRETRACT
  4666. else destination[E_AXIS] += FILAMENTCHANGE_FINALRETRACT;
  4667. #endif
  4668. RUNPLAN;
  4669. //finish moves
  4670. st_synchronize();
  4671. //disable extruder steppers so filament can be removed
  4672. disable_e0();
  4673. disable_e1();
  4674. disable_e2();
  4675. disable_e3();
  4676. delay(100);
  4677. LCD_ALERTMESSAGEPGM(MSG_FILAMENTCHANGE);
  4678. millis_t next_tick = 0;
  4679. KEEPALIVE_STATE(WAIT_FOR_USER);
  4680. while (!lcd_clicked()) {
  4681. #if DISABLED(AUTO_FILAMENT_CHANGE)
  4682. millis_t ms = millis();
  4683. if (ms >= next_tick) {
  4684. lcd_quick_feedback();
  4685. next_tick = ms + 2500; // feedback every 2.5s while waiting
  4686. }
  4687. idle(true);
  4688. #else
  4689. current_position[E_AXIS] += AUTO_FILAMENT_CHANGE_LENGTH;
  4690. destination[E_AXIS] = current_position[E_AXIS];
  4691. line_to_destination(AUTO_FILAMENT_CHANGE_FEEDRATE);
  4692. st_synchronize();
  4693. #endif
  4694. } // while(!lcd_clicked)
  4695. KEEPALIVE_STATE(IN_HANDLER);
  4696. lcd_quick_feedback(); // click sound feedback
  4697. #if ENABLED(AUTO_FILAMENT_CHANGE)
  4698. current_position[E_AXIS] = 0;
  4699. st_synchronize();
  4700. #endif
  4701. //return to normal
  4702. if (code_seen('L')) destination[E_AXIS] -= code_value();
  4703. #ifdef FILAMENTCHANGE_FINALRETRACT
  4704. else destination[E_AXIS] -= FILAMENTCHANGE_FINALRETRACT;
  4705. #endif
  4706. current_position[E_AXIS] = destination[E_AXIS]; //the long retract of L is compensated by manual filament feeding
  4707. plan_set_e_position(current_position[E_AXIS]);
  4708. RUNPLAN; //should do nothing
  4709. lcd_reset_alert_level();
  4710. #if ENABLED(DELTA)
  4711. // Move XYZ to starting position, then E
  4712. calculate_delta(lastpos);
  4713. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], fr60, active_extruder);
  4714. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], lastpos[E_AXIS], fr60, active_extruder);
  4715. #else
  4716. // Move XY to starting position, then Z, then E
  4717. destination[X_AXIS] = lastpos[X_AXIS];
  4718. destination[Y_AXIS] = lastpos[Y_AXIS];
  4719. line_to_destination();
  4720. destination[Z_AXIS] = lastpos[Z_AXIS];
  4721. line_to_destination();
  4722. destination[E_AXIS] = lastpos[E_AXIS];
  4723. line_to_destination();
  4724. #endif
  4725. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  4726. filrunoutEnqueued = false;
  4727. #endif
  4728. }
  4729. #endif // FILAMENTCHANGEENABLE
  4730. #if ENABLED(DUAL_X_CARRIAGE)
  4731. /**
  4732. * M605: Set dual x-carriage movement mode
  4733. *
  4734. * M605 S0: Full control mode. The slicer has full control over x-carriage movement
  4735. * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  4736. * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  4737. * millimeters x-offset and an optional differential hotend temperature of
  4738. * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  4739. * the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  4740. *
  4741. * Note: the X axis should be homed after changing dual x-carriage mode.
  4742. */
  4743. inline void gcode_M605() {
  4744. st_synchronize();
  4745. if (code_seen('S')) dual_x_carriage_mode = code_value();
  4746. switch (dual_x_carriage_mode) {
  4747. case DXC_DUPLICATION_MODE:
  4748. if (code_seen('X')) duplicate_extruder_x_offset = max(code_value(), X2_MIN_POS - x_home_pos(0));
  4749. if (code_seen('R')) duplicate_extruder_temp_offset = code_value();
  4750. SERIAL_ECHO_START;
  4751. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  4752. SERIAL_CHAR(' ');
  4753. SERIAL_ECHO(extruder_offset[X_AXIS][0]);
  4754. SERIAL_CHAR(',');
  4755. SERIAL_ECHO(extruder_offset[Y_AXIS][0]);
  4756. SERIAL_CHAR(' ');
  4757. SERIAL_ECHO(duplicate_extruder_x_offset);
  4758. SERIAL_CHAR(',');
  4759. SERIAL_ECHOLN(extruder_offset[Y_AXIS][1]);
  4760. break;
  4761. case DXC_FULL_CONTROL_MODE:
  4762. case DXC_AUTO_PARK_MODE:
  4763. break;
  4764. default:
  4765. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  4766. break;
  4767. }
  4768. active_extruder_parked = false;
  4769. extruder_duplication_enabled = false;
  4770. delayed_move_time = 0;
  4771. }
  4772. #endif // DUAL_X_CARRIAGE
  4773. /**
  4774. * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S
  4775. */
  4776. inline void gcode_M907() {
  4777. #if HAS_DIGIPOTSS
  4778. for (int i = 0; i < NUM_AXIS; i++)
  4779. if (code_seen(axis_codes[i])) digipot_current(i, code_value());
  4780. if (code_seen('B')) digipot_current(4, code_value());
  4781. if (code_seen('S')) for (int i = 0; i <= 4; i++) digipot_current(i, code_value());
  4782. #endif
  4783. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  4784. if (code_seen('X')) digipot_current(0, code_value());
  4785. #endif
  4786. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  4787. if (code_seen('Z')) digipot_current(1, code_value());
  4788. #endif
  4789. #ifdef MOTOR_CURRENT_PWM_E_PIN
  4790. if (code_seen('E')) digipot_current(2, code_value());
  4791. #endif
  4792. #if ENABLED(DIGIPOT_I2C)
  4793. // this one uses actual amps in floating point
  4794. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) digipot_i2c_set_current(i, code_value());
  4795. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  4796. 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());
  4797. #endif
  4798. }
  4799. #if HAS_DIGIPOTSS
  4800. /**
  4801. * M908: Control digital trimpot directly (M908 P<pin> S<current>)
  4802. */
  4803. inline void gcode_M908() {
  4804. digitalPotWrite(
  4805. code_seen('P') ? code_value() : 0,
  4806. code_seen('S') ? code_value() : 0
  4807. );
  4808. }
  4809. #endif // HAS_DIGIPOTSS
  4810. #if HAS_MICROSTEPS
  4811. // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  4812. inline void gcode_M350() {
  4813. if (code_seen('S')) for (int i = 0; i <= 4; i++) microstep_mode(i, code_value());
  4814. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) microstep_mode(i, (uint8_t)code_value());
  4815. if (code_seen('B')) microstep_mode(4, code_value());
  4816. microstep_readings();
  4817. }
  4818. /**
  4819. * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B
  4820. * S# determines MS1 or MS2, X# sets the pin high/low.
  4821. */
  4822. inline void gcode_M351() {
  4823. if (code_seen('S')) switch (code_value_short()) {
  4824. case 1:
  4825. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) microstep_ms(i, code_value(), -1);
  4826. if (code_seen('B')) microstep_ms(4, code_value(), -1);
  4827. break;
  4828. case 2:
  4829. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) microstep_ms(i, -1, code_value());
  4830. if (code_seen('B')) microstep_ms(4, -1, code_value());
  4831. break;
  4832. }
  4833. microstep_readings();
  4834. }
  4835. #endif // HAS_MICROSTEPS
  4836. /**
  4837. * M999: Restart after being stopped
  4838. */
  4839. inline void gcode_M999() {
  4840. Running = true;
  4841. lcd_reset_alert_level();
  4842. // gcode_LastN = Stopped_gcode_LastN;
  4843. FlushSerialRequestResend();
  4844. }
  4845. /**
  4846. * T0-T3: Switch tool, usually switching extruders
  4847. *
  4848. * F[mm/min] Set the movement feedrate
  4849. */
  4850. inline void gcode_T(uint8_t tmp_extruder) {
  4851. if (tmp_extruder >= EXTRUDERS) {
  4852. SERIAL_ECHO_START;
  4853. SERIAL_CHAR('T');
  4854. SERIAL_PROTOCOL_F(tmp_extruder, DEC);
  4855. SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
  4856. }
  4857. else {
  4858. target_extruder = tmp_extruder;
  4859. #if EXTRUDERS > 1
  4860. bool make_move = false;
  4861. #endif
  4862. if (code_seen('F')) {
  4863. #if EXTRUDERS > 1
  4864. make_move = true;
  4865. #endif
  4866. float next_feedrate = code_value();
  4867. if (next_feedrate > 0.0) feedrate = next_feedrate;
  4868. }
  4869. #if EXTRUDERS > 1
  4870. if (tmp_extruder != active_extruder) {
  4871. // Save current position to return to after applying extruder offset
  4872. set_destination_to_current();
  4873. #if ENABLED(DUAL_X_CARRIAGE)
  4874. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE && IsRunning() &&
  4875. (delayed_move_time != 0 || current_position[X_AXIS] != x_home_pos(active_extruder))) {
  4876. // Park old head: 1) raise 2) move to park position 3) lower
  4877. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT,
  4878. current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  4879. plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT,
  4880. current_position[E_AXIS], max_feedrate[X_AXIS], active_extruder);
  4881. plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS],
  4882. current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  4883. st_synchronize();
  4884. }
  4885. // apply Y & Z extruder offset (x offset is already used in determining home pos)
  4886. current_position[Y_AXIS] -= extruder_offset[Y_AXIS][active_extruder] - extruder_offset[Y_AXIS][tmp_extruder];
  4887. current_position[Z_AXIS] -= extruder_offset[Z_AXIS][active_extruder] - extruder_offset[Z_AXIS][tmp_extruder];
  4888. active_extruder = tmp_extruder;
  4889. // This function resets the max/min values - the current position may be overwritten below.
  4890. set_axis_is_at_home(X_AXIS);
  4891. if (dual_x_carriage_mode == DXC_FULL_CONTROL_MODE) {
  4892. current_position[X_AXIS] = inactive_extruder_x_pos;
  4893. inactive_extruder_x_pos = destination[X_AXIS];
  4894. }
  4895. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  4896. active_extruder_parked = (active_extruder == 0); // this triggers the second extruder to move into the duplication position
  4897. if (active_extruder == 0 || active_extruder_parked)
  4898. current_position[X_AXIS] = inactive_extruder_x_pos;
  4899. else
  4900. current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset;
  4901. inactive_extruder_x_pos = destination[X_AXIS];
  4902. extruder_duplication_enabled = false;
  4903. }
  4904. else {
  4905. // record raised toolhead position for use by unpark
  4906. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  4907. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  4908. active_extruder_parked = true;
  4909. delayed_move_time = 0;
  4910. }
  4911. #else // !DUAL_X_CARRIAGE
  4912. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  4913. // Offset extruder, make sure to apply the bed level rotation matrix
  4914. vector_3 tmp_offset_vec = vector_3(extruder_offset[X_AXIS][tmp_extruder],
  4915. extruder_offset[Y_AXIS][tmp_extruder],
  4916. extruder_offset[Z_AXIS][tmp_extruder]),
  4917. act_offset_vec = vector_3(extruder_offset[X_AXIS][active_extruder],
  4918. extruder_offset[Y_AXIS][active_extruder],
  4919. extruder_offset[Z_AXIS][active_extruder]),
  4920. offset_vec = tmp_offset_vec - act_offset_vec;
  4921. offset_vec.apply_rotation(plan_bed_level_matrix.transpose(plan_bed_level_matrix));
  4922. current_position[X_AXIS] += offset_vec.x;
  4923. current_position[Y_AXIS] += offset_vec.y;
  4924. current_position[Z_AXIS] += offset_vec.z;
  4925. #else // !AUTO_BED_LEVELING_FEATURE
  4926. // Offset extruder (only by XY)
  4927. for (int i=X_AXIS; i<=Y_AXIS; i++)
  4928. current_position[i] += extruder_offset[i][tmp_extruder] - extruder_offset[i][active_extruder];
  4929. #endif // !AUTO_BED_LEVELING_FEATURE
  4930. // Set the new active extruder and position
  4931. active_extruder = tmp_extruder;
  4932. #endif // !DUAL_X_CARRIAGE
  4933. #if ENABLED(DELTA)
  4934. sync_plan_position_delta();
  4935. #else
  4936. sync_plan_position();
  4937. #endif
  4938. // Move to the old position if 'F' was in the parameters
  4939. if (make_move && IsRunning()) prepare_move();
  4940. }
  4941. #if ENABLED(EXT_SOLENOID)
  4942. st_synchronize();
  4943. disable_all_solenoids();
  4944. enable_solenoid_on_active_extruder();
  4945. #endif // EXT_SOLENOID
  4946. #endif // EXTRUDERS > 1
  4947. SERIAL_ECHO_START;
  4948. SERIAL_ECHO(MSG_ACTIVE_EXTRUDER);
  4949. SERIAL_PROTOCOLLN((int)active_extruder);
  4950. }
  4951. }
  4952. /**
  4953. * Process a single command and dispatch it to its handler
  4954. * This is called from the main loop()
  4955. */
  4956. void process_next_command() {
  4957. current_command = command_queue[cmd_queue_index_r];
  4958. if ((marlin_debug_flags & DEBUG_ECHO)) {
  4959. SERIAL_ECHO_START;
  4960. SERIAL_ECHOLN(current_command);
  4961. }
  4962. // Sanitize the current command:
  4963. // - Skip leading spaces
  4964. // - Bypass N[-0-9][0-9]*[ ]*
  4965. // - Overwrite * with nul to mark the end
  4966. while (*current_command == ' ') ++current_command;
  4967. if (*current_command == 'N' && ((current_command[1] >= '0' && current_command[1] <= '9') || current_command[1] == '-')) {
  4968. current_command += 2; // skip N[-0-9]
  4969. while (*current_command >= '0' && *current_command <= '9') ++current_command; // skip [0-9]*
  4970. while (*current_command == ' ') ++current_command; // skip [ ]*
  4971. }
  4972. char* starpos = strchr(current_command, '*'); // * should always be the last parameter
  4973. if (starpos) while (*starpos == ' ' || *starpos == '*') *starpos-- = '\0'; // nullify '*' and ' '
  4974. // Get the command code, which must be G, M, or T
  4975. char command_code = *current_command;
  4976. // Skip the letter-code and spaces to get the numeric part
  4977. current_command_args = current_command + 1;
  4978. while (*current_command_args == ' ') ++current_command_args;
  4979. // The code must have a numeric value
  4980. bool code_is_good = (*current_command_args >= '0' && *current_command_args <= '9');
  4981. int codenum; // define ahead of goto
  4982. // Bail early if there's no code
  4983. if (!code_is_good) goto ExitUnknownCommand;
  4984. // Args pointer optimizes code_seen, especially those taking XYZEF
  4985. // This wastes a little cpu on commands that expect no arguments.
  4986. while (*current_command_args == ' ' || (*current_command_args >= '0' && *current_command_args <= '9')) ++current_command_args;
  4987. // Interpret the code int
  4988. seen_pointer = current_command;
  4989. codenum = code_value_short();
  4990. KEEPALIVE_STATE(IN_HANDLER);
  4991. // Handle a known G, M, or T
  4992. switch (command_code) {
  4993. case 'G': switch (codenum) {
  4994. // G0, G1
  4995. case 0:
  4996. case 1:
  4997. gcode_G0_G1();
  4998. break;
  4999. // G2, G3
  5000. #if DISABLED(SCARA)
  5001. case 2: // G2 - CW ARC
  5002. case 3: // G3 - CCW ARC
  5003. gcode_G2_G3(codenum == 2);
  5004. break;
  5005. #endif
  5006. // G4 Dwell
  5007. case 4:
  5008. gcode_G4();
  5009. break;
  5010. #if ENABLED(FWRETRACT)
  5011. case 10: // G10: retract
  5012. case 11: // G11: retract_recover
  5013. gcode_G10_G11(codenum == 10);
  5014. break;
  5015. #endif //FWRETRACT
  5016. case 28: // G28: Home all axes, one at a time
  5017. gcode_G28();
  5018. break;
  5019. #if ENABLED(AUTO_BED_LEVELING_FEATURE) || ENABLED(MESH_BED_LEVELING)
  5020. case 29: // G29 Detailed Z probe, probes the bed at 3 or more points.
  5021. gcode_G29();
  5022. break;
  5023. #endif
  5024. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5025. #if DISABLED(Z_PROBE_SLED)
  5026. case 30: // G30 Single Z probe
  5027. gcode_G30();
  5028. break;
  5029. #else // Z_PROBE_SLED
  5030. case 31: // G31: dock the sled
  5031. case 32: // G32: undock the sled
  5032. dock_sled(codenum == 31);
  5033. break;
  5034. #endif // Z_PROBE_SLED
  5035. #endif // AUTO_BED_LEVELING_FEATURE
  5036. case 90: // G90
  5037. relative_mode = false;
  5038. break;
  5039. case 91: // G91
  5040. relative_mode = true;
  5041. break;
  5042. case 92: // G92
  5043. gcode_G92();
  5044. break;
  5045. }
  5046. break;
  5047. case 'M': switch (codenum) {
  5048. #if ENABLED(ULTIPANEL)
  5049. case 0: // M0 - Unconditional stop - Wait for user button press on LCD
  5050. case 1: // M1 - Conditional stop - Wait for user button press on LCD
  5051. gcode_M0_M1();
  5052. break;
  5053. #endif // ULTIPANEL
  5054. case 17:
  5055. gcode_M17();
  5056. break;
  5057. #if ENABLED(SDSUPPORT)
  5058. case 20: // M20 - list SD card
  5059. gcode_M20(); break;
  5060. case 21: // M21 - init SD card
  5061. gcode_M21(); break;
  5062. case 22: //M22 - release SD card
  5063. gcode_M22(); break;
  5064. case 23: //M23 - Select file
  5065. gcode_M23(); break;
  5066. case 24: //M24 - Start SD print
  5067. gcode_M24(); break;
  5068. case 25: //M25 - Pause SD print
  5069. gcode_M25(); break;
  5070. case 26: //M26 - Set SD index
  5071. gcode_M26(); break;
  5072. case 27: //M27 - Get SD status
  5073. gcode_M27(); break;
  5074. case 28: //M28 - Start SD write
  5075. gcode_M28(); break;
  5076. case 29: //M29 - Stop SD write
  5077. gcode_M29(); break;
  5078. case 30: //M30 <filename> Delete File
  5079. gcode_M30(); break;
  5080. case 32: //M32 - Select file and start SD print
  5081. gcode_M32(); break;
  5082. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  5083. case 33: //M33 - Get the long full path to a file or folder
  5084. gcode_M33(); break;
  5085. #endif // LONG_FILENAME_HOST_SUPPORT
  5086. case 928: //M928 - Start SD write
  5087. gcode_M928(); break;
  5088. #endif //SDSUPPORT
  5089. case 31: //M31 take time since the start of the SD print or an M109 command
  5090. gcode_M31();
  5091. break;
  5092. case 42: //M42 -Change pin status via gcode
  5093. gcode_M42();
  5094. break;
  5095. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  5096. case 48: // M48 Z probe repeatability
  5097. gcode_M48();
  5098. break;
  5099. #endif // AUTO_BED_LEVELING_FEATURE && Z_MIN_PROBE_REPEATABILITY_TEST
  5100. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  5101. case 100:
  5102. gcode_M100();
  5103. break;
  5104. #endif
  5105. case 104: // M104
  5106. gcode_M104();
  5107. break;
  5108. case 110: // M110: Set Current Line Number
  5109. gcode_M110();
  5110. break;
  5111. case 111: // M111: Set debug level
  5112. gcode_M111();
  5113. break;
  5114. case 112: // M112: Emergency Stop
  5115. gcode_M112();
  5116. break;
  5117. case 140: // M140: Set bed temp
  5118. gcode_M140();
  5119. break;
  5120. case 105: // M105: Read current temperature
  5121. gcode_M105();
  5122. return; // "ok" already printed
  5123. case 109: // M109: Wait for temperature
  5124. gcode_M109();
  5125. break;
  5126. #if HAS_TEMP_BED
  5127. case 190: // M190: Wait for bed heater to reach target
  5128. gcode_M190();
  5129. break;
  5130. #endif // HAS_TEMP_BED
  5131. #if FAN_COUNT > 0
  5132. case 106: // M106: Fan On
  5133. gcode_M106();
  5134. break;
  5135. case 107: // M107: Fan Off
  5136. gcode_M107();
  5137. break;
  5138. #endif // FAN_COUNT > 0
  5139. #if ENABLED(BARICUDA)
  5140. // PWM for HEATER_1_PIN
  5141. #if HAS_HEATER_1
  5142. case 126: // M126: valve open
  5143. gcode_M126();
  5144. break;
  5145. case 127: // M127: valve closed
  5146. gcode_M127();
  5147. break;
  5148. #endif // HAS_HEATER_1
  5149. // PWM for HEATER_2_PIN
  5150. #if HAS_HEATER_2
  5151. case 128: // M128: valve open
  5152. gcode_M128();
  5153. break;
  5154. case 129: // M129: valve closed
  5155. gcode_M129();
  5156. break;
  5157. #endif // HAS_HEATER_2
  5158. #endif // BARICUDA
  5159. #if HAS_POWER_SWITCH
  5160. case 80: // M80: Turn on Power Supply
  5161. gcode_M80();
  5162. break;
  5163. #endif // HAS_POWER_SWITCH
  5164. case 81: // M81: Turn off Power, including Power Supply, if possible
  5165. gcode_M81();
  5166. break;
  5167. case 82:
  5168. gcode_M82();
  5169. break;
  5170. case 83:
  5171. gcode_M83();
  5172. break;
  5173. case 18: // (for compatibility)
  5174. case 84: // M84
  5175. gcode_M18_M84();
  5176. break;
  5177. case 85: // M85
  5178. gcode_M85();
  5179. break;
  5180. case 92: // M92: Set the steps-per-unit for one or more axes
  5181. gcode_M92();
  5182. break;
  5183. case 115: // M115: Report capabilities
  5184. gcode_M115();
  5185. break;
  5186. case 117: // M117: Set LCD message text, if possible
  5187. gcode_M117();
  5188. break;
  5189. case 114: // M114: Report current position
  5190. gcode_M114();
  5191. break;
  5192. case 120: // M120: Enable endstops
  5193. gcode_M120();
  5194. break;
  5195. case 121: // M121: Disable endstops
  5196. gcode_M121();
  5197. break;
  5198. case 119: // M119: Report endstop states
  5199. gcode_M119();
  5200. break;
  5201. #if ENABLED(ULTIPANEL)
  5202. case 145: // M145: Set material heatup parameters
  5203. gcode_M145();
  5204. break;
  5205. #endif
  5206. #if ENABLED(BLINKM)
  5207. case 150: // M150
  5208. gcode_M150();
  5209. break;
  5210. #endif //BLINKM
  5211. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5212. gcode_M200();
  5213. break;
  5214. case 201: // M201
  5215. gcode_M201();
  5216. break;
  5217. #if 0 // Not used for Sprinter/grbl gen6
  5218. case 202: // M202
  5219. gcode_M202();
  5220. break;
  5221. #endif
  5222. case 203: // M203 max feedrate mm/sec
  5223. gcode_M203();
  5224. break;
  5225. case 204: // M204 acclereration S normal moves T filmanent only moves
  5226. gcode_M204();
  5227. break;
  5228. 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
  5229. gcode_M205();
  5230. break;
  5231. case 206: // M206 additional homing offset
  5232. gcode_M206();
  5233. break;
  5234. #if ENABLED(DELTA)
  5235. case 665: // M665 set delta configurations L<diagonal_rod> R<delta_radius> S<segments_per_sec>
  5236. gcode_M665();
  5237. break;
  5238. #endif
  5239. #if ENABLED(DELTA) || ENABLED(Z_DUAL_ENDSTOPS)
  5240. case 666: // M666 set delta / dual endstop adjustment
  5241. gcode_M666();
  5242. break;
  5243. #endif
  5244. #if ENABLED(FWRETRACT)
  5245. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  5246. gcode_M207();
  5247. break;
  5248. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  5249. gcode_M208();
  5250. break;
  5251. 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.
  5252. gcode_M209();
  5253. break;
  5254. #endif // FWRETRACT
  5255. #if EXTRUDERS > 1
  5256. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  5257. gcode_M218();
  5258. break;
  5259. #endif
  5260. case 220: // M220 S<factor in percent>- set speed factor override percentage
  5261. gcode_M220();
  5262. break;
  5263. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  5264. gcode_M221();
  5265. break;
  5266. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  5267. gcode_M226();
  5268. break;
  5269. #if HAS_SERVOS
  5270. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  5271. gcode_M280();
  5272. break;
  5273. #endif // HAS_SERVOS
  5274. #if HAS_BUZZER
  5275. case 300: // M300 - Play beep tone
  5276. gcode_M300();
  5277. break;
  5278. #endif // HAS_BUZZER
  5279. #if ENABLED(PIDTEMP)
  5280. case 301: // M301
  5281. gcode_M301();
  5282. break;
  5283. #endif // PIDTEMP
  5284. #if ENABLED(PIDTEMPBED)
  5285. case 304: // M304
  5286. gcode_M304();
  5287. break;
  5288. #endif // PIDTEMPBED
  5289. #if defined(CHDK) || HAS_PHOTOGRAPH
  5290. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  5291. gcode_M240();
  5292. break;
  5293. #endif // CHDK || PHOTOGRAPH_PIN
  5294. #if ENABLED(HAS_LCD_CONTRAST)
  5295. case 250: // M250 Set LCD contrast value: C<value> (value 0..63)
  5296. gcode_M250();
  5297. break;
  5298. #endif // HAS_LCD_CONTRAST
  5299. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  5300. case 302: // allow cold extrudes, or set the minimum extrude temperature
  5301. gcode_M302();
  5302. break;
  5303. #endif // PREVENT_DANGEROUS_EXTRUDE
  5304. case 303: // M303 PID autotune
  5305. gcode_M303();
  5306. break;
  5307. #if ENABLED(SCARA)
  5308. case 360: // M360 SCARA Theta pos1
  5309. if (gcode_M360()) return;
  5310. break;
  5311. case 361: // M361 SCARA Theta pos2
  5312. if (gcode_M361()) return;
  5313. break;
  5314. case 362: // M362 SCARA Psi pos1
  5315. if (gcode_M362()) return;
  5316. break;
  5317. case 363: // M363 SCARA Psi pos2
  5318. if (gcode_M363()) return;
  5319. break;
  5320. case 364: // M364 SCARA Psi pos3 (90 deg to Theta)
  5321. if (gcode_M364()) return;
  5322. break;
  5323. case 365: // M365 Set SCARA scaling for X Y Z
  5324. gcode_M365();
  5325. break;
  5326. #endif // SCARA
  5327. case 400: // M400 finish all moves
  5328. gcode_M400();
  5329. break;
  5330. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && (HAS_SERVO_ENDSTOPS || ENABLED(Z_PROBE_ALLEN_KEY)) && DISABLED(Z_PROBE_SLED)
  5331. case 401:
  5332. gcode_M401();
  5333. break;
  5334. case 402:
  5335. gcode_M402();
  5336. break;
  5337. #endif // AUTO_BED_LEVELING_FEATURE && (HAS_SERVO_ENDSTOPS || Z_PROBE_ALLEN_KEY) && !Z_PROBE_SLED
  5338. #if ENABLED(FILAMENT_SENSOR)
  5339. case 404: //M404 Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  5340. gcode_M404();
  5341. break;
  5342. case 405: //M405 Turn on filament sensor for control
  5343. gcode_M405();
  5344. break;
  5345. case 406: //M406 Turn off filament sensor for control
  5346. gcode_M406();
  5347. break;
  5348. case 407: //M407 Display measured filament diameter
  5349. gcode_M407();
  5350. break;
  5351. #endif // FILAMENT_SENSOR
  5352. case 410: // M410 quickstop - Abort all the planned moves.
  5353. gcode_M410();
  5354. break;
  5355. #if ENABLED(MESH_BED_LEVELING)
  5356. case 420: // M420 Enable/Disable Mesh Bed Leveling
  5357. gcode_M420();
  5358. break;
  5359. case 421: // M421 Set a Mesh Bed Leveling Z coordinate
  5360. gcode_M421();
  5361. break;
  5362. #endif
  5363. case 428: // M428 Apply current_position to home_offset
  5364. gcode_M428();
  5365. break;
  5366. case 500: // M500 Store settings in EEPROM
  5367. gcode_M500();
  5368. break;
  5369. case 501: // M501 Read settings from EEPROM
  5370. gcode_M501();
  5371. break;
  5372. case 502: // M502 Revert to default settings
  5373. gcode_M502();
  5374. break;
  5375. case 503: // M503 print settings currently in memory
  5376. gcode_M503();
  5377. break;
  5378. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  5379. case 540:
  5380. gcode_M540();
  5381. break;
  5382. #endif
  5383. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  5384. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  5385. gcode_SET_Z_PROBE_OFFSET();
  5386. break;
  5387. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  5388. #if ENABLED(FILAMENTCHANGEENABLE)
  5389. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  5390. gcode_M600();
  5391. break;
  5392. #endif // FILAMENTCHANGEENABLE
  5393. #if ENABLED(DUAL_X_CARRIAGE)
  5394. case 605:
  5395. gcode_M605();
  5396. break;
  5397. #endif // DUAL_X_CARRIAGE
  5398. case 907: // M907 Set digital trimpot motor current using axis codes.
  5399. gcode_M907();
  5400. break;
  5401. #if HAS_DIGIPOTSS
  5402. case 908: // M908 Control digital trimpot directly.
  5403. gcode_M908();
  5404. break;
  5405. #endif // HAS_DIGIPOTSS
  5406. #if HAS_MICROSTEPS
  5407. case 350: // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  5408. gcode_M350();
  5409. break;
  5410. case 351: // M351 Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  5411. gcode_M351();
  5412. break;
  5413. #endif // HAS_MICROSTEPS
  5414. case 999: // M999: Restart after being Stopped
  5415. gcode_M999();
  5416. break;
  5417. }
  5418. break;
  5419. case 'T':
  5420. gcode_T(codenum);
  5421. break;
  5422. default: code_is_good = false;
  5423. }
  5424. KEEPALIVE_STATE(NOT_BUSY);
  5425. ExitUnknownCommand:
  5426. // Still unknown command? Throw an error
  5427. if (!code_is_good) unknown_command_error();
  5428. ok_to_send();
  5429. }
  5430. void FlushSerialRequestResend() {
  5431. //char command_queue[cmd_queue_index_r][100]="Resend:";
  5432. MYSERIAL.flush();
  5433. SERIAL_PROTOCOLPGM(MSG_RESEND);
  5434. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  5435. ok_to_send();
  5436. }
  5437. void ok_to_send() {
  5438. refresh_cmd_timeout();
  5439. if (!send_ok[cmd_queue_index_r]) return;
  5440. SERIAL_PROTOCOLPGM(MSG_OK);
  5441. #if ENABLED(ADVANCED_OK)
  5442. char* p = command_queue[cmd_queue_index_r];
  5443. if (*p == 'N') {
  5444. SERIAL_PROTOCOL(' ');
  5445. SERIAL_ECHO(*p++);
  5446. while ((*p >= '0' && *p <= '9') || *p == '-')
  5447. SERIAL_ECHO(*p++);
  5448. }
  5449. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - movesplanned() - 1));
  5450. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  5451. #endif
  5452. SERIAL_EOL;
  5453. }
  5454. void clamp_to_software_endstops(float target[3]) {
  5455. if (min_software_endstops) {
  5456. NOLESS(target[X_AXIS], min_pos[X_AXIS]);
  5457. NOLESS(target[Y_AXIS], min_pos[Y_AXIS]);
  5458. float negative_z_offset = 0;
  5459. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5460. if (zprobe_zoffset < 0) negative_z_offset += zprobe_zoffset;
  5461. if (home_offset[Z_AXIS] < 0) {
  5462. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5463. if (marlin_debug_flags & DEBUG_LEVELING) {
  5464. SERIAL_ECHOPAIR("> clamp_to_software_endstops > Add home_offset[Z_AXIS]:", home_offset[Z_AXIS]);
  5465. SERIAL_EOL;
  5466. }
  5467. #endif
  5468. negative_z_offset += home_offset[Z_AXIS];
  5469. }
  5470. #endif
  5471. NOLESS(target[Z_AXIS], min_pos[Z_AXIS] + negative_z_offset);
  5472. }
  5473. if (max_software_endstops) {
  5474. NOMORE(target[X_AXIS], max_pos[X_AXIS]);
  5475. NOMORE(target[Y_AXIS], max_pos[Y_AXIS]);
  5476. NOMORE(target[Z_AXIS], max_pos[Z_AXIS]);
  5477. }
  5478. }
  5479. #if ENABLED(DELTA)
  5480. void recalc_delta_settings(float radius, float diagonal_rod) {
  5481. delta_tower1_x = -SIN_60 * (radius + DELTA_RADIUS_TRIM_TOWER_1); // front left tower
  5482. delta_tower1_y = -COS_60 * (radius + DELTA_RADIUS_TRIM_TOWER_1);
  5483. delta_tower2_x = SIN_60 * (radius + DELTA_RADIUS_TRIM_TOWER_2); // front right tower
  5484. delta_tower2_y = -COS_60 * (radius + DELTA_RADIUS_TRIM_TOWER_2);
  5485. delta_tower3_x = 0.0; // back middle tower
  5486. delta_tower3_y = (radius + DELTA_RADIUS_TRIM_TOWER_3);
  5487. delta_diagonal_rod_2_tower_1 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_1);
  5488. delta_diagonal_rod_2_tower_2 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_2);
  5489. delta_diagonal_rod_2_tower_3 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_3);
  5490. }
  5491. void calculate_delta(float cartesian[3]) {
  5492. delta[TOWER_1] = sqrt(delta_diagonal_rod_2_tower_1
  5493. - sq(delta_tower1_x - cartesian[X_AXIS])
  5494. - sq(delta_tower1_y - cartesian[Y_AXIS])
  5495. ) + cartesian[Z_AXIS];
  5496. delta[TOWER_2] = sqrt(delta_diagonal_rod_2_tower_2
  5497. - sq(delta_tower2_x - cartesian[X_AXIS])
  5498. - sq(delta_tower2_y - cartesian[Y_AXIS])
  5499. ) + cartesian[Z_AXIS];
  5500. delta[TOWER_3] = sqrt(delta_diagonal_rod_2_tower_3
  5501. - sq(delta_tower3_x - cartesian[X_AXIS])
  5502. - sq(delta_tower3_y - cartesian[Y_AXIS])
  5503. ) + cartesian[Z_AXIS];
  5504. /*
  5505. SERIAL_ECHOPGM("cartesian x="); SERIAL_ECHO(cartesian[X_AXIS]);
  5506. SERIAL_ECHOPGM(" y="); SERIAL_ECHO(cartesian[Y_AXIS]);
  5507. SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(cartesian[Z_AXIS]);
  5508. SERIAL_ECHOPGM("delta a="); SERIAL_ECHO(delta[TOWER_1]);
  5509. SERIAL_ECHOPGM(" b="); SERIAL_ECHO(delta[TOWER_2]);
  5510. SERIAL_ECHOPGM(" c="); SERIAL_ECHOLN(delta[TOWER_3]);
  5511. */
  5512. }
  5513. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5514. // Adjust print surface height by linear interpolation over the bed_level array.
  5515. void adjust_delta(float cartesian[3]) {
  5516. if (delta_grid_spacing[0] == 0 || delta_grid_spacing[1] == 0) return; // G29 not done!
  5517. int half = (AUTO_BED_LEVELING_GRID_POINTS - 1) / 2;
  5518. float h1 = 0.001 - half, h2 = half - 0.001,
  5519. grid_x = max(h1, min(h2, cartesian[X_AXIS] / delta_grid_spacing[0])),
  5520. grid_y = max(h1, min(h2, cartesian[Y_AXIS] / delta_grid_spacing[1]));
  5521. int floor_x = floor(grid_x), floor_y = floor(grid_y);
  5522. float ratio_x = grid_x - floor_x, ratio_y = grid_y - floor_y,
  5523. z1 = bed_level[floor_x + half][floor_y + half],
  5524. z2 = bed_level[floor_x + half][floor_y + half + 1],
  5525. z3 = bed_level[floor_x + half + 1][floor_y + half],
  5526. z4 = bed_level[floor_x + half + 1][floor_y + half + 1],
  5527. left = (1 - ratio_y) * z1 + ratio_y * z2,
  5528. right = (1 - ratio_y) * z3 + ratio_y * z4,
  5529. offset = (1 - ratio_x) * left + ratio_x * right;
  5530. delta[X_AXIS] += offset;
  5531. delta[Y_AXIS] += offset;
  5532. delta[Z_AXIS] += offset;
  5533. /*
  5534. SERIAL_ECHOPGM("grid_x="); SERIAL_ECHO(grid_x);
  5535. SERIAL_ECHOPGM(" grid_y="); SERIAL_ECHO(grid_y);
  5536. SERIAL_ECHOPGM(" floor_x="); SERIAL_ECHO(floor_x);
  5537. SERIAL_ECHOPGM(" floor_y="); SERIAL_ECHO(floor_y);
  5538. SERIAL_ECHOPGM(" ratio_x="); SERIAL_ECHO(ratio_x);
  5539. SERIAL_ECHOPGM(" ratio_y="); SERIAL_ECHO(ratio_y);
  5540. SERIAL_ECHOPGM(" z1="); SERIAL_ECHO(z1);
  5541. SERIAL_ECHOPGM(" z2="); SERIAL_ECHO(z2);
  5542. SERIAL_ECHOPGM(" z3="); SERIAL_ECHO(z3);
  5543. SERIAL_ECHOPGM(" z4="); SERIAL_ECHO(z4);
  5544. SERIAL_ECHOPGM(" left="); SERIAL_ECHO(left);
  5545. SERIAL_ECHOPGM(" right="); SERIAL_ECHO(right);
  5546. SERIAL_ECHOPGM(" offset="); SERIAL_ECHOLN(offset);
  5547. */
  5548. }
  5549. #endif // AUTO_BED_LEVELING_FEATURE
  5550. #endif // DELTA
  5551. #if ENABLED(MESH_BED_LEVELING)
  5552. // This function is used to split lines on mesh borders so each segment is only part of one mesh area
  5553. void mesh_plan_buffer_line(float x, float y, float z, const float e, float feed_rate, const uint8_t& extruder, uint8_t x_splits = 0xff, uint8_t y_splits = 0xff) {
  5554. if (!mbl.active) {
  5555. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  5556. set_current_to_destination();
  5557. return;
  5558. }
  5559. int pix = mbl.select_x_index(current_position[X_AXIS]);
  5560. int piy = mbl.select_y_index(current_position[Y_AXIS]);
  5561. int ix = mbl.select_x_index(x);
  5562. int iy = mbl.select_y_index(y);
  5563. pix = min(pix, MESH_NUM_X_POINTS - 2);
  5564. piy = min(piy, MESH_NUM_Y_POINTS - 2);
  5565. ix = min(ix, MESH_NUM_X_POINTS - 2);
  5566. iy = min(iy, MESH_NUM_Y_POINTS - 2);
  5567. if (pix == ix && piy == iy) {
  5568. // Start and end on same mesh square
  5569. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  5570. set_current_to_destination();
  5571. return;
  5572. }
  5573. float nx, ny, nz, ne, normalized_dist;
  5574. if (ix > pix && TEST(x_splits, ix)) {
  5575. nx = mbl.get_x(ix);
  5576. normalized_dist = (nx - current_position[X_AXIS]) / (x - current_position[X_AXIS]);
  5577. ny = current_position[Y_AXIS] + (y - current_position[Y_AXIS]) * normalized_dist;
  5578. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  5579. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  5580. CBI(x_splits, ix);
  5581. }
  5582. else if (ix < pix && TEST(x_splits, pix)) {
  5583. nx = mbl.get_x(pix);
  5584. normalized_dist = (nx - current_position[X_AXIS]) / (x - current_position[X_AXIS]);
  5585. ny = current_position[Y_AXIS] + (y - current_position[Y_AXIS]) * normalized_dist;
  5586. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  5587. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  5588. CBI(x_splits, pix);
  5589. }
  5590. else if (iy > piy && TEST(y_splits, iy)) {
  5591. ny = mbl.get_y(iy);
  5592. normalized_dist = (ny - current_position[Y_AXIS]) / (y - current_position[Y_AXIS]);
  5593. nx = current_position[X_AXIS] + (x - current_position[X_AXIS]) * normalized_dist;
  5594. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  5595. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  5596. CBI(y_splits, iy);
  5597. }
  5598. else if (iy < piy && TEST(y_splits, piy)) {
  5599. ny = mbl.get_y(piy);
  5600. normalized_dist = (ny - current_position[Y_AXIS]) / (y - current_position[Y_AXIS]);
  5601. nx = current_position[X_AXIS] + (x - current_position[X_AXIS]) * normalized_dist;
  5602. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  5603. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  5604. CBI(y_splits, piy);
  5605. }
  5606. else {
  5607. // Already split on a border
  5608. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  5609. set_current_to_destination();
  5610. return;
  5611. }
  5612. // Do the split and look for more borders
  5613. destination[X_AXIS] = nx;
  5614. destination[Y_AXIS] = ny;
  5615. destination[Z_AXIS] = nz;
  5616. destination[E_AXIS] = ne;
  5617. mesh_plan_buffer_line(nx, ny, nz, ne, feed_rate, extruder, x_splits, y_splits);
  5618. destination[X_AXIS] = x;
  5619. destination[Y_AXIS] = y;
  5620. destination[Z_AXIS] = z;
  5621. destination[E_AXIS] = e;
  5622. mesh_plan_buffer_line(x, y, z, e, feed_rate, extruder, x_splits, y_splits);
  5623. }
  5624. #endif // MESH_BED_LEVELING
  5625. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  5626. inline void prevent_dangerous_extrude(float& curr_e, float& dest_e) {
  5627. if (marlin_debug_flags & DEBUG_DRYRUN) return;
  5628. float de = dest_e - curr_e;
  5629. if (de) {
  5630. if (degHotend(active_extruder) < extrude_min_temp) {
  5631. curr_e = dest_e; // Behave as if the move really took place, but ignore E part
  5632. SERIAL_ECHO_START;
  5633. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  5634. }
  5635. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  5636. if (labs(de) > EXTRUDE_MAXLENGTH) {
  5637. curr_e = dest_e; // Behave as if the move really took place, but ignore E part
  5638. SERIAL_ECHO_START;
  5639. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  5640. }
  5641. #endif
  5642. }
  5643. }
  5644. #endif // PREVENT_DANGEROUS_EXTRUDE
  5645. #if ENABLED(DELTA) || ENABLED(SCARA)
  5646. inline bool prepare_move_delta(float target[NUM_AXIS]) {
  5647. float difference[NUM_AXIS];
  5648. for (int8_t i = 0; i < NUM_AXIS; i++) difference[i] = target[i] - current_position[i];
  5649. float cartesian_mm = sqrt(sq(difference[X_AXIS]) + sq(difference[Y_AXIS]) + sq(difference[Z_AXIS]));
  5650. if (cartesian_mm < 0.000001) cartesian_mm = abs(difference[E_AXIS]);
  5651. if (cartesian_mm < 0.000001) return false;
  5652. float seconds = 6000 * cartesian_mm / feedrate / feedrate_multiplier;
  5653. int steps = max(1, int(delta_segments_per_second * seconds));
  5654. // SERIAL_ECHOPGM("mm="); SERIAL_ECHO(cartesian_mm);
  5655. // SERIAL_ECHOPGM(" seconds="); SERIAL_ECHO(seconds);
  5656. // SERIAL_ECHOPGM(" steps="); SERIAL_ECHOLN(steps);
  5657. for (int s = 1; s <= steps; s++) {
  5658. float fraction = float(s) / float(steps);
  5659. for (int8_t i = 0; i < NUM_AXIS; i++)
  5660. target[i] = current_position[i] + difference[i] * fraction;
  5661. calculate_delta(target);
  5662. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5663. adjust_delta(target);
  5664. #endif
  5665. //SERIAL_ECHOPGM("target[X_AXIS]="); SERIAL_ECHOLN(target[X_AXIS]);
  5666. //SERIAL_ECHOPGM("target[Y_AXIS]="); SERIAL_ECHOLN(target[Y_AXIS]);
  5667. //SERIAL_ECHOPGM("target[Z_AXIS]="); SERIAL_ECHOLN(target[Z_AXIS]);
  5668. //SERIAL_ECHOPGM("delta[X_AXIS]="); SERIAL_ECHOLN(delta[X_AXIS]);
  5669. //SERIAL_ECHOPGM("delta[Y_AXIS]="); SERIAL_ECHOLN(delta[Y_AXIS]);
  5670. //SERIAL_ECHOPGM("delta[Z_AXIS]="); SERIAL_ECHOLN(delta[Z_AXIS]);
  5671. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], target[E_AXIS], feedrate / 60 * feedrate_multiplier / 100.0, active_extruder);
  5672. }
  5673. return true;
  5674. }
  5675. #endif // DELTA || SCARA
  5676. #if ENABLED(SCARA)
  5677. inline bool prepare_move_scara(float target[NUM_AXIS]) { return prepare_move_delta(target); }
  5678. #endif
  5679. #if ENABLED(DUAL_X_CARRIAGE)
  5680. inline bool prepare_move_dual_x_carriage() {
  5681. if (active_extruder_parked) {
  5682. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && active_extruder == 0) {
  5683. // move duplicate extruder into correct duplication position.
  5684. plan_set_position(inactive_extruder_x_pos, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  5685. plan_buffer_line(current_position[X_AXIS] + duplicate_extruder_x_offset,
  5686. current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], max_feedrate[X_AXIS], 1);
  5687. sync_plan_position();
  5688. st_synchronize();
  5689. extruder_duplication_enabled = true;
  5690. active_extruder_parked = false;
  5691. }
  5692. else if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) { // handle unparking of head
  5693. if (current_position[E_AXIS] == destination[E_AXIS]) {
  5694. // This is a travel move (with no extrusion)
  5695. // Skip it, but keep track of the current position
  5696. // (so it can be used as the start of the next non-travel move)
  5697. if (delayed_move_time != 0xFFFFFFFFUL) {
  5698. set_current_to_destination();
  5699. NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]);
  5700. delayed_move_time = millis();
  5701. return false;
  5702. }
  5703. }
  5704. delayed_move_time = 0;
  5705. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  5706. plan_buffer_line(raised_parked_position[X_AXIS], raised_parked_position[Y_AXIS], raised_parked_position[Z_AXIS], current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  5707. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], raised_parked_position[Z_AXIS], current_position[E_AXIS], min(max_feedrate[X_AXIS], max_feedrate[Y_AXIS]), active_extruder);
  5708. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  5709. active_extruder_parked = false;
  5710. }
  5711. }
  5712. return true;
  5713. }
  5714. #endif // DUAL_X_CARRIAGE
  5715. #if DISABLED(DELTA) && DISABLED(SCARA)
  5716. inline bool prepare_move_cartesian() {
  5717. // Do not use feedrate_multiplier for E or Z only moves
  5718. if (current_position[X_AXIS] == destination[X_AXIS] && current_position[Y_AXIS] == destination[Y_AXIS]) {
  5719. line_to_destination();
  5720. }
  5721. else {
  5722. #if ENABLED(MESH_BED_LEVELING)
  5723. mesh_plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], (feedrate / 60) * (feedrate_multiplier / 100.0), active_extruder);
  5724. return false;
  5725. #else
  5726. line_to_destination(feedrate * feedrate_multiplier / 100.0);
  5727. #endif
  5728. }
  5729. return true;
  5730. }
  5731. #endif // !DELTA && !SCARA
  5732. /**
  5733. * Prepare a single move and get ready for the next one
  5734. *
  5735. * (This may call plan_buffer_line several times to put
  5736. * smaller moves into the planner for DELTA or SCARA.)
  5737. */
  5738. void prepare_move() {
  5739. clamp_to_software_endstops(destination);
  5740. refresh_cmd_timeout();
  5741. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  5742. prevent_dangerous_extrude(current_position[E_AXIS], destination[E_AXIS]);
  5743. #endif
  5744. #if ENABLED(SCARA)
  5745. if (!prepare_move_scara(destination)) return;
  5746. #elif ENABLED(DELTA)
  5747. if (!prepare_move_delta(destination)) return;
  5748. #endif
  5749. #if ENABLED(DUAL_X_CARRIAGE)
  5750. if (!prepare_move_dual_x_carriage()) return;
  5751. #endif
  5752. #if DISABLED(DELTA) && DISABLED(SCARA)
  5753. if (!prepare_move_cartesian()) return;
  5754. #endif
  5755. set_current_to_destination();
  5756. }
  5757. /**
  5758. * Plan an arc in 2 dimensions
  5759. *
  5760. * The arc is approximated by generating many small linear segments.
  5761. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm)
  5762. * Arcs should only be made relatively large (over 5mm), as larger arcs with
  5763. * larger segments will tend to be more efficient. Your slicer should have
  5764. * options for G2/G3 arc generation. In future these options may be GCode tunable.
  5765. */
  5766. void plan_arc(
  5767. float target[NUM_AXIS], // Destination position
  5768. float* offset, // Center of rotation relative to current_position
  5769. uint8_t clockwise // Clockwise?
  5770. ) {
  5771. float radius = hypot(offset[X_AXIS], offset[Y_AXIS]),
  5772. center_axis0 = current_position[X_AXIS] + offset[X_AXIS],
  5773. center_axis1 = current_position[Y_AXIS] + offset[Y_AXIS],
  5774. linear_travel = target[Z_AXIS] - current_position[Z_AXIS],
  5775. extruder_travel = target[E_AXIS] - current_position[E_AXIS],
  5776. r_axis0 = -offset[X_AXIS], // Radius vector from center to current location
  5777. r_axis1 = -offset[Y_AXIS],
  5778. rt_axis0 = target[X_AXIS] - center_axis0,
  5779. rt_axis1 = target[Y_AXIS] - center_axis1;
  5780. // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required.
  5781. float angular_travel = atan2(r_axis0 * rt_axis1 - r_axis1 * rt_axis0, r_axis0 * rt_axis0 + r_axis1 * rt_axis1);
  5782. if (angular_travel < 0) angular_travel += RADIANS(360);
  5783. if (clockwise) angular_travel -= RADIANS(360);
  5784. // Make a circle if the angular rotation is 0
  5785. if (current_position[X_AXIS] == target[X_AXIS] && current_position[Y_AXIS] == target[Y_AXIS] && angular_travel == 0)
  5786. angular_travel += RADIANS(360);
  5787. float mm_of_travel = hypot(angular_travel * radius, fabs(linear_travel));
  5788. if (mm_of_travel < 0.001) return;
  5789. uint16_t segments = floor(mm_of_travel / (MM_PER_ARC_SEGMENT));
  5790. if (segments == 0) segments = 1;
  5791. float theta_per_segment = angular_travel / segments;
  5792. float linear_per_segment = linear_travel / segments;
  5793. float extruder_per_segment = extruder_travel / segments;
  5794. /* Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
  5795. and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
  5796. r_T = [cos(phi) -sin(phi);
  5797. sin(phi) cos(phi] * r ;
  5798. For arc generation, the center of the circle is the axis of rotation and the radius vector is
  5799. defined from the circle center to the initial position. Each line segment is formed by successive
  5800. vector rotations. This requires only two cos() and sin() computations to form the rotation
  5801. matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
  5802. all double numbers are single precision on the Arduino. (True double precision will not have
  5803. round off issues for CNC applications.) Single precision error can accumulate to be greater than
  5804. tool precision in some cases. Therefore, arc path correction is implemented.
  5805. Small angle approximation may be used to reduce computation overhead further. This approximation
  5806. holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words,
  5807. theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
  5808. to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
  5809. numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
  5810. issue for CNC machines with the single precision Arduino calculations.
  5811. This approximation also allows plan_arc to immediately insert a line segment into the planner
  5812. without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
  5813. a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead.
  5814. This is important when there are successive arc motions.
  5815. */
  5816. // Vector rotation matrix values
  5817. float cos_T = 1 - 0.5 * theta_per_segment * theta_per_segment; // Small angle approximation
  5818. float sin_T = theta_per_segment;
  5819. float arc_target[NUM_AXIS];
  5820. float sin_Ti;
  5821. float cos_Ti;
  5822. float r_axisi;
  5823. uint16_t i;
  5824. int8_t count = 0;
  5825. // Initialize the linear axis
  5826. arc_target[Z_AXIS] = current_position[Z_AXIS];
  5827. // Initialize the extruder axis
  5828. arc_target[E_AXIS] = current_position[E_AXIS];
  5829. float feed_rate = feedrate * feedrate_multiplier / 60 / 100.0;
  5830. for (i = 1; i < segments; i++) { // Increment (segments-1)
  5831. if (count < N_ARC_CORRECTION) {
  5832. // Apply vector rotation matrix to previous r_axis0 / 1
  5833. r_axisi = r_axis0 * sin_T + r_axis1 * cos_T;
  5834. r_axis0 = r_axis0 * cos_T - r_axis1 * sin_T;
  5835. r_axis1 = r_axisi;
  5836. count++;
  5837. }
  5838. else {
  5839. // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
  5840. // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
  5841. cos_Ti = cos(i * theta_per_segment);
  5842. sin_Ti = sin(i * theta_per_segment);
  5843. r_axis0 = -offset[X_AXIS] * cos_Ti + offset[Y_AXIS] * sin_Ti;
  5844. r_axis1 = -offset[X_AXIS] * sin_Ti - offset[Y_AXIS] * cos_Ti;
  5845. count = 0;
  5846. }
  5847. // Update arc_target location
  5848. arc_target[X_AXIS] = center_axis0 + r_axis0;
  5849. arc_target[Y_AXIS] = center_axis1 + r_axis1;
  5850. arc_target[Z_AXIS] += linear_per_segment;
  5851. arc_target[E_AXIS] += extruder_per_segment;
  5852. clamp_to_software_endstops(arc_target);
  5853. #if ENABLED(DELTA) || ENABLED(SCARA)
  5854. calculate_delta(arc_target);
  5855. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5856. adjust_delta(arc_target);
  5857. #endif
  5858. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], arc_target[E_AXIS], feed_rate, active_extruder);
  5859. #else
  5860. plan_buffer_line(arc_target[X_AXIS], arc_target[Y_AXIS], arc_target[Z_AXIS], arc_target[E_AXIS], feed_rate, active_extruder);
  5861. #endif
  5862. }
  5863. // Ensure last segment arrives at target location.
  5864. #if ENABLED(DELTA) || ENABLED(SCARA)
  5865. calculate_delta(target);
  5866. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5867. adjust_delta(target);
  5868. #endif
  5869. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], target[E_AXIS], feed_rate, active_extruder);
  5870. #else
  5871. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], feed_rate, active_extruder);
  5872. #endif
  5873. // As far as the parser is concerned, the position is now == target. In reality the
  5874. // motion control system might still be processing the action and the real tool position
  5875. // in any intermediate location.
  5876. set_current_to_destination();
  5877. }
  5878. #if HAS_CONTROLLERFAN
  5879. void controllerFan() {
  5880. static millis_t lastMotor = 0; // Last time a motor was turned on
  5881. static millis_t lastMotorCheck = 0; // Last time the state was checked
  5882. millis_t ms = millis();
  5883. if (ms >= lastMotorCheck + 2500) { // Not a time critical function, so we only check every 2500ms
  5884. lastMotorCheck = ms;
  5885. if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON || soft_pwm_bed > 0
  5886. || E0_ENABLE_READ == E_ENABLE_ON // If any of the drivers are enabled...
  5887. #if EXTRUDERS > 1
  5888. || E1_ENABLE_READ == E_ENABLE_ON
  5889. #if HAS_X2_ENABLE
  5890. || X2_ENABLE_READ == X_ENABLE_ON
  5891. #endif
  5892. #if EXTRUDERS > 2
  5893. || E2_ENABLE_READ == E_ENABLE_ON
  5894. #if EXTRUDERS > 3
  5895. || E3_ENABLE_READ == E_ENABLE_ON
  5896. #endif
  5897. #endif
  5898. #endif
  5899. ) {
  5900. lastMotor = ms; //... set time to NOW so the fan will turn on
  5901. }
  5902. uint8_t speed = (lastMotor == 0 || ms >= lastMotor + ((CONTROLLERFAN_SECS) * 1000UL)) ? 0 : CONTROLLERFAN_SPEED;
  5903. // allows digital or PWM fan output to be used (see M42 handling)
  5904. digitalWrite(CONTROLLERFAN_PIN, speed);
  5905. analogWrite(CONTROLLERFAN_PIN, speed);
  5906. }
  5907. }
  5908. #endif // HAS_CONTROLLERFAN
  5909. #if ENABLED(SCARA)
  5910. void calculate_SCARA_forward_Transform(float f_scara[3]) {
  5911. // Perform forward kinematics, and place results in delta[3]
  5912. // The maths and first version has been done by QHARLEY . Integrated into masterbranch 06/2014 and slightly restructured by Joachim Cerny in June 2014
  5913. float x_sin, x_cos, y_sin, y_cos;
  5914. //SERIAL_ECHOPGM("f_delta x="); SERIAL_ECHO(f_scara[X_AXIS]);
  5915. //SERIAL_ECHOPGM(" y="); SERIAL_ECHO(f_scara[Y_AXIS]);
  5916. x_sin = sin(f_scara[X_AXIS] / SCARA_RAD2DEG) * Linkage_1;
  5917. x_cos = cos(f_scara[X_AXIS] / SCARA_RAD2DEG) * Linkage_1;
  5918. y_sin = sin(f_scara[Y_AXIS] / SCARA_RAD2DEG) * Linkage_2;
  5919. y_cos = cos(f_scara[Y_AXIS] / SCARA_RAD2DEG) * Linkage_2;
  5920. //SERIAL_ECHOPGM(" x_sin="); SERIAL_ECHO(x_sin);
  5921. //SERIAL_ECHOPGM(" x_cos="); SERIAL_ECHO(x_cos);
  5922. //SERIAL_ECHOPGM(" y_sin="); SERIAL_ECHO(y_sin);
  5923. //SERIAL_ECHOPGM(" y_cos="); SERIAL_ECHOLN(y_cos);
  5924. delta[X_AXIS] = x_cos + y_cos + SCARA_offset_x; //theta
  5925. delta[Y_AXIS] = x_sin + y_sin + SCARA_offset_y; //theta+phi
  5926. //SERIAL_ECHOPGM(" delta[X_AXIS]="); SERIAL_ECHO(delta[X_AXIS]);
  5927. //SERIAL_ECHOPGM(" delta[Y_AXIS]="); SERIAL_ECHOLN(delta[Y_AXIS]);
  5928. }
  5929. void calculate_delta(float cartesian[3]) {
  5930. //reverse kinematics.
  5931. // Perform reversed kinematics, and place results in delta[3]
  5932. // The maths and first version has been done by QHARLEY . Integrated into masterbranch 06/2014 and slightly restructured by Joachim Cerny in June 2014
  5933. float SCARA_pos[2];
  5934. static float SCARA_C2, SCARA_S2, SCARA_K1, SCARA_K2, SCARA_theta, SCARA_psi;
  5935. SCARA_pos[X_AXIS] = cartesian[X_AXIS] * axis_scaling[X_AXIS] - SCARA_offset_x; //Translate SCARA to standard X Y
  5936. SCARA_pos[Y_AXIS] = cartesian[Y_AXIS] * axis_scaling[Y_AXIS] - SCARA_offset_y; // With scaling factor.
  5937. #if (Linkage_1 == Linkage_2)
  5938. SCARA_C2 = ((sq(SCARA_pos[X_AXIS]) + sq(SCARA_pos[Y_AXIS])) / (2 * (float)L1_2)) - 1;
  5939. #else
  5940. SCARA_C2 = (sq(SCARA_pos[X_AXIS]) + sq(SCARA_pos[Y_AXIS]) - (float)L1_2 - (float)L2_2) / 45000;
  5941. #endif
  5942. SCARA_S2 = sqrt(1 - sq(SCARA_C2));
  5943. SCARA_K1 = Linkage_1 + Linkage_2 * SCARA_C2;
  5944. SCARA_K2 = Linkage_2 * SCARA_S2;
  5945. SCARA_theta = (atan2(SCARA_pos[X_AXIS], SCARA_pos[Y_AXIS]) - atan2(SCARA_K1, SCARA_K2)) * -1;
  5946. SCARA_psi = atan2(SCARA_S2, SCARA_C2);
  5947. delta[X_AXIS] = SCARA_theta * SCARA_RAD2DEG; // Multiply by 180/Pi - theta is support arm angle
  5948. delta[Y_AXIS] = (SCARA_theta + SCARA_psi) * SCARA_RAD2DEG; // - equal to sub arm angle (inverted motor)
  5949. delta[Z_AXIS] = cartesian[Z_AXIS];
  5950. /*
  5951. SERIAL_ECHOPGM("cartesian x="); SERIAL_ECHO(cartesian[X_AXIS]);
  5952. SERIAL_ECHOPGM(" y="); SERIAL_ECHO(cartesian[Y_AXIS]);
  5953. SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(cartesian[Z_AXIS]);
  5954. SERIAL_ECHOPGM("scara x="); SERIAL_ECHO(SCARA_pos[X_AXIS]);
  5955. SERIAL_ECHOPGM(" y="); SERIAL_ECHOLN(SCARA_pos[Y_AXIS]);
  5956. SERIAL_ECHOPGM("delta x="); SERIAL_ECHO(delta[X_AXIS]);
  5957. SERIAL_ECHOPGM(" y="); SERIAL_ECHO(delta[Y_AXIS]);
  5958. SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(delta[Z_AXIS]);
  5959. SERIAL_ECHOPGM("C2="); SERIAL_ECHO(SCARA_C2);
  5960. SERIAL_ECHOPGM(" S2="); SERIAL_ECHO(SCARA_S2);
  5961. SERIAL_ECHOPGM(" Theta="); SERIAL_ECHO(SCARA_theta);
  5962. SERIAL_ECHOPGM(" Psi="); SERIAL_ECHOLN(SCARA_psi);
  5963. SERIAL_EOL;
  5964. */
  5965. }
  5966. #endif // SCARA
  5967. #if ENABLED(TEMP_STAT_LEDS)
  5968. static bool red_led = false;
  5969. static millis_t next_status_led_update_ms = 0;
  5970. void handle_status_leds(void) {
  5971. float max_temp = 0.0;
  5972. if (millis() > next_status_led_update_ms) {
  5973. next_status_led_update_ms += 500; // Update every 0.5s
  5974. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder)
  5975. max_temp = max(max(max_temp, degHotend(cur_extruder)), degTargetHotend(cur_extruder));
  5976. #if HAS_TEMP_BED
  5977. max_temp = max(max(max_temp, degTargetBed()), degBed());
  5978. #endif
  5979. bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led;
  5980. if (new_led != red_led) {
  5981. red_led = new_led;
  5982. digitalWrite(STAT_LED_RED, new_led ? HIGH : LOW);
  5983. digitalWrite(STAT_LED_BLUE, new_led ? LOW : HIGH);
  5984. }
  5985. }
  5986. }
  5987. #endif
  5988. void enable_all_steppers() {
  5989. enable_x();
  5990. enable_y();
  5991. enable_z();
  5992. enable_e0();
  5993. enable_e1();
  5994. enable_e2();
  5995. enable_e3();
  5996. }
  5997. void disable_all_steppers() {
  5998. disable_x();
  5999. disable_y();
  6000. disable_z();
  6001. disable_e0();
  6002. disable_e1();
  6003. disable_e2();
  6004. disable_e3();
  6005. }
  6006. /**
  6007. * Standard idle routine keeps the machine alive
  6008. */
  6009. void idle(
  6010. #if ENABLED(FILAMENTCHANGEENABLE)
  6011. bool no_stepper_sleep/*=false*/
  6012. #endif
  6013. ) {
  6014. manage_heater();
  6015. manage_inactivity(
  6016. #if ENABLED(FILAMENTCHANGEENABLE)
  6017. no_stepper_sleep
  6018. #endif
  6019. );
  6020. host_keepalive();
  6021. lcd_update();
  6022. }
  6023. /**
  6024. * Manage several activities:
  6025. * - Check for Filament Runout
  6026. * - Keep the command buffer full
  6027. * - Check for maximum inactive time between commands
  6028. * - Check for maximum inactive time between stepper commands
  6029. * - Check if pin CHDK needs to go LOW
  6030. * - Check for KILL button held down
  6031. * - Check for HOME button held down
  6032. * - Check if cooling fan needs to be switched on
  6033. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  6034. */
  6035. void manage_inactivity(bool ignore_stepper_queue/*=false*/) {
  6036. #if HAS_FILRUNOUT
  6037. if (IS_SD_PRINTING && !(READ(FILRUNOUT_PIN) ^ FIL_RUNOUT_INVERTING))
  6038. filrunout();
  6039. #endif
  6040. if (commands_in_queue < BUFSIZE) get_command();
  6041. millis_t ms = millis();
  6042. if (max_inactive_time && ms > previous_cmd_ms + max_inactive_time) kill(PSTR(MSG_KILLED));
  6043. if (stepper_inactive_time && ms > previous_cmd_ms + stepper_inactive_time
  6044. && !ignore_stepper_queue && !blocks_queued()) {
  6045. #if ENABLED(DISABLE_INACTIVE_X)
  6046. disable_x();
  6047. #endif
  6048. #if ENABLED(DISABLE_INACTIVE_Y)
  6049. disable_y();
  6050. #endif
  6051. #if ENABLED(DISABLE_INACTIVE_Z)
  6052. disable_z();
  6053. #endif
  6054. #if ENABLED(DISABLE_INACTIVE_E)
  6055. disable_e0();
  6056. disable_e1();
  6057. disable_e2();
  6058. disable_e3();
  6059. #endif
  6060. }
  6061. #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH
  6062. if (chdkActive && ms > chdkHigh + CHDK_DELAY) {
  6063. chdkActive = false;
  6064. WRITE(CHDK, LOW);
  6065. }
  6066. #endif
  6067. #if HAS_KILL
  6068. // Check if the kill button was pressed and wait just in case it was an accidental
  6069. // key kill key press
  6070. // -------------------------------------------------------------------------------
  6071. static int killCount = 0; // make the inactivity button a bit less responsive
  6072. const int KILL_DELAY = 750;
  6073. if (!READ(KILL_PIN))
  6074. killCount++;
  6075. else if (killCount > 0)
  6076. killCount--;
  6077. // Exceeded threshold and we can confirm that it was not accidental
  6078. // KILL the machine
  6079. // ----------------------------------------------------------------
  6080. if (killCount >= KILL_DELAY) kill(PSTR(MSG_KILLED));
  6081. #endif
  6082. #if HAS_HOME
  6083. // Check to see if we have to home, use poor man's debouncer
  6084. // ---------------------------------------------------------
  6085. static int homeDebounceCount = 0; // poor man's debouncing count
  6086. const int HOME_DEBOUNCE_DELAY = 2500;
  6087. if (!READ(HOME_PIN)) {
  6088. if (!homeDebounceCount) {
  6089. enqueue_and_echo_commands_P(PSTR("G28"));
  6090. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  6091. }
  6092. if (homeDebounceCount < HOME_DEBOUNCE_DELAY)
  6093. homeDebounceCount++;
  6094. else
  6095. homeDebounceCount = 0;
  6096. }
  6097. #endif
  6098. #if HAS_CONTROLLERFAN
  6099. controllerFan(); // Check if fan should be turned on to cool stepper drivers down
  6100. #endif
  6101. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  6102. if (ms > previous_cmd_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000)
  6103. if (degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP) {
  6104. bool oldstatus;
  6105. switch (active_extruder) {
  6106. case 0:
  6107. oldstatus = E0_ENABLE_READ;
  6108. enable_e0();
  6109. break;
  6110. #if EXTRUDERS > 1
  6111. case 1:
  6112. oldstatus = E1_ENABLE_READ;
  6113. enable_e1();
  6114. break;
  6115. #if EXTRUDERS > 2
  6116. case 2:
  6117. oldstatus = E2_ENABLE_READ;
  6118. enable_e2();
  6119. break;
  6120. #if EXTRUDERS > 3
  6121. case 3:
  6122. oldstatus = E3_ENABLE_READ;
  6123. enable_e3();
  6124. break;
  6125. #endif
  6126. #endif
  6127. #endif
  6128. }
  6129. float oldepos = current_position[E_AXIS], oldedes = destination[E_AXIS];
  6130. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  6131. destination[E_AXIS] + (EXTRUDER_RUNOUT_EXTRUDE) * (EXTRUDER_RUNOUT_ESTEPS) / axis_steps_per_unit[E_AXIS],
  6132. (EXTRUDER_RUNOUT_SPEED) / 60. * (EXTRUDER_RUNOUT_ESTEPS) / axis_steps_per_unit[E_AXIS], active_extruder);
  6133. current_position[E_AXIS] = oldepos;
  6134. destination[E_AXIS] = oldedes;
  6135. plan_set_e_position(oldepos);
  6136. previous_cmd_ms = ms; // refresh_cmd_timeout()
  6137. st_synchronize();
  6138. switch (active_extruder) {
  6139. case 0:
  6140. E0_ENABLE_WRITE(oldstatus);
  6141. break;
  6142. #if EXTRUDERS > 1
  6143. case 1:
  6144. E1_ENABLE_WRITE(oldstatus);
  6145. break;
  6146. #if EXTRUDERS > 2
  6147. case 2:
  6148. E2_ENABLE_WRITE(oldstatus);
  6149. break;
  6150. #if EXTRUDERS > 3
  6151. case 3:
  6152. E3_ENABLE_WRITE(oldstatus);
  6153. break;
  6154. #endif
  6155. #endif
  6156. #endif
  6157. }
  6158. }
  6159. #endif
  6160. #if ENABLED(DUAL_X_CARRIAGE)
  6161. // handle delayed move timeout
  6162. if (delayed_move_time && ms > delayed_move_time + 1000 && IsRunning()) {
  6163. // travel moves have been received so enact them
  6164. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  6165. set_destination_to_current();
  6166. prepare_move();
  6167. }
  6168. #endif
  6169. #if ENABLED(TEMP_STAT_LEDS)
  6170. handle_status_leds();
  6171. #endif
  6172. check_axes_activity();
  6173. }
  6174. void kill(const char* lcd_msg) {
  6175. #if ENABLED(ULTRA_LCD)
  6176. lcd_setalertstatuspgm(lcd_msg);
  6177. #else
  6178. UNUSED(lcd_msg);
  6179. #endif
  6180. cli(); // Stop interrupts
  6181. disable_all_heaters();
  6182. disable_all_steppers();
  6183. #if HAS_POWER_SWITCH
  6184. pinMode(PS_ON_PIN, INPUT);
  6185. #endif
  6186. SERIAL_ERROR_START;
  6187. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  6188. // FMC small patch to update the LCD before ending
  6189. sei(); // enable interrupts
  6190. for (int i = 5; i--; lcd_update()) delay(200); // Wait a short time
  6191. cli(); // disable interrupts
  6192. suicide();
  6193. while (1) {
  6194. #if ENABLED(USE_WATCHDOG)
  6195. watchdog_reset();
  6196. #endif
  6197. } // Wait for reset
  6198. }
  6199. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  6200. void filrunout() {
  6201. if (!filrunoutEnqueued) {
  6202. filrunoutEnqueued = true;
  6203. enqueue_and_echo_commands_P(PSTR(FILAMENT_RUNOUT_SCRIPT));
  6204. st_synchronize();
  6205. }
  6206. }
  6207. #endif // FILAMENT_RUNOUT_SENSOR
  6208. #if ENABLED(FAST_PWM_FAN)
  6209. void setPwmFrequency(uint8_t pin, int val) {
  6210. val &= 0x07;
  6211. switch (digitalPinToTimer(pin)) {
  6212. #if defined(TCCR0A)
  6213. case TIMER0A:
  6214. case TIMER0B:
  6215. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  6216. // TCCR0B |= val;
  6217. break;
  6218. #endif
  6219. #if defined(TCCR1A)
  6220. case TIMER1A:
  6221. case TIMER1B:
  6222. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  6223. // TCCR1B |= val;
  6224. break;
  6225. #endif
  6226. #if defined(TCCR2)
  6227. case TIMER2:
  6228. case TIMER2:
  6229. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  6230. TCCR2 |= val;
  6231. break;
  6232. #endif
  6233. #if defined(TCCR2A)
  6234. case TIMER2A:
  6235. case TIMER2B:
  6236. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  6237. TCCR2B |= val;
  6238. break;
  6239. #endif
  6240. #if defined(TCCR3A)
  6241. case TIMER3A:
  6242. case TIMER3B:
  6243. case TIMER3C:
  6244. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  6245. TCCR3B |= val;
  6246. break;
  6247. #endif
  6248. #if defined(TCCR4A)
  6249. case TIMER4A:
  6250. case TIMER4B:
  6251. case TIMER4C:
  6252. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  6253. TCCR4B |= val;
  6254. break;
  6255. #endif
  6256. #if defined(TCCR5A)
  6257. case TIMER5A:
  6258. case TIMER5B:
  6259. case TIMER5C:
  6260. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  6261. TCCR5B |= val;
  6262. break;
  6263. #endif
  6264. }
  6265. }
  6266. #endif // FAST_PWM_FAN
  6267. void Stop() {
  6268. disable_all_heaters();
  6269. if (IsRunning()) {
  6270. Running = false;
  6271. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  6272. SERIAL_ERROR_START;
  6273. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  6274. LCD_MESSAGEPGM(MSG_STOPPED);
  6275. }
  6276. }
  6277. /**
  6278. * Set target_extruder from the T parameter or the active_extruder
  6279. *
  6280. * Returns TRUE if the target is invalid
  6281. */
  6282. bool setTargetedHotend(int code) {
  6283. target_extruder = active_extruder;
  6284. if (code_seen('T')) {
  6285. target_extruder = code_value_short();
  6286. if (target_extruder >= EXTRUDERS) {
  6287. SERIAL_ECHO_START;
  6288. SERIAL_CHAR('M');
  6289. SERIAL_ECHO(code);
  6290. SERIAL_ECHOPGM(" " MSG_INVALID_EXTRUDER " ");
  6291. SERIAL_ECHOLN(target_extruder);
  6292. return true;
  6293. }
  6294. }
  6295. return false;
  6296. }
  6297. float calculate_volumetric_multiplier(float diameter) {
  6298. if (!volumetric_enabled || diameter == 0) return 1.0;
  6299. float d2 = diameter * 0.5;
  6300. return 1.0 / (M_PI * d2 * d2);
  6301. }
  6302. void calculate_volumetric_multipliers() {
  6303. for (int i = 0; i < EXTRUDERS; i++)
  6304. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  6305. }