Marlin_main.cpp 503 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2016, 2017 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * About Marlin
  24. *
  25. * This firmware is a mashup between Sprinter and grbl.
  26. * - https://github.com/kliment/Sprinter
  27. * - https://github.com/grbl/grbl
  28. */
  29. /**
  30. * -----------------
  31. * G-Codes in Marlin
  32. * -----------------
  33. *
  34. * Helpful G-code references:
  35. * - http://linuxcnc.org/handbook/gcode/g-code.html
  36. * - http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  37. *
  38. * Help to document Marlin's G-codes online:
  39. * - http://reprap.org/wiki/G-code
  40. * - https://github.com/MarlinFirmware/MarlinDocumentation
  41. *
  42. * -----------------
  43. *
  44. * "G" Codes
  45. *
  46. * G0 -> G1
  47. * G1 - Coordinated Movement X Y Z E
  48. * G2 - CW ARC
  49. * G3 - CCW ARC
  50. * G4 - Dwell S<seconds> or P<milliseconds>
  51. * G5 - Cubic B-spline with XYZE destination and IJPQ offsets
  52. * G6 - Direct stepper move (Requires UNREGISTERED_MOVE_SUPPORT). Hangprinter defaults to relative moves. Others default to absolute moves.
  53. * G10 - Retract filament according to settings of M207 (Requires FWRETRACT)
  54. * G11 - Retract recover filament according to settings of M208 (Requires FWRETRACT)
  55. * G12 - Clean tool (Requires NOZZLE_CLEAN_FEATURE)
  56. * G17 - Select Plane XY (Requires CNC_WORKSPACE_PLANES)
  57. * G18 - Select Plane ZX (Requires CNC_WORKSPACE_PLANES)
  58. * G19 - Select Plane YZ (Requires CNC_WORKSPACE_PLANES)
  59. * G20 - Set input units to inches (Requires INCH_MODE_SUPPORT)
  60. * G21 - Set input units to millimeters (Requires INCH_MODE_SUPPORT)
  61. * G26 - Mesh Validation Pattern (Requires G26_MESH_VALIDATION)
  62. * G27 - Park Nozzle (Requires NOZZLE_PARK_FEATURE)
  63. * G28 - Home one or more axes
  64. * G29 - Start or continue the bed leveling probe procedure (Requires bed leveling)
  65. * G30 - Single Z probe, probes bed at X Y location (defaults to current XY location)
  66. * G31 - Dock sled (Z_PROBE_SLED only)
  67. * G32 - Undock sled (Z_PROBE_SLED only)
  68. * G33 - Delta Auto-Calibration (Requires DELTA_AUTO_CALIBRATION)
  69. * G38 - Probe in any direction using the Z_MIN_PROBE (Requires G38_PROBE_TARGET)
  70. * G42 - Coordinated move to a mesh point (Requires MESH_BED_LEVELING, AUTO_BED_LEVELING_BLINEAR, or AUTO_BED_LEVELING_UBL)
  71. * G90 - Use Absolute Coordinates
  72. * G91 - Use Relative Coordinates
  73. * G92 - Set current position to coordinates given
  74. * G95 - Set torque mode (Requires MECHADUINO_I2C_COMMANDS enabled)
  75. * G96 - Set encoder reference point (Requires MECHADUINO_I2C_COMMANDS enabled)
  76. *
  77. * "M" Codes
  78. *
  79. * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  80. * M1 -> M0
  81. * M3 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to clockwise
  82. * M4 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to counter-clockwise
  83. * M5 - Turn laser/spindle off
  84. * M17 - Enable/Power all stepper motors
  85. * M18 - Disable all stepper motors; same as M84
  86. * M20 - List SD card. (Requires SDSUPPORT)
  87. * M21 - Init SD card. (Requires SDSUPPORT)
  88. * M22 - Release SD card. (Requires SDSUPPORT)
  89. * M23 - Select SD file: "M23 /path/file.gco". (Requires SDSUPPORT)
  90. * M24 - Start/resume SD print. (Requires SDSUPPORT)
  91. * M25 - Pause SD print. (Requires SDSUPPORT)
  92. * M26 - Set SD position in bytes: "M26 S12345". (Requires SDSUPPORT)
  93. * M27 - Report SD print status. (Requires SDSUPPORT)
  94. * OR, with 'S<seconds>' set the SD status auto-report interval. (Requires AUTO_REPORT_SD_STATUS)
  95. * OR, with 'C' get the current filename.
  96. * M28 - Start SD write: "M28 /path/file.gco". (Requires SDSUPPORT)
  97. * M29 - Stop SD write. (Requires SDSUPPORT)
  98. * M30 - Delete file from SD: "M30 /path/file.gco"
  99. * M31 - Report time since last M109 or SD card start to serial.
  100. * M32 - Select file and start SD print: "M32 [S<bytepos>] !/path/file.gco#". (Requires SDSUPPORT)
  101. * Use P to run other files as sub-programs: "M32 P !filename#"
  102. * The '#' is necessary when calling from within sd files, as it stops buffer prereading
  103. * M33 - Get the longname version of a path. (Requires LONG_FILENAME_HOST_SUPPORT)
  104. * M34 - Set SD Card sorting options. (Requires SDCARD_SORT_ALPHA)
  105. * M42 - Change pin status via gcode: M42 P<pin> S<value>. LED pin assumed if P is omitted.
  106. * M43 - Display pin status, watch pins for changes, watch endstops & toggle LED, Z servo probe test, toggle pins
  107. * M48 - Measure Z Probe repeatability: M48 P<points> X<pos> Y<pos> V<level> E<engage> L<legs> S<chizoid>. (Requires Z_MIN_PROBE_REPEATABILITY_TEST)
  108. * M75 - Start the print job timer.
  109. * M76 - Pause the print job timer.
  110. * M77 - Stop the print job timer.
  111. * M78 - Show statistical information about the print jobs. (Requires PRINTCOUNTER)
  112. * M80 - Turn on Power Supply. (Requires POWER_SUPPLY > 0)
  113. * M81 - Turn off Power Supply. (Requires POWER_SUPPLY > 0)
  114. * M82 - Set E codes absolute (default).
  115. * M83 - Set E codes relative while in Absolute (G90) mode.
  116. * M84 - Disable steppers until next move, or use S<seconds> to specify an idle
  117. * duration after which steppers should turn off. S0 disables the timeout.
  118. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  119. * M92 - Set planner.axis_steps_per_mm for one or more axes.
  120. * M100 - Watch Free Memory (for debugging) (Requires M100_FREE_MEMORY_WATCHER)
  121. * M104 - Set extruder target temp.
  122. * M105 - Report current temperatures.
  123. * M106 - Set print fan speed.
  124. * M107 - Print fan off.
  125. * M108 - Break out of heating loops (M109, M190, M303). With no controller, breaks out of M0/M1. (Requires EMERGENCY_PARSER)
  126. * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  127. * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  128. * If AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  129. * M110 - Set the current line number. (Used by host printing)
  130. * M111 - Set debug flags: "M111 S<flagbits>". See flag bits defined in enum.h.
  131. * M112 - Emergency stop.
  132. * M113 - Get or set the timeout interval for Host Keepalive "busy" messages. (Requires HOST_KEEPALIVE_FEATURE)
  133. * M114 - Report current position.
  134. * - S1 Compute length traveled since last G96 using encoder position data (Requires MECHADUINO_I2C_COMMANDS, only kinematic axes)
  135. * M115 - Report capabilities. (Extended capabilities requires EXTENDED_CAPABILITIES_REPORT)
  136. * M117 - Display a message on the controller screen. (Requires an LCD)
  137. * M118 - Display a message in the host console.
  138. * M119 - Report endstops status.
  139. * M120 - Enable endstops detection.
  140. * M121 - Disable endstops detection.
  141. * M122 - Debug stepper (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660)
  142. * M125 - Save current position and move to filament change position. (Requires PARK_HEAD_ON_PAUSE)
  143. * M126 - Solenoid Air Valve Open. (Requires BARICUDA)
  144. * M127 - Solenoid Air Valve Closed. (Requires BARICUDA)
  145. * M128 - EtoP Open. (Requires BARICUDA)
  146. * M129 - EtoP Closed. (Requires BARICUDA)
  147. * M140 - Set bed target temp. S<temp>
  148. * M145 - Set heatup values for materials on the LCD. H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS)
  149. * M149 - Set temperature units. (Requires TEMPERATURE_UNITS_SUPPORT)
  150. * M150 - Set Status LED Color as R<red> U<green> B<blue> P<bright>. Values 0-255. (Requires BLINKM, RGB_LED, RGBW_LED, NEOPIXEL_LED, or PCA9632).
  151. * M155 - Auto-report temperatures with interval of S<seconds>. (Requires AUTO_REPORT_TEMPERATURES)
  152. * M163 - Set a single proportion for a mixing extruder. (Requires MIXING_EXTRUDER)
  153. * M164 - Commit the mix (Req. MIXING_EXTRUDER) and optionally save as a virtual tool (Req. MIXING_VIRTUAL_TOOLS > 1)
  154. * M165 - Set the mix for a mixing extruder wuth parameters ABCDHI. (Requires MIXING_EXTRUDER and DIRECT_MIXING_IN_G1)
  155. * M190 - Sxxx Wait for bed current temp to reach target temp. ** Waits only when heating! **
  156. * Rxxx Wait for bed current temp to reach target temp. ** Waits for heating or cooling. **
  157. * M200 - Set filament diameter, D<diameter>, setting E axis units to cubic. (Use S0 to revert to linear units.)
  158. * M201 - Set max acceleration in units/s^2 for print moves: "M201 X<accel> Y<accel> Z<accel> E<accel>"
  159. * M202 - Set max acceleration in units/s^2 for travel moves: "M202 X<accel> Y<accel> Z<accel> E<accel>" ** UNUSED IN MARLIN! **
  160. * M203 - Set maximum feedrate: "M203 X<fr> Y<fr> Z<fr> E<fr>" in units/sec.
  161. * M204 - Set default acceleration in units/sec^2: P<printing> R<extruder_only> T<travel>
  162. * M205 - Set advanced settings. Current units apply:
  163. S<print> T<travel> minimum speeds
  164. Q<minimum segment time>
  165. X<max X jerk>, Y<max Y jerk>, Z<max Z jerk>, E<max E jerk>
  166. * M206 - Set additional homing offset. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  167. * M207 - Set Retract Length: S<length>, Feedrate: F<units/min>, and Z lift: Z<distance>. (Requires FWRETRACT)
  168. * M208 - Set Recover (unretract) Additional (!) Length: S<length> and Feedrate: F<units/min>. (Requires FWRETRACT)
  169. * M209 - Turn Automatic Retract Detection on/off: S<0|1> (For slicers that don't support G10/11). (Requires FWRETRACT)
  170. Every normal extrude-only move will be classified as retract depending on the direction.
  171. * M211 - Enable, Disable, and/or Report software endstops: S<0|1> (Requires MIN_SOFTWARE_ENDSTOPS or MAX_SOFTWARE_ENDSTOPS)
  172. * M218 - Set/get a tool offset: "M218 T<index> X<offset> Y<offset>". (Requires 2 or more extruders)
  173. * M220 - Set Feedrate Percentage: "M220 S<percent>" (i.e., "FR" on the LCD)
  174. * M221 - Set Flow Percentage: "M221 S<percent>"
  175. * M226 - Wait until a pin is in a given state: "M226 P<pin> S<state>"
  176. * M240 - Trigger a camera to take a photograph. (Requires CHDK or PHOTOGRAPH_PIN)
  177. * M250 - Set LCD contrast: "M250 C<contrast>" (0-63). (Requires LCD support)
  178. * M260 - i2c Send Data (Requires EXPERIMENTAL_I2CBUS)
  179. * M261 - i2c Request Data (Requires EXPERIMENTAL_I2CBUS)
  180. * M280 - Set servo position absolute: "M280 P<index> S<angle|µs>". (Requires servos)
  181. * M290 - Babystepping (Requires BABYSTEPPING)
  182. * M300 - Play beep sound S<frequency Hz> P<duration ms>
  183. * M301 - Set PID parameters P I and D. (Requires PIDTEMP)
  184. * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>. (Requires PREVENT_COLD_EXTRUSION)
  185. * M303 - PID relay autotune S<temperature> sets the target temperature. Default 150C. (Requires PIDTEMP)
  186. * M304 - Set bed PID parameters P I and D. (Requires PIDTEMPBED)
  187. * M350 - Set microstepping mode. (Requires digital microstepping pins.)
  188. * M351 - Toggle MS1 MS2 pins directly. (Requires digital microstepping pins.)
  189. * M355 - Set Case Light on/off and set brightness. (Requires CASE_LIGHT_PIN)
  190. * M380 - Activate solenoid on active extruder. (Requires EXT_SOLENOID)
  191. * M381 - Disable all solenoids. (Requires EXT_SOLENOID)
  192. * M400 - Finish all moves.
  193. * M401 - Deploy and activate Z probe. (Requires a probe)
  194. * M402 - Deactivate and stow Z probe. (Requires a probe)
  195. * M404 - Display or set the Nominal Filament Width: "W<diameter>". (Requires FILAMENT_WIDTH_SENSOR)
  196. * M405 - Enable Filament Sensor flow control. "M405 D<delay_cm>". (Requires FILAMENT_WIDTH_SENSOR)
  197. * M406 - Disable Filament Sensor flow control. (Requires FILAMENT_WIDTH_SENSOR)
  198. * M407 - Display measured filament diameter in millimeters. (Requires FILAMENT_WIDTH_SENSOR)
  199. * M410 - Quickstop. Abort all planned moves.
  200. * M420 - Enable/Disable Leveling (with current values) S1=enable S0=disable (Requires MESH_BED_LEVELING or ABL)
  201. * M421 - Set a single Z coordinate in the Mesh Leveling grid. X<units> Y<units> Z<units> (Requires MESH_BED_LEVELING, AUTO_BED_LEVELING_BILINEAR, or AUTO_BED_LEVELING_UBL)
  202. * M428 - Set the home_offset based on the current_position. Nearest edge applies. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  203. * M500 - Store parameters in EEPROM. (Requires EEPROM_SETTINGS)
  204. * M501 - Restore parameters from EEPROM. (Requires EEPROM_SETTINGS)
  205. * M502 - Revert to the default "factory settings". ** Does not write them to EEPROM! **
  206. * M503 - Print the current settings (in memory): "M503 S<verbose>". S0 specifies compact output.
  207. * M524 - Abort SD card print job started with M24 (Requires SDSUPPORT)
  208. * M540 - Enable/disable SD card abort on endstop hit: "M540 S<state>". (Requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  209. * M600 - Pause for filament change: "M600 X<pos> Y<pos> Z<raise> E<first_retract> L<later_retract>". (Requires ADVANCED_PAUSE_FEATURE)
  210. * M603 - Configure filament change: "M603 T<tool> U<unload_length> L<load_length>". (Requires ADVANCED_PAUSE_FEATURE)
  211. * M605 - Set Dual X-Carriage movement mode: "M605 S<mode> [X<x_offset>] [R<temp_offset>]". (Requires DUAL_X_CARRIAGE)
  212. * M665 - Set Delta configurations: "M665 H<delta height> L<diagonal rod> R<delta radius> S<segments/s> B<calibration radius> X<Alpha angle trim> Y<Beta angle trim> Z<Gamma angle trim> (Requires DELTA)
  213. * M665 - Set Hangprinter configurations: "M665 W<Ay> E<Az> R<Bx> T<By> Y<Bz> U<Cx> I<Cy> O<Cz> P<Dz> S<segments/s>" (Requires HANGPRINTER)
  214. * M666 - Set/get endstop offsets for delta (Requires DELTA) or dual endstops (Requires [XYZ]_DUAL_ENDSTOPS).
  215. * M701 - Load filament (requires FILAMENT_LOAD_UNLOAD_GCODES)
  216. * M702 - Unload filament (requires FILAMENT_LOAD_UNLOAD_GCODES)
  217. * M851 - Set Z probe's Z offset in current units. (Negative = below the nozzle.)
  218. * M852 - Set skew factors: "M852 [I<xy>] [J<xz>] [K<yz>]". (Requires SKEW_CORRECTION_GCODE, and SKEW_CORRECTION_FOR_Z for IJ)
  219. * M860 - Report the position of position encoder modules.
  220. * M861 - Report the status of position encoder modules.
  221. * M862 - Perform an axis continuity test for position encoder modules.
  222. * M863 - Perform steps-per-mm calibration for position encoder modules.
  223. * M864 - Change position encoder module I2C address.
  224. * M865 - Check position encoder module firmware version.
  225. * M866 - Report or reset position encoder module error count.
  226. * M867 - Enable/disable or toggle error correction for position encoder modules.
  227. * M868 - Report or set position encoder module error correction threshold.
  228. * M869 - Report position encoder module error.
  229. * M900 - Get or Set Linear Advance K-factor. (Requires LIN_ADVANCE)
  230. * M906 - Set or get motor current in milliamps using axis codes X, Y, Z, E. Report values if no axis codes given. (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660)
  231. * M907 - Set digital trimpot motor current using axis codes. (Requires a board with digital trimpots)
  232. * M908 - Control digital trimpot directly. (Requires DAC_STEPPER_CURRENT or DIGIPOTSS_PIN)
  233. * M909 - Print digipot/DAC current value. (Requires DAC_STEPPER_CURRENT)
  234. * M910 - Commit digipot/DAC value to external EEPROM via I2C. (Requires DAC_STEPPER_CURRENT)
  235. * M911 - Report stepper driver overtemperature pre-warn condition. (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660)
  236. * M912 - Clear stepper driver overtemperature pre-warn condition flag. (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660)
  237. * M913 - Set HYBRID_THRESHOLD speed. (Requires HYBRID_THRESHOLD)
  238. * M914 - Set SENSORLESS_HOMING sensitivity. (Requires SENSORLESS_HOMING)
  239. *
  240. * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  241. * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  242. * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  243. * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  244. * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  245. *
  246. * ************ Custom codes - This can change to suit future G-code regulations
  247. * M928 - Start SD logging: "M928 filename.gco". Stop with M29. (Requires SDSUPPORT)
  248. * M999 - Restart after being stopped by error
  249. *
  250. * "T" Codes
  251. *
  252. * T0-T3 - Select an extruder (tool) by index: "T<n> F<units/min>"
  253. *
  254. */
  255. #include "Marlin.h"
  256. #include "ultralcd.h"
  257. #include "planner.h"
  258. #include "stepper.h"
  259. #include "endstops.h"
  260. #include "temperature.h"
  261. #include "cardreader.h"
  262. #include "configuration_store.h"
  263. #include "language.h"
  264. #include "pins_arduino.h"
  265. #include "math.h"
  266. #include "nozzle.h"
  267. #include "printcounter.h"
  268. #include "duration_t.h"
  269. #include "types.h"
  270. #include "parser.h"
  271. #if ENABLED(AUTO_POWER_CONTROL)
  272. #include "power.h"
  273. #endif
  274. #if ABL_PLANAR
  275. #include "vector_3.h"
  276. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  277. #include "least_squares_fit.h"
  278. #endif
  279. #elif ENABLED(MESH_BED_LEVELING)
  280. #include "mesh_bed_leveling.h"
  281. #endif
  282. #if ENABLED(BEZIER_CURVE_SUPPORT)
  283. #include "planner_bezier.h"
  284. #endif
  285. #if ENABLED(FWRETRACT)
  286. #include "fwretract.h"
  287. #endif
  288. #if ENABLED(POWER_LOSS_RECOVERY)
  289. #include "power_loss_recovery.h"
  290. #endif
  291. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  292. #include "runout.h"
  293. #endif
  294. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  295. #include "buzzer.h"
  296. #endif
  297. #if ENABLED(USE_WATCHDOG)
  298. #include "watchdog.h"
  299. #endif
  300. #if ENABLED(MAX7219_DEBUG)
  301. #include "Max7219_Debug_LEDs.h"
  302. #endif
  303. #if HAS_COLOR_LEDS
  304. #include "leds.h"
  305. #endif
  306. #if HAS_SERVOS
  307. #include "servo.h"
  308. #endif
  309. #if HAS_DIGIPOTSS
  310. #include <SPI.h>
  311. #endif
  312. #if HAS_TRINAMIC
  313. #include "tmc_util.h"
  314. #endif
  315. #if ENABLED(DAC_STEPPER_CURRENT)
  316. #include "stepper_dac.h"
  317. #endif
  318. #if ENABLED(EXPERIMENTAL_I2CBUS)
  319. #include "twibus.h"
  320. #endif
  321. #if ENABLED(I2C_POSITION_ENCODERS)
  322. #include "I2CPositionEncoder.h"
  323. #endif
  324. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  325. void gcode_M100();
  326. void M100_dump_routine(const char * const title, const char *start, const char *end);
  327. #endif
  328. #if ENABLED(G26_MESH_VALIDATION)
  329. bool g26_debug_flag; // =false
  330. void gcode_G26();
  331. #endif
  332. #if ENABLED(SDSUPPORT)
  333. CardReader card;
  334. #endif
  335. #if ENABLED(EXPERIMENTAL_I2CBUS)
  336. TWIBus i2c;
  337. #endif
  338. #if ENABLED(G38_PROBE_TARGET)
  339. bool G38_move = false,
  340. G38_endstop_hit = false;
  341. #endif
  342. #if ENABLED(AUTO_BED_LEVELING_UBL)
  343. #include "ubl.h"
  344. #endif
  345. #if ENABLED(CNC_COORDINATE_SYSTEMS)
  346. int8_t active_coordinate_system = -1; // machine space
  347. float coordinate_system[MAX_COORDINATE_SYSTEMS][XYZ];
  348. #endif
  349. bool Running = true;
  350. uint8_t marlin_debug_flags = DEBUG_NONE;
  351. /**
  352. * Cartesian Current Position
  353. * Used to track the native machine position as moves are queued.
  354. * Used by 'buffer_line_to_current_position' to do a move after changing it.
  355. * Used by 'SYNC_PLAN_POSITION_KINEMATIC' to update 'planner.position'.
  356. */
  357. float current_position[XYZE] = { 0 };
  358. /**
  359. * Cartesian Destination
  360. * The destination for a move, filled in by G-code movement commands,
  361. * and expected by functions like 'prepare_move_to_destination'.
  362. * Set with 'gcode_get_destination' or 'set_destination_from_current'.
  363. */
  364. float destination[XYZE] = { 0 };
  365. /**
  366. * axis_homed
  367. * Flags that each linear axis was homed.
  368. * XYZ on cartesian, ABC on delta, ABZ on SCARA.
  369. *
  370. * axis_known_position
  371. * Flags that the position is known in each linear axis. Set when homed.
  372. * Cleared whenever a stepper powers off, potentially losing its position.
  373. */
  374. uint8_t axis_homed, axis_known_position; // = 0
  375. /**
  376. * GCode line number handling. Hosts may opt to include line numbers when
  377. * sending commands to Marlin, and lines will be checked for sequentiality.
  378. * M110 N<int> sets the current line number.
  379. */
  380. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  381. /**
  382. * GCode Command Queue
  383. * A simple ring buffer of BUFSIZE command strings.
  384. *
  385. * Commands are copied into this buffer by the command injectors
  386. * (immediate, serial, sd card) and they are processed sequentially by
  387. * the main loop. The process_next_command function parses the next
  388. * command and hands off execution to individual handler functions.
  389. */
  390. uint8_t commands_in_queue = 0, // Count of commands in the queue
  391. cmd_queue_index_r = 0, // Ring buffer read (out) position
  392. cmd_queue_index_w = 0; // Ring buffer write (in) position
  393. char command_queue[BUFSIZE][MAX_CMD_SIZE];
  394. /**
  395. * Next Injected Command pointer. NULL if no commands are being injected.
  396. * Used by Marlin internally to ensure that commands initiated from within
  397. * are enqueued ahead of any pending serial or sd card commands.
  398. */
  399. static const char *injected_commands_P = NULL;
  400. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  401. TempUnit input_temp_units = TEMPUNIT_C;
  402. #endif
  403. /**
  404. * Feed rates are often configured with mm/m
  405. * but the planner and stepper like mm/s units.
  406. */
  407. static const float homing_feedrate_mm_s[] PROGMEM = {
  408. #if ENABLED(HANGPRINTER)
  409. MMM_TO_MMS(DUMMY_HOMING_FEEDRATE), MMM_TO_MMS(DUMMY_HOMING_FEEDRATE),
  410. MMM_TO_MMS(DUMMY_HOMING_FEEDRATE), MMM_TO_MMS(DUMMY_HOMING_FEEDRATE), 0
  411. #else
  412. #if ENABLED(DELTA)
  413. MMM_TO_MMS(HOMING_FEEDRATE_Z), MMM_TO_MMS(HOMING_FEEDRATE_Z),
  414. #else
  415. MMM_TO_MMS(HOMING_FEEDRATE_XY), MMM_TO_MMS(HOMING_FEEDRATE_XY),
  416. #endif
  417. MMM_TO_MMS(HOMING_FEEDRATE_Z), 0
  418. #endif
  419. };
  420. FORCE_INLINE float homing_feedrate(const AxisEnum a) { return pgm_read_float(&homing_feedrate_mm_s[a]); }
  421. float feedrate_mm_s = MMM_TO_MMS(1500.0f);
  422. static float saved_feedrate_mm_s;
  423. int16_t feedrate_percentage = 100, saved_feedrate_percentage;
  424. // Initialized by settings.load()
  425. bool axis_relative_modes[XYZE] = AXIS_RELATIVE_MODES;
  426. #if HAS_WORKSPACE_OFFSET
  427. #if HAS_POSITION_SHIFT
  428. // The distance that XYZ has been offset by G92. Reset by G28.
  429. float position_shift[XYZ] = { 0 };
  430. #endif
  431. #if HAS_HOME_OFFSET
  432. // This offset is added to the configured home position.
  433. // Set by M206, M428, or menu item. Saved to EEPROM.
  434. float home_offset[XYZ] = { 0 };
  435. #endif
  436. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  437. // The above two are combined to save on computes
  438. float workspace_offset[XYZ] = { 0 };
  439. #endif
  440. #endif
  441. // Software Endstops are based on the configured limits.
  442. float soft_endstop_min[XYZ] = { X_MIN_BED, Y_MIN_BED, Z_MIN_POS },
  443. soft_endstop_max[XYZ] = { X_MAX_BED, Y_MAX_BED, Z_MAX_POS };
  444. #if HAS_SOFTWARE_ENDSTOPS
  445. bool soft_endstops_enabled = true;
  446. #if IS_KINEMATIC
  447. float soft_endstop_radius, soft_endstop_radius_2;
  448. #endif
  449. #endif
  450. #if FAN_COUNT > 0
  451. int16_t fanSpeeds[FAN_COUNT] = { 0 };
  452. #if ENABLED(EXTRA_FAN_SPEED)
  453. int16_t old_fanSpeeds[FAN_COUNT],
  454. new_fanSpeeds[FAN_COUNT];
  455. #endif
  456. #if ENABLED(PROBING_FANS_OFF)
  457. bool fans_paused; // = false;
  458. int16_t paused_fanSpeeds[FAN_COUNT] = { 0 };
  459. #endif
  460. #endif
  461. #if ENABLED(USE_CONTROLLER_FAN)
  462. int controllerFanSpeed; // = 0;
  463. #endif
  464. // The active extruder (tool). Set with T<extruder> command.
  465. uint8_t active_extruder; // = 0;
  466. // Relative Mode. Enable with G91, disable with G90.
  467. static bool relative_mode; // = false;
  468. // For M109 and M190, this flag may be cleared (by M108) to exit the wait loop
  469. volatile bool wait_for_heatup = true;
  470. // For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop
  471. #if HAS_RESUME_CONTINUE
  472. volatile bool wait_for_user; // = false;
  473. #endif
  474. #if HAS_AUTO_REPORTING || ENABLED(HOST_KEEPALIVE_FEATURE)
  475. bool suspend_auto_report; // = false
  476. #endif
  477. const char axis_codes[XYZE] = { 'X', 'Y', 'Z', 'E' };
  478. #if ENABLED(HANGPRINTER)
  479. const char axis_codes_hangprinter[ABCDE] = { 'A', 'B', 'C', 'D', 'E' };
  480. #define RAW_AXIS_CODES(I) axis_codes_hangprinter[I]
  481. #else
  482. #define RAW_AXIS_CODES(I) axis_codes[I]
  483. #endif
  484. // Number of characters read in the current line of serial input
  485. static int serial_count; // = 0;
  486. // Inactivity shutdown
  487. millis_t previous_move_ms; // = 0;
  488. static millis_t max_inactive_time; // = 0;
  489. static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000UL;
  490. // Buzzer - I2C on the LCD or a BEEPER_PIN
  491. #if ENABLED(LCD_USE_I2C_BUZZER)
  492. #define BUZZ(d,f) lcd_buzz(d, f)
  493. #elif PIN_EXISTS(BEEPER)
  494. Buzzer buzzer;
  495. #define BUZZ(d,f) buzzer.tone(d, f)
  496. #else
  497. #define BUZZ(d,f) NOOP
  498. #endif
  499. uint8_t target_extruder;
  500. #if HAS_BED_PROBE
  501. float zprobe_zoffset; // Initialized by settings.load()
  502. #endif
  503. #if HAS_ABL
  504. float xy_probe_feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  505. #define XY_PROBE_FEEDRATE_MM_S xy_probe_feedrate_mm_s
  506. #elif defined(XY_PROBE_SPEED)
  507. #define XY_PROBE_FEEDRATE_MM_S MMM_TO_MMS(XY_PROBE_SPEED)
  508. #else
  509. #define XY_PROBE_FEEDRATE_MM_S PLANNER_XY_FEEDRATE()
  510. #endif
  511. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  512. #if ENABLED(DELTA)
  513. #define ADJUST_DELTA(V) \
  514. if (planner.leveling_active) { \
  515. const float zadj = bilinear_z_offset(V); \
  516. delta[A_AXIS] += zadj; \
  517. delta[B_AXIS] += zadj; \
  518. delta[C_AXIS] += zadj; \
  519. }
  520. #else
  521. #define ADJUST_DELTA(V) if (planner.leveling_active) { delta[Z_AXIS] += bilinear_z_offset(V); }
  522. #endif
  523. #elif IS_KINEMATIC
  524. #define ADJUST_DELTA(V) NOOP
  525. #endif
  526. #if HAS_HEATED_BED && ENABLED(WAIT_FOR_BED_HEATER)
  527. const static char msg_wait_for_bed_heating[] PROGMEM = "Wait for bed heating...\n";
  528. #endif
  529. // Extruder offsets
  530. #if HOTENDS > 1
  531. float hotend_offset[XYZ][HOTENDS]; // Initialized by settings.load()
  532. #endif
  533. #if HAS_Z_SERVO_PROBE
  534. const int z_servo_angle[2] = Z_SERVO_ANGLES;
  535. #endif
  536. #if ENABLED(BARICUDA)
  537. uint8_t baricuda_valve_pressure = 0,
  538. baricuda_e_to_p_pressure = 0;
  539. #endif
  540. #if HAS_POWER_SWITCH
  541. bool powersupply_on = (
  542. #if ENABLED(PS_DEFAULT_OFF)
  543. false
  544. #else
  545. true
  546. #endif
  547. );
  548. #if ENABLED(AUTO_POWER_CONTROL)
  549. #define PSU_ON() powerManager.power_on()
  550. #define PSU_OFF() powerManager.power_off()
  551. #else
  552. #define PSU_ON() PSU_PIN_ON()
  553. #define PSU_OFF() PSU_PIN_OFF()
  554. #endif
  555. #endif
  556. #if ENABLED(DELTA)
  557. float delta[ABC];
  558. // Initialized by settings.load()
  559. float delta_height,
  560. delta_endstop_adj[ABC] = { 0 },
  561. delta_radius,
  562. delta_tower_angle_trim[ABC],
  563. delta_tower[ABC][2],
  564. delta_diagonal_rod,
  565. delta_calibration_radius,
  566. delta_diagonal_rod_2_tower[ABC],
  567. delta_segments_per_second,
  568. delta_clip_start_height = Z_MAX_POS;
  569. float delta_safe_distance_from_top();
  570. #elif ENABLED(HANGPRINTER)
  571. float anchor_A_y,
  572. anchor_A_z,
  573. anchor_B_x,
  574. anchor_B_y,
  575. anchor_B_z,
  576. anchor_C_x,
  577. anchor_C_y,
  578. anchor_C_z,
  579. anchor_D_z,
  580. line_lengths[ABCD],
  581. line_lengths_origin[ABCD],
  582. delta_segments_per_second;
  583. #endif
  584. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  585. int bilinear_grid_spacing[2], bilinear_start[2];
  586. float bilinear_grid_factor[2],
  587. z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  588. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  589. #define ABL_BG_SPACING(A) bilinear_grid_spacing_virt[A]
  590. #define ABL_BG_FACTOR(A) bilinear_grid_factor_virt[A]
  591. #define ABL_BG_POINTS_X ABL_GRID_POINTS_VIRT_X
  592. #define ABL_BG_POINTS_Y ABL_GRID_POINTS_VIRT_Y
  593. #define ABL_BG_GRID(X,Y) z_values_virt[X][Y]
  594. #else
  595. #define ABL_BG_SPACING(A) bilinear_grid_spacing[A]
  596. #define ABL_BG_FACTOR(A) bilinear_grid_factor[A]
  597. #define ABL_BG_POINTS_X GRID_MAX_POINTS_X
  598. #define ABL_BG_POINTS_Y GRID_MAX_POINTS_Y
  599. #define ABL_BG_GRID(X,Y) z_values[X][Y]
  600. #endif
  601. #endif
  602. #if IS_SCARA
  603. // Float constants for SCARA calculations
  604. const float L1 = SCARA_LINKAGE_1, L2 = SCARA_LINKAGE_2,
  605. L1_2 = sq(float(L1)), L1_2_2 = 2.0 * L1_2,
  606. L2_2 = sq(float(L2));
  607. float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND,
  608. delta[ABC];
  609. #endif
  610. float cartes[XYZ] = { 0 };
  611. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  612. bool filament_sensor; // = false; // M405 turns on filament sensor control. M406 turns it off.
  613. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA, // Nominal filament width. Change with M404.
  614. filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; // Measured filament diameter
  615. uint8_t meas_delay_cm = MEASUREMENT_DELAY_CM; // Distance delay setting
  616. int8_t measurement_delay[MAX_MEASUREMENT_DELAY + 1], // Ring buffer to delayed measurement. Store extruder factor after subtracting 100
  617. filwidth_delay_index[2] = { 0, -1 }; // Indexes into ring buffer
  618. #endif
  619. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  620. AdvancedPauseMenuResponse advanced_pause_menu_response;
  621. float filament_change_unload_length[EXTRUDERS],
  622. filament_change_load_length[EXTRUDERS];
  623. #endif
  624. #if ENABLED(MIXING_EXTRUDER)
  625. float mixing_factor[MIXING_STEPPERS]; // Reciprocal of mix proportion. 0.0 = off, otherwise >= 1.0.
  626. #if MIXING_VIRTUAL_TOOLS > 1
  627. float mixing_virtual_tool_mix[MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS];
  628. #endif
  629. #endif
  630. static bool send_ok[BUFSIZE];
  631. #if HAS_SERVOS
  632. Servo servo[NUM_SERVOS];
  633. #define MOVE_SERVO(I, P) servo[I].move(P)
  634. #if HAS_Z_SERVO_PROBE
  635. #define DEPLOY_Z_SERVO() MOVE_SERVO(Z_PROBE_SERVO_NR, z_servo_angle[0])
  636. #define STOW_Z_SERVO() MOVE_SERVO(Z_PROBE_SERVO_NR, z_servo_angle[1])
  637. #endif
  638. #endif
  639. #ifdef CHDK
  640. millis_t chdkHigh = 0;
  641. bool chdkActive = false;
  642. #endif
  643. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  644. MarlinBusyState busy_state = NOT_BUSY;
  645. static millis_t next_busy_signal_ms = 0;
  646. uint8_t host_keepalive_interval = DEFAULT_KEEPALIVE_INTERVAL;
  647. #else
  648. #define host_keepalive() NOOP
  649. #endif
  650. #if ENABLED(I2C_POSITION_ENCODERS)
  651. I2CPositionEncodersMgr I2CPEM;
  652. #endif
  653. #if ENABLED(CNC_WORKSPACE_PLANES)
  654. static WorkspacePlane workspace_plane = PLANE_XY;
  655. #endif
  656. FORCE_INLINE float pgm_read_any(const float *p) { return pgm_read_float_near(p); }
  657. FORCE_INLINE signed char pgm_read_any(const signed char *p) { return pgm_read_byte_near(p); }
  658. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  659. static const PROGMEM type array##_P[XYZ] = { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  660. static inline type array(const AxisEnum axis) { return pgm_read_any(&array##_P[axis]); } \
  661. typedef void __void_##CONFIG##__
  662. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  663. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  664. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  665. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  666. XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM);
  667. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  668. /**
  669. * ***************************************************************************
  670. * ******************************** FUNCTIONS ********************************
  671. * ***************************************************************************
  672. */
  673. void stop();
  674. void get_available_commands();
  675. void process_next_command();
  676. void process_parsed_command();
  677. void get_cartesian_from_steppers();
  678. void set_current_from_steppers_for_axis(const AxisEnum axis);
  679. #if ENABLED(ARC_SUPPORT)
  680. void plan_arc(const float (&cart)[XYZE], const float (&offset)[2], const bool clockwise);
  681. #endif
  682. #if ENABLED(BEZIER_CURVE_SUPPORT)
  683. void plan_cubic_move(const float (&cart)[XYZE], const float (&offset)[4]);
  684. #endif
  685. void report_current_position();
  686. void report_current_position_detail();
  687. #if ENABLED(DEBUG_LEVELING_FEATURE)
  688. void print_xyz(const char* prefix, const char* suffix, const float x, const float y, const float z) {
  689. serialprintPGM(prefix);
  690. SERIAL_CHAR('(');
  691. SERIAL_ECHO(x);
  692. SERIAL_ECHOPAIR(", ", y);
  693. SERIAL_ECHOPAIR(", ", z);
  694. SERIAL_CHAR(')');
  695. if (suffix) serialprintPGM(suffix); else SERIAL_EOL();
  696. }
  697. void print_xyz(const char* prefix, const char* suffix, const float xyz[]) {
  698. print_xyz(prefix, suffix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]);
  699. }
  700. #define DEBUG_POS(SUFFIX,VAR) do { \
  701. print_xyz(PSTR(" " STRINGIFY(VAR) "="), PSTR(" : " SUFFIX "\n"), VAR); }while(0)
  702. #endif
  703. /**
  704. * sync_plan_position
  705. *
  706. * Set the planner/stepper positions directly from current_position with
  707. * no kinematic translation. Used for homing axes and cartesian/core syncing.
  708. *
  709. * This is not possible for Hangprinter because current_position and position are different sizes
  710. */
  711. void sync_plan_position() {
  712. #if DISABLED(HANGPRINTER)
  713. #if ENABLED(DEBUG_LEVELING_FEATURE)
  714. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position", current_position);
  715. #endif
  716. planner.set_position_mm(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART]);
  717. #endif
  718. }
  719. void sync_plan_position_e() { planner.set_e_position_mm(current_position[E_CART]); }
  720. #if IS_KINEMATIC
  721. inline void sync_plan_position_kinematic() {
  722. #if ENABLED(DEBUG_LEVELING_FEATURE)
  723. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position_kinematic", current_position);
  724. #endif
  725. planner.set_position_mm_kinematic(current_position);
  726. }
  727. #endif
  728. #if ENABLED(SDSUPPORT)
  729. #include "SdFatUtil.h"
  730. int freeMemory() { return SdFatUtil::FreeRam(); }
  731. #else
  732. extern "C" {
  733. extern char __bss_end;
  734. extern char __heap_start;
  735. extern void* __brkval;
  736. int freeMemory() {
  737. int free_memory;
  738. if (int(__brkval) == 0)
  739. free_memory = (int(&free_memory)) - (int(&__bss_end));
  740. else
  741. free_memory = (int(&free_memory)) - (int(__brkval));
  742. return free_memory;
  743. }
  744. }
  745. #endif // !SDSUPPORT
  746. #if ENABLED(DIGIPOT_I2C)
  747. extern void digipot_i2c_set_current(uint8_t channel, float current);
  748. extern void digipot_i2c_init();
  749. #endif
  750. /**
  751. * Inject the next "immediate" command, when possible, onto the front of the queue.
  752. * Return true if any immediate commands remain to inject.
  753. */
  754. static bool drain_injected_commands_P() {
  755. if (injected_commands_P != NULL) {
  756. size_t i = 0;
  757. char c, cmd[30];
  758. strncpy_P(cmd, injected_commands_P, sizeof(cmd) - 1);
  759. cmd[sizeof(cmd) - 1] = '\0';
  760. while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command
  761. cmd[i] = '\0';
  762. if (enqueue_and_echo_command(cmd)) // success?
  763. injected_commands_P = c ? injected_commands_P + i + 1 : NULL; // next command or done
  764. }
  765. return (injected_commands_P != NULL); // return whether any more remain
  766. }
  767. /**
  768. * Record one or many commands to run from program memory.
  769. * Aborts the current queue, if any.
  770. * Note: drain_injected_commands_P() must be called repeatedly to drain the commands afterwards
  771. */
  772. void enqueue_and_echo_commands_P(const char * const pgcode) {
  773. injected_commands_P = pgcode;
  774. (void)drain_injected_commands_P(); // first command executed asap (when possible)
  775. }
  776. /**
  777. * Clear the Marlin command queue
  778. */
  779. void clear_command_queue() {
  780. cmd_queue_index_r = cmd_queue_index_w = commands_in_queue = 0;
  781. }
  782. /**
  783. * Once a new command is in the ring buffer, call this to commit it
  784. */
  785. inline void _commit_command(bool say_ok) {
  786. send_ok[cmd_queue_index_w] = say_ok;
  787. if (++cmd_queue_index_w >= BUFSIZE) cmd_queue_index_w = 0;
  788. commands_in_queue++;
  789. }
  790. /**
  791. * Copy a command from RAM into the main command buffer.
  792. * Return true if the command was successfully added.
  793. * Return false for a full buffer, or if the 'command' is a comment.
  794. */
  795. inline bool _enqueuecommand(const char* cmd, bool say_ok=false) {
  796. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  797. strcpy(command_queue[cmd_queue_index_w], cmd);
  798. _commit_command(say_ok);
  799. return true;
  800. }
  801. /**
  802. * Enqueue with Serial Echo
  803. */
  804. bool enqueue_and_echo_command(const char* cmd) {
  805. if (_enqueuecommand(cmd)) {
  806. SERIAL_ECHO_START();
  807. SERIAL_ECHOPAIR(MSG_ENQUEUEING, cmd);
  808. SERIAL_CHAR('"');
  809. SERIAL_EOL();
  810. return true;
  811. }
  812. return false;
  813. }
  814. #if HAS_QUEUE_NOW
  815. void enqueue_and_echo_command_now(const char* cmd) {
  816. while (!enqueue_and_echo_command(cmd)) idle();
  817. }
  818. #if HAS_LCD_QUEUE_NOW
  819. void enqueue_and_echo_commands_now_P(const char * const pgcode) {
  820. enqueue_and_echo_commands_P(pgcode);
  821. while (drain_injected_commands_P()) idle();
  822. }
  823. #endif
  824. #endif
  825. void setup_killpin() {
  826. #if HAS_KILL
  827. SET_INPUT_PULLUP(KILL_PIN);
  828. #endif
  829. }
  830. void setup_powerhold() {
  831. #if HAS_SUICIDE
  832. OUT_WRITE(SUICIDE_PIN, HIGH);
  833. #endif
  834. #if HAS_POWER_SWITCH
  835. #if ENABLED(PS_DEFAULT_OFF)
  836. PSU_OFF();
  837. #else
  838. PSU_ON();
  839. #endif
  840. #endif
  841. }
  842. void suicide() {
  843. #if HAS_SUICIDE
  844. OUT_WRITE(SUICIDE_PIN, LOW);
  845. #endif
  846. }
  847. void servo_init() {
  848. #if NUM_SERVOS >= 1 && HAS_SERVO_0
  849. servo[0].attach(SERVO0_PIN);
  850. servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position.
  851. #endif
  852. #if NUM_SERVOS >= 2 && HAS_SERVO_1
  853. servo[1].attach(SERVO1_PIN);
  854. servo[1].detach();
  855. #endif
  856. #if NUM_SERVOS >= 3 && HAS_SERVO_2
  857. servo[2].attach(SERVO2_PIN);
  858. servo[2].detach();
  859. #endif
  860. #if NUM_SERVOS >= 4 && HAS_SERVO_3
  861. servo[3].attach(SERVO3_PIN);
  862. servo[3].detach();
  863. #endif
  864. #if HAS_Z_SERVO_PROBE
  865. /**
  866. * Set position of Z Servo Endstop
  867. *
  868. * The servo might be deployed and positioned too low to stow
  869. * when starting up the machine or rebooting the board.
  870. * There's no way to know where the nozzle is positioned until
  871. * homing has been done - no homing with z-probe without init!
  872. *
  873. */
  874. STOW_Z_SERVO();
  875. #endif
  876. }
  877. /**
  878. * Stepper Reset (RigidBoard, et.al.)
  879. */
  880. #if HAS_STEPPER_RESET
  881. void disableStepperDrivers() {
  882. OUT_WRITE(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips
  883. }
  884. void enableStepperDrivers() { SET_INPUT(STEPPER_RESET_PIN); } // set to input, which allows it to be pulled high by pullups
  885. #endif
  886. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  887. void i2c_on_receive(int bytes) { // just echo all bytes received to serial
  888. i2c.receive(bytes);
  889. }
  890. void i2c_on_request() { // just send dummy data for now
  891. i2c.reply("Hello World!\n");
  892. }
  893. #endif
  894. void gcode_line_error(const char* err, bool doFlush = true) {
  895. SERIAL_ERROR_START();
  896. serialprintPGM(err);
  897. SERIAL_ERRORLN(gcode_LastN);
  898. //Serial.println(gcode_N);
  899. if (doFlush) flush_and_request_resend();
  900. serial_count = 0;
  901. }
  902. /**
  903. * Get all commands waiting on the serial port and queue them.
  904. * Exit when the buffer is full or when no more characters are
  905. * left on the serial port.
  906. */
  907. inline void get_serial_commands() {
  908. static char serial_line_buffer[MAX_CMD_SIZE];
  909. static bool serial_comment_mode = false;
  910. // If the command buffer is empty for too long,
  911. // send "wait" to indicate Marlin is still waiting.
  912. #if NO_TIMEOUTS > 0
  913. static millis_t last_command_time = 0;
  914. const millis_t ms = millis();
  915. if (commands_in_queue == 0 && !MYSERIAL0.available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  916. SERIAL_ECHOLNPGM(MSG_WAIT);
  917. last_command_time = ms;
  918. }
  919. #endif
  920. /**
  921. * Loop while serial characters are incoming and the queue is not full
  922. */
  923. int c;
  924. while (commands_in_queue < BUFSIZE && (c = MYSERIAL0.read()) >= 0) {
  925. char serial_char = c;
  926. /**
  927. * If the character ends the line
  928. */
  929. if (serial_char == '\n' || serial_char == '\r') {
  930. serial_comment_mode = false; // end of line == end of comment
  931. // Skip empty lines and comments
  932. if (!serial_count) { thermalManager.manage_heater(); continue; }
  933. serial_line_buffer[serial_count] = 0; // Terminate string
  934. serial_count = 0; // Reset buffer
  935. char* command = serial_line_buffer;
  936. while (*command == ' ') command++; // Skip leading spaces
  937. char *npos = (*command == 'N') ? command : NULL; // Require the N parameter to start the line
  938. if (npos) {
  939. bool M110 = strstr_P(command, PSTR("M110")) != NULL;
  940. if (M110) {
  941. char* n2pos = strchr(command + 4, 'N');
  942. if (n2pos) npos = n2pos;
  943. }
  944. gcode_N = strtol(npos + 1, NULL, 10);
  945. if (gcode_N != gcode_LastN + 1 && !M110)
  946. return gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  947. char *apos = strrchr(command, '*');
  948. if (apos) {
  949. uint8_t checksum = 0, count = uint8_t(apos - command);
  950. while (count) checksum ^= command[--count];
  951. if (strtol(apos + 1, NULL, 10) != checksum)
  952. return gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  953. }
  954. else
  955. return gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  956. gcode_LastN = gcode_N;
  957. }
  958. #if ENABLED(SDSUPPORT)
  959. else if (card.saving && strcmp(command, "M29") != 0) // No line number with M29 in Pronterface
  960. return gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  961. #endif
  962. // Movement commands alert when stopped
  963. if (IsStopped()) {
  964. char* gpos = strchr(command, 'G');
  965. if (gpos) {
  966. switch (strtol(gpos + 1, NULL, 10)) {
  967. case 0:
  968. case 1:
  969. #if ENABLED(ARC_SUPPORT)
  970. case 2:
  971. case 3:
  972. #endif
  973. #if ENABLED(BEZIER_CURVE_SUPPORT)
  974. case 5:
  975. #endif
  976. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  977. LCD_MESSAGEPGM(MSG_STOPPED);
  978. break;
  979. }
  980. }
  981. }
  982. #if DISABLED(EMERGENCY_PARSER)
  983. // Process critical commands early
  984. if (strcmp(command, "M108") == 0) {
  985. wait_for_heatup = false;
  986. #if ENABLED(NEWPANEL)
  987. wait_for_user = false;
  988. #endif
  989. }
  990. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  991. if (strcmp(command, "M410") == 0) quickstop_stepper();
  992. #endif
  993. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  994. last_command_time = ms;
  995. #endif
  996. // Add the command to the queue
  997. _enqueuecommand(serial_line_buffer, true);
  998. }
  999. else if (serial_count >= MAX_CMD_SIZE - 1) {
  1000. // Keep fetching, but ignore normal characters beyond the max length
  1001. // The command will be injected when EOL is reached
  1002. }
  1003. else if (serial_char == '\\') { // Handle escapes
  1004. if ((c = MYSERIAL0.read()) >= 0 && !serial_comment_mode) // if we have one more character, copy it over
  1005. serial_line_buffer[serial_count++] = (char)c;
  1006. // otherwise do nothing
  1007. }
  1008. else { // it's not a newline, carriage return or escape char
  1009. if (serial_char == ';') serial_comment_mode = true;
  1010. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  1011. }
  1012. } // queue has space, serial has data
  1013. }
  1014. #if ENABLED(SDSUPPORT)
  1015. #if ENABLED(PRINTER_EVENT_LEDS) && HAS_RESUME_CONTINUE
  1016. static bool lights_off_after_print; // = false
  1017. #endif
  1018. /**
  1019. * Get commands from the SD Card until the command buffer is full
  1020. * or until the end of the file is reached. The special character '#'
  1021. * can also interrupt buffering.
  1022. */
  1023. inline void get_sdcard_commands() {
  1024. static bool stop_buffering = false,
  1025. sd_comment_mode = false;
  1026. if (!card.sdprinting) return;
  1027. /**
  1028. * '#' stops reading from SD to the buffer prematurely, so procedural
  1029. * macro calls are possible. If it occurs, stop_buffering is triggered
  1030. * and the buffer is run dry; this character _can_ occur in serial com
  1031. * due to checksums, however, no checksums are used in SD printing.
  1032. */
  1033. if (commands_in_queue == 0) stop_buffering = false;
  1034. uint16_t sd_count = 0;
  1035. bool card_eof = card.eof();
  1036. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  1037. const int16_t n = card.get();
  1038. char sd_char = (char)n;
  1039. card_eof = card.eof();
  1040. if (card_eof || n == -1
  1041. || sd_char == '\n' || sd_char == '\r'
  1042. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  1043. ) {
  1044. if (card_eof) {
  1045. card.printingHasFinished();
  1046. if (card.sdprinting)
  1047. sd_count = 0; // If a sub-file was printing, continue from call point
  1048. else {
  1049. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  1050. #if ENABLED(PRINTER_EVENT_LEDS)
  1051. LCD_MESSAGEPGM(MSG_INFO_COMPLETED_PRINTS);
  1052. leds.set_green();
  1053. #if HAS_RESUME_CONTINUE
  1054. lights_off_after_print = true;
  1055. enqueue_and_echo_commands_P(PSTR("M0 S"
  1056. #if ENABLED(NEWPANEL)
  1057. "1800"
  1058. #else
  1059. "60"
  1060. #endif
  1061. ));
  1062. #else
  1063. safe_delay(2000);
  1064. leds.set_off();
  1065. #endif
  1066. #endif // PRINTER_EVENT_LEDS
  1067. }
  1068. }
  1069. else if (n == -1) {
  1070. SERIAL_ERROR_START();
  1071. SERIAL_ECHOLNPGM(MSG_SD_ERR_READ);
  1072. }
  1073. if (sd_char == '#') stop_buffering = true;
  1074. sd_comment_mode = false; // for new command
  1075. // Skip empty lines and comments
  1076. if (!sd_count) { thermalManager.manage_heater(); continue; }
  1077. command_queue[cmd_queue_index_w][sd_count] = '\0'; // terminate string
  1078. sd_count = 0; // clear sd line buffer
  1079. _commit_command(false);
  1080. }
  1081. else if (sd_count >= MAX_CMD_SIZE - 1) {
  1082. /**
  1083. * Keep fetching, but ignore normal characters beyond the max length
  1084. * The command will be injected when EOL is reached
  1085. */
  1086. }
  1087. else {
  1088. if (sd_char == ';') sd_comment_mode = true;
  1089. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  1090. }
  1091. }
  1092. }
  1093. #if ENABLED(POWER_LOSS_RECOVERY)
  1094. inline bool drain_job_recovery_commands() {
  1095. static uint8_t job_recovery_commands_index = 0; // Resets on reboot
  1096. if (job_recovery_commands_count) {
  1097. if (_enqueuecommand(job_recovery_commands[job_recovery_commands_index])) {
  1098. ++job_recovery_commands_index;
  1099. if (!--job_recovery_commands_count) job_recovery_phase = JOB_RECOVERY_DONE;
  1100. }
  1101. return true;
  1102. }
  1103. return false;
  1104. }
  1105. #endif
  1106. #endif // SDSUPPORT
  1107. /**
  1108. * Add to the circular command queue the next command from:
  1109. * - The command-injection queue (injected_commands_P)
  1110. * - The active serial input (usually USB)
  1111. * - Commands left in the queue after power-loss
  1112. * - The SD card file being actively printed
  1113. */
  1114. void get_available_commands() {
  1115. // Immediate commands block the other queues
  1116. if (drain_injected_commands_P()) return;
  1117. get_serial_commands();
  1118. #if ENABLED(POWER_LOSS_RECOVERY)
  1119. // Commands for power-loss recovery take precedence
  1120. if (job_recovery_phase == JOB_RECOVERY_YES && drain_job_recovery_commands()) return;
  1121. #endif
  1122. #if ENABLED(SDSUPPORT)
  1123. get_sdcard_commands();
  1124. #endif
  1125. }
  1126. /**
  1127. * Set target_extruder from the T parameter or the active_extruder
  1128. *
  1129. * Returns TRUE if the target is invalid
  1130. */
  1131. bool get_target_extruder_from_command(const uint16_t code) {
  1132. if (parser.seenval('T')) {
  1133. const int8_t e = parser.value_byte();
  1134. if (e >= EXTRUDERS) {
  1135. SERIAL_ECHO_START();
  1136. SERIAL_CHAR('M');
  1137. SERIAL_ECHO(code);
  1138. SERIAL_ECHOLNPAIR(" " MSG_INVALID_EXTRUDER " ", e);
  1139. return true;
  1140. }
  1141. target_extruder = e;
  1142. }
  1143. else
  1144. target_extruder = active_extruder;
  1145. return false;
  1146. }
  1147. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  1148. bool extruder_duplication_enabled = false; // Used in Dual X mode 2
  1149. #endif
  1150. #if ENABLED(DUAL_X_CARRIAGE)
  1151. static DualXMode dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  1152. static float x_home_pos(const int extruder) {
  1153. if (extruder == 0)
  1154. return base_home_pos(X_AXIS);
  1155. else
  1156. /**
  1157. * In dual carriage mode the extruder offset provides an override of the
  1158. * second X-carriage position when homed - otherwise X2_HOME_POS is used.
  1159. * This allows soft recalibration of the second extruder home position
  1160. * without firmware reflash (through the M218 command).
  1161. */
  1162. return hotend_offset[X_AXIS][1] > 0 ? hotend_offset[X_AXIS][1] : X2_HOME_POS;
  1163. }
  1164. static int x_home_dir(const int extruder) { return extruder ? X2_HOME_DIR : X_HOME_DIR; }
  1165. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  1166. static bool active_extruder_parked = false; // used in mode 1 & 2
  1167. static float raised_parked_position[XYZE]; // used in mode 1
  1168. static millis_t delayed_move_time = 0; // used in mode 1
  1169. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  1170. static int16_t duplicate_extruder_temp_offset = 0; // used in mode 2
  1171. #endif // DUAL_X_CARRIAGE
  1172. #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE) || ENABLED(DELTA)
  1173. /**
  1174. * Software endstops can be used to monitor the open end of
  1175. * an axis that has a hardware endstop on the other end. Or
  1176. * they can prevent axes from moving past endstops and grinding.
  1177. *
  1178. * To keep doing their job as the coordinate system changes,
  1179. * the software endstop positions must be refreshed to remain
  1180. * at the same positions relative to the machine.
  1181. */
  1182. void update_software_endstops(const AxisEnum axis) {
  1183. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  1184. workspace_offset[axis] = home_offset[axis] + position_shift[axis];
  1185. #endif
  1186. #if ENABLED(DUAL_X_CARRIAGE)
  1187. if (axis == X_AXIS) {
  1188. // In Dual X mode hotend_offset[X] is T1's home position
  1189. const float dual_max_x = MAX(hotend_offset[X_AXIS][1], X2_MAX_POS);
  1190. if (active_extruder != 0) {
  1191. // T1 can move from X2_MIN_POS to X2_MAX_POS or X2 home position (whichever is larger)
  1192. soft_endstop_min[X_AXIS] = X2_MIN_POS;
  1193. soft_endstop_max[X_AXIS] = dual_max_x;
  1194. }
  1195. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  1196. // In Duplication Mode, T0 can move as far left as X_MIN_POS
  1197. // but not so far to the right that T1 would move past the end
  1198. soft_endstop_min[X_AXIS] = base_min_pos(X_AXIS);
  1199. soft_endstop_max[X_AXIS] = MIN(base_max_pos(X_AXIS), dual_max_x - duplicate_extruder_x_offset);
  1200. }
  1201. else {
  1202. // In other modes, T0 can move from X_MIN_POS to X_MAX_POS
  1203. soft_endstop_min[axis] = base_min_pos(axis);
  1204. soft_endstop_max[axis] = base_max_pos(axis);
  1205. }
  1206. }
  1207. #elif ENABLED(DELTA)
  1208. soft_endstop_min[axis] = base_min_pos(axis);
  1209. soft_endstop_max[axis] = axis == Z_AXIS ? delta_height
  1210. #if HAS_BED_PROBE
  1211. - zprobe_zoffset
  1212. #endif
  1213. : base_max_pos(axis);
  1214. #else
  1215. soft_endstop_min[axis] = base_min_pos(axis);
  1216. soft_endstop_max[axis] = base_max_pos(axis);
  1217. #endif
  1218. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1219. if (DEBUGGING(LEVELING)) {
  1220. SERIAL_ECHOPAIR("For ", axis_codes[axis]);
  1221. #if HAS_HOME_OFFSET
  1222. SERIAL_ECHOPAIR(" axis:\n home_offset = ", home_offset[axis]);
  1223. #endif
  1224. #if HAS_POSITION_SHIFT
  1225. SERIAL_ECHOPAIR("\n position_shift = ", position_shift[axis]);
  1226. #endif
  1227. SERIAL_ECHOPAIR("\n soft_endstop_min = ", soft_endstop_min[axis]);
  1228. SERIAL_ECHOLNPAIR("\n soft_endstop_max = ", soft_endstop_max[axis]);
  1229. }
  1230. #endif
  1231. #if ENABLED(DELTA)
  1232. switch (axis) {
  1233. #if HAS_SOFTWARE_ENDSTOPS
  1234. case X_AXIS:
  1235. case Y_AXIS:
  1236. // Get a minimum radius for clamping
  1237. soft_endstop_radius = MIN3(ABS(MAX(soft_endstop_min[X_AXIS], soft_endstop_min[Y_AXIS])), soft_endstop_max[X_AXIS], soft_endstop_max[Y_AXIS]);
  1238. soft_endstop_radius_2 = sq(soft_endstop_radius);
  1239. break;
  1240. #endif
  1241. case Z_AXIS:
  1242. delta_clip_start_height = soft_endstop_max[axis] - delta_safe_distance_from_top();
  1243. default: break;
  1244. }
  1245. #endif
  1246. }
  1247. #endif // HAS_WORKSPACE_OFFSET || DUAL_X_CARRIAGE || DELTA
  1248. #if HAS_M206_COMMAND
  1249. /**
  1250. * Change the home offset for an axis.
  1251. * Also refreshes the workspace offset.
  1252. */
  1253. static void set_home_offset(const AxisEnum axis, const float v) {
  1254. home_offset[axis] = v;
  1255. update_software_endstops(axis);
  1256. }
  1257. #endif // HAS_M206_COMMAND
  1258. /**
  1259. * Set an axis' current position to its home position (after homing).
  1260. *
  1261. * For Core and Cartesian robots this applies one-to-one when an
  1262. * individual axis has been homed.
  1263. *
  1264. * DELTA should wait until all homing is done before setting the XYZ
  1265. * current_position to home, because homing is a single operation.
  1266. * In the case where the axis positions are already known and previously
  1267. * homed, DELTA could home to X or Y individually by moving either one
  1268. * to the center. However, homing Z always homes XY and Z.
  1269. *
  1270. * SCARA should wait until all XY homing is done before setting the XY
  1271. * current_position to home, because neither X nor Y is at home until
  1272. * both are at home. Z can however be homed individually.
  1273. *
  1274. * Callers must sync the planner position after calling this!
  1275. */
  1276. static void set_axis_is_at_home(const AxisEnum axis) {
  1277. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1278. if (DEBUGGING(LEVELING)) {
  1279. SERIAL_ECHOPAIR(">>> set_axis_is_at_home(", axis_codes[axis]);
  1280. SERIAL_CHAR(')');
  1281. SERIAL_EOL();
  1282. }
  1283. #endif
  1284. SBI(axis_known_position, axis);
  1285. SBI(axis_homed, axis);
  1286. #if HAS_POSITION_SHIFT
  1287. position_shift[axis] = 0;
  1288. update_software_endstops(axis);
  1289. #endif
  1290. #if ENABLED(DUAL_X_CARRIAGE)
  1291. if (axis == X_AXIS && (active_extruder == 1 || dual_x_carriage_mode == DXC_DUPLICATION_MODE)) {
  1292. current_position[X_AXIS] = x_home_pos(active_extruder);
  1293. return;
  1294. }
  1295. #endif
  1296. #if ENABLED(MORGAN_SCARA)
  1297. /**
  1298. * Morgan SCARA homes XY at the same time
  1299. */
  1300. if (axis == X_AXIS || axis == Y_AXIS) {
  1301. float homeposition[XYZ] = {
  1302. base_home_pos(X_AXIS),
  1303. base_home_pos(Y_AXIS),
  1304. base_home_pos(Z_AXIS)
  1305. };
  1306. // SERIAL_ECHOPAIR("homeposition X:", homeposition[X_AXIS]);
  1307. // SERIAL_ECHOLNPAIR(" Y:", homeposition[Y_AXIS]);
  1308. /**
  1309. * Get Home position SCARA arm angles using inverse kinematics,
  1310. * and calculate homing offset using forward kinematics
  1311. */
  1312. inverse_kinematics(homeposition);
  1313. forward_kinematics_SCARA(delta[A_AXIS], delta[B_AXIS]);
  1314. // SERIAL_ECHOPAIR("Cartesian X:", cartes[X_AXIS]);
  1315. // SERIAL_ECHOLNPAIR(" Y:", cartes[Y_AXIS]);
  1316. current_position[axis] = cartes[axis];
  1317. /**
  1318. * SCARA home positions are based on configuration since the actual
  1319. * limits are determined by the inverse kinematic transform.
  1320. */
  1321. soft_endstop_min[axis] = base_min_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1322. soft_endstop_max[axis] = base_max_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1323. }
  1324. else
  1325. #elif ENABLED(DELTA)
  1326. current_position[axis] = (axis == Z_AXIS ? delta_height
  1327. #if HAS_BED_PROBE
  1328. - zprobe_zoffset
  1329. #endif
  1330. : base_home_pos(axis));
  1331. #else
  1332. current_position[axis] = base_home_pos(axis);
  1333. #endif
  1334. /**
  1335. * Z Probe Z Homing? Account for the probe's Z offset.
  1336. */
  1337. #if HAS_BED_PROBE && Z_HOME_DIR < 0
  1338. if (axis == Z_AXIS) {
  1339. #if HOMING_Z_WITH_PROBE
  1340. current_position[Z_AXIS] -= zprobe_zoffset;
  1341. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1342. if (DEBUGGING(LEVELING)) {
  1343. SERIAL_ECHOLNPGM("*** Z HOMED WITH PROBE (Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) ***");
  1344. SERIAL_ECHOLNPAIR("> zprobe_zoffset = ", zprobe_zoffset);
  1345. }
  1346. #endif
  1347. #elif ENABLED(DEBUG_LEVELING_FEATURE)
  1348. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("*** Z HOMED TO ENDSTOP (Z_MIN_PROBE_ENDSTOP) ***");
  1349. #endif
  1350. }
  1351. #endif
  1352. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1353. if (DEBUGGING(LEVELING)) {
  1354. #if HAS_HOME_OFFSET
  1355. SERIAL_ECHOPAIR("> home_offset[", axis_codes[axis]);
  1356. SERIAL_ECHOLNPAIR("] = ", home_offset[axis]);
  1357. #endif
  1358. DEBUG_POS("", current_position);
  1359. SERIAL_ECHOPAIR("<<< set_axis_is_at_home(", axis_codes[axis]);
  1360. SERIAL_CHAR(')');
  1361. SERIAL_EOL();
  1362. }
  1363. #endif
  1364. #if ENABLED(I2C_POSITION_ENCODERS)
  1365. I2CPEM.homed(axis);
  1366. #endif
  1367. }
  1368. /**
  1369. * Homing bump feedrate (mm/s)
  1370. */
  1371. inline float get_homing_bump_feedrate(const AxisEnum axis) {
  1372. #if HOMING_Z_WITH_PROBE
  1373. if (axis == Z_AXIS) return MMM_TO_MMS(Z_PROBE_SPEED_SLOW);
  1374. #endif
  1375. static const uint8_t homing_bump_divisor[] PROGMEM = HOMING_BUMP_DIVISOR;
  1376. uint8_t hbd = pgm_read_byte(&homing_bump_divisor[axis]);
  1377. if (hbd < 1) {
  1378. hbd = 10;
  1379. SERIAL_ECHO_START();
  1380. SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1");
  1381. }
  1382. return homing_feedrate(axis) / hbd;
  1383. }
  1384. /**
  1385. * Some planner shorthand inline functions
  1386. */
  1387. /**
  1388. * Move the planner to the current position from wherever it last moved
  1389. * (or from wherever it has been told it is located).
  1390. *
  1391. * Impossible on Hangprinter because current_position and position are of different sizes
  1392. */
  1393. inline void buffer_line_to_current_position() {
  1394. #if DISABLED(HANGPRINTER) // emptying this function probably breaks do_blocking_move_to()
  1395. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART], feedrate_mm_s, active_extruder);
  1396. #endif
  1397. }
  1398. /**
  1399. * Move the planner to the position stored in the destination array, which is
  1400. * used by G0/G1/G2/G3/G5 and many other functions to set a destination.
  1401. */
  1402. inline void buffer_line_to_destination(const float &fr_mm_s) {
  1403. #if ENABLED(HANGPRINTER)
  1404. UNUSED(fr_mm_s);
  1405. #else
  1406. planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_CART], fr_mm_s, active_extruder);
  1407. #endif
  1408. }
  1409. #if IS_KINEMATIC
  1410. /**
  1411. * Calculate delta, start a line, and set current_position to destination
  1412. */
  1413. void prepare_uninterpolated_move_to_destination(const float fr_mm_s=0) {
  1414. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1415. if (DEBUGGING(LEVELING)) DEBUG_POS("prepare_uninterpolated_move_to_destination", destination);
  1416. #endif
  1417. #if UBL_SEGMENTED
  1418. // ubl segmented line will do z-only moves in single segment
  1419. ubl.prepare_segmented_line_to(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s));
  1420. #else
  1421. if ( current_position[X_AXIS] == destination[X_AXIS]
  1422. && current_position[Y_AXIS] == destination[Y_AXIS]
  1423. && current_position[Z_AXIS] == destination[Z_AXIS]
  1424. && current_position[E_CART] == destination[E_CART]
  1425. ) return;
  1426. planner.buffer_line_kinematic(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s), active_extruder);
  1427. #endif
  1428. set_current_from_destination();
  1429. }
  1430. #endif // IS_KINEMATIC
  1431. /**
  1432. * Plan a move to (X, Y, Z) and set the current_position.
  1433. * The final current_position may not be the one that was requested
  1434. * Caution: 'destination' is modified by this function.
  1435. */
  1436. void do_blocking_move_to(const float rx, const float ry, const float rz, const float &fr_mm_s/*=0.0*/) {
  1437. const float old_feedrate_mm_s = feedrate_mm_s;
  1438. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1439. if (DEBUGGING(LEVELING)) print_xyz(PSTR(">>> do_blocking_move_to"), NULL, LOGICAL_X_POSITION(rx), LOGICAL_Y_POSITION(ry), LOGICAL_Z_POSITION(rz));
  1440. #endif
  1441. const float z_feedrate = fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS);
  1442. #if ENABLED(DELTA)
  1443. if (!position_is_reachable(rx, ry)) return;
  1444. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1445. set_destination_from_current(); // sync destination at the start
  1446. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1447. if (DEBUGGING(LEVELING)) DEBUG_POS("set_destination_from_current", destination);
  1448. #endif
  1449. // when in the danger zone
  1450. if (current_position[Z_AXIS] > delta_clip_start_height) {
  1451. if (rz > delta_clip_start_height) { // staying in the danger zone
  1452. destination[X_AXIS] = rx; // move directly (uninterpolated)
  1453. destination[Y_AXIS] = ry;
  1454. destination[Z_AXIS] = rz;
  1455. prepare_uninterpolated_move_to_destination(); // set_current_from_destination
  1456. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1457. if (DEBUGGING(LEVELING)) DEBUG_POS("danger zone move", current_position);
  1458. #endif
  1459. return;
  1460. }
  1461. destination[Z_AXIS] = delta_clip_start_height;
  1462. prepare_uninterpolated_move_to_destination(); // set_current_from_destination
  1463. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1464. if (DEBUGGING(LEVELING)) DEBUG_POS("zone border move", current_position);
  1465. #endif
  1466. }
  1467. if (rz > current_position[Z_AXIS]) { // raising?
  1468. destination[Z_AXIS] = rz;
  1469. prepare_uninterpolated_move_to_destination(z_feedrate); // set_current_from_destination
  1470. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1471. if (DEBUGGING(LEVELING)) DEBUG_POS("z raise move", current_position);
  1472. #endif
  1473. }
  1474. destination[X_AXIS] = rx;
  1475. destination[Y_AXIS] = ry;
  1476. prepare_move_to_destination(); // set_current_from_destination
  1477. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1478. if (DEBUGGING(LEVELING)) DEBUG_POS("xy move", current_position);
  1479. #endif
  1480. if (rz < current_position[Z_AXIS]) { // lowering?
  1481. destination[Z_AXIS] = rz;
  1482. prepare_uninterpolated_move_to_destination(z_feedrate); // set_current_from_destination
  1483. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1484. if (DEBUGGING(LEVELING)) DEBUG_POS("z lower move", current_position);
  1485. #endif
  1486. }
  1487. #elif IS_SCARA
  1488. if (!position_is_reachable(rx, ry)) return;
  1489. set_destination_from_current();
  1490. // If Z needs to raise, do it before moving XY
  1491. if (destination[Z_AXIS] < rz) {
  1492. destination[Z_AXIS] = rz;
  1493. prepare_uninterpolated_move_to_destination(z_feedrate);
  1494. }
  1495. destination[X_AXIS] = rx;
  1496. destination[Y_AXIS] = ry;
  1497. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S);
  1498. // If Z needs to lower, do it after moving XY
  1499. if (destination[Z_AXIS] > rz) {
  1500. destination[Z_AXIS] = rz;
  1501. prepare_uninterpolated_move_to_destination(z_feedrate);
  1502. }
  1503. #else
  1504. // If Z needs to raise, do it before moving XY
  1505. if (current_position[Z_AXIS] < rz) {
  1506. feedrate_mm_s = z_feedrate;
  1507. current_position[Z_AXIS] = rz;
  1508. buffer_line_to_current_position();
  1509. }
  1510. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1511. current_position[X_AXIS] = rx;
  1512. current_position[Y_AXIS] = ry;
  1513. buffer_line_to_current_position();
  1514. // If Z needs to lower, do it after moving XY
  1515. if (current_position[Z_AXIS] > rz) {
  1516. feedrate_mm_s = z_feedrate;
  1517. current_position[Z_AXIS] = rz;
  1518. buffer_line_to_current_position();
  1519. }
  1520. #endif
  1521. planner.synchronize();
  1522. feedrate_mm_s = old_feedrate_mm_s;
  1523. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1524. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< do_blocking_move_to");
  1525. #endif
  1526. }
  1527. void do_blocking_move_to_x(const float &rx, const float &fr_mm_s/*=0.0*/) {
  1528. do_blocking_move_to(rx, current_position[Y_AXIS], current_position[Z_AXIS], fr_mm_s);
  1529. }
  1530. void do_blocking_move_to_z(const float &rz, const float &fr_mm_s/*=0.0*/) {
  1531. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], rz, fr_mm_s);
  1532. }
  1533. void do_blocking_move_to_xy(const float &rx, const float &ry, const float &fr_mm_s/*=0.0*/) {
  1534. do_blocking_move_to(rx, ry, current_position[Z_AXIS], fr_mm_s);
  1535. }
  1536. //
  1537. // Prepare to do endstop or probe moves
  1538. // with custom feedrates.
  1539. //
  1540. // - Save current feedrates
  1541. // - Reset the rate multiplier
  1542. // - Reset the command timeout
  1543. // - Enable the endstops (for endstop moves)
  1544. //
  1545. void setup_for_endstop_or_probe_move() {
  1546. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1547. if (DEBUGGING(LEVELING)) DEBUG_POS("setup_for_endstop_or_probe_move", current_position);
  1548. #endif
  1549. saved_feedrate_mm_s = feedrate_mm_s;
  1550. saved_feedrate_percentage = feedrate_percentage;
  1551. feedrate_percentage = 100;
  1552. }
  1553. void clean_up_after_endstop_or_probe_move() {
  1554. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1555. if (DEBUGGING(LEVELING)) DEBUG_POS("clean_up_after_endstop_or_probe_move", current_position);
  1556. #endif
  1557. feedrate_mm_s = saved_feedrate_mm_s;
  1558. feedrate_percentage = saved_feedrate_percentage;
  1559. }
  1560. #if HAS_AXIS_UNHOMED_ERR
  1561. bool axis_unhomed_error(const bool x/*=true*/, const bool y/*=true*/, const bool z/*=true*/) {
  1562. #if ENABLED(HOME_AFTER_DEACTIVATE)
  1563. const bool xx = x && !TEST(axis_known_position, X_AXIS),
  1564. yy = y && !TEST(axis_known_position, Y_AXIS),
  1565. zz = z && !TEST(axis_known_position, Z_AXIS);
  1566. #else
  1567. const bool xx = x && !TEST(axis_homed, X_AXIS),
  1568. yy = y && !TEST(axis_homed, Y_AXIS),
  1569. zz = z && !TEST(axis_homed, Z_AXIS);
  1570. #endif
  1571. if (xx || yy || zz) {
  1572. SERIAL_ECHO_START();
  1573. SERIAL_ECHOPGM(MSG_HOME " ");
  1574. if (xx) SERIAL_ECHOPGM(MSG_X);
  1575. if (yy) SERIAL_ECHOPGM(MSG_Y);
  1576. if (zz) SERIAL_ECHOPGM(MSG_Z);
  1577. SERIAL_ECHOLNPGM(" " MSG_FIRST);
  1578. #if ENABLED(ULTRA_LCD)
  1579. lcd_status_printf_P(0, PSTR(MSG_HOME " %s%s%s " MSG_FIRST), xx ? MSG_X : "", yy ? MSG_Y : "", zz ? MSG_Z : "");
  1580. #endif
  1581. return true;
  1582. }
  1583. return false;
  1584. }
  1585. #endif // HAS_AXIS_UNHOMED_ERR
  1586. #if ENABLED(Z_PROBE_SLED)
  1587. #ifndef SLED_DOCKING_OFFSET
  1588. #define SLED_DOCKING_OFFSET 0
  1589. #endif
  1590. /**
  1591. * Method to dock/undock a sled designed by Charles Bell.
  1592. *
  1593. * stow[in] If false, move to MAX_X and engage the solenoid
  1594. * If true, move to MAX_X and release the solenoid
  1595. */
  1596. static void dock_sled(bool stow) {
  1597. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1598. if (DEBUGGING(LEVELING)) {
  1599. SERIAL_ECHOPAIR("dock_sled(", stow);
  1600. SERIAL_CHAR(')');
  1601. SERIAL_EOL();
  1602. }
  1603. #endif
  1604. // Dock sled a bit closer to ensure proper capturing
  1605. do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET - ((stow) ? 1 : 0));
  1606. #if HAS_SOLENOID_1 && DISABLED(EXT_SOLENOID)
  1607. WRITE(SOL1_PIN, !stow); // switch solenoid
  1608. #endif
  1609. }
  1610. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1611. FORCE_INLINE void do_blocking_move_to(const float (&raw)[XYZ], const float &fr_mm_s) {
  1612. do_blocking_move_to(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS], fr_mm_s);
  1613. }
  1614. void run_deploy_moves_script() {
  1615. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_Z)
  1616. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_X
  1617. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_X current_position[X_AXIS]
  1618. #endif
  1619. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Y
  1620. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Y current_position[Y_AXIS]
  1621. #endif
  1622. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Z
  1623. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Z current_position[Z_AXIS]
  1624. #endif
  1625. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE
  1626. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE 0.0
  1627. #endif
  1628. const float deploy_1[] = { Z_PROBE_ALLEN_KEY_DEPLOY_1_X, Z_PROBE_ALLEN_KEY_DEPLOY_1_Y, Z_PROBE_ALLEN_KEY_DEPLOY_1_Z };
  1629. do_blocking_move_to(deploy_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE));
  1630. #endif
  1631. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_Z)
  1632. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_X
  1633. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_X current_position[X_AXIS]
  1634. #endif
  1635. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Y
  1636. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Y current_position[Y_AXIS]
  1637. #endif
  1638. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Z
  1639. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Z current_position[Z_AXIS]
  1640. #endif
  1641. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE
  1642. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE 0.0
  1643. #endif
  1644. const float deploy_2[] = { Z_PROBE_ALLEN_KEY_DEPLOY_2_X, Z_PROBE_ALLEN_KEY_DEPLOY_2_Y, Z_PROBE_ALLEN_KEY_DEPLOY_2_Z };
  1645. do_blocking_move_to(deploy_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE));
  1646. #endif
  1647. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_Z)
  1648. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_X
  1649. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_X current_position[X_AXIS]
  1650. #endif
  1651. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Y
  1652. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Y current_position[Y_AXIS]
  1653. #endif
  1654. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Z
  1655. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Z current_position[Z_AXIS]
  1656. #endif
  1657. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE
  1658. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE 0.0
  1659. #endif
  1660. const float deploy_3[] = { Z_PROBE_ALLEN_KEY_DEPLOY_3_X, Z_PROBE_ALLEN_KEY_DEPLOY_3_Y, Z_PROBE_ALLEN_KEY_DEPLOY_3_Z };
  1661. do_blocking_move_to(deploy_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE));
  1662. #endif
  1663. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_Z)
  1664. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_X
  1665. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_X current_position[X_AXIS]
  1666. #endif
  1667. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Y
  1668. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Y current_position[Y_AXIS]
  1669. #endif
  1670. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Z
  1671. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Z current_position[Z_AXIS]
  1672. #endif
  1673. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE
  1674. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE 0.0
  1675. #endif
  1676. const float deploy_4[] = { Z_PROBE_ALLEN_KEY_DEPLOY_4_X, Z_PROBE_ALLEN_KEY_DEPLOY_4_Y, Z_PROBE_ALLEN_KEY_DEPLOY_4_Z };
  1677. do_blocking_move_to(deploy_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE));
  1678. #endif
  1679. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_Z)
  1680. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_X
  1681. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_X current_position[X_AXIS]
  1682. #endif
  1683. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Y
  1684. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Y current_position[Y_AXIS]
  1685. #endif
  1686. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Z
  1687. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Z current_position[Z_AXIS]
  1688. #endif
  1689. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE
  1690. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE 0.0
  1691. #endif
  1692. const float deploy_5[] = { Z_PROBE_ALLEN_KEY_DEPLOY_5_X, Z_PROBE_ALLEN_KEY_DEPLOY_5_Y, Z_PROBE_ALLEN_KEY_DEPLOY_5_Z };
  1693. do_blocking_move_to(deploy_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE));
  1694. #endif
  1695. }
  1696. void run_stow_moves_script() {
  1697. #if defined(Z_PROBE_ALLEN_KEY_STOW_1_X) || defined(Z_PROBE_ALLEN_KEY_STOW_1_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_1_Z)
  1698. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_X
  1699. #define Z_PROBE_ALLEN_KEY_STOW_1_X current_position[X_AXIS]
  1700. #endif
  1701. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Y
  1702. #define Z_PROBE_ALLEN_KEY_STOW_1_Y current_position[Y_AXIS]
  1703. #endif
  1704. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Z
  1705. #define Z_PROBE_ALLEN_KEY_STOW_1_Z current_position[Z_AXIS]
  1706. #endif
  1707. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE
  1708. #define Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE 0.0
  1709. #endif
  1710. const float stow_1[] = { Z_PROBE_ALLEN_KEY_STOW_1_X, Z_PROBE_ALLEN_KEY_STOW_1_Y, Z_PROBE_ALLEN_KEY_STOW_1_Z };
  1711. do_blocking_move_to(stow_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE));
  1712. #endif
  1713. #if defined(Z_PROBE_ALLEN_KEY_STOW_2_X) || defined(Z_PROBE_ALLEN_KEY_STOW_2_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_2_Z)
  1714. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_X
  1715. #define Z_PROBE_ALLEN_KEY_STOW_2_X current_position[X_AXIS]
  1716. #endif
  1717. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Y
  1718. #define Z_PROBE_ALLEN_KEY_STOW_2_Y current_position[Y_AXIS]
  1719. #endif
  1720. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Z
  1721. #define Z_PROBE_ALLEN_KEY_STOW_2_Z current_position[Z_AXIS]
  1722. #endif
  1723. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE
  1724. #define Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE 0.0
  1725. #endif
  1726. const float stow_2[] = { Z_PROBE_ALLEN_KEY_STOW_2_X, Z_PROBE_ALLEN_KEY_STOW_2_Y, Z_PROBE_ALLEN_KEY_STOW_2_Z };
  1727. do_blocking_move_to(stow_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE));
  1728. #endif
  1729. #if defined(Z_PROBE_ALLEN_KEY_STOW_3_X) || defined(Z_PROBE_ALLEN_KEY_STOW_3_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_3_Z)
  1730. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_X
  1731. #define Z_PROBE_ALLEN_KEY_STOW_3_X current_position[X_AXIS]
  1732. #endif
  1733. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Y
  1734. #define Z_PROBE_ALLEN_KEY_STOW_3_Y current_position[Y_AXIS]
  1735. #endif
  1736. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Z
  1737. #define Z_PROBE_ALLEN_KEY_STOW_3_Z current_position[Z_AXIS]
  1738. #endif
  1739. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE
  1740. #define Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE 0.0
  1741. #endif
  1742. const float stow_3[] = { Z_PROBE_ALLEN_KEY_STOW_3_X, Z_PROBE_ALLEN_KEY_STOW_3_Y, Z_PROBE_ALLEN_KEY_STOW_3_Z };
  1743. do_blocking_move_to(stow_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE));
  1744. #endif
  1745. #if defined(Z_PROBE_ALLEN_KEY_STOW_4_X) || defined(Z_PROBE_ALLEN_KEY_STOW_4_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_4_Z)
  1746. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_X
  1747. #define Z_PROBE_ALLEN_KEY_STOW_4_X current_position[X_AXIS]
  1748. #endif
  1749. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Y
  1750. #define Z_PROBE_ALLEN_KEY_STOW_4_Y current_position[Y_AXIS]
  1751. #endif
  1752. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Z
  1753. #define Z_PROBE_ALLEN_KEY_STOW_4_Z current_position[Z_AXIS]
  1754. #endif
  1755. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE
  1756. #define Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE 0.0
  1757. #endif
  1758. const float stow_4[] = { Z_PROBE_ALLEN_KEY_STOW_4_X, Z_PROBE_ALLEN_KEY_STOW_4_Y, Z_PROBE_ALLEN_KEY_STOW_4_Z };
  1759. do_blocking_move_to(stow_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE));
  1760. #endif
  1761. #if defined(Z_PROBE_ALLEN_KEY_STOW_5_X) || defined(Z_PROBE_ALLEN_KEY_STOW_5_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_5_Z)
  1762. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_X
  1763. #define Z_PROBE_ALLEN_KEY_STOW_5_X current_position[X_AXIS]
  1764. #endif
  1765. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Y
  1766. #define Z_PROBE_ALLEN_KEY_STOW_5_Y current_position[Y_AXIS]
  1767. #endif
  1768. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Z
  1769. #define Z_PROBE_ALLEN_KEY_STOW_5_Z current_position[Z_AXIS]
  1770. #endif
  1771. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE
  1772. #define Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE 0.0
  1773. #endif
  1774. const float stow_5[] = { Z_PROBE_ALLEN_KEY_STOW_5_X, Z_PROBE_ALLEN_KEY_STOW_5_Y, Z_PROBE_ALLEN_KEY_STOW_5_Z };
  1775. do_blocking_move_to(stow_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE));
  1776. #endif
  1777. }
  1778. #endif // Z_PROBE_ALLEN_KEY
  1779. #if ENABLED(PROBING_FANS_OFF)
  1780. void fans_pause(const bool p) {
  1781. if (p != fans_paused) {
  1782. fans_paused = p;
  1783. if (p)
  1784. for (uint8_t x = 0; x < FAN_COUNT; x++) {
  1785. paused_fanSpeeds[x] = fanSpeeds[x];
  1786. fanSpeeds[x] = 0;
  1787. }
  1788. else
  1789. for (uint8_t x = 0; x < FAN_COUNT; x++)
  1790. fanSpeeds[x] = paused_fanSpeeds[x];
  1791. }
  1792. }
  1793. #endif // PROBING_FANS_OFF
  1794. #if HAS_BED_PROBE
  1795. // TRIGGERED_WHEN_STOWED_TEST can easily be extended to servo probes, ... if needed.
  1796. #if ENABLED(PROBE_IS_TRIGGERED_WHEN_STOWED_TEST)
  1797. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1798. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING)
  1799. #else
  1800. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING)
  1801. #endif
  1802. #endif
  1803. #if QUIET_PROBING
  1804. void probing_pause(const bool p) {
  1805. #if ENABLED(PROBING_HEATERS_OFF)
  1806. thermalManager.pause(p);
  1807. #endif
  1808. #if ENABLED(PROBING_FANS_OFF)
  1809. fans_pause(p);
  1810. #endif
  1811. if (p) safe_delay(
  1812. #if DELAY_BEFORE_PROBING > 25
  1813. DELAY_BEFORE_PROBING
  1814. #else
  1815. 25
  1816. #endif
  1817. );
  1818. }
  1819. #endif // QUIET_PROBING
  1820. #if ENABLED(BLTOUCH)
  1821. void bltouch_command(int angle) {
  1822. MOVE_SERVO(Z_PROBE_SERVO_NR, angle); // Give the BL-Touch the command and wait
  1823. safe_delay(BLTOUCH_DELAY);
  1824. }
  1825. bool set_bltouch_deployed(const bool deploy) {
  1826. if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered
  1827. bltouch_command(BLTOUCH_RESET); // try to reset it.
  1828. bltouch_command(BLTOUCH_DEPLOY); // Also needs to deploy and stow to
  1829. bltouch_command(BLTOUCH_STOW); // clear the triggered condition.
  1830. safe_delay(1500); // Wait for internal self-test to complete.
  1831. // (Measured completion time was 0.65 seconds
  1832. // after reset, deploy, and stow sequence)
  1833. if (TEST_BLTOUCH()) { // If it still claims to be triggered...
  1834. SERIAL_ERROR_START();
  1835. SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH);
  1836. stop(); // punt!
  1837. return true;
  1838. }
  1839. }
  1840. bltouch_command(deploy ? BLTOUCH_DEPLOY : BLTOUCH_STOW);
  1841. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1842. if (DEBUGGING(LEVELING)) {
  1843. SERIAL_ECHOPAIR("set_bltouch_deployed(", deploy);
  1844. SERIAL_CHAR(')');
  1845. SERIAL_EOL();
  1846. }
  1847. #endif
  1848. return false;
  1849. }
  1850. #endif // BLTOUCH
  1851. /**
  1852. * Raise Z to a minimum height to make room for a probe to move
  1853. */
  1854. inline void do_probe_raise(const float z_raise) {
  1855. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1856. if (DEBUGGING(LEVELING)) {
  1857. SERIAL_ECHOPAIR("do_probe_raise(", z_raise);
  1858. SERIAL_CHAR(')');
  1859. SERIAL_EOL();
  1860. }
  1861. #endif
  1862. float z_dest = z_raise;
  1863. if (zprobe_zoffset < 0) z_dest -= zprobe_zoffset;
  1864. NOMORE(z_dest, Z_MAX_POS);
  1865. if (z_dest > current_position[Z_AXIS])
  1866. do_blocking_move_to_z(z_dest);
  1867. }
  1868. // returns false for ok and true for failure
  1869. bool set_probe_deployed(const bool deploy) {
  1870. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1871. if (DEBUGGING(LEVELING)) {
  1872. DEBUG_POS("set_probe_deployed", current_position);
  1873. SERIAL_ECHOLNPAIR("deploy: ", deploy);
  1874. }
  1875. #endif
  1876. if (endstops.z_probe_enabled == deploy) return false;
  1877. // Make room for probe to deploy (or stow)
  1878. // Fix-mounted probe should only raise for deploy
  1879. #if ENABLED(FIX_MOUNTED_PROBE)
  1880. const bool deploy_stow_condition = deploy;
  1881. #else
  1882. constexpr bool deploy_stow_condition = true;
  1883. #endif
  1884. // For beds that fall when Z is powered off only raise for trusted Z
  1885. #if ENABLED(UNKNOWN_Z_NO_RAISE)
  1886. const bool unknown_condition = TEST(axis_known_position, Z_AXIS);
  1887. #else
  1888. constexpr float unknown_condition = true;
  1889. #endif
  1890. if (deploy_stow_condition && unknown_condition)
  1891. do_probe_raise(MAX(Z_CLEARANCE_BETWEEN_PROBES, Z_CLEARANCE_DEPLOY_PROBE));
  1892. #if ENABLED(Z_PROBE_SLED) || ENABLED(Z_PROBE_ALLEN_KEY)
  1893. #if ENABLED(Z_PROBE_SLED)
  1894. #define _AUE_ARGS true, false, false
  1895. #else
  1896. #define _AUE_ARGS
  1897. #endif
  1898. if (axis_unhomed_error(_AUE_ARGS)) {
  1899. SERIAL_ERROR_START();
  1900. SERIAL_ERRORLNPGM(MSG_STOP_UNHOMED);
  1901. stop();
  1902. return true;
  1903. }
  1904. #endif
  1905. const float oldXpos = current_position[X_AXIS],
  1906. oldYpos = current_position[Y_AXIS];
  1907. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1908. // If endstop is already false, the Z probe is deployed
  1909. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // closed after the probe specific actions.
  1910. // Would a goto be less ugly?
  1911. //while (!_TRIGGERED_WHEN_STOWED_TEST) idle(); // would offer the opportunity
  1912. // for a triggered when stowed manual probe.
  1913. if (!deploy) endstops.enable_z_probe(false); // Switch off triggered when stowed probes early
  1914. // otherwise an Allen-Key probe can't be stowed.
  1915. #endif
  1916. #if ENABLED(SOLENOID_PROBE)
  1917. #if HAS_SOLENOID_1
  1918. WRITE(SOL1_PIN, deploy);
  1919. #endif
  1920. #elif ENABLED(Z_PROBE_SLED)
  1921. dock_sled(!deploy);
  1922. #elif HAS_Z_SERVO_PROBE && DISABLED(BLTOUCH)
  1923. MOVE_SERVO(Z_PROBE_SERVO_NR, z_servo_angle[deploy ? 0 : 1]);
  1924. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1925. deploy ? run_deploy_moves_script() : run_stow_moves_script();
  1926. #endif
  1927. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1928. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1929. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // State hasn't changed?
  1930. if (IsRunning()) {
  1931. SERIAL_ERROR_START();
  1932. SERIAL_ERRORLNPGM("Z-Probe failed");
  1933. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1934. }
  1935. stop();
  1936. return true;
  1937. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1938. #endif
  1939. do_blocking_move_to(oldXpos, oldYpos, current_position[Z_AXIS]); // return to position before deploy
  1940. endstops.enable_z_probe(deploy);
  1941. return false;
  1942. }
  1943. /**
  1944. * @brief Used by run_z_probe to do a single Z probe move.
  1945. *
  1946. * @param z Z destination
  1947. * @param fr_mm_s Feedrate in mm/s
  1948. * @return true to indicate an error
  1949. */
  1950. static bool do_probe_move(const float z, const float fr_mm_s) {
  1951. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1952. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> do_probe_move", current_position);
  1953. #endif
  1954. #if HAS_HEATED_BED && ENABLED(WAIT_FOR_BED_HEATER)
  1955. // Wait for bed to heat back up between probing points
  1956. if (thermalManager.isHeatingBed()) {
  1957. serialprintPGM(msg_wait_for_bed_heating);
  1958. LCD_MESSAGEPGM(MSG_BED_HEATING);
  1959. while (thermalManager.isHeatingBed()) safe_delay(200);
  1960. lcd_reset_status();
  1961. }
  1962. #endif
  1963. // Deploy BLTouch at the start of any probe
  1964. #if ENABLED(BLTOUCH)
  1965. if (set_bltouch_deployed(true)) return true;
  1966. #endif
  1967. #if QUIET_PROBING
  1968. probing_pause(true);
  1969. #endif
  1970. // Move down until probe triggered
  1971. do_blocking_move_to_z(z, fr_mm_s);
  1972. // Check to see if the probe was triggered
  1973. const bool probe_triggered = TEST(endstops.trigger_state(),
  1974. #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN)
  1975. Z_MIN
  1976. #else
  1977. Z_MIN_PROBE
  1978. #endif
  1979. );
  1980. #if QUIET_PROBING
  1981. probing_pause(false);
  1982. #endif
  1983. // Retract BLTouch immediately after a probe if it was triggered
  1984. #if ENABLED(BLTOUCH)
  1985. if (probe_triggered && set_bltouch_deployed(false)) return true;
  1986. #endif
  1987. endstops.hit_on_purpose();
  1988. // Get Z where the steppers were interrupted
  1989. set_current_from_steppers_for_axis(Z_AXIS);
  1990. // Tell the planner where we actually are
  1991. SYNC_PLAN_POSITION_KINEMATIC();
  1992. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1993. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< do_probe_move", current_position);
  1994. #endif
  1995. return !probe_triggered;
  1996. }
  1997. /**
  1998. * @details Used by probe_pt to do a single Z probe at the current position.
  1999. * Leaves current_position[Z_AXIS] at the height where the probe triggered.
  2000. *
  2001. * @return The raw Z position where the probe was triggered
  2002. */
  2003. static float run_z_probe() {
  2004. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2005. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> run_z_probe", current_position);
  2006. #endif
  2007. // Stop the probe before it goes too low to prevent damage.
  2008. // If Z isn't known then probe to -10mm.
  2009. const float z_probe_low_point = TEST(axis_known_position, Z_AXIS) ? -zprobe_zoffset + Z_PROBE_LOW_POINT : -10.0;
  2010. // Double-probing does a fast probe followed by a slow probe
  2011. #if MULTIPLE_PROBING == 2
  2012. // Do a first probe at the fast speed
  2013. if (do_probe_move(z_probe_low_point, MMM_TO_MMS(Z_PROBE_SPEED_FAST))) {
  2014. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2015. if (DEBUGGING(LEVELING)) {
  2016. SERIAL_ECHOLNPGM("FAST Probe fail!");
  2017. DEBUG_POS("<<< run_z_probe", current_position);
  2018. }
  2019. #endif
  2020. return NAN;
  2021. }
  2022. float first_probe_z = current_position[Z_AXIS];
  2023. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2024. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("1st Probe Z:", first_probe_z);
  2025. #endif
  2026. // move up to make clearance for the probe
  2027. do_blocking_move_to_z(current_position[Z_AXIS] + Z_CLEARANCE_MULTI_PROBE, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  2028. #else
  2029. // If the nozzle is well over the travel height then
  2030. // move down quickly before doing the slow probe
  2031. float z = Z_CLEARANCE_DEPLOY_PROBE + 5.0;
  2032. if (zprobe_zoffset < 0) z -= zprobe_zoffset;
  2033. if (current_position[Z_AXIS] > z) {
  2034. // If we don't make it to the z position (i.e. the probe triggered), move up to make clearance for the probe
  2035. if (!do_probe_move(z, MMM_TO_MMS(Z_PROBE_SPEED_FAST)))
  2036. do_blocking_move_to_z(current_position[Z_AXIS] + Z_CLEARANCE_BETWEEN_PROBES, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  2037. }
  2038. #endif
  2039. #if MULTIPLE_PROBING > 2
  2040. float probes_total = 0;
  2041. for (uint8_t p = MULTIPLE_PROBING + 1; --p;) {
  2042. #endif
  2043. // move down slowly to find bed
  2044. if (do_probe_move(z_probe_low_point, MMM_TO_MMS(Z_PROBE_SPEED_SLOW))) {
  2045. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2046. if (DEBUGGING(LEVELING)) {
  2047. SERIAL_ECHOLNPGM("SLOW Probe fail!");
  2048. DEBUG_POS("<<< run_z_probe", current_position);
  2049. }
  2050. #endif
  2051. return NAN;
  2052. }
  2053. #if MULTIPLE_PROBING > 2
  2054. probes_total += current_position[Z_AXIS];
  2055. if (p > 1) do_blocking_move_to_z(current_position[Z_AXIS] + Z_CLEARANCE_MULTI_PROBE, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  2056. }
  2057. #endif
  2058. #if MULTIPLE_PROBING > 2
  2059. // Return the average value of all probes
  2060. const float measured_z = probes_total * (1.0f / (MULTIPLE_PROBING));
  2061. #elif MULTIPLE_PROBING == 2
  2062. const float z2 = current_position[Z_AXIS];
  2063. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2064. if (DEBUGGING(LEVELING)) {
  2065. SERIAL_ECHOPAIR("2nd Probe Z:", z2);
  2066. SERIAL_ECHOLNPAIR(" Discrepancy:", first_probe_z - z2);
  2067. }
  2068. #endif
  2069. // Return a weighted average of the fast and slow probes
  2070. const float measured_z = (z2 * 3.0 + first_probe_z * 2.0) * 0.2;
  2071. #else
  2072. // Return the single probe result
  2073. const float measured_z = current_position[Z_AXIS];
  2074. #endif
  2075. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2076. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< run_z_probe", current_position);
  2077. #endif
  2078. return measured_z;
  2079. }
  2080. /**
  2081. * - Move to the given XY
  2082. * - Deploy the probe, if not already deployed
  2083. * - Probe the bed, get the Z position
  2084. * - Depending on the 'stow' flag
  2085. * - Stow the probe, or
  2086. * - Raise to the BETWEEN height
  2087. * - Return the probed Z position
  2088. */
  2089. float probe_pt(const float &rx, const float &ry, const ProbePtRaise raise_after/*=PROBE_PT_NONE*/, const uint8_t verbose_level/*=0*/, const bool probe_relative/*=true*/) {
  2090. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2091. if (DEBUGGING(LEVELING)) {
  2092. SERIAL_ECHOPAIR(">>> probe_pt(", LOGICAL_X_POSITION(rx));
  2093. SERIAL_ECHOPAIR(", ", LOGICAL_Y_POSITION(ry));
  2094. SERIAL_ECHOPAIR(", ", raise_after == PROBE_PT_RAISE ? "raise" : raise_after == PROBE_PT_STOW ? "stow" : "none");
  2095. SERIAL_ECHOPAIR(", ", int(verbose_level));
  2096. SERIAL_ECHOPAIR(", ", probe_relative ? "probe" : "nozzle");
  2097. SERIAL_ECHOLNPGM("_relative)");
  2098. DEBUG_POS("", current_position);
  2099. }
  2100. #endif
  2101. // TODO: Adapt for SCARA, where the offset rotates
  2102. float nx = rx, ny = ry;
  2103. if (probe_relative) {
  2104. if (!position_is_reachable_by_probe(rx, ry)) return NAN; // The given position is in terms of the probe
  2105. nx -= (X_PROBE_OFFSET_FROM_EXTRUDER); // Get the nozzle position
  2106. ny -= (Y_PROBE_OFFSET_FROM_EXTRUDER);
  2107. }
  2108. else if (!position_is_reachable(nx, ny)) return NAN; // The given position is in terms of the nozzle
  2109. const float nz =
  2110. #if ENABLED(DELTA)
  2111. // Move below clip height or xy move will be aborted by do_blocking_move_to
  2112. MIN(current_position[Z_AXIS], delta_clip_start_height)
  2113. #else
  2114. current_position[Z_AXIS]
  2115. #endif
  2116. ;
  2117. const float old_feedrate_mm_s = feedrate_mm_s;
  2118. feedrate_mm_s = XY_PROBE_FEEDRATE_MM_S;
  2119. // Move the probe to the starting XYZ
  2120. do_blocking_move_to(nx, ny, nz);
  2121. float measured_z = NAN;
  2122. if (!DEPLOY_PROBE()) {
  2123. measured_z = run_z_probe() + zprobe_zoffset;
  2124. const bool big_raise = raise_after == PROBE_PT_BIG_RAISE;
  2125. if (big_raise || raise_after == PROBE_PT_RAISE)
  2126. do_blocking_move_to_z(current_position[Z_AXIS] + (big_raise ? 25 : Z_CLEARANCE_BETWEEN_PROBES), MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  2127. else if (raise_after == PROBE_PT_STOW)
  2128. if (STOW_PROBE()) measured_z = NAN;
  2129. }
  2130. if (verbose_level > 2) {
  2131. SERIAL_PROTOCOLPGM("Bed X: ");
  2132. SERIAL_PROTOCOL_F(LOGICAL_X_POSITION(rx), 3);
  2133. SERIAL_PROTOCOLPGM(" Y: ");
  2134. SERIAL_PROTOCOL_F(LOGICAL_Y_POSITION(ry), 3);
  2135. SERIAL_PROTOCOLPGM(" Z: ");
  2136. SERIAL_PROTOCOL_F(measured_z, 3);
  2137. SERIAL_EOL();
  2138. }
  2139. feedrate_mm_s = old_feedrate_mm_s;
  2140. if (isnan(measured_z)) {
  2141. LCD_MESSAGEPGM(MSG_ERR_PROBING_FAILED);
  2142. SERIAL_ERROR_START();
  2143. SERIAL_ERRORLNPGM(MSG_ERR_PROBING_FAILED);
  2144. }
  2145. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2146. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< probe_pt");
  2147. #endif
  2148. return measured_z;
  2149. }
  2150. #endif // HAS_BED_PROBE
  2151. #if HAS_LEVELING
  2152. bool leveling_is_valid() {
  2153. return
  2154. #if ENABLED(MESH_BED_LEVELING)
  2155. mbl.has_mesh()
  2156. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2157. !!bilinear_grid_spacing[X_AXIS]
  2158. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2159. ubl.mesh_is_valid()
  2160. #else // 3POINT, LINEAR
  2161. true
  2162. #endif
  2163. ;
  2164. }
  2165. /**
  2166. * Turn bed leveling on or off, fixing the current
  2167. * position as-needed.
  2168. *
  2169. * Disable: Current position = physical position
  2170. * Enable: Current position = "unleveled" physical position
  2171. */
  2172. void set_bed_leveling_enabled(const bool enable/*=true*/) {
  2173. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2174. const bool can_change = (!enable || leveling_is_valid());
  2175. #else
  2176. constexpr bool can_change = true;
  2177. #endif
  2178. if (can_change && enable != planner.leveling_active) {
  2179. planner.synchronize();
  2180. #if ENABLED(MESH_BED_LEVELING)
  2181. if (!enable)
  2182. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2183. const bool enabling = enable && leveling_is_valid();
  2184. planner.leveling_active = enabling;
  2185. if (enabling) planner.unapply_leveling(current_position);
  2186. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2187. #if PLANNER_LEVELING
  2188. if (planner.leveling_active) { // leveling from on to off
  2189. // change unleveled current_position to physical current_position without moving steppers.
  2190. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2191. planner.leveling_active = false; // disable only AFTER calling apply_leveling
  2192. }
  2193. else { // leveling from off to on
  2194. planner.leveling_active = true; // enable BEFORE calling unapply_leveling, otherwise ignored
  2195. // change physical current_position to unleveled current_position without moving steppers.
  2196. planner.unapply_leveling(current_position);
  2197. }
  2198. #else
  2199. // UBL equivalents for apply/unapply_leveling
  2200. #if ENABLED(SKEW_CORRECTION)
  2201. float pos[XYZ] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  2202. planner.skew(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS]);
  2203. #else
  2204. const float (&pos)[XYZE] = current_position;
  2205. #endif
  2206. if (planner.leveling_active) {
  2207. current_position[Z_AXIS] += ubl.get_z_correction(pos[X_AXIS], pos[Y_AXIS]);
  2208. planner.leveling_active = false;
  2209. }
  2210. else {
  2211. planner.leveling_active = true;
  2212. current_position[Z_AXIS] -= ubl.get_z_correction(pos[X_AXIS], pos[Y_AXIS]);
  2213. }
  2214. #endif
  2215. #else // ABL
  2216. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2217. // Force bilinear_z_offset to re-calculate next time
  2218. const float reset[XYZ] = { -9999.999, -9999.999, 0 };
  2219. (void)bilinear_z_offset(reset);
  2220. #endif
  2221. // Enable or disable leveling compensation in the planner
  2222. planner.leveling_active = enable;
  2223. if (!enable)
  2224. // When disabling just get the current position from the steppers.
  2225. // This will yield the smallest error when first converted back to steps.
  2226. set_current_from_steppers_for_axis(
  2227. #if ABL_PLANAR
  2228. ALL_AXES
  2229. #else
  2230. Z_AXIS
  2231. #endif
  2232. );
  2233. else
  2234. // When enabling, remove compensation from the current position,
  2235. // so compensation will give the right stepper counts.
  2236. planner.unapply_leveling(current_position);
  2237. SYNC_PLAN_POSITION_KINEMATIC();
  2238. #endif // ABL
  2239. }
  2240. }
  2241. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  2242. void set_z_fade_height(const float zfh, const bool do_report/*=true*/) {
  2243. if (planner.z_fade_height == zfh) return;
  2244. const bool leveling_was_active = planner.leveling_active;
  2245. set_bed_leveling_enabled(false);
  2246. planner.set_z_fade_height(zfh);
  2247. if (leveling_was_active) {
  2248. const float oldpos[] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  2249. set_bed_leveling_enabled(true);
  2250. if (do_report && memcmp(oldpos, current_position, sizeof(oldpos)))
  2251. report_current_position();
  2252. }
  2253. }
  2254. #endif // LEVELING_FADE_HEIGHT
  2255. /**
  2256. * Reset calibration results to zero.
  2257. */
  2258. void reset_bed_level() {
  2259. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2260. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("reset_bed_level");
  2261. #endif
  2262. set_bed_leveling_enabled(false);
  2263. #if ENABLED(MESH_BED_LEVELING)
  2264. mbl.reset();
  2265. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2266. ubl.reset();
  2267. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2268. bilinear_start[X_AXIS] = bilinear_start[Y_AXIS] =
  2269. bilinear_grid_spacing[X_AXIS] = bilinear_grid_spacing[Y_AXIS] = 0;
  2270. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2271. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2272. z_values[x][y] = NAN;
  2273. #elif ABL_PLANAR
  2274. planner.bed_level_matrix.set_to_identity();
  2275. #endif
  2276. }
  2277. #endif // HAS_LEVELING
  2278. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(MESH_BED_LEVELING)
  2279. /**
  2280. * Enable to produce output in JSON format suitable
  2281. * for SCAD or JavaScript mesh visualizers.
  2282. *
  2283. * Visualize meshes in OpenSCAD using the included script.
  2284. *
  2285. * buildroot/shared/scripts/MarlinMesh.scad
  2286. */
  2287. //#define SCAD_MESH_OUTPUT
  2288. /**
  2289. * Print calibration results for plotting or manual frame adjustment.
  2290. */
  2291. void print_2d_array(const uint8_t sx, const uint8_t sy, const uint8_t precision, const element_2d_fn fn) {
  2292. #ifndef SCAD_MESH_OUTPUT
  2293. for (uint8_t x = 0; x < sx; x++) {
  2294. for (uint8_t i = 0; i < precision + 2 + (x < 10 ? 1 : 0); i++)
  2295. SERIAL_PROTOCOLCHAR(' ');
  2296. SERIAL_PROTOCOL(int(x));
  2297. }
  2298. SERIAL_EOL();
  2299. #endif
  2300. #ifdef SCAD_MESH_OUTPUT
  2301. SERIAL_PROTOCOLLNPGM("measured_z = ["); // open 2D array
  2302. #endif
  2303. for (uint8_t y = 0; y < sy; y++) {
  2304. #ifdef SCAD_MESH_OUTPUT
  2305. SERIAL_PROTOCOLPGM(" ["); // open sub-array
  2306. #else
  2307. if (y < 10) SERIAL_PROTOCOLCHAR(' ');
  2308. SERIAL_PROTOCOL(int(y));
  2309. #endif
  2310. for (uint8_t x = 0; x < sx; x++) {
  2311. SERIAL_PROTOCOLCHAR(' ');
  2312. const float offset = fn(x, y);
  2313. if (!isnan(offset)) {
  2314. if (offset >= 0) SERIAL_PROTOCOLCHAR('+');
  2315. SERIAL_PROTOCOL_F(offset, int(precision));
  2316. }
  2317. else {
  2318. #ifdef SCAD_MESH_OUTPUT
  2319. for (uint8_t i = 3; i < precision + 3; i++)
  2320. SERIAL_PROTOCOLCHAR(' ');
  2321. SERIAL_PROTOCOLPGM("NAN");
  2322. #else
  2323. for (uint8_t i = 0; i < precision + 3; i++)
  2324. SERIAL_PROTOCOLCHAR(i ? '=' : ' ');
  2325. #endif
  2326. }
  2327. #ifdef SCAD_MESH_OUTPUT
  2328. if (x < sx - 1) SERIAL_PROTOCOLCHAR(',');
  2329. #endif
  2330. }
  2331. #ifdef SCAD_MESH_OUTPUT
  2332. SERIAL_PROTOCOLCHAR(' ');
  2333. SERIAL_PROTOCOLCHAR(']'); // close sub-array
  2334. if (y < sy - 1) SERIAL_PROTOCOLCHAR(',');
  2335. #endif
  2336. SERIAL_EOL();
  2337. }
  2338. #ifdef SCAD_MESH_OUTPUT
  2339. SERIAL_PROTOCOLPGM("];"); // close 2D array
  2340. #endif
  2341. SERIAL_EOL();
  2342. }
  2343. #endif
  2344. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2345. /**
  2346. * Extrapolate a single point from its neighbors
  2347. */
  2348. static void extrapolate_one_point(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) {
  2349. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2350. if (DEBUGGING(LEVELING)) {
  2351. SERIAL_ECHOPGM("Extrapolate [");
  2352. if (x < 10) SERIAL_CHAR(' ');
  2353. SERIAL_ECHO(int(x));
  2354. SERIAL_CHAR(xdir ? (xdir > 0 ? '+' : '-') : ' ');
  2355. SERIAL_CHAR(' ');
  2356. if (y < 10) SERIAL_CHAR(' ');
  2357. SERIAL_ECHO(int(y));
  2358. SERIAL_CHAR(ydir ? (ydir > 0 ? '+' : '-') : ' ');
  2359. SERIAL_CHAR(']');
  2360. }
  2361. #endif
  2362. if (!isnan(z_values[x][y])) {
  2363. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2364. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM(" (done)");
  2365. #endif
  2366. return; // Don't overwrite good values.
  2367. }
  2368. SERIAL_EOL();
  2369. // Get X neighbors, Y neighbors, and XY neighbors
  2370. const uint8_t x1 = x + xdir, y1 = y + ydir, x2 = x1 + xdir, y2 = y1 + ydir;
  2371. float a1 = z_values[x1][y ], a2 = z_values[x2][y ],
  2372. b1 = z_values[x ][y1], b2 = z_values[x ][y2],
  2373. c1 = z_values[x1][y1], c2 = z_values[x2][y2];
  2374. // Treat far unprobed points as zero, near as equal to far
  2375. if (isnan(a2)) a2 = 0.0; if (isnan(a1)) a1 = a2;
  2376. if (isnan(b2)) b2 = 0.0; if (isnan(b1)) b1 = b2;
  2377. if (isnan(c2)) c2 = 0.0; if (isnan(c1)) c1 = c2;
  2378. const float a = 2 * a1 - a2, b = 2 * b1 - b2, c = 2 * c1 - c2;
  2379. // Take the average instead of the median
  2380. z_values[x][y] = (a + b + c) / 3.0;
  2381. // Median is robust (ignores outliers).
  2382. // z_values[x][y] = (a < b) ? ((b < c) ? b : (c < a) ? a : c)
  2383. // : ((c < b) ? b : (a < c) ? a : c);
  2384. }
  2385. //Enable this if your SCARA uses 180° of total area
  2386. //#define EXTRAPOLATE_FROM_EDGE
  2387. #if ENABLED(EXTRAPOLATE_FROM_EDGE)
  2388. #if GRID_MAX_POINTS_X < GRID_MAX_POINTS_Y
  2389. #define HALF_IN_X
  2390. #elif GRID_MAX_POINTS_Y < GRID_MAX_POINTS_X
  2391. #define HALF_IN_Y
  2392. #endif
  2393. #endif
  2394. /**
  2395. * Fill in the unprobed points (corners of circular print surface)
  2396. * using linear extrapolation, away from the center.
  2397. */
  2398. static void extrapolate_unprobed_bed_level() {
  2399. #ifdef HALF_IN_X
  2400. constexpr uint8_t ctrx2 = 0, xlen = GRID_MAX_POINTS_X - 1;
  2401. #else
  2402. constexpr uint8_t ctrx1 = (GRID_MAX_POINTS_X - 1) / 2, // left-of-center
  2403. ctrx2 = (GRID_MAX_POINTS_X) / 2, // right-of-center
  2404. xlen = ctrx1;
  2405. #endif
  2406. #ifdef HALF_IN_Y
  2407. constexpr uint8_t ctry2 = 0, ylen = GRID_MAX_POINTS_Y - 1;
  2408. #else
  2409. constexpr uint8_t ctry1 = (GRID_MAX_POINTS_Y - 1) / 2, // top-of-center
  2410. ctry2 = (GRID_MAX_POINTS_Y) / 2, // bottom-of-center
  2411. ylen = ctry1;
  2412. #endif
  2413. for (uint8_t xo = 0; xo <= xlen; xo++)
  2414. for (uint8_t yo = 0; yo <= ylen; yo++) {
  2415. uint8_t x2 = ctrx2 + xo, y2 = ctry2 + yo;
  2416. #ifndef HALF_IN_X
  2417. const uint8_t x1 = ctrx1 - xo;
  2418. #endif
  2419. #ifndef HALF_IN_Y
  2420. const uint8_t y1 = ctry1 - yo;
  2421. #ifndef HALF_IN_X
  2422. extrapolate_one_point(x1, y1, +1, +1); // left-below + +
  2423. #endif
  2424. extrapolate_one_point(x2, y1, -1, +1); // right-below - +
  2425. #endif
  2426. #ifndef HALF_IN_X
  2427. extrapolate_one_point(x1, y2, +1, -1); // left-above + -
  2428. #endif
  2429. extrapolate_one_point(x2, y2, -1, -1); // right-above - -
  2430. }
  2431. }
  2432. static void print_bilinear_leveling_grid() {
  2433. SERIAL_ECHOLNPGM("Bilinear Leveling Grid:");
  2434. print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 3,
  2435. [](const uint8_t ix, const uint8_t iy) { return z_values[ix][iy]; }
  2436. );
  2437. }
  2438. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2439. #define ABL_GRID_POINTS_VIRT_X (GRID_MAX_POINTS_X - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2440. #define ABL_GRID_POINTS_VIRT_Y (GRID_MAX_POINTS_Y - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2441. #define ABL_TEMP_POINTS_X (GRID_MAX_POINTS_X + 2)
  2442. #define ABL_TEMP_POINTS_Y (GRID_MAX_POINTS_Y + 2)
  2443. float z_values_virt[ABL_GRID_POINTS_VIRT_X][ABL_GRID_POINTS_VIRT_Y];
  2444. int bilinear_grid_spacing_virt[2] = { 0 };
  2445. float bilinear_grid_factor_virt[2] = { 0 };
  2446. static void print_bilinear_leveling_grid_virt() {
  2447. SERIAL_ECHOLNPGM("Subdivided with CATMULL ROM Leveling Grid:");
  2448. print_2d_array(ABL_GRID_POINTS_VIRT_X, ABL_GRID_POINTS_VIRT_Y, 5,
  2449. [](const uint8_t ix, const uint8_t iy) { return z_values_virt[ix][iy]; }
  2450. );
  2451. }
  2452. #define LINEAR_EXTRAPOLATION(E, I) ((E) * 2 - (I))
  2453. float bed_level_virt_coord(const uint8_t x, const uint8_t y) {
  2454. uint8_t ep = 0, ip = 1;
  2455. if (!x || x == ABL_TEMP_POINTS_X - 1) {
  2456. if (x) {
  2457. ep = GRID_MAX_POINTS_X - 1;
  2458. ip = GRID_MAX_POINTS_X - 2;
  2459. }
  2460. if (WITHIN(y, 1, ABL_TEMP_POINTS_Y - 2))
  2461. return LINEAR_EXTRAPOLATION(
  2462. z_values[ep][y - 1],
  2463. z_values[ip][y - 1]
  2464. );
  2465. else
  2466. return LINEAR_EXTRAPOLATION(
  2467. bed_level_virt_coord(ep + 1, y),
  2468. bed_level_virt_coord(ip + 1, y)
  2469. );
  2470. }
  2471. if (!y || y == ABL_TEMP_POINTS_Y - 1) {
  2472. if (y) {
  2473. ep = GRID_MAX_POINTS_Y - 1;
  2474. ip = GRID_MAX_POINTS_Y - 2;
  2475. }
  2476. if (WITHIN(x, 1, ABL_TEMP_POINTS_X - 2))
  2477. return LINEAR_EXTRAPOLATION(
  2478. z_values[x - 1][ep],
  2479. z_values[x - 1][ip]
  2480. );
  2481. else
  2482. return LINEAR_EXTRAPOLATION(
  2483. bed_level_virt_coord(x, ep + 1),
  2484. bed_level_virt_coord(x, ip + 1)
  2485. );
  2486. }
  2487. return z_values[x - 1][y - 1];
  2488. }
  2489. static float bed_level_virt_cmr(const float p[4], const uint8_t i, const float t) {
  2490. return (
  2491. p[i-1] * -t * sq(1 - t)
  2492. + p[i] * (2 - 5 * sq(t) + 3 * t * sq(t))
  2493. + p[i+1] * t * (1 + 4 * t - 3 * sq(t))
  2494. - p[i+2] * sq(t) * (1 - t)
  2495. ) * 0.5;
  2496. }
  2497. static float bed_level_virt_2cmr(const uint8_t x, const uint8_t y, const float &tx, const float &ty) {
  2498. float row[4], column[4];
  2499. for (uint8_t i = 0; i < 4; i++) {
  2500. for (uint8_t j = 0; j < 4; j++) {
  2501. column[j] = bed_level_virt_coord(i + x - 1, j + y - 1);
  2502. }
  2503. row[i] = bed_level_virt_cmr(column, 1, ty);
  2504. }
  2505. return bed_level_virt_cmr(row, 1, tx);
  2506. }
  2507. void bed_level_virt_interpolate() {
  2508. bilinear_grid_spacing_virt[X_AXIS] = bilinear_grid_spacing[X_AXIS] / (BILINEAR_SUBDIVISIONS);
  2509. bilinear_grid_spacing_virt[Y_AXIS] = bilinear_grid_spacing[Y_AXIS] / (BILINEAR_SUBDIVISIONS);
  2510. bilinear_grid_factor_virt[X_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[X_AXIS]);
  2511. bilinear_grid_factor_virt[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[Y_AXIS]);
  2512. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2513. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2514. for (uint8_t ty = 0; ty < BILINEAR_SUBDIVISIONS; ty++)
  2515. for (uint8_t tx = 0; tx < BILINEAR_SUBDIVISIONS; tx++) {
  2516. if ((ty && y == GRID_MAX_POINTS_Y - 1) || (tx && x == GRID_MAX_POINTS_X - 1))
  2517. continue;
  2518. z_values_virt[x * (BILINEAR_SUBDIVISIONS) + tx][y * (BILINEAR_SUBDIVISIONS) + ty] =
  2519. bed_level_virt_2cmr(
  2520. x + 1,
  2521. y + 1,
  2522. (float)tx / (BILINEAR_SUBDIVISIONS),
  2523. (float)ty / (BILINEAR_SUBDIVISIONS)
  2524. );
  2525. }
  2526. }
  2527. #endif // ABL_BILINEAR_SUBDIVISION
  2528. // Refresh after other values have been updated
  2529. void refresh_bed_level() {
  2530. bilinear_grid_factor[X_AXIS] = RECIPROCAL(bilinear_grid_spacing[X_AXIS]);
  2531. bilinear_grid_factor[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing[Y_AXIS]);
  2532. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2533. bed_level_virt_interpolate();
  2534. #endif
  2535. }
  2536. #endif // AUTO_BED_LEVELING_BILINEAR
  2537. #if ENABLED(SENSORLESS_HOMING)
  2538. /**
  2539. * Set sensorless homing if the axis has it, accounting for Core Kinematics.
  2540. */
  2541. void sensorless_homing_per_axis(const AxisEnum axis, const bool enable=true) {
  2542. switch (axis) {
  2543. #if X_SENSORLESS
  2544. case X_AXIS:
  2545. tmc_sensorless_homing(stepperX, enable);
  2546. #if CORE_IS_XY && Y_SENSORLESS
  2547. tmc_sensorless_homing(stepperY, enable);
  2548. #elif CORE_IS_XZ && Z_SENSORLESS
  2549. tmc_sensorless_homing(stepperZ, enable);
  2550. #endif
  2551. break;
  2552. #endif
  2553. #if Y_SENSORLESS
  2554. case Y_AXIS:
  2555. tmc_sensorless_homing(stepperY, enable);
  2556. #if CORE_IS_XY && X_SENSORLESS
  2557. tmc_sensorless_homing(stepperX, enable);
  2558. #elif CORE_IS_YZ && Z_SENSORLESS
  2559. tmc_sensorless_homing(stepperZ, enable);
  2560. #endif
  2561. break;
  2562. #endif
  2563. #if Z_SENSORLESS
  2564. case Z_AXIS:
  2565. tmc_sensorless_homing(stepperZ, enable);
  2566. #if CORE_IS_XZ && X_SENSORLESS
  2567. tmc_sensorless_homing(stepperX, enable);
  2568. #elif CORE_IS_YZ && Y_SENSORLESS
  2569. tmc_sensorless_homing(stepperY, enable);
  2570. #endif
  2571. break;
  2572. #endif
  2573. default: break;
  2574. }
  2575. }
  2576. #endif // SENSORLESS_HOMING
  2577. /**
  2578. * Home an individual linear axis
  2579. */
  2580. static void do_homing_move(const AxisEnum axis, const float distance, const float fr_mm_s=0) {
  2581. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2582. if (DEBUGGING(LEVELING)) {
  2583. SERIAL_ECHOPAIR(">>> do_homing_move(", axis_codes[axis]);
  2584. SERIAL_ECHOPAIR(", ", distance);
  2585. SERIAL_ECHOPGM(", ");
  2586. if (fr_mm_s)
  2587. SERIAL_ECHO(fr_mm_s);
  2588. else {
  2589. SERIAL_ECHOPAIR("[", homing_feedrate(axis));
  2590. SERIAL_CHAR(']');
  2591. }
  2592. SERIAL_ECHOLNPGM(")");
  2593. }
  2594. #endif
  2595. #if HOMING_Z_WITH_PROBE && HAS_HEATED_BED && ENABLED(WAIT_FOR_BED_HEATER)
  2596. // Wait for bed to heat back up between probing points
  2597. if (axis == Z_AXIS && distance < 0 && thermalManager.isHeatingBed()) {
  2598. serialprintPGM(msg_wait_for_bed_heating);
  2599. LCD_MESSAGEPGM(MSG_BED_HEATING);
  2600. while (thermalManager.isHeatingBed()) safe_delay(200);
  2601. lcd_reset_status();
  2602. }
  2603. #endif
  2604. // Only do some things when moving towards an endstop
  2605. const int8_t axis_home_dir =
  2606. #if ENABLED(DUAL_X_CARRIAGE)
  2607. (axis == X_AXIS) ? x_home_dir(active_extruder) :
  2608. #endif
  2609. home_dir(axis);
  2610. const bool is_home_dir = (axis_home_dir > 0) == (distance > 0);
  2611. if (is_home_dir) {
  2612. #if HOMING_Z_WITH_PROBE && QUIET_PROBING
  2613. if (axis == Z_AXIS) probing_pause(true);
  2614. #endif
  2615. // Disable stealthChop if used. Enable diag1 pin on driver.
  2616. #if ENABLED(SENSORLESS_HOMING)
  2617. sensorless_homing_per_axis(axis);
  2618. #endif
  2619. }
  2620. // Tell the planner the axis is at 0
  2621. current_position[axis] = 0;
  2622. // Do the move, which is required to hit an endstop
  2623. #if IS_SCARA
  2624. SYNC_PLAN_POSITION_KINEMATIC();
  2625. current_position[axis] = distance;
  2626. inverse_kinematics(current_position);
  2627. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], current_position[E_CART], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder);
  2628. #elif ENABLED(HANGPRINTER) // TODO: Hangprinter homing is not finished (Jan 7, 2018)
  2629. SYNC_PLAN_POSITION_KINEMATIC();
  2630. current_position[axis] = distance;
  2631. inverse_kinematics(current_position);
  2632. planner.buffer_line(line_lengths[A_AXIS], line_lengths[B_AXIS], line_lengths[C_AXIS], line_lengths[D_AXIS], current_position[E_CART], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder);
  2633. #else
  2634. sync_plan_position();
  2635. current_position[axis] = distance; // Set delta/cartesian axes directly
  2636. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder);
  2637. #endif
  2638. planner.synchronize();
  2639. if (is_home_dir) {
  2640. #if HOMING_Z_WITH_PROBE && QUIET_PROBING
  2641. if (axis == Z_AXIS) probing_pause(false);
  2642. #endif
  2643. endstops.validate_homing_move();
  2644. // Re-enable stealthChop if used. Disable diag1 pin on driver.
  2645. #if ENABLED(SENSORLESS_HOMING)
  2646. sensorless_homing_per_axis(axis, false);
  2647. #endif
  2648. }
  2649. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2650. if (DEBUGGING(LEVELING)) {
  2651. SERIAL_ECHOPAIR("<<< do_homing_move(", axis_codes[axis]);
  2652. SERIAL_CHAR(')');
  2653. SERIAL_EOL();
  2654. }
  2655. #endif
  2656. }
  2657. /**
  2658. * Home an individual "raw axis" to its endstop.
  2659. * This applies to XYZ on Cartesian and Core robots, and
  2660. * to the individual ABC steppers on DELTA and SCARA.
  2661. *
  2662. * At the end of the procedure the axis is marked as
  2663. * homed and the current position of that axis is updated.
  2664. * Kinematic robots should wait till all axes are homed
  2665. * before updating the current position.
  2666. */
  2667. static void homeaxis(const AxisEnum axis) {
  2668. #if IS_SCARA
  2669. // Only Z homing (with probe) is permitted
  2670. if (axis != Z_AXIS) { BUZZ(100, 880); return; }
  2671. #else
  2672. #define CAN_HOME(A) \
  2673. (axis == _AXIS(A) && ((A##_MIN_PIN > -1 && A##_HOME_DIR < 0) || (A##_MAX_PIN > -1 && A##_HOME_DIR > 0)))
  2674. if (!CAN_HOME(X) && !CAN_HOME(Y) && !CAN_HOME(Z)) return;
  2675. #endif
  2676. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2677. if (DEBUGGING(LEVELING)) {
  2678. SERIAL_ECHOPAIR(">>> homeaxis(", axis_codes[axis]);
  2679. SERIAL_CHAR(')');
  2680. SERIAL_EOL();
  2681. }
  2682. #endif
  2683. const int axis_home_dir = (
  2684. #if ENABLED(DUAL_X_CARRIAGE)
  2685. axis == X_AXIS ? x_home_dir(active_extruder) :
  2686. #endif
  2687. home_dir(axis)
  2688. );
  2689. // Homing Z towards the bed? Deploy the Z probe or endstop.
  2690. #if HOMING_Z_WITH_PROBE
  2691. if (axis == Z_AXIS && DEPLOY_PROBE()) return;
  2692. #endif
  2693. // Set flags for X, Y, Z motor locking
  2694. #if ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS)
  2695. switch (axis) {
  2696. #if ENABLED(X_DUAL_ENDSTOPS)
  2697. case X_AXIS:
  2698. #endif
  2699. #if ENABLED(Y_DUAL_ENDSTOPS)
  2700. case Y_AXIS:
  2701. #endif
  2702. #if ENABLED(Z_DUAL_ENDSTOPS)
  2703. case Z_AXIS:
  2704. #endif
  2705. stepper.set_homing_dual_axis(true);
  2706. default: break;
  2707. }
  2708. #endif
  2709. // Fast move towards endstop until triggered
  2710. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2711. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 1 Fast:");
  2712. #endif
  2713. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2714. // BLTOUCH needs to be deployed every time
  2715. if (axis == Z_AXIS && set_bltouch_deployed(true)) return;
  2716. #endif
  2717. do_homing_move(axis, 1.5f * max_length(axis) * axis_home_dir);
  2718. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2719. // BLTOUCH needs to be stowed after trigger to rearm itself
  2720. if (axis == Z_AXIS) set_bltouch_deployed(false);
  2721. #endif
  2722. // When homing Z with probe respect probe clearance
  2723. const float bump = axis_home_dir * (
  2724. #if HOMING_Z_WITH_PROBE
  2725. (axis == Z_AXIS && (Z_HOME_BUMP_MM)) ? MAX(Z_CLEARANCE_BETWEEN_PROBES, Z_HOME_BUMP_MM) :
  2726. #endif
  2727. home_bump_mm(axis)
  2728. );
  2729. // If a second homing move is configured...
  2730. if (bump) {
  2731. // Move away from the endstop by the axis HOME_BUMP_MM
  2732. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2733. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Move Away:");
  2734. #endif
  2735. do_homing_move(axis, -bump
  2736. #if HOMING_Z_WITH_PROBE
  2737. , axis == Z_AXIS ? MMM_TO_MMS(Z_PROBE_SPEED_FAST) : 0.00
  2738. #endif
  2739. );
  2740. // Slow move towards endstop until triggered
  2741. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2742. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 2 Slow:");
  2743. #endif
  2744. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2745. // BLTOUCH needs to be deployed every time
  2746. if (axis == Z_AXIS && set_bltouch_deployed(true)) return;
  2747. #endif
  2748. do_homing_move(axis, 2 * bump, get_homing_bump_feedrate(axis));
  2749. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2750. // BLTOUCH needs to be stowed after trigger to rearm itself
  2751. if (axis == Z_AXIS) set_bltouch_deployed(false);
  2752. #endif
  2753. }
  2754. /**
  2755. * Home axes that have dual endstops... differently
  2756. */
  2757. #if ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS)
  2758. const bool pos_dir = axis_home_dir > 0;
  2759. #if ENABLED(X_DUAL_ENDSTOPS)
  2760. if (axis == X_AXIS) {
  2761. const float adj = ABS(endstops.x_endstop_adj);
  2762. if (adj) {
  2763. if (pos_dir ? (endstops.x_endstop_adj > 0) : (endstops.x_endstop_adj < 0)) stepper.set_x_lock(true); else stepper.set_x2_lock(true);
  2764. do_homing_move(axis, pos_dir ? -adj : adj);
  2765. stepper.set_x_lock(false);
  2766. stepper.set_x2_lock(false);
  2767. }
  2768. }
  2769. #endif
  2770. #if ENABLED(Y_DUAL_ENDSTOPS)
  2771. if (axis == Y_AXIS) {
  2772. const float adj = ABS(endstops.y_endstop_adj);
  2773. if (adj) {
  2774. if (pos_dir ? (endstops.y_endstop_adj > 0) : (endstops.y_endstop_adj < 0)) stepper.set_y_lock(true); else stepper.set_y2_lock(true);
  2775. do_homing_move(axis, pos_dir ? -adj : adj);
  2776. stepper.set_y_lock(false);
  2777. stepper.set_y2_lock(false);
  2778. }
  2779. }
  2780. #endif
  2781. #if ENABLED(Z_DUAL_ENDSTOPS)
  2782. if (axis == Z_AXIS) {
  2783. const float adj = ABS(endstops.z_endstop_adj);
  2784. if (adj) {
  2785. if (pos_dir ? (endstops.z_endstop_adj > 0) : (endstops.z_endstop_adj < 0)) stepper.set_z_lock(true); else stepper.set_z2_lock(true);
  2786. do_homing_move(axis, pos_dir ? -adj : adj);
  2787. stepper.set_z_lock(false);
  2788. stepper.set_z2_lock(false);
  2789. }
  2790. }
  2791. #endif
  2792. stepper.set_homing_dual_axis(false);
  2793. #endif
  2794. #if IS_SCARA
  2795. set_axis_is_at_home(axis);
  2796. SYNC_PLAN_POSITION_KINEMATIC();
  2797. #elif ENABLED(DELTA)
  2798. // Delta has already moved all three towers up in G28
  2799. // so here it re-homes each tower in turn.
  2800. // Delta homing treats the axes as normal linear axes.
  2801. // retrace by the amount specified in delta_endstop_adj + additional dist in order to have minimum steps
  2802. if (delta_endstop_adj[axis] * Z_HOME_DIR <= 0) {
  2803. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2804. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("delta_endstop_adj:");
  2805. #endif
  2806. do_homing_move(axis, delta_endstop_adj[axis] - (MIN_STEPS_PER_SEGMENT + 1) * planner.steps_to_mm[axis] * Z_HOME_DIR);
  2807. }
  2808. #else
  2809. // For cartesian/core machines,
  2810. // set the axis to its home position
  2811. set_axis_is_at_home(axis);
  2812. sync_plan_position();
  2813. destination[axis] = current_position[axis];
  2814. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2815. if (DEBUGGING(LEVELING)) DEBUG_POS("> AFTER set_axis_is_at_home", current_position);
  2816. #endif
  2817. #endif
  2818. // Put away the Z probe
  2819. #if HOMING_Z_WITH_PROBE
  2820. if (axis == Z_AXIS && STOW_PROBE()) return;
  2821. #endif
  2822. // Clear retracted status if homing the Z axis
  2823. #if ENABLED(FWRETRACT)
  2824. if (axis == Z_AXIS) fwretract.hop_amount = 0.0;
  2825. #endif
  2826. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2827. if (DEBUGGING(LEVELING)) {
  2828. SERIAL_ECHOPAIR("<<< homeaxis(", axis_codes[axis]);
  2829. SERIAL_CHAR(')');
  2830. SERIAL_EOL();
  2831. }
  2832. #endif
  2833. } // homeaxis()
  2834. #if ENABLED(MIXING_EXTRUDER)
  2835. void normalize_mix() {
  2836. float mix_total = 0.0;
  2837. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mix_total += mixing_factor[i];
  2838. // Scale all values if they don't add up to ~1.0
  2839. if (!NEAR(mix_total, 1.0)) {
  2840. SERIAL_PROTOCOLLNPGM("Warning: Mix factors must add up to 1.0. Scaling.");
  2841. const float inverse_sum = RECIPROCAL(mix_total);
  2842. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_factor[i] *= inverse_sum;
  2843. }
  2844. }
  2845. #if ENABLED(DIRECT_MIXING_IN_G1)
  2846. // Get mixing parameters from the GCode
  2847. // The total "must" be 1.0 (but it will be normalized)
  2848. // If no mix factors are given, the old mix is preserved
  2849. void gcode_get_mix() {
  2850. const char mixing_codes[] = { 'A', 'B'
  2851. #if MIXING_STEPPERS > 2
  2852. , 'C'
  2853. #if MIXING_STEPPERS > 3
  2854. , 'D'
  2855. #if MIXING_STEPPERS > 4
  2856. , 'H'
  2857. #if MIXING_STEPPERS > 5
  2858. , 'I'
  2859. #endif // MIXING_STEPPERS > 5
  2860. #endif // MIXING_STEPPERS > 4
  2861. #endif // MIXING_STEPPERS > 3
  2862. #endif // MIXING_STEPPERS > 2
  2863. };
  2864. byte mix_bits = 0;
  2865. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) {
  2866. if (parser.seenval(mixing_codes[i])) {
  2867. SBI(mix_bits, i);
  2868. mixing_factor[i] = MAX(parser.value_float(), 0.0);
  2869. }
  2870. }
  2871. // If any mixing factors were included, clear the rest
  2872. // If none were included, preserve the last mix
  2873. if (mix_bits) {
  2874. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  2875. if (!TEST(mix_bits, i)) mixing_factor[i] = 0.0;
  2876. normalize_mix();
  2877. }
  2878. }
  2879. #endif
  2880. #endif
  2881. /**
  2882. * ***************************************************************************
  2883. * ***************************** G-CODE HANDLING *****************************
  2884. * ***************************************************************************
  2885. */
  2886. /**
  2887. * Set XYZE destination and feedrate from the current GCode command
  2888. *
  2889. * - Set destination from included axis codes
  2890. * - Set to current for missing axis codes
  2891. * - Set the feedrate, if included
  2892. */
  2893. void gcode_get_destination() {
  2894. LOOP_XYZE(i) {
  2895. if (parser.seen(axis_codes[i])) {
  2896. const float v = parser.value_axis_units((AxisEnum)i);
  2897. destination[i] = (axis_relative_modes[i] || relative_mode)
  2898. ? current_position[i] + v
  2899. : (i == E_CART) ? v : LOGICAL_TO_NATIVE(v, i);
  2900. }
  2901. else
  2902. destination[i] = current_position[i];
  2903. }
  2904. if (parser.linearval('F') > 0)
  2905. feedrate_mm_s = MMM_TO_MMS(parser.value_feedrate());
  2906. #if ENABLED(PRINTCOUNTER)
  2907. if (!DEBUGGING(DRYRUN))
  2908. print_job_timer.incFilamentUsed(destination[E_CART] - current_position[E_CART]);
  2909. #endif
  2910. // Get ABCDHI mixing factors
  2911. #if ENABLED(MIXING_EXTRUDER) && ENABLED(DIRECT_MIXING_IN_G1)
  2912. gcode_get_mix();
  2913. #endif
  2914. }
  2915. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  2916. /**
  2917. * Output a "busy" message at regular intervals
  2918. * while the machine is not accepting commands.
  2919. */
  2920. void host_keepalive() {
  2921. const millis_t ms = millis();
  2922. if (!suspend_auto_report && host_keepalive_interval && busy_state != NOT_BUSY) {
  2923. if (PENDING(ms, next_busy_signal_ms)) return;
  2924. switch (busy_state) {
  2925. case IN_HANDLER:
  2926. case IN_PROCESS:
  2927. SERIAL_ECHO_START();
  2928. SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING);
  2929. break;
  2930. case PAUSED_FOR_USER:
  2931. SERIAL_ECHO_START();
  2932. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER);
  2933. break;
  2934. case PAUSED_FOR_INPUT:
  2935. SERIAL_ECHO_START();
  2936. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT);
  2937. break;
  2938. default:
  2939. break;
  2940. }
  2941. }
  2942. next_busy_signal_ms = ms + host_keepalive_interval * 1000UL;
  2943. }
  2944. #endif // HOST_KEEPALIVE_FEATURE
  2945. /**************************************************
  2946. ***************** GCode Handlers *****************
  2947. **************************************************/
  2948. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  2949. #define G0_G1_CONDITION !axis_unhomed_error(parser.seen('X'), parser.seen('Y'), parser.seen('Z'))
  2950. #else
  2951. #define G0_G1_CONDITION true
  2952. #endif
  2953. /**
  2954. * G0, G1: Coordinated movement of X Y Z E axes
  2955. */
  2956. inline void gcode_G0_G1(
  2957. #if IS_SCARA
  2958. bool fast_move=false
  2959. #endif
  2960. ) {
  2961. if (IsRunning() && G0_G1_CONDITION) {
  2962. gcode_get_destination(); // For X Y Z E F
  2963. #if ENABLED(FWRETRACT)
  2964. if (MIN_AUTORETRACT <= MAX_AUTORETRACT) {
  2965. // When M209 Autoretract is enabled, convert E-only moves to firmware retract/prime moves
  2966. if (fwretract.autoretract_enabled && parser.seen('E') && !(parser.seen('X') || parser.seen('Y') || parser.seen('Z'))) {
  2967. const float echange = destination[E_CART] - current_position[E_CART];
  2968. // Is this a retract or prime move?
  2969. if (WITHIN(ABS(echange), MIN_AUTORETRACT, MAX_AUTORETRACT) && fwretract.retracted[active_extruder] == (echange > 0.0)) {
  2970. current_position[E_CART] = destination[E_CART]; // Hide a G1-based retract/prime from calculations
  2971. sync_plan_position_e(); // AND from the planner
  2972. return fwretract.retract(echange < 0.0); // Firmware-based retract/prime (double-retract ignored)
  2973. }
  2974. }
  2975. }
  2976. #endif // FWRETRACT
  2977. #if IS_SCARA
  2978. fast_move ? prepare_uninterpolated_move_to_destination() : prepare_move_to_destination();
  2979. #else
  2980. prepare_move_to_destination();
  2981. #endif
  2982. #if ENABLED(NANODLP_Z_SYNC)
  2983. #if ENABLED(NANODLP_ALL_AXIS)
  2984. #define _MOVE_SYNC parser.seenval('X') || parser.seenval('Y') || parser.seenval('Z') // For any move wait and output sync message
  2985. #else
  2986. #define _MOVE_SYNC parser.seenval('Z') // Only for Z move
  2987. #endif
  2988. if (_MOVE_SYNC) {
  2989. planner.synchronize();
  2990. SERIAL_ECHOLNPGM(MSG_Z_MOVE_COMP);
  2991. }
  2992. #endif
  2993. }
  2994. }
  2995. /**
  2996. * G2: Clockwise Arc
  2997. * G3: Counterclockwise Arc
  2998. *
  2999. * This command has two forms: IJ-form and R-form.
  3000. *
  3001. * - I specifies an X offset. J specifies a Y offset.
  3002. * At least one of the IJ parameters is required.
  3003. * X and Y can be omitted to do a complete circle.
  3004. * The given XY is not error-checked. The arc ends
  3005. * based on the angle of the destination.
  3006. * Mixing I or J with R will throw an error.
  3007. *
  3008. * - R specifies the radius. X or Y is required.
  3009. * Omitting both X and Y will throw an error.
  3010. * X or Y must differ from the current XY.
  3011. * Mixing R with I or J will throw an error.
  3012. *
  3013. * - P specifies the number of full circles to do
  3014. * before the specified arc move.
  3015. *
  3016. * Examples:
  3017. *
  3018. * G2 I10 ; CW circle centered at X+10
  3019. * G3 X20 Y12 R14 ; CCW circle with r=14 ending at X20 Y12
  3020. */
  3021. #if ENABLED(ARC_SUPPORT)
  3022. inline void gcode_G2_G3(const bool clockwise) {
  3023. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  3024. if (axis_unhomed_error()) return;
  3025. #endif
  3026. if (IsRunning()) {
  3027. #if ENABLED(SF_ARC_FIX)
  3028. const bool relative_mode_backup = relative_mode;
  3029. relative_mode = true;
  3030. #endif
  3031. gcode_get_destination();
  3032. #if ENABLED(SF_ARC_FIX)
  3033. relative_mode = relative_mode_backup;
  3034. #endif
  3035. float arc_offset[2] = { 0, 0 };
  3036. if (parser.seenval('R')) {
  3037. const float r = parser.value_linear_units(),
  3038. p1 = current_position[X_AXIS], q1 = current_position[Y_AXIS],
  3039. p2 = destination[X_AXIS], q2 = destination[Y_AXIS];
  3040. if (r && (p2 != p1 || q2 != q1)) {
  3041. const float e = clockwise ^ (r < 0) ? -1 : 1, // clockwise -1/1, counterclockwise 1/-1
  3042. dx = p2 - p1, dy = q2 - q1, // X and Y differences
  3043. d = HYPOT(dx, dy), // Linear distance between the points
  3044. h = SQRT(sq(r) - sq(d * 0.5f)), // Distance to the arc pivot-point
  3045. mx = (p1 + p2) * 0.5f, my = (q1 + q2) * 0.5f, // Point between the two points
  3046. sx = -dy / d, sy = dx / d, // Slope of the perpendicular bisector
  3047. cx = mx + e * h * sx, cy = my + e * h * sy; // Pivot-point of the arc
  3048. arc_offset[0] = cx - p1;
  3049. arc_offset[1] = cy - q1;
  3050. }
  3051. }
  3052. else {
  3053. if (parser.seenval('I')) arc_offset[0] = parser.value_linear_units();
  3054. if (parser.seenval('J')) arc_offset[1] = parser.value_linear_units();
  3055. }
  3056. if (arc_offset[0] || arc_offset[1]) {
  3057. #if ENABLED(ARC_P_CIRCLES)
  3058. // P indicates number of circles to do
  3059. int8_t circles_to_do = parser.byteval('P');
  3060. if (!WITHIN(circles_to_do, 0, 100)) {
  3061. SERIAL_ERROR_START();
  3062. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  3063. }
  3064. while (circles_to_do--)
  3065. plan_arc(current_position, arc_offset, clockwise);
  3066. #endif
  3067. // Send the arc to the planner
  3068. plan_arc(destination, arc_offset, clockwise);
  3069. }
  3070. else {
  3071. // Bad arguments
  3072. SERIAL_ERROR_START();
  3073. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  3074. }
  3075. }
  3076. }
  3077. #endif // ARC_SUPPORT
  3078. void dwell(millis_t time) {
  3079. time += millis();
  3080. while (PENDING(millis(), time)) idle();
  3081. }
  3082. /**
  3083. * G4: Dwell S<seconds> or P<milliseconds>
  3084. */
  3085. inline void gcode_G4() {
  3086. millis_t dwell_ms = 0;
  3087. if (parser.seenval('P')) dwell_ms = parser.value_millis(); // milliseconds to wait
  3088. if (parser.seenval('S')) dwell_ms = parser.value_millis_from_seconds(); // seconds to wait
  3089. planner.synchronize();
  3090. #if ENABLED(NANODLP_Z_SYNC)
  3091. SERIAL_ECHOLNPGM(MSG_Z_MOVE_COMP);
  3092. #endif
  3093. if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL);
  3094. dwell(dwell_ms);
  3095. }
  3096. #if ENABLED(BEZIER_CURVE_SUPPORT)
  3097. /**
  3098. * Parameters interpreted according to:
  3099. * http://linuxcnc.org/docs/2.6/html/gcode/gcode.html#sec:G5-Cubic-Spline
  3100. * However I, J omission is not supported at this point; all
  3101. * parameters can be omitted and default to zero.
  3102. */
  3103. /**
  3104. * G5: Cubic B-spline
  3105. */
  3106. inline void gcode_G5() {
  3107. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  3108. if (axis_unhomed_error()) return;
  3109. #endif
  3110. if (IsRunning()) {
  3111. #if ENABLED(CNC_WORKSPACE_PLANES)
  3112. if (workspace_plane != PLANE_XY) {
  3113. SERIAL_ERROR_START();
  3114. SERIAL_ERRORLNPGM(MSG_ERR_BAD_PLANE_MODE);
  3115. return;
  3116. }
  3117. #endif
  3118. gcode_get_destination();
  3119. const float offset[] = {
  3120. parser.linearval('I'),
  3121. parser.linearval('J'),
  3122. parser.linearval('P'),
  3123. parser.linearval('Q')
  3124. };
  3125. plan_cubic_move(destination, offset);
  3126. }
  3127. }
  3128. #endif // BEZIER_CURVE_SUPPORT
  3129. #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
  3130. /**
  3131. * G6 implementation for Hangprinter based on
  3132. * http://reprap.org/wiki/GCodes#G6:_Direct_Stepper_Move
  3133. * Accessed Jan 8, 2018
  3134. *
  3135. * G6 is used frequently to tighten lines with Hangprinter, so Hangprinter default is relative moves.
  3136. * Hangprinter uses switches
  3137. * S1 for absolute moves
  3138. * S2 for saving recording new line length after unregistered move
  3139. * (typically used while tuning LINE_BUILDUP_COMPENSATION_FEATURE parameters)
  3140. */
  3141. /**
  3142. * G6: Direct Stepper Move
  3143. */
  3144. inline void gcode_G6() {
  3145. bool count_it = false;
  3146. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  3147. if (axis_unhomed_error()) return;
  3148. #endif
  3149. if (IsRunning()) {
  3150. float go[MOV_AXIS] = { 0.0 },
  3151. tmp_fr_mm_s = 0.0;
  3152. LOOP_MOV_AXIS(i)
  3153. if (parser.seen(RAW_AXIS_CODES(i)))
  3154. go[i] = parser.value_axis_units((AxisEnum)i);
  3155. #if ENABLED(HANGPRINTER)
  3156. #define GO_SRC line_lengths
  3157. #elif ENABLED(DELTA)
  3158. #define GO_SRC delta
  3159. #else
  3160. #define GO_SRC current_position
  3161. #endif
  3162. if (
  3163. #if ENABLED(HANGPRINTER) // Sending R to another machine is the same as not sending S1 to Hangprinter
  3164. parser.byteval('S') != 2
  3165. #else
  3166. parser.seen('R')
  3167. #endif
  3168. )
  3169. LOOP_MOV_AXIS(i) go[i] += GO_SRC[i];
  3170. else
  3171. LOOP_MOV_AXIS(i) if (!parser.seen(RAW_AXIS_CODES(i))) go[i] += GO_SRC[i];
  3172. tmp_fr_mm_s = parser.linearval('F') > 0.0 ? MMM_TO_MMS(parser.value_feedrate()) : feedrate_mm_s;
  3173. #if ENABLED(HANGPRINTER)
  3174. if (parser.byteval('S') == 2) {
  3175. LOOP_MOV_AXIS(i) line_lengths[i] = go[i];
  3176. count_it = true;
  3177. }
  3178. #endif
  3179. planner.buffer_segment(go[A_AXIS], go[B_AXIS], go[C_AXIS]
  3180. #if ENABLED(HANGPRINTER)
  3181. , go[D_AXIS]
  3182. #endif
  3183. , current_position[E_CART], tmp_fr_mm_s, active_extruder, 0.0, count_it
  3184. );
  3185. }
  3186. }
  3187. #endif
  3188. #if ENABLED(FWRETRACT)
  3189. /**
  3190. * G10 - Retract filament according to settings of M207
  3191. */
  3192. inline void gcode_G10() {
  3193. #if EXTRUDERS > 1
  3194. const bool rs = parser.boolval('S');
  3195. #endif
  3196. fwretract.retract(true
  3197. #if EXTRUDERS > 1
  3198. , rs
  3199. #endif
  3200. );
  3201. }
  3202. /**
  3203. * G11 - Recover filament according to settings of M208
  3204. */
  3205. inline void gcode_G11() { fwretract.retract(false); }
  3206. #endif // FWRETRACT
  3207. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  3208. /**
  3209. * G12: Clean the nozzle
  3210. */
  3211. inline void gcode_G12() {
  3212. // Don't allow nozzle cleaning without homing first
  3213. if (axis_unhomed_error()) return;
  3214. const uint8_t pattern = parser.ushortval('P', 0),
  3215. strokes = parser.ushortval('S', NOZZLE_CLEAN_STROKES),
  3216. objects = parser.ushortval('T', NOZZLE_CLEAN_TRIANGLES);
  3217. const float radius = parser.floatval('R', NOZZLE_CLEAN_CIRCLE_RADIUS);
  3218. Nozzle::clean(pattern, strokes, radius, objects);
  3219. }
  3220. #endif
  3221. #if ENABLED(CNC_WORKSPACE_PLANES)
  3222. inline void report_workspace_plane() {
  3223. SERIAL_ECHO_START();
  3224. SERIAL_ECHOPGM("Workspace Plane ");
  3225. serialprintPGM(
  3226. workspace_plane == PLANE_YZ ? PSTR("YZ\n") :
  3227. workspace_plane == PLANE_ZX ? PSTR("ZX\n") :
  3228. PSTR("XY\n")
  3229. );
  3230. }
  3231. inline void set_workspace_plane(const WorkspacePlane plane) {
  3232. workspace_plane = plane;
  3233. if (DEBUGGING(INFO)) report_workspace_plane();
  3234. }
  3235. /**
  3236. * G17: Select Plane XY
  3237. * G18: Select Plane ZX
  3238. * G19: Select Plane YZ
  3239. */
  3240. inline void gcode_G17() { set_workspace_plane(PLANE_XY); }
  3241. inline void gcode_G18() { set_workspace_plane(PLANE_ZX); }
  3242. inline void gcode_G19() { set_workspace_plane(PLANE_YZ); }
  3243. #endif // CNC_WORKSPACE_PLANES
  3244. #if ENABLED(CNC_COORDINATE_SYSTEMS)
  3245. /**
  3246. * Select a coordinate system and update the workspace offset.
  3247. * System index -1 is used to specify machine-native.
  3248. */
  3249. bool select_coordinate_system(const int8_t _new) {
  3250. if (active_coordinate_system == _new) return false;
  3251. float old_offset[XYZ] = { 0 }, new_offset[XYZ] = { 0 };
  3252. if (WITHIN(active_coordinate_system, 0, MAX_COORDINATE_SYSTEMS - 1))
  3253. COPY(old_offset, coordinate_system[active_coordinate_system]);
  3254. if (WITHIN(_new, 0, MAX_COORDINATE_SYSTEMS - 1))
  3255. COPY(new_offset, coordinate_system[_new]);
  3256. active_coordinate_system = _new;
  3257. LOOP_XYZ(i) {
  3258. const float diff = new_offset[i] - old_offset[i];
  3259. if (diff) {
  3260. position_shift[i] += diff;
  3261. update_software_endstops((AxisEnum)i);
  3262. }
  3263. }
  3264. return true;
  3265. }
  3266. /**
  3267. * G53: Apply native workspace to the current move
  3268. *
  3269. * In CNC G-code G53 is a modifier.
  3270. * It precedes a movement command (or other modifiers) on the same line.
  3271. * This is the first command to use parser.chain() to make this possible.
  3272. *
  3273. * Marlin also uses G53 on a line by itself to go back to native space.
  3274. */
  3275. inline void gcode_G53() {
  3276. const int8_t _system = active_coordinate_system;
  3277. active_coordinate_system = -1;
  3278. if (parser.chain()) { // If this command has more following...
  3279. process_parsed_command();
  3280. active_coordinate_system = _system;
  3281. }
  3282. }
  3283. /**
  3284. * G54-G59.3: Select a new workspace
  3285. *
  3286. * A workspace is an XYZ offset to the machine native space.
  3287. * All workspaces default to 0,0,0 at start, or with EEPROM
  3288. * support they may be restored from a previous session.
  3289. *
  3290. * G92 is used to set the current workspace's offset.
  3291. */
  3292. inline void gcode_G54_59(uint8_t subcode=0) {
  3293. const int8_t _space = parser.codenum - 54 + subcode;
  3294. if (select_coordinate_system(_space)) {
  3295. SERIAL_PROTOCOLLNPAIR("Select workspace ", _space);
  3296. report_current_position();
  3297. }
  3298. }
  3299. FORCE_INLINE void gcode_G54() { gcode_G54_59(); }
  3300. FORCE_INLINE void gcode_G55() { gcode_G54_59(); }
  3301. FORCE_INLINE void gcode_G56() { gcode_G54_59(); }
  3302. FORCE_INLINE void gcode_G57() { gcode_G54_59(); }
  3303. FORCE_INLINE void gcode_G58() { gcode_G54_59(); }
  3304. FORCE_INLINE void gcode_G59() { gcode_G54_59(parser.subcode); }
  3305. #endif
  3306. #if ENABLED(INCH_MODE_SUPPORT)
  3307. /**
  3308. * G20: Set input mode to inches
  3309. */
  3310. inline void gcode_G20() { parser.set_input_linear_units(LINEARUNIT_INCH); }
  3311. /**
  3312. * G21: Set input mode to millimeters
  3313. */
  3314. inline void gcode_G21() { parser.set_input_linear_units(LINEARUNIT_MM); }
  3315. #endif
  3316. #if ENABLED(NOZZLE_PARK_FEATURE)
  3317. /**
  3318. * G27: Park the nozzle
  3319. */
  3320. inline void gcode_G27() {
  3321. // Don't allow nozzle parking without homing first
  3322. if (axis_unhomed_error()) return;
  3323. Nozzle::park(parser.ushortval('P'));
  3324. }
  3325. #endif // NOZZLE_PARK_FEATURE
  3326. #if ENABLED(QUICK_HOME)
  3327. static void quick_home_xy() {
  3328. // Pretend the current position is 0,0
  3329. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  3330. sync_plan_position();
  3331. const int x_axis_home_dir =
  3332. #if ENABLED(DUAL_X_CARRIAGE)
  3333. x_home_dir(active_extruder)
  3334. #else
  3335. home_dir(X_AXIS)
  3336. #endif
  3337. ;
  3338. const float mlx = max_length(X_AXIS),
  3339. mly = max_length(Y_AXIS),
  3340. mlratio = mlx > mly ? mly / mlx : mlx / mly,
  3341. fr_mm_s = MIN(homing_feedrate(X_AXIS), homing_feedrate(Y_AXIS)) * SQRT(sq(mlratio) + 1.0);
  3342. #if ENABLED(SENSORLESS_HOMING)
  3343. sensorless_homing_per_axis(X_AXIS);
  3344. sensorless_homing_per_axis(Y_AXIS);
  3345. #endif
  3346. do_blocking_move_to_xy(1.5 * mlx * x_axis_home_dir, 1.5 * mly * home_dir(Y_AXIS), fr_mm_s);
  3347. endstops.validate_homing_move();
  3348. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  3349. #if ENABLED(SENSORLESS_HOMING)
  3350. sensorless_homing_per_axis(X_AXIS, false);
  3351. sensorless_homing_per_axis(Y_AXIS, false);
  3352. #endif
  3353. }
  3354. #endif // QUICK_HOME
  3355. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3356. void log_machine_info() {
  3357. SERIAL_ECHOPGM("Machine Type: ");
  3358. #if ENABLED(DELTA)
  3359. SERIAL_ECHOLNPGM("Delta");
  3360. #elif IS_SCARA
  3361. SERIAL_ECHOLNPGM("SCARA");
  3362. #elif IS_CORE
  3363. SERIAL_ECHOLNPGM("Core");
  3364. #else
  3365. SERIAL_ECHOLNPGM("Cartesian");
  3366. #endif
  3367. SERIAL_ECHOPGM("Probe: ");
  3368. #if ENABLED(PROBE_MANUALLY)
  3369. SERIAL_ECHOLNPGM("PROBE_MANUALLY");
  3370. #elif ENABLED(FIX_MOUNTED_PROBE)
  3371. SERIAL_ECHOLNPGM("FIX_MOUNTED_PROBE");
  3372. #elif ENABLED(BLTOUCH)
  3373. SERIAL_ECHOLNPGM("BLTOUCH");
  3374. #elif HAS_Z_SERVO_PROBE
  3375. SERIAL_ECHOLNPGM("SERVO PROBE");
  3376. #elif ENABLED(Z_PROBE_SLED)
  3377. SERIAL_ECHOLNPGM("Z_PROBE_SLED");
  3378. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  3379. SERIAL_ECHOLNPGM("Z_PROBE_ALLEN_KEY");
  3380. #else
  3381. SERIAL_ECHOLNPGM("NONE");
  3382. #endif
  3383. #if HAS_BED_PROBE
  3384. SERIAL_ECHOPAIR("Probe Offset X:", X_PROBE_OFFSET_FROM_EXTRUDER);
  3385. SERIAL_ECHOPAIR(" Y:", Y_PROBE_OFFSET_FROM_EXTRUDER);
  3386. SERIAL_ECHOPAIR(" Z:", zprobe_zoffset);
  3387. #if X_PROBE_OFFSET_FROM_EXTRUDER > 0
  3388. SERIAL_ECHOPGM(" (Right");
  3389. #elif X_PROBE_OFFSET_FROM_EXTRUDER < 0
  3390. SERIAL_ECHOPGM(" (Left");
  3391. #elif Y_PROBE_OFFSET_FROM_EXTRUDER != 0
  3392. SERIAL_ECHOPGM(" (Middle");
  3393. #else
  3394. SERIAL_ECHOPGM(" (Aligned With");
  3395. #endif
  3396. #if Y_PROBE_OFFSET_FROM_EXTRUDER > 0
  3397. #if IS_SCARA
  3398. SERIAL_ECHOPGM("-Distal");
  3399. #else
  3400. SERIAL_ECHOPGM("-Back");
  3401. #endif
  3402. #elif Y_PROBE_OFFSET_FROM_EXTRUDER < 0
  3403. #if IS_SCARA
  3404. SERIAL_ECHOPGM("-Proximal");
  3405. #else
  3406. SERIAL_ECHOPGM("-Front");
  3407. #endif
  3408. #elif X_PROBE_OFFSET_FROM_EXTRUDER != 0
  3409. SERIAL_ECHOPGM("-Center");
  3410. #endif
  3411. if (zprobe_zoffset < 0)
  3412. SERIAL_ECHOPGM(" & Below");
  3413. else if (zprobe_zoffset > 0)
  3414. SERIAL_ECHOPGM(" & Above");
  3415. else
  3416. SERIAL_ECHOPGM(" & Same Z as");
  3417. SERIAL_ECHOLNPGM(" Nozzle)");
  3418. #endif
  3419. #if HAS_ABL
  3420. SERIAL_ECHOPGM("Auto Bed Leveling: ");
  3421. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3422. SERIAL_ECHOPGM("LINEAR");
  3423. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3424. SERIAL_ECHOPGM("BILINEAR");
  3425. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3426. SERIAL_ECHOPGM("3POINT");
  3427. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  3428. SERIAL_ECHOPGM("UBL");
  3429. #endif
  3430. if (planner.leveling_active) {
  3431. SERIAL_ECHOLNPGM(" (enabled)");
  3432. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  3433. if (planner.z_fade_height)
  3434. SERIAL_ECHOLNPAIR("Z Fade: ", planner.z_fade_height);
  3435. #endif
  3436. #if ABL_PLANAR
  3437. const float diff[XYZ] = {
  3438. planner.get_axis_position_mm(X_AXIS) - current_position[X_AXIS],
  3439. planner.get_axis_position_mm(Y_AXIS) - current_position[Y_AXIS],
  3440. planner.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]
  3441. };
  3442. SERIAL_ECHOPGM("ABL Adjustment X");
  3443. if (diff[X_AXIS] > 0) SERIAL_CHAR('+');
  3444. SERIAL_ECHO(diff[X_AXIS]);
  3445. SERIAL_ECHOPGM(" Y");
  3446. if (diff[Y_AXIS] > 0) SERIAL_CHAR('+');
  3447. SERIAL_ECHO(diff[Y_AXIS]);
  3448. SERIAL_ECHOPGM(" Z");
  3449. if (diff[Z_AXIS] > 0) SERIAL_CHAR('+');
  3450. SERIAL_ECHO(diff[Z_AXIS]);
  3451. #else
  3452. #if ENABLED(AUTO_BED_LEVELING_UBL)
  3453. SERIAL_ECHOPGM("UBL Adjustment Z");
  3454. const float rz = ubl.get_z_correction(current_position[X_AXIS], current_position[Y_AXIS]);
  3455. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3456. SERIAL_ECHOPAIR("Bilinear Grid X", bilinear_start[X_AXIS]);
  3457. SERIAL_ECHOPAIR(" Y", bilinear_start[Y_AXIS]);
  3458. SERIAL_ECHOPAIR(" W", ABL_BG_SPACING(X_AXIS));
  3459. SERIAL_ECHOLNPAIR(" H", ABL_BG_SPACING(Y_AXIS));
  3460. SERIAL_ECHOPGM("ABL Adjustment Z");
  3461. const float rz = bilinear_z_offset(current_position);
  3462. #endif
  3463. SERIAL_ECHO(ftostr43sign(rz, '+'));
  3464. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  3465. if (planner.z_fade_height) {
  3466. SERIAL_ECHOPAIR(" (", ftostr43sign(rz * planner.fade_scaling_factor_for_z(current_position[Z_AXIS]), '+'));
  3467. SERIAL_CHAR(')');
  3468. }
  3469. #endif
  3470. #endif
  3471. }
  3472. else
  3473. SERIAL_ECHOLNPGM(" (disabled)");
  3474. SERIAL_EOL();
  3475. #elif ENABLED(MESH_BED_LEVELING)
  3476. SERIAL_ECHOPGM("Mesh Bed Leveling");
  3477. if (planner.leveling_active) {
  3478. SERIAL_ECHOLNPGM(" (enabled)");
  3479. SERIAL_ECHOPAIR("MBL Adjustment Z", ftostr43sign(mbl.get_z(current_position[X_AXIS], current_position[Y_AXIS]
  3480. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  3481. , 1.0
  3482. #endif
  3483. ), '+'));
  3484. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  3485. if (planner.z_fade_height) {
  3486. SERIAL_ECHOPAIR(" (", ftostr43sign(
  3487. mbl.get_z(current_position[X_AXIS], current_position[Y_AXIS], planner.fade_scaling_factor_for_z(current_position[Z_AXIS])), '+'
  3488. ));
  3489. SERIAL_CHAR(')');
  3490. }
  3491. #endif
  3492. }
  3493. else
  3494. SERIAL_ECHOPGM(" (disabled)");
  3495. SERIAL_EOL();
  3496. #endif // MESH_BED_LEVELING
  3497. }
  3498. #endif // DEBUG_LEVELING_FEATURE
  3499. #if ENABLED(DELTA)
  3500. #if ENABLED(SENSORLESS_HOMING)
  3501. inline void delta_sensorless_homing(const bool on=true) {
  3502. sensorless_homing_per_axis(A_AXIS, on);
  3503. sensorless_homing_per_axis(B_AXIS, on);
  3504. sensorless_homing_per_axis(C_AXIS, on);
  3505. }
  3506. #endif
  3507. /**
  3508. * A delta can only safely home all axes at the same time
  3509. * This is like quick_home_xy() but for 3 towers.
  3510. */
  3511. inline void home_delta() {
  3512. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3513. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> home_delta", current_position);
  3514. #endif
  3515. // Init the current position of all carriages to 0,0,0
  3516. ZERO(current_position);
  3517. sync_plan_position();
  3518. // Disable stealthChop if used. Enable diag1 pin on driver.
  3519. #if ENABLED(SENSORLESS_HOMING)
  3520. delta_sensorless_homing();
  3521. #endif
  3522. // Move all carriages together linearly until an endstop is hit.
  3523. current_position[X_AXIS] = current_position[Y_AXIS] = current_position[Z_AXIS] = (delta_height + 10);
  3524. feedrate_mm_s = homing_feedrate(X_AXIS);
  3525. buffer_line_to_current_position();
  3526. planner.synchronize();
  3527. // Re-enable stealthChop if used. Disable diag1 pin on driver.
  3528. #if ENABLED(SENSORLESS_HOMING)
  3529. delta_sensorless_homing(false);
  3530. #endif
  3531. endstops.validate_homing_move();
  3532. // At least one carriage has reached the top.
  3533. // Now re-home each carriage separately.
  3534. homeaxis(A_AXIS);
  3535. homeaxis(B_AXIS);
  3536. homeaxis(C_AXIS);
  3537. // Set all carriages to their home positions
  3538. // Do this here all at once for Delta, because
  3539. // XYZ isn't ABC. Applying this per-tower would
  3540. // give the impression that they are the same.
  3541. LOOP_XYZ(i) set_axis_is_at_home((AxisEnum)i);
  3542. SYNC_PLAN_POSITION_KINEMATIC();
  3543. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3544. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< home_delta", current_position);
  3545. #endif
  3546. }
  3547. #elif ENABLED(HANGPRINTER)
  3548. /**
  3549. * A hangprinter cannot home itself
  3550. */
  3551. inline void home_hangprinter() {
  3552. SERIAL_ECHOLNPGM("Warning: G28 is not implemented for Hangprinter.");
  3553. }
  3554. #endif
  3555. #ifdef Z_AFTER_PROBING
  3556. void move_z_after_probing() {
  3557. if (current_position[Z_AXIS] != Z_AFTER_PROBING) {
  3558. do_blocking_move_to_z(Z_AFTER_PROBING);
  3559. current_position[Z_AXIS] = Z_AFTER_PROBING;
  3560. }
  3561. }
  3562. #endif
  3563. #if ENABLED(Z_SAFE_HOMING)
  3564. inline void home_z_safely() {
  3565. // Disallow Z homing if X or Y are unknown
  3566. if (!TEST(axis_known_position, X_AXIS) || !TEST(axis_known_position, Y_AXIS)) {
  3567. LCD_MESSAGEPGM(MSG_ERR_Z_HOMING);
  3568. SERIAL_ECHO_START();
  3569. SERIAL_ECHOLNPGM(MSG_ERR_Z_HOMING);
  3570. return;
  3571. }
  3572. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3573. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Z_SAFE_HOMING >>>");
  3574. #endif
  3575. SYNC_PLAN_POSITION_KINEMATIC();
  3576. /**
  3577. * Move the Z probe (or just the nozzle) to the safe homing point
  3578. */
  3579. destination[X_AXIS] = Z_SAFE_HOMING_X_POINT;
  3580. destination[Y_AXIS] = Z_SAFE_HOMING_Y_POINT;
  3581. destination[Z_AXIS] = current_position[Z_AXIS]; // Z is already at the right height
  3582. #if HOMING_Z_WITH_PROBE
  3583. destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  3584. destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  3585. #endif
  3586. if (position_is_reachable(destination[X_AXIS], destination[Y_AXIS])) {
  3587. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3588. if (DEBUGGING(LEVELING)) DEBUG_POS("Z_SAFE_HOMING", destination);
  3589. #endif
  3590. // This causes the carriage on Dual X to unpark
  3591. #if ENABLED(DUAL_X_CARRIAGE)
  3592. active_extruder_parked = false;
  3593. #endif
  3594. #if ENABLED(SENSORLESS_HOMING)
  3595. safe_delay(500); // Short delay needed to settle
  3596. #endif
  3597. do_blocking_move_to_xy(destination[X_AXIS], destination[Y_AXIS]);
  3598. homeaxis(Z_AXIS);
  3599. }
  3600. else {
  3601. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  3602. SERIAL_ECHO_START();
  3603. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  3604. }
  3605. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3606. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING");
  3607. #endif
  3608. }
  3609. #endif // Z_SAFE_HOMING
  3610. #if ENABLED(PROBE_MANUALLY)
  3611. bool g29_in_progress = false;
  3612. #else
  3613. constexpr bool g29_in_progress = false;
  3614. #endif
  3615. /**
  3616. * G28: Home all axes according to settings
  3617. *
  3618. * Parameters
  3619. *
  3620. * None Home to all axes with no parameters.
  3621. * With QUICK_HOME enabled XY will home together, then Z.
  3622. *
  3623. * O Home only if position is unknown
  3624. *
  3625. * Rn Raise by n mm/inches before homing
  3626. *
  3627. * Cartesian parameters
  3628. *
  3629. * X Home to the X endstop
  3630. * Y Home to the Y endstop
  3631. * Z Home to the Z endstop
  3632. *
  3633. */
  3634. inline void gcode_G28(const bool always_home_all) {
  3635. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3636. if (DEBUGGING(LEVELING)) {
  3637. SERIAL_ECHOLNPGM(">>> G28");
  3638. log_machine_info();
  3639. }
  3640. #endif
  3641. #if ENABLED(MARLIN_DEV_MODE)
  3642. if (parser.seen('S')) {
  3643. LOOP_XYZ(a) set_axis_is_at_home((AxisEnum)a);
  3644. SYNC_PLAN_POSITION_KINEMATIC();
  3645. SERIAL_ECHOLNPGM("Simulated Homing");
  3646. report_current_position();
  3647. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3648. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< G28");
  3649. #endif
  3650. return;
  3651. }
  3652. #endif
  3653. if (all_axes_known() && parser.boolval('O')) { // home only if needed
  3654. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3655. if (DEBUGGING(LEVELING)) {
  3656. SERIAL_ECHOLNPGM("> homing not needed, skip");
  3657. SERIAL_ECHOLNPGM("<<< G28");
  3658. }
  3659. #endif
  3660. return;
  3661. }
  3662. // Wait for planner moves to finish!
  3663. planner.synchronize();
  3664. // Cancel the active G29 session
  3665. #if ENABLED(PROBE_MANUALLY)
  3666. g29_in_progress = false;
  3667. #endif
  3668. // Disable the leveling matrix before homing
  3669. #if HAS_LEVELING
  3670. #if ENABLED(RESTORE_LEVELING_AFTER_G28)
  3671. const bool leveling_was_active = planner.leveling_active;
  3672. #endif
  3673. set_bed_leveling_enabled(false);
  3674. #endif
  3675. #if ENABLED(CNC_WORKSPACE_PLANES)
  3676. workspace_plane = PLANE_XY;
  3677. #endif
  3678. #if ENABLED(BLTOUCH)
  3679. // Make sure any BLTouch error condition is cleared
  3680. bltouch_command(BLTOUCH_RESET);
  3681. set_bltouch_deployed(false);
  3682. #endif
  3683. // Always home with tool 0 active
  3684. #if HOTENDS > 1
  3685. #if DISABLED(DELTA) || ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  3686. const uint8_t old_tool_index = active_extruder;
  3687. #endif
  3688. tool_change(0, 0, true);
  3689. #endif
  3690. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  3691. extruder_duplication_enabled = false;
  3692. #endif
  3693. setup_for_endstop_or_probe_move();
  3694. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3695. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.enable(true)");
  3696. #endif
  3697. endstops.enable(true); // Enable endstops for next homing move
  3698. #if ENABLED(DELTA)
  3699. home_delta();
  3700. UNUSED(always_home_all);
  3701. #elif ENABLED(HANGPRINTER)
  3702. home_hangprinter();
  3703. UNUSED(always_home_all);
  3704. #else // NOT Delta or Hangprinter
  3705. const bool homeX = always_home_all || parser.seen('X'),
  3706. homeY = always_home_all || parser.seen('Y'),
  3707. homeZ = always_home_all || parser.seen('Z'),
  3708. home_all = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ);
  3709. set_destination_from_current();
  3710. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  3711. if (home_all || homeZ) homeaxis(Z_AXIS);
  3712. #endif
  3713. const float z_homing_height = (
  3714. #if ENABLED(UNKNOWN_Z_NO_RAISE)
  3715. !TEST(axis_known_position, Z_AXIS) ? 0 :
  3716. #endif
  3717. (parser.seenval('R') ? parser.value_linear_units() : Z_HOMING_HEIGHT)
  3718. );
  3719. if (z_homing_height && (home_all || homeX || homeY)) {
  3720. // Raise Z before homing any other axes and z is not already high enough (never lower z)
  3721. destination[Z_AXIS] = z_homing_height;
  3722. if (destination[Z_AXIS] > current_position[Z_AXIS]) {
  3723. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3724. if (DEBUGGING(LEVELING))
  3725. SERIAL_ECHOLNPAIR("Raise Z (before homing) to ", destination[Z_AXIS]);
  3726. #endif
  3727. do_blocking_move_to_z(destination[Z_AXIS]);
  3728. }
  3729. }
  3730. #if ENABLED(QUICK_HOME)
  3731. if (home_all || (homeX && homeY)) quick_home_xy();
  3732. #endif
  3733. // Home Y (before X)
  3734. #if ENABLED(HOME_Y_BEFORE_X)
  3735. if (home_all || homeY
  3736. #if ENABLED(CODEPENDENT_XY_HOMING)
  3737. || homeX
  3738. #endif
  3739. ) homeaxis(Y_AXIS);
  3740. #endif
  3741. // Home X
  3742. if (home_all || homeX
  3743. #if ENABLED(CODEPENDENT_XY_HOMING) && DISABLED(HOME_Y_BEFORE_X)
  3744. || homeY
  3745. #endif
  3746. ) {
  3747. #if ENABLED(DUAL_X_CARRIAGE)
  3748. // Always home the 2nd (right) extruder first
  3749. active_extruder = 1;
  3750. homeaxis(X_AXIS);
  3751. // Remember this extruder's position for later tool change
  3752. inactive_extruder_x_pos = current_position[X_AXIS];
  3753. // Home the 1st (left) extruder
  3754. active_extruder = 0;
  3755. homeaxis(X_AXIS);
  3756. // Consider the active extruder to be parked
  3757. COPY(raised_parked_position, current_position);
  3758. delayed_move_time = 0;
  3759. active_extruder_parked = true;
  3760. #else
  3761. homeaxis(X_AXIS);
  3762. #endif
  3763. }
  3764. // Home Y (after X)
  3765. #if DISABLED(HOME_Y_BEFORE_X)
  3766. if (home_all || homeY) homeaxis(Y_AXIS);
  3767. #endif
  3768. // Home Z last if homing towards the bed
  3769. #if Z_HOME_DIR < 0
  3770. if (home_all || homeZ) {
  3771. #if ENABLED(Z_SAFE_HOMING)
  3772. home_z_safely();
  3773. #else
  3774. homeaxis(Z_AXIS);
  3775. #endif
  3776. #if HOMING_Z_WITH_PROBE && defined(Z_AFTER_PROBING)
  3777. move_z_after_probing();
  3778. #endif
  3779. } // home_all || homeZ
  3780. #endif // Z_HOME_DIR < 0
  3781. SYNC_PLAN_POSITION_KINEMATIC();
  3782. #endif // !DELTA (gcode_G28)
  3783. endstops.not_homing();
  3784. #if ENABLED(DELTA) && ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  3785. // move to a height where we can use the full xy-area
  3786. do_blocking_move_to_z(delta_clip_start_height);
  3787. #endif
  3788. #if ENABLED(RESTORE_LEVELING_AFTER_G28)
  3789. set_bed_leveling_enabled(leveling_was_active);
  3790. #endif
  3791. clean_up_after_endstop_or_probe_move();
  3792. // Restore the active tool after homing
  3793. #if HOTENDS > 1 && (DISABLED(DELTA) || ENABLED(DELTA_HOME_TO_SAFE_ZONE))
  3794. #if ENABLED(PARKING_EXTRUDER)
  3795. #define NO_FETCH false // fetch the previous toolhead
  3796. #else
  3797. #define NO_FETCH true
  3798. #endif
  3799. tool_change(old_tool_index, 0, NO_FETCH);
  3800. #endif
  3801. lcd_refresh();
  3802. report_current_position();
  3803. #if ENABLED(NANODLP_Z_SYNC)
  3804. #if ENABLED(NANODLP_ALL_AXIS)
  3805. #define _HOME_SYNC true // For any axis, output sync text.
  3806. #else
  3807. #define _HOME_SYNC (home_all || homeZ) // Only for Z-axis
  3808. #endif
  3809. if (_HOME_SYNC)
  3810. SERIAL_ECHOLNPGM(MSG_Z_MOVE_COMP);
  3811. #endif
  3812. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3813. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< G28");
  3814. #endif
  3815. } // G28
  3816. void home_all_axes() { gcode_G28(true); }
  3817. #if ENABLED(MESH_BED_LEVELING) || ENABLED(PROBE_MANUALLY)
  3818. inline void _manual_goto_xy(const float &rx, const float &ry) {
  3819. #ifdef MANUAL_PROBE_START_Z
  3820. #if MANUAL_PROBE_HEIGHT > 0
  3821. do_blocking_move_to(rx, ry, MANUAL_PROBE_HEIGHT);
  3822. do_blocking_move_to_z(MAX(0,MANUAL_PROBE_START_Z));
  3823. #else
  3824. do_blocking_move_to(rx, ry, MAX(0,MANUAL_PROBE_START_Z));
  3825. #endif
  3826. #elif MANUAL_PROBE_HEIGHT > 0
  3827. const float prev_z = current_position[Z_AXIS];
  3828. do_blocking_move_to(rx, ry, MANUAL_PROBE_HEIGHT);
  3829. do_blocking_move_to_z(prev_z);
  3830. #else
  3831. do_blocking_move_to_xy(rx, ry);
  3832. #endif
  3833. current_position[X_AXIS] = rx;
  3834. current_position[Y_AXIS] = ry;
  3835. #if ENABLED(LCD_BED_LEVELING)
  3836. lcd_wait_for_move = false;
  3837. #endif
  3838. }
  3839. #endif
  3840. #if ENABLED(MESH_BED_LEVELING)
  3841. // Save 130 bytes with non-duplication of PSTR
  3842. void echo_not_entered() { SERIAL_PROTOCOLLNPGM(" not entered."); }
  3843. /**
  3844. * G29: Mesh-based Z probe, probes a grid and produces a
  3845. * mesh to compensate for variable bed height
  3846. *
  3847. * Parameters With MESH_BED_LEVELING:
  3848. *
  3849. * S0 Produce a mesh report
  3850. * S1 Start probing mesh points
  3851. * S2 Probe the next mesh point
  3852. * S3 Xn Yn Zn.nn Manually modify a single point
  3853. * S4 Zn.nn Set z offset. Positive away from bed, negative closer to bed.
  3854. * S5 Reset and disable mesh
  3855. *
  3856. * The S0 report the points as below
  3857. *
  3858. * +----> X-axis 1-n
  3859. * |
  3860. * |
  3861. * v Y-axis 1-n
  3862. *
  3863. */
  3864. inline void gcode_G29() {
  3865. static int mbl_probe_index = -1;
  3866. #if HAS_SOFTWARE_ENDSTOPS
  3867. static bool enable_soft_endstops;
  3868. #endif
  3869. MeshLevelingState state = (MeshLevelingState)parser.byteval('S', (int8_t)MeshReport);
  3870. if (!WITHIN(state, 0, 5)) {
  3871. SERIAL_PROTOCOLLNPGM("S out of range (0-5).");
  3872. return;
  3873. }
  3874. int8_t px, py;
  3875. switch (state) {
  3876. case MeshReport:
  3877. if (leveling_is_valid()) {
  3878. SERIAL_PROTOCOLLNPAIR("State: ", planner.leveling_active ? MSG_ON : MSG_OFF);
  3879. mbl.report_mesh();
  3880. }
  3881. else
  3882. SERIAL_PROTOCOLLNPGM("Mesh bed leveling has no data.");
  3883. break;
  3884. case MeshStart:
  3885. mbl.reset();
  3886. mbl_probe_index = 0;
  3887. if (!lcd_wait_for_move) {
  3888. enqueue_and_echo_commands_P(PSTR("G28\nG29 S2"));
  3889. return;
  3890. }
  3891. state = MeshNext;
  3892. case MeshNext:
  3893. if (mbl_probe_index < 0) {
  3894. SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first.");
  3895. return;
  3896. }
  3897. // For each G29 S2...
  3898. if (mbl_probe_index == 0) {
  3899. #if HAS_SOFTWARE_ENDSTOPS
  3900. // For the initial G29 S2 save software endstop state
  3901. enable_soft_endstops = soft_endstops_enabled;
  3902. #endif
  3903. // Move close to the bed before the first point
  3904. do_blocking_move_to_z(0);
  3905. }
  3906. else {
  3907. // Save Z for the previous mesh position
  3908. mbl.set_zigzag_z(mbl_probe_index - 1, current_position[Z_AXIS]);
  3909. #if HAS_SOFTWARE_ENDSTOPS
  3910. soft_endstops_enabled = enable_soft_endstops;
  3911. #endif
  3912. }
  3913. // If there's another point to sample, move there with optional lift.
  3914. if (mbl_probe_index < GRID_MAX_POINTS) {
  3915. #if HAS_SOFTWARE_ENDSTOPS
  3916. // Disable software endstops to allow manual adjustment
  3917. // If G29 is not completed, they will not be re-enabled
  3918. soft_endstops_enabled = false;
  3919. #endif
  3920. mbl.zigzag(mbl_probe_index++, px, py);
  3921. _manual_goto_xy(mbl.index_to_xpos[px], mbl.index_to_ypos[py]);
  3922. }
  3923. else {
  3924. // One last "return to the bed" (as originally coded) at completion
  3925. current_position[Z_AXIS] = MANUAL_PROBE_HEIGHT;
  3926. buffer_line_to_current_position();
  3927. planner.synchronize();
  3928. // After recording the last point, activate home and activate
  3929. mbl_probe_index = -1;
  3930. SERIAL_PROTOCOLLNPGM("Mesh probing done.");
  3931. BUZZ(100, 659);
  3932. BUZZ(100, 698);
  3933. home_all_axes();
  3934. set_bed_leveling_enabled(true);
  3935. #if ENABLED(MESH_G28_REST_ORIGIN)
  3936. current_position[Z_AXIS] = 0;
  3937. set_destination_from_current();
  3938. buffer_line_to_destination(homing_feedrate(Z_AXIS));
  3939. planner.synchronize();
  3940. #endif
  3941. #if ENABLED(LCD_BED_LEVELING)
  3942. lcd_wait_for_move = false;
  3943. #endif
  3944. }
  3945. break;
  3946. case MeshSet:
  3947. if (parser.seenval('X')) {
  3948. px = parser.value_int() - 1;
  3949. if (!WITHIN(px, 0, GRID_MAX_POINTS_X - 1)) {
  3950. SERIAL_PROTOCOLPAIR("X out of range (1-", int(GRID_MAX_POINTS_X));
  3951. SERIAL_PROTOCOLLNPGM(")");
  3952. return;
  3953. }
  3954. }
  3955. else {
  3956. SERIAL_CHAR('X'); echo_not_entered();
  3957. return;
  3958. }
  3959. if (parser.seenval('Y')) {
  3960. py = parser.value_int() - 1;
  3961. if (!WITHIN(py, 0, GRID_MAX_POINTS_Y - 1)) {
  3962. SERIAL_PROTOCOLPAIR("Y out of range (1-", int(GRID_MAX_POINTS_Y));
  3963. SERIAL_PROTOCOLLNPGM(")");
  3964. return;
  3965. }
  3966. }
  3967. else {
  3968. SERIAL_CHAR('Y'); echo_not_entered();
  3969. return;
  3970. }
  3971. if (parser.seenval('Z'))
  3972. mbl.z_values[px][py] = parser.value_linear_units();
  3973. else {
  3974. SERIAL_CHAR('Z'); echo_not_entered();
  3975. return;
  3976. }
  3977. break;
  3978. case MeshSetZOffset:
  3979. if (parser.seenval('Z'))
  3980. mbl.z_offset = parser.value_linear_units();
  3981. else {
  3982. SERIAL_CHAR('Z'); echo_not_entered();
  3983. return;
  3984. }
  3985. break;
  3986. case MeshReset:
  3987. reset_bed_level();
  3988. break;
  3989. } // switch (state)
  3990. if (state == MeshNext) {
  3991. SERIAL_PROTOCOLPAIR("MBL G29 point ", MIN(mbl_probe_index, GRID_MAX_POINTS));
  3992. SERIAL_PROTOCOLLNPAIR(" of ", int(GRID_MAX_POINTS));
  3993. }
  3994. report_current_position();
  3995. }
  3996. #elif OLDSCHOOL_ABL
  3997. #if ABL_GRID
  3998. #if ENABLED(PROBE_Y_FIRST)
  3999. #define PR_OUTER_VAR xCount
  4000. #define PR_OUTER_END abl_grid_points_x
  4001. #define PR_INNER_VAR yCount
  4002. #define PR_INNER_END abl_grid_points_y
  4003. #else
  4004. #define PR_OUTER_VAR yCount
  4005. #define PR_OUTER_END abl_grid_points_y
  4006. #define PR_INNER_VAR xCount
  4007. #define PR_INNER_END abl_grid_points_x
  4008. #endif
  4009. #endif
  4010. /**
  4011. * G29: Detailed Z probe, probes the bed at 3 or more points.
  4012. * Will fail if the printer has not been homed with G28.
  4013. *
  4014. * Enhanced G29 Auto Bed Leveling Probe Routine
  4015. *
  4016. * O Auto-level only if needed
  4017. *
  4018. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  4019. * or alter the bed level data. Useful to check the topology
  4020. * after a first run of G29.
  4021. *
  4022. * J Jettison current bed leveling data
  4023. *
  4024. * V Set the verbose level (0-4). Example: "G29 V3"
  4025. *
  4026. * Parameters With LINEAR leveling only:
  4027. *
  4028. * P Set the size of the grid that will be probed (P x P points).
  4029. * Example: "G29 P4"
  4030. *
  4031. * X Set the X size of the grid that will be probed (X x Y points).
  4032. * Example: "G29 X7 Y5"
  4033. *
  4034. * Y Set the Y size of the grid that will be probed (X x Y points).
  4035. *
  4036. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  4037. * This is useful for manual bed leveling and finding flaws in the bed (to
  4038. * assist with part placement).
  4039. * Not supported by non-linear delta printer bed leveling.
  4040. *
  4041. * Parameters With LINEAR and BILINEAR leveling only:
  4042. *
  4043. * S Set the XY travel speed between probe points (in units/min)
  4044. *
  4045. * F Set the Front limit of the probing grid
  4046. * B Set the Back limit of the probing grid
  4047. * L Set the Left limit of the probing grid
  4048. * R Set the Right limit of the probing grid
  4049. *
  4050. * Parameters with DEBUG_LEVELING_FEATURE only:
  4051. *
  4052. * C Make a totally fake grid with no actual probing.
  4053. * For use in testing when no probing is possible.
  4054. *
  4055. * Parameters with BILINEAR leveling only:
  4056. *
  4057. * Z Supply an additional Z probe offset
  4058. *
  4059. * Extra parameters with PROBE_MANUALLY:
  4060. *
  4061. * To do manual probing simply repeat G29 until the procedure is complete.
  4062. * The first G29 accepts parameters. 'G29 Q' for status, 'G29 A' to abort.
  4063. *
  4064. * Q Query leveling and G29 state
  4065. *
  4066. * A Abort current leveling procedure
  4067. *
  4068. * Extra parameters with BILINEAR only:
  4069. *
  4070. * W Write a mesh point. (If G29 is idle.)
  4071. * I X index for mesh point
  4072. * J Y index for mesh point
  4073. * X X for mesh point, overrides I
  4074. * Y Y for mesh point, overrides J
  4075. * Z Z for mesh point. Otherwise, raw current Z.
  4076. *
  4077. * Without PROBE_MANUALLY:
  4078. *
  4079. * E By default G29 will engage the Z probe, test the bed, then disengage.
  4080. * Include "E" to engage/disengage the Z probe for each sample.
  4081. * There's no extra effect if you have a fixed Z probe.
  4082. *
  4083. */
  4084. inline void gcode_G29() {
  4085. #if ENABLED(DEBUG_LEVELING_FEATURE) || ENABLED(PROBE_MANUALLY)
  4086. const bool seenQ = parser.seen('Q');
  4087. #else
  4088. constexpr bool seenQ = false;
  4089. #endif
  4090. // G29 Q is also available if debugging
  4091. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4092. const uint8_t old_debug_flags = marlin_debug_flags;
  4093. if (seenQ) marlin_debug_flags |= DEBUG_LEVELING;
  4094. if (DEBUGGING(LEVELING)) {
  4095. DEBUG_POS(">>> G29", current_position);
  4096. log_machine_info();
  4097. }
  4098. marlin_debug_flags = old_debug_flags;
  4099. #if DISABLED(PROBE_MANUALLY)
  4100. if (seenQ) return;
  4101. #endif
  4102. #endif
  4103. #if ENABLED(PROBE_MANUALLY)
  4104. const bool seenA = parser.seen('A');
  4105. #else
  4106. constexpr bool seenA = false;
  4107. #endif
  4108. const bool no_action = seenA || seenQ,
  4109. faux =
  4110. #if ENABLED(DEBUG_LEVELING_FEATURE) && DISABLED(PROBE_MANUALLY)
  4111. parser.boolval('C')
  4112. #else
  4113. no_action
  4114. #endif
  4115. ;
  4116. // Don't allow auto-leveling without homing first
  4117. if (axis_unhomed_error()) return;
  4118. if (!no_action && planner.leveling_active && parser.boolval('O')) { // Auto-level only if needed
  4119. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4120. if (DEBUGGING(LEVELING)) {
  4121. SERIAL_ECHOLNPGM("> Auto-level not needed, skip");
  4122. SERIAL_ECHOLNPGM("<<< G29");
  4123. }
  4124. #endif
  4125. return;
  4126. }
  4127. // Define local vars 'static' for manual probing, 'auto' otherwise
  4128. #if ENABLED(PROBE_MANUALLY)
  4129. #define ABL_VAR static
  4130. #else
  4131. #define ABL_VAR
  4132. #endif
  4133. ABL_VAR int verbose_level;
  4134. ABL_VAR float xProbe, yProbe, measured_z;
  4135. ABL_VAR bool dryrun, abl_should_enable;
  4136. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  4137. ABL_VAR int16_t abl_probe_index;
  4138. #endif
  4139. #if HAS_SOFTWARE_ENDSTOPS && ENABLED(PROBE_MANUALLY)
  4140. ABL_VAR bool enable_soft_endstops = true;
  4141. #endif
  4142. #if ABL_GRID
  4143. #if ENABLED(PROBE_MANUALLY)
  4144. ABL_VAR uint8_t PR_OUTER_VAR;
  4145. ABL_VAR int8_t PR_INNER_VAR;
  4146. #endif
  4147. ABL_VAR int left_probe_bed_position, right_probe_bed_position, front_probe_bed_position, back_probe_bed_position;
  4148. ABL_VAR float xGridSpacing = 0, yGridSpacing = 0;
  4149. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4150. ABL_VAR uint8_t abl_grid_points_x = GRID_MAX_POINTS_X,
  4151. abl_grid_points_y = GRID_MAX_POINTS_Y;
  4152. ABL_VAR bool do_topography_map;
  4153. #else // Bilinear
  4154. uint8_t constexpr abl_grid_points_x = GRID_MAX_POINTS_X,
  4155. abl_grid_points_y = GRID_MAX_POINTS_Y;
  4156. #endif
  4157. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4158. ABL_VAR int16_t abl_points;
  4159. #elif ENABLED(PROBE_MANUALLY) // Bilinear
  4160. int16_t constexpr abl_points = GRID_MAX_POINTS;
  4161. #endif
  4162. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4163. ABL_VAR float zoffset;
  4164. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  4165. ABL_VAR int indexIntoAB[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  4166. ABL_VAR float eqnAMatrix[GRID_MAX_POINTS * 3], // "A" matrix of the linear system of equations
  4167. eqnBVector[GRID_MAX_POINTS], // "B" vector of Z points
  4168. mean;
  4169. #endif
  4170. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  4171. #if ENABLED(PROBE_MANUALLY)
  4172. int8_t constexpr abl_points = 3; // used to show total points
  4173. #endif
  4174. // Probe at 3 arbitrary points
  4175. ABL_VAR vector_3 points[3] = {
  4176. vector_3(PROBE_PT_1_X, PROBE_PT_1_Y, 0),
  4177. vector_3(PROBE_PT_2_X, PROBE_PT_2_Y, 0),
  4178. vector_3(PROBE_PT_3_X, PROBE_PT_3_Y, 0)
  4179. };
  4180. #endif // AUTO_BED_LEVELING_3POINT
  4181. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4182. struct linear_fit_data lsf_results;
  4183. incremental_LSF_reset(&lsf_results);
  4184. #endif
  4185. /**
  4186. * On the initial G29 fetch command parameters.
  4187. */
  4188. if (!g29_in_progress) {
  4189. #if ENABLED(DUAL_X_CARRIAGE)
  4190. if (active_extruder != 0) tool_change(0);
  4191. #endif
  4192. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  4193. abl_probe_index = -1;
  4194. #endif
  4195. abl_should_enable = planner.leveling_active;
  4196. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4197. const bool seen_w = parser.seen('W');
  4198. if (seen_w) {
  4199. if (!leveling_is_valid()) {
  4200. SERIAL_ERROR_START();
  4201. SERIAL_ERRORLNPGM("No bilinear grid");
  4202. return;
  4203. }
  4204. const float rz = parser.seenval('Z') ? RAW_Z_POSITION(parser.value_linear_units()) : current_position[Z_AXIS];
  4205. if (!WITHIN(rz, -10, 10)) {
  4206. SERIAL_ERROR_START();
  4207. SERIAL_ERRORLNPGM("Bad Z value");
  4208. return;
  4209. }
  4210. const float rx = RAW_X_POSITION(parser.linearval('X', NAN)),
  4211. ry = RAW_Y_POSITION(parser.linearval('Y', NAN));
  4212. int8_t i = parser.byteval('I', -1),
  4213. j = parser.byteval('J', -1);
  4214. if (!isnan(rx) && !isnan(ry)) {
  4215. // Get nearest i / j from rx / ry
  4216. i = (rx - bilinear_start[X_AXIS] + 0.5f * xGridSpacing) / xGridSpacing;
  4217. j = (ry - bilinear_start[Y_AXIS] + 0.5f * yGridSpacing) / yGridSpacing;
  4218. i = constrain(i, 0, GRID_MAX_POINTS_X - 1);
  4219. j = constrain(j, 0, GRID_MAX_POINTS_Y - 1);
  4220. }
  4221. if (WITHIN(i, 0, GRID_MAX_POINTS_X - 1) && WITHIN(j, 0, GRID_MAX_POINTS_Y)) {
  4222. set_bed_leveling_enabled(false);
  4223. z_values[i][j] = rz;
  4224. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  4225. bed_level_virt_interpolate();
  4226. #endif
  4227. set_bed_leveling_enabled(abl_should_enable);
  4228. if (abl_should_enable) report_current_position();
  4229. }
  4230. return;
  4231. } // parser.seen('W')
  4232. #else
  4233. constexpr bool seen_w = false;
  4234. #endif
  4235. // Jettison bed leveling data
  4236. if (!seen_w && parser.seen('J')) {
  4237. reset_bed_level();
  4238. return;
  4239. }
  4240. verbose_level = parser.intval('V');
  4241. if (!WITHIN(verbose_level, 0, 4)) {
  4242. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  4243. return;
  4244. }
  4245. dryrun = parser.boolval('D')
  4246. #if ENABLED(PROBE_MANUALLY)
  4247. || no_action
  4248. #endif
  4249. ;
  4250. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4251. do_topography_map = verbose_level > 2 || parser.boolval('T');
  4252. // X and Y specify points in each direction, overriding the default
  4253. // These values may be saved with the completed mesh
  4254. abl_grid_points_x = parser.intval('X', GRID_MAX_POINTS_X);
  4255. abl_grid_points_y = parser.intval('Y', GRID_MAX_POINTS_Y);
  4256. if (parser.seenval('P')) abl_grid_points_x = abl_grid_points_y = parser.value_int();
  4257. if (!WITHIN(abl_grid_points_x, 2, GRID_MAX_POINTS_X)) {
  4258. SERIAL_PROTOCOLLNPGM("?Probe points (X) is implausible (2-" STRINGIFY(GRID_MAX_POINTS_X) ").");
  4259. return;
  4260. }
  4261. if (!WITHIN(abl_grid_points_y, 2, GRID_MAX_POINTS_Y)) {
  4262. SERIAL_PROTOCOLLNPGM("?Probe points (Y) is implausible (2-" STRINGIFY(GRID_MAX_POINTS_Y) ").");
  4263. return;
  4264. }
  4265. abl_points = abl_grid_points_x * abl_grid_points_y;
  4266. mean = 0;
  4267. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4268. zoffset = parser.linearval('Z');
  4269. #endif
  4270. #if ABL_GRID
  4271. xy_probe_feedrate_mm_s = MMM_TO_MMS(parser.linearval('S', XY_PROBE_SPEED));
  4272. left_probe_bed_position = parser.seenval('L') ? int(RAW_X_POSITION(parser.value_linear_units())) : LEFT_PROBE_BED_POSITION;
  4273. right_probe_bed_position = parser.seenval('R') ? int(RAW_X_POSITION(parser.value_linear_units())) : RIGHT_PROBE_BED_POSITION;
  4274. front_probe_bed_position = parser.seenval('F') ? int(RAW_Y_POSITION(parser.value_linear_units())) : FRONT_PROBE_BED_POSITION;
  4275. back_probe_bed_position = parser.seenval('B') ? int(RAW_Y_POSITION(parser.value_linear_units())) : BACK_PROBE_BED_POSITION;
  4276. if (
  4277. #if IS_SCARA || ENABLED(DELTA)
  4278. !position_is_reachable_by_probe(left_probe_bed_position, 0)
  4279. || !position_is_reachable_by_probe(right_probe_bed_position, 0)
  4280. || !position_is_reachable_by_probe(0, front_probe_bed_position)
  4281. || !position_is_reachable_by_probe(0, back_probe_bed_position)
  4282. #else
  4283. !position_is_reachable_by_probe(left_probe_bed_position, front_probe_bed_position)
  4284. || !position_is_reachable_by_probe(right_probe_bed_position, back_probe_bed_position)
  4285. #endif
  4286. ) {
  4287. SERIAL_PROTOCOLLNPGM("? (L,R,F,B) out of bounds.");
  4288. return;
  4289. }
  4290. // probe at the points of a lattice grid
  4291. xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (abl_grid_points_x - 1);
  4292. yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (abl_grid_points_y - 1);
  4293. #endif // ABL_GRID
  4294. if (verbose_level > 0) {
  4295. SERIAL_PROTOCOLPGM("G29 Auto Bed Leveling");
  4296. if (dryrun) SERIAL_PROTOCOLPGM(" (DRYRUN)");
  4297. SERIAL_EOL();
  4298. }
  4299. planner.synchronize();
  4300. // Disable auto bed leveling during G29.
  4301. // Be formal so G29 can be done successively without G28.
  4302. if (!no_action) set_bed_leveling_enabled(false);
  4303. #if HAS_BED_PROBE
  4304. // Deploy the probe. Probe will raise if needed.
  4305. if (DEPLOY_PROBE()) {
  4306. set_bed_leveling_enabled(abl_should_enable);
  4307. return;
  4308. }
  4309. #endif
  4310. if (!faux) setup_for_endstop_or_probe_move();
  4311. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4312. #if ENABLED(PROBE_MANUALLY)
  4313. if (!no_action)
  4314. #endif
  4315. if ( xGridSpacing != bilinear_grid_spacing[X_AXIS]
  4316. || yGridSpacing != bilinear_grid_spacing[Y_AXIS]
  4317. || left_probe_bed_position != bilinear_start[X_AXIS]
  4318. || front_probe_bed_position != bilinear_start[Y_AXIS]
  4319. ) {
  4320. // Reset grid to 0.0 or "not probed". (Also disables ABL)
  4321. reset_bed_level();
  4322. // Initialize a grid with the given dimensions
  4323. bilinear_grid_spacing[X_AXIS] = xGridSpacing;
  4324. bilinear_grid_spacing[Y_AXIS] = yGridSpacing;
  4325. bilinear_start[X_AXIS] = left_probe_bed_position;
  4326. bilinear_start[Y_AXIS] = front_probe_bed_position;
  4327. // Can't re-enable (on error) until the new grid is written
  4328. abl_should_enable = false;
  4329. }
  4330. #endif // AUTO_BED_LEVELING_BILINEAR
  4331. #if ENABLED(AUTO_BED_LEVELING_3POINT)
  4332. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4333. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> 3-point Leveling");
  4334. #endif
  4335. // Probe at 3 arbitrary points
  4336. points[0].z = points[1].z = points[2].z = 0;
  4337. #endif // AUTO_BED_LEVELING_3POINT
  4338. } // !g29_in_progress
  4339. #if ENABLED(PROBE_MANUALLY)
  4340. // For manual probing, get the next index to probe now.
  4341. // On the first probe this will be incremented to 0.
  4342. if (!no_action) {
  4343. ++abl_probe_index;
  4344. g29_in_progress = true;
  4345. }
  4346. // Abort current G29 procedure, go back to idle state
  4347. if (seenA && g29_in_progress) {
  4348. SERIAL_PROTOCOLLNPGM("Manual G29 aborted");
  4349. #if HAS_SOFTWARE_ENDSTOPS
  4350. soft_endstops_enabled = enable_soft_endstops;
  4351. #endif
  4352. set_bed_leveling_enabled(abl_should_enable);
  4353. g29_in_progress = false;
  4354. #if ENABLED(LCD_BED_LEVELING)
  4355. lcd_wait_for_move = false;
  4356. #endif
  4357. }
  4358. // Query G29 status
  4359. if (verbose_level || seenQ) {
  4360. SERIAL_PROTOCOLPGM("Manual G29 ");
  4361. if (g29_in_progress) {
  4362. SERIAL_PROTOCOLPAIR("point ", MIN(abl_probe_index + 1, abl_points));
  4363. SERIAL_PROTOCOLLNPAIR(" of ", abl_points);
  4364. }
  4365. else
  4366. SERIAL_PROTOCOLLNPGM("idle");
  4367. }
  4368. if (no_action) return;
  4369. if (abl_probe_index == 0) {
  4370. // For the initial G29 save software endstop state
  4371. #if HAS_SOFTWARE_ENDSTOPS
  4372. enable_soft_endstops = soft_endstops_enabled;
  4373. #endif
  4374. // Move close to the bed before the first point
  4375. do_blocking_move_to_z(0);
  4376. }
  4377. else {
  4378. #if ENABLED(AUTO_BED_LEVELING_LINEAR) || ENABLED(AUTO_BED_LEVELING_3POINT)
  4379. const uint16_t index = abl_probe_index - 1;
  4380. #endif
  4381. // For G29 after adjusting Z.
  4382. // Save the previous Z before going to the next point
  4383. measured_z = current_position[Z_AXIS];
  4384. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4385. mean += measured_z;
  4386. eqnBVector[index] = measured_z;
  4387. eqnAMatrix[index + 0 * abl_points] = xProbe;
  4388. eqnAMatrix[index + 1 * abl_points] = yProbe;
  4389. eqnAMatrix[index + 2 * abl_points] = 1;
  4390. incremental_LSF(&lsf_results, xProbe, yProbe, measured_z);
  4391. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  4392. points[index].z = measured_z;
  4393. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4394. z_values[xCount][yCount] = measured_z + zoffset;
  4395. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4396. if (DEBUGGING(LEVELING)) {
  4397. SERIAL_PROTOCOLPAIR("Save X", xCount);
  4398. SERIAL_PROTOCOLPAIR(" Y", yCount);
  4399. SERIAL_PROTOCOLLNPAIR(" Z", measured_z + zoffset);
  4400. }
  4401. #endif
  4402. #endif
  4403. }
  4404. //
  4405. // If there's another point to sample, move there with optional lift.
  4406. //
  4407. #if ABL_GRID
  4408. // Skip any unreachable points
  4409. while (abl_probe_index < abl_points) {
  4410. // Set xCount, yCount based on abl_probe_index, with zig-zag
  4411. PR_OUTER_VAR = abl_probe_index / PR_INNER_END;
  4412. PR_INNER_VAR = abl_probe_index - (PR_OUTER_VAR * PR_INNER_END);
  4413. // Probe in reverse order for every other row/column
  4414. bool zig = (PR_OUTER_VAR & 1); // != ((PR_OUTER_END) & 1);
  4415. if (zig) PR_INNER_VAR = (PR_INNER_END - 1) - PR_INNER_VAR;
  4416. const float xBase = xCount * xGridSpacing + left_probe_bed_position,
  4417. yBase = yCount * yGridSpacing + front_probe_bed_position;
  4418. xProbe = FLOOR(xBase + (xBase < 0 ? 0 : 0.5));
  4419. yProbe = FLOOR(yBase + (yBase < 0 ? 0 : 0.5));
  4420. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4421. indexIntoAB[xCount][yCount] = abl_probe_index;
  4422. #endif
  4423. // Keep looping till a reachable point is found
  4424. if (position_is_reachable(xProbe, yProbe)) break;
  4425. ++abl_probe_index;
  4426. }
  4427. // Is there a next point to move to?
  4428. if (abl_probe_index < abl_points) {
  4429. _manual_goto_xy(xProbe, yProbe); // Can be used here too!
  4430. #if HAS_SOFTWARE_ENDSTOPS
  4431. // Disable software endstops to allow manual adjustment
  4432. // If G29 is not completed, they will not be re-enabled
  4433. soft_endstops_enabled = false;
  4434. #endif
  4435. return;
  4436. }
  4437. else {
  4438. // Leveling done! Fall through to G29 finishing code below
  4439. SERIAL_PROTOCOLLNPGM("Grid probing done.");
  4440. // Re-enable software endstops, if needed
  4441. #if HAS_SOFTWARE_ENDSTOPS
  4442. soft_endstops_enabled = enable_soft_endstops;
  4443. #endif
  4444. }
  4445. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  4446. // Probe at 3 arbitrary points
  4447. if (abl_probe_index < abl_points) {
  4448. xProbe = points[abl_probe_index].x;
  4449. yProbe = points[abl_probe_index].y;
  4450. _manual_goto_xy(xProbe, yProbe);
  4451. #if HAS_SOFTWARE_ENDSTOPS
  4452. // Disable software endstops to allow manual adjustment
  4453. // If G29 is not completed, they will not be re-enabled
  4454. soft_endstops_enabled = false;
  4455. #endif
  4456. return;
  4457. }
  4458. else {
  4459. SERIAL_PROTOCOLLNPGM("3-point probing done.");
  4460. // Re-enable software endstops, if needed
  4461. #if HAS_SOFTWARE_ENDSTOPS
  4462. soft_endstops_enabled = enable_soft_endstops;
  4463. #endif
  4464. if (!dryrun) {
  4465. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  4466. if (planeNormal.z < 0) {
  4467. planeNormal.x *= -1;
  4468. planeNormal.y *= -1;
  4469. planeNormal.z *= -1;
  4470. }
  4471. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  4472. // Can't re-enable (on error) until the new grid is written
  4473. abl_should_enable = false;
  4474. }
  4475. }
  4476. #endif // AUTO_BED_LEVELING_3POINT
  4477. #else // !PROBE_MANUALLY
  4478. {
  4479. const ProbePtRaise raise_after = parser.boolval('E') ? PROBE_PT_STOW : PROBE_PT_RAISE;
  4480. measured_z = 0;
  4481. #if ABL_GRID
  4482. bool zig = PR_OUTER_END & 1; // Always end at RIGHT and BACK_PROBE_BED_POSITION
  4483. measured_z = 0;
  4484. // Outer loop is Y with PROBE_Y_FIRST disabled
  4485. for (uint8_t PR_OUTER_VAR = 0; PR_OUTER_VAR < PR_OUTER_END && !isnan(measured_z); PR_OUTER_VAR++) {
  4486. int8_t inStart, inStop, inInc;
  4487. if (zig) { // away from origin
  4488. inStart = 0;
  4489. inStop = PR_INNER_END;
  4490. inInc = 1;
  4491. }
  4492. else { // towards origin
  4493. inStart = PR_INNER_END - 1;
  4494. inStop = -1;
  4495. inInc = -1;
  4496. }
  4497. zig ^= true; // zag
  4498. // Inner loop is Y with PROBE_Y_FIRST enabled
  4499. for (int8_t PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; PR_INNER_VAR += inInc) {
  4500. float xBase = left_probe_bed_position + xGridSpacing * xCount,
  4501. yBase = front_probe_bed_position + yGridSpacing * yCount;
  4502. xProbe = FLOOR(xBase + (xBase < 0 ? 0 : 0.5));
  4503. yProbe = FLOOR(yBase + (yBase < 0 ? 0 : 0.5));
  4504. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4505. indexIntoAB[xCount][yCount] = ++abl_probe_index; // 0...
  4506. #endif
  4507. #if IS_KINEMATIC
  4508. // Avoid probing outside the round or hexagonal area
  4509. if (!position_is_reachable_by_probe(xProbe, yProbe)) continue;
  4510. #endif
  4511. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, raise_after, verbose_level);
  4512. if (isnan(measured_z)) {
  4513. set_bed_leveling_enabled(abl_should_enable);
  4514. break;
  4515. }
  4516. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4517. mean += measured_z;
  4518. eqnBVector[abl_probe_index] = measured_z;
  4519. eqnAMatrix[abl_probe_index + 0 * abl_points] = xProbe;
  4520. eqnAMatrix[abl_probe_index + 1 * abl_points] = yProbe;
  4521. eqnAMatrix[abl_probe_index + 2 * abl_points] = 1;
  4522. incremental_LSF(&lsf_results, xProbe, yProbe, measured_z);
  4523. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4524. z_values[xCount][yCount] = measured_z + zoffset;
  4525. #endif
  4526. abl_should_enable = false;
  4527. idle();
  4528. } // inner
  4529. } // outer
  4530. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  4531. // Probe at 3 arbitrary points
  4532. for (uint8_t i = 0; i < 3; ++i) {
  4533. // Retain the last probe position
  4534. xProbe = points[i].x;
  4535. yProbe = points[i].y;
  4536. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, raise_after, verbose_level);
  4537. if (isnan(measured_z)) {
  4538. set_bed_leveling_enabled(abl_should_enable);
  4539. break;
  4540. }
  4541. points[i].z = measured_z;
  4542. }
  4543. if (!dryrun && !isnan(measured_z)) {
  4544. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  4545. if (planeNormal.z < 0) {
  4546. planeNormal.x *= -1;
  4547. planeNormal.y *= -1;
  4548. planeNormal.z *= -1;
  4549. }
  4550. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  4551. // Can't re-enable (on error) until the new grid is written
  4552. abl_should_enable = false;
  4553. }
  4554. #endif // AUTO_BED_LEVELING_3POINT
  4555. // Stow the probe. No raise for FIX_MOUNTED_PROBE.
  4556. if (STOW_PROBE()) {
  4557. set_bed_leveling_enabled(abl_should_enable);
  4558. measured_z = NAN;
  4559. }
  4560. }
  4561. #endif // !PROBE_MANUALLY
  4562. //
  4563. // G29 Finishing Code
  4564. //
  4565. // Unless this is a dry run, auto bed leveling will
  4566. // definitely be enabled after this point.
  4567. //
  4568. // If code above wants to continue leveling, it should
  4569. // return or loop before this point.
  4570. //
  4571. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4572. if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position);
  4573. #endif
  4574. #if ENABLED(PROBE_MANUALLY)
  4575. g29_in_progress = false;
  4576. #if ENABLED(LCD_BED_LEVELING)
  4577. lcd_wait_for_move = false;
  4578. #endif
  4579. #endif
  4580. // Calculate leveling, print reports, correct the position
  4581. if (!isnan(measured_z)) {
  4582. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4583. if (!dryrun) extrapolate_unprobed_bed_level();
  4584. print_bilinear_leveling_grid();
  4585. refresh_bed_level();
  4586. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  4587. print_bilinear_leveling_grid_virt();
  4588. #endif
  4589. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  4590. // For LINEAR leveling calculate matrix, print reports, correct the position
  4591. /**
  4592. * solve the plane equation ax + by + d = z
  4593. * A is the matrix with rows [x y 1] for all the probed points
  4594. * B is the vector of the Z positions
  4595. * the normal vector to the plane is formed by the coefficients of the
  4596. * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  4597. * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4598. */
  4599. float plane_equation_coefficients[3];
  4600. finish_incremental_LSF(&lsf_results);
  4601. plane_equation_coefficients[0] = -lsf_results.A; // We should be able to eliminate the '-' on these three lines and down below
  4602. plane_equation_coefficients[1] = -lsf_results.B; // but that is not yet tested.
  4603. plane_equation_coefficients[2] = -lsf_results.D;
  4604. mean /= abl_points;
  4605. if (verbose_level) {
  4606. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4607. SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8);
  4608. SERIAL_PROTOCOLPGM(" b: ");
  4609. SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8);
  4610. SERIAL_PROTOCOLPGM(" d: ");
  4611. SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8);
  4612. SERIAL_EOL();
  4613. if (verbose_level > 2) {
  4614. SERIAL_PROTOCOLPGM("Mean of sampled points: ");
  4615. SERIAL_PROTOCOL_F(mean, 8);
  4616. SERIAL_EOL();
  4617. }
  4618. }
  4619. // Create the matrix but don't correct the position yet
  4620. if (!dryrun)
  4621. planner.bed_level_matrix = matrix_3x3::create_look_at(
  4622. vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1) // We can eliminate the '-' here and up above
  4623. );
  4624. // Show the Topography map if enabled
  4625. if (do_topography_map) {
  4626. SERIAL_PROTOCOLLNPGM("\nBed Height Topography:\n"
  4627. " +--- BACK --+\n"
  4628. " | |\n"
  4629. " L | (+) | R\n"
  4630. " E | | I\n"
  4631. " F | (-) N (+) | G\n"
  4632. " T | | H\n"
  4633. " | (-) | T\n"
  4634. " | |\n"
  4635. " O-- FRONT --+\n"
  4636. " (0,0)");
  4637. float min_diff = 999;
  4638. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4639. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4640. int ind = indexIntoAB[xx][yy];
  4641. float diff = eqnBVector[ind] - mean,
  4642. x_tmp = eqnAMatrix[ind + 0 * abl_points],
  4643. y_tmp = eqnAMatrix[ind + 1 * abl_points],
  4644. z_tmp = 0;
  4645. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4646. NOMORE(min_diff, eqnBVector[ind] - z_tmp);
  4647. if (diff >= 0.0)
  4648. SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment
  4649. else
  4650. SERIAL_PROTOCOLCHAR(' ');
  4651. SERIAL_PROTOCOL_F(diff, 5);
  4652. } // xx
  4653. SERIAL_EOL();
  4654. } // yy
  4655. SERIAL_EOL();
  4656. if (verbose_level > 3) {
  4657. SERIAL_PROTOCOLLNPGM("\nCorrected Bed Height vs. Bed Topology:");
  4658. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4659. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4660. int ind = indexIntoAB[xx][yy];
  4661. float x_tmp = eqnAMatrix[ind + 0 * abl_points],
  4662. y_tmp = eqnAMatrix[ind + 1 * abl_points],
  4663. z_tmp = 0;
  4664. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4665. float diff = eqnBVector[ind] - z_tmp - min_diff;
  4666. if (diff >= 0.0)
  4667. SERIAL_PROTOCOLPGM(" +");
  4668. // Include + for column alignment
  4669. else
  4670. SERIAL_PROTOCOLCHAR(' ');
  4671. SERIAL_PROTOCOL_F(diff, 5);
  4672. } // xx
  4673. SERIAL_EOL();
  4674. } // yy
  4675. SERIAL_EOL();
  4676. }
  4677. } //do_topography_map
  4678. #endif // AUTO_BED_LEVELING_LINEAR
  4679. #if ABL_PLANAR
  4680. // For LINEAR and 3POINT leveling correct the current position
  4681. if (verbose_level > 0)
  4682. planner.bed_level_matrix.debug(PSTR("\n\nBed Level Correction Matrix:"));
  4683. if (!dryrun) {
  4684. //
  4685. // Correct the current XYZ position based on the tilted plane.
  4686. //
  4687. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4688. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 uncorrected XYZ", current_position);
  4689. #endif
  4690. float converted[XYZ];
  4691. COPY(converted, current_position);
  4692. planner.leveling_active = true;
  4693. planner.unapply_leveling(converted); // use conversion machinery
  4694. planner.leveling_active = false;
  4695. // Use the last measured distance to the bed, if possible
  4696. if ( NEAR(current_position[X_AXIS], xProbe - (X_PROBE_OFFSET_FROM_EXTRUDER))
  4697. && NEAR(current_position[Y_AXIS], yProbe - (Y_PROBE_OFFSET_FROM_EXTRUDER))
  4698. ) {
  4699. const float simple_z = current_position[Z_AXIS] - measured_z;
  4700. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4701. if (DEBUGGING(LEVELING)) {
  4702. SERIAL_ECHOPAIR("Z from Probe:", simple_z);
  4703. SERIAL_ECHOPAIR(" Matrix:", converted[Z_AXIS]);
  4704. SERIAL_ECHOLNPAIR(" Discrepancy:", simple_z - converted[Z_AXIS]);
  4705. }
  4706. #endif
  4707. converted[Z_AXIS] = simple_z;
  4708. }
  4709. // The rotated XY and corrected Z are now current_position
  4710. COPY(current_position, converted);
  4711. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4712. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 corrected XYZ", current_position);
  4713. #endif
  4714. }
  4715. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4716. if (!dryrun) {
  4717. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4718. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("G29 uncorrected Z:", current_position[Z_AXIS]);
  4719. #endif
  4720. // Unapply the offset because it is going to be immediately applied
  4721. // and cause compensation movement in Z
  4722. current_position[Z_AXIS] -= bilinear_z_offset(current_position);
  4723. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4724. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR(" corrected Z:", current_position[Z_AXIS]);
  4725. #endif
  4726. }
  4727. #endif // ABL_PLANAR
  4728. #ifdef Z_PROBE_END_SCRIPT
  4729. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4730. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
  4731. #endif
  4732. planner.synchronize();
  4733. enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT));
  4734. #endif
  4735. // Auto Bed Leveling is complete! Enable if possible.
  4736. planner.leveling_active = dryrun ? abl_should_enable : true;
  4737. } // !isnan(measured_z)
  4738. // Restore state after probing
  4739. if (!faux) clean_up_after_endstop_or_probe_move();
  4740. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4741. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< G29");
  4742. #endif
  4743. KEEPALIVE_STATE(IN_HANDLER);
  4744. if (planner.leveling_active)
  4745. SYNC_PLAN_POSITION_KINEMATIC();
  4746. #if HAS_BED_PROBE && defined(Z_AFTER_PROBING)
  4747. move_z_after_probing();
  4748. #endif
  4749. report_current_position();
  4750. }
  4751. #endif // OLDSCHOOL_ABL
  4752. #if HAS_BED_PROBE
  4753. /**
  4754. * G30: Do a single Z probe at the current XY
  4755. *
  4756. * Parameters:
  4757. *
  4758. * X Probe X position (default current X)
  4759. * Y Probe Y position (default current Y)
  4760. * E Engage the probe for each probe (default 1)
  4761. */
  4762. inline void gcode_G30() {
  4763. const float xpos = parser.linearval('X', current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER),
  4764. ypos = parser.linearval('Y', current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER);
  4765. if (!position_is_reachable_by_probe(xpos, ypos)) return;
  4766. // Disable leveling so the planner won't mess with us
  4767. #if HAS_LEVELING
  4768. set_bed_leveling_enabled(false);
  4769. #endif
  4770. setup_for_endstop_or_probe_move();
  4771. const ProbePtRaise raise_after = parser.boolval('E', true) ? PROBE_PT_STOW : PROBE_PT_NONE;
  4772. const float measured_z = probe_pt(xpos, ypos, raise_after, parser.intval('V', 1));
  4773. if (!isnan(measured_z)) {
  4774. SERIAL_PROTOCOLPAIR_F("Bed X: ", xpos);
  4775. SERIAL_PROTOCOLPAIR_F(" Y: ", ypos);
  4776. SERIAL_PROTOCOLLNPAIR_F(" Z: ", measured_z);
  4777. }
  4778. clean_up_after_endstop_or_probe_move();
  4779. #ifdef Z_AFTER_PROBING
  4780. if (raise_after == PROBE_PT_STOW) move_z_after_probing();
  4781. #endif
  4782. report_current_position();
  4783. }
  4784. #if ENABLED(Z_PROBE_SLED)
  4785. /**
  4786. * G31: Deploy the Z probe
  4787. */
  4788. inline void gcode_G31() { DEPLOY_PROBE(); }
  4789. /**
  4790. * G32: Stow the Z probe
  4791. */
  4792. inline void gcode_G32() { STOW_PROBE(); }
  4793. #endif // Z_PROBE_SLED
  4794. #endif // HAS_BED_PROBE
  4795. #if ENABLED(DELTA_AUTO_CALIBRATION)
  4796. constexpr uint8_t _7P_STEP = 1, // 7-point step - to change number of calibration points
  4797. _4P_STEP = _7P_STEP * 2, // 4-point step
  4798. NPP = _7P_STEP * 6; // number of calibration points on the radius
  4799. enum CalEnum : char { // the 7 main calibration points - add definitions if needed
  4800. CEN = 0,
  4801. __A = 1,
  4802. _AB = __A + _7P_STEP,
  4803. __B = _AB + _7P_STEP,
  4804. _BC = __B + _7P_STEP,
  4805. __C = _BC + _7P_STEP,
  4806. _CA = __C + _7P_STEP,
  4807. };
  4808. #define LOOP_CAL_PT(VAR, S, N) for (uint8_t VAR=S; VAR<=NPP; VAR+=N)
  4809. #define F_LOOP_CAL_PT(VAR, S, N) for (float VAR=S; VAR<NPP+0.9999; VAR+=N)
  4810. #define I_LOOP_CAL_PT(VAR, S, N) for (float VAR=S; VAR>CEN+0.9999; VAR-=N)
  4811. #define LOOP_CAL_ALL(VAR) LOOP_CAL_PT(VAR, CEN, 1)
  4812. #define LOOP_CAL_RAD(VAR) LOOP_CAL_PT(VAR, __A, _7P_STEP)
  4813. #define LOOP_CAL_ACT(VAR, _4P, _OP) LOOP_CAL_PT(VAR, _OP ? _AB : __A, _4P ? _4P_STEP : _7P_STEP)
  4814. #if HOTENDS > 1
  4815. const uint8_t old_tool_index = active_extruder;
  4816. #define AC_CLEANUP() ac_cleanup(old_tool_index)
  4817. #else
  4818. #define AC_CLEANUP() ac_cleanup()
  4819. #endif
  4820. float lcd_probe_pt(const float &rx, const float &ry);
  4821. void ac_home() {
  4822. endstops.enable(true);
  4823. home_delta();
  4824. endstops.not_homing();
  4825. }
  4826. void ac_setup(const bool reset_bed) {
  4827. #if HOTENDS > 1
  4828. tool_change(0, 0, true);
  4829. #endif
  4830. planner.synchronize();
  4831. setup_for_endstop_or_probe_move();
  4832. #if HAS_LEVELING
  4833. if (reset_bed) reset_bed_level(); // After full calibration bed-level data is no longer valid
  4834. #endif
  4835. }
  4836. void ac_cleanup(
  4837. #if HOTENDS > 1
  4838. const uint8_t old_tool_index
  4839. #endif
  4840. ) {
  4841. #if ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  4842. do_blocking_move_to_z(delta_clip_start_height);
  4843. #endif
  4844. #if HAS_BED_PROBE
  4845. STOW_PROBE();
  4846. #endif
  4847. clean_up_after_endstop_or_probe_move();
  4848. #if HOTENDS > 1
  4849. tool_change(old_tool_index, 0, true);
  4850. #endif
  4851. }
  4852. void print_signed_float(const char * const prefix, const float &f) {
  4853. SERIAL_PROTOCOLPGM(" ");
  4854. serialprintPGM(prefix);
  4855. SERIAL_PROTOCOLCHAR(':');
  4856. if (f >= 0) SERIAL_CHAR('+');
  4857. SERIAL_PROTOCOL_F(f, 2);
  4858. }
  4859. /**
  4860. * - Print the delta settings
  4861. */
  4862. static void print_calibration_settings(const bool end_stops, const bool tower_angles) {
  4863. SERIAL_PROTOCOLPAIR(".Height:", delta_height);
  4864. if (end_stops) {
  4865. print_signed_float(PSTR("Ex"), delta_endstop_adj[A_AXIS]);
  4866. print_signed_float(PSTR("Ey"), delta_endstop_adj[B_AXIS]);
  4867. print_signed_float(PSTR("Ez"), delta_endstop_adj[C_AXIS]);
  4868. }
  4869. if (end_stops && tower_angles) {
  4870. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  4871. SERIAL_EOL();
  4872. SERIAL_CHAR('.');
  4873. SERIAL_PROTOCOL_SP(13);
  4874. }
  4875. if (tower_angles) {
  4876. print_signed_float(PSTR("Tx"), delta_tower_angle_trim[A_AXIS]);
  4877. print_signed_float(PSTR("Ty"), delta_tower_angle_trim[B_AXIS]);
  4878. print_signed_float(PSTR("Tz"), delta_tower_angle_trim[C_AXIS]);
  4879. }
  4880. if ((!end_stops && tower_angles) || (end_stops && !tower_angles)) { // XOR
  4881. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  4882. }
  4883. SERIAL_EOL();
  4884. }
  4885. /**
  4886. * - Print the probe results
  4887. */
  4888. static void print_calibration_results(const float z_pt[NPP + 1], const bool tower_points, const bool opposite_points) {
  4889. SERIAL_PROTOCOLPGM(". ");
  4890. print_signed_float(PSTR("c"), z_pt[CEN]);
  4891. if (tower_points) {
  4892. print_signed_float(PSTR(" x"), z_pt[__A]);
  4893. print_signed_float(PSTR(" y"), z_pt[__B]);
  4894. print_signed_float(PSTR(" z"), z_pt[__C]);
  4895. }
  4896. if (tower_points && opposite_points) {
  4897. SERIAL_EOL();
  4898. SERIAL_CHAR('.');
  4899. SERIAL_PROTOCOL_SP(13);
  4900. }
  4901. if (opposite_points) {
  4902. print_signed_float(PSTR("yz"), z_pt[_BC]);
  4903. print_signed_float(PSTR("zx"), z_pt[_CA]);
  4904. print_signed_float(PSTR("xy"), z_pt[_AB]);
  4905. }
  4906. SERIAL_EOL();
  4907. }
  4908. /**
  4909. * - Calculate the standard deviation from the zero plane
  4910. */
  4911. static float std_dev_points(float z_pt[NPP + 1], const bool _0p_cal, const bool _1p_cal, const bool _4p_cal, const bool _4p_opp) {
  4912. if (!_0p_cal) {
  4913. float S2 = sq(z_pt[CEN]);
  4914. int16_t N = 1;
  4915. if (!_1p_cal) { // std dev from zero plane
  4916. LOOP_CAL_ACT(rad, _4p_cal, _4p_opp) {
  4917. S2 += sq(z_pt[rad]);
  4918. N++;
  4919. }
  4920. return LROUND(SQRT(S2 / N) * 1000.0) / 1000.0 + 0.00001;
  4921. }
  4922. }
  4923. return 0.00001;
  4924. }
  4925. /**
  4926. * - Probe a point
  4927. */
  4928. static float calibration_probe(const float &nx, const float &ny, const bool stow) {
  4929. #if HAS_BED_PROBE
  4930. return probe_pt(nx, ny, stow ? PROBE_PT_STOW : PROBE_PT_RAISE, 0, false);
  4931. #else
  4932. UNUSED(stow);
  4933. return lcd_probe_pt(nx, ny);
  4934. #endif
  4935. }
  4936. /**
  4937. * - Probe a grid
  4938. */
  4939. static bool probe_calibration_points(float z_pt[NPP + 1], const int8_t probe_points, const bool towers_set, const bool stow_after_each) {
  4940. const bool _0p_calibration = probe_points == 0,
  4941. _1p_calibration = probe_points == 1 || probe_points == -1,
  4942. _4p_calibration = probe_points == 2,
  4943. _4p_opposite_points = _4p_calibration && !towers_set,
  4944. _7p_calibration = probe_points >= 3,
  4945. _7p_no_intermediates = probe_points == 3,
  4946. _7p_1_intermediates = probe_points == 4,
  4947. _7p_2_intermediates = probe_points == 5,
  4948. _7p_4_intermediates = probe_points == 6,
  4949. _7p_6_intermediates = probe_points == 7,
  4950. _7p_8_intermediates = probe_points == 8,
  4951. _7p_11_intermediates = probe_points == 9,
  4952. _7p_14_intermediates = probe_points == 10,
  4953. _7p_intermed_points = probe_points >= 4,
  4954. _7p_6_center = probe_points >= 5 && probe_points <= 7,
  4955. _7p_9_center = probe_points >= 8;
  4956. LOOP_CAL_ALL(rad) z_pt[rad] = 0.0;
  4957. if (!_0p_calibration) {
  4958. if (!_7p_no_intermediates && !_7p_4_intermediates && !_7p_11_intermediates) { // probe the center
  4959. z_pt[CEN] += calibration_probe(0, 0, stow_after_each);
  4960. if (isnan(z_pt[CEN])) return false;
  4961. }
  4962. if (_7p_calibration) { // probe extra center points
  4963. const float start = _7p_9_center ? float(_CA) + _7P_STEP / 3.0 : _7p_6_center ? float(_CA) : float(__C),
  4964. steps = _7p_9_center ? _4P_STEP / 3.0 : _7p_6_center ? _7P_STEP : _4P_STEP;
  4965. I_LOOP_CAL_PT(rad, start, steps) {
  4966. const float a = RADIANS(210 + (360 / NPP) * (rad - 1)),
  4967. r = delta_calibration_radius * 0.1;
  4968. z_pt[CEN] += calibration_probe(cos(a) * r, sin(a) * r, stow_after_each);
  4969. if (isnan(z_pt[CEN])) return false;
  4970. }
  4971. z_pt[CEN] /= float(_7p_2_intermediates ? 7 : probe_points);
  4972. }
  4973. if (!_1p_calibration) { // probe the radius
  4974. const CalEnum start = _4p_opposite_points ? _AB : __A;
  4975. const float steps = _7p_14_intermediates ? _7P_STEP / 15.0 : // 15r * 6 + 10c = 100
  4976. _7p_11_intermediates ? _7P_STEP / 12.0 : // 12r * 6 + 9c = 81
  4977. _7p_8_intermediates ? _7P_STEP / 9.0 : // 9r * 6 + 10c = 64
  4978. _7p_6_intermediates ? _7P_STEP / 7.0 : // 7r * 6 + 7c = 49
  4979. _7p_4_intermediates ? _7P_STEP / 5.0 : // 5r * 6 + 6c = 36
  4980. _7p_2_intermediates ? _7P_STEP / 3.0 : // 3r * 6 + 7c = 25
  4981. _7p_1_intermediates ? _7P_STEP / 2.0 : // 2r * 6 + 4c = 16
  4982. _7p_no_intermediates ? _7P_STEP : // 1r * 6 + 3c = 9
  4983. _4P_STEP; // .5r * 6 + 1c = 4
  4984. bool zig_zag = true;
  4985. F_LOOP_CAL_PT(rad, start, _7p_9_center ? steps * 3 : steps) {
  4986. const int8_t offset = _7p_9_center ? 2 : 0;
  4987. for (int8_t circle = 0; circle <= offset; circle++) {
  4988. const float a = RADIANS(210 + (360 / NPP) * (rad - 1)),
  4989. r = delta_calibration_radius * (1 - 0.1 * (zig_zag ? offset - circle : circle)),
  4990. interpol = fmod(rad, 1);
  4991. const float z_temp = calibration_probe(cos(a) * r, sin(a) * r, stow_after_each);
  4992. if (isnan(z_temp)) return false;
  4993. // split probe point to neighbouring calibration points
  4994. z_pt[uint8_t(LROUND(rad - interpol + NPP - 1)) % NPP + 1] += z_temp * sq(cos(RADIANS(interpol * 90)));
  4995. z_pt[uint8_t(LROUND(rad - interpol)) % NPP + 1] += z_temp * sq(sin(RADIANS(interpol * 90)));
  4996. }
  4997. zig_zag = !zig_zag;
  4998. }
  4999. if (_7p_intermed_points)
  5000. LOOP_CAL_RAD(rad)
  5001. z_pt[rad] /= _7P_STEP / steps;
  5002. do_blocking_move_to_xy(0.0, 0.0);
  5003. }
  5004. }
  5005. return true;
  5006. }
  5007. /**
  5008. * kinematics routines and auto tune matrix scaling parameters:
  5009. * see https://github.com/LVD-AC/Marlin-AC/tree/1.1.x-AC/documentation for
  5010. * - formulae for approximative forward kinematics in the end-stop displacement matrix
  5011. * - definition of the matrix scaling parameters
  5012. */
  5013. static void reverse_kinematics_probe_points(float z_pt[NPP + 1], float mm_at_pt_axis[NPP + 1][ABC]) {
  5014. float pos[XYZ] = { 0.0 };
  5015. LOOP_CAL_ALL(rad) {
  5016. const float a = RADIANS(210 + (360 / NPP) * (rad - 1)),
  5017. r = (rad == CEN ? 0.0 : delta_calibration_radius);
  5018. pos[X_AXIS] = cos(a) * r;
  5019. pos[Y_AXIS] = sin(a) * r;
  5020. pos[Z_AXIS] = z_pt[rad];
  5021. inverse_kinematics(pos);
  5022. LOOP_XYZ(axis) mm_at_pt_axis[rad][axis] = delta[axis];
  5023. }
  5024. }
  5025. static void forward_kinematics_probe_points(float mm_at_pt_axis[NPP + 1][ABC], float z_pt[NPP + 1]) {
  5026. const float r_quot = delta_calibration_radius / delta_radius;
  5027. #define ZPP(N,I,A) ((1 / 3.0 + r_quot * (N) / 3.0 ) * mm_at_pt_axis[I][A])
  5028. #define Z00(I, A) ZPP( 0, I, A)
  5029. #define Zp1(I, A) ZPP(+1, I, A)
  5030. #define Zm1(I, A) ZPP(-1, I, A)
  5031. #define Zp2(I, A) ZPP(+2, I, A)
  5032. #define Zm2(I, A) ZPP(-2, I, A)
  5033. z_pt[CEN] = Z00(CEN, A_AXIS) + Z00(CEN, B_AXIS) + Z00(CEN, C_AXIS);
  5034. z_pt[__A] = Zp2(__A, A_AXIS) + Zm1(__A, B_AXIS) + Zm1(__A, C_AXIS);
  5035. z_pt[__B] = Zm1(__B, A_AXIS) + Zp2(__B, B_AXIS) + Zm1(__B, C_AXIS);
  5036. z_pt[__C] = Zm1(__C, A_AXIS) + Zm1(__C, B_AXIS) + Zp2(__C, C_AXIS);
  5037. z_pt[_BC] = Zm2(_BC, A_AXIS) + Zp1(_BC, B_AXIS) + Zp1(_BC, C_AXIS);
  5038. z_pt[_CA] = Zp1(_CA, A_AXIS) + Zm2(_CA, B_AXIS) + Zp1(_CA, C_AXIS);
  5039. z_pt[_AB] = Zp1(_AB, A_AXIS) + Zp1(_AB, B_AXIS) + Zm2(_AB, C_AXIS);
  5040. }
  5041. static void calc_kinematics_diff_probe_points(float z_pt[NPP + 1], float delta_e[ABC], float delta_r, float delta_t[ABC]) {
  5042. const float z_center = z_pt[CEN];
  5043. float diff_mm_at_pt_axis[NPP + 1][ABC],
  5044. new_mm_at_pt_axis[NPP + 1][ABC];
  5045. reverse_kinematics_probe_points(z_pt, diff_mm_at_pt_axis);
  5046. delta_radius += delta_r;
  5047. LOOP_XYZ(axis) delta_tower_angle_trim[axis] += delta_t[axis];
  5048. recalc_delta_settings();
  5049. reverse_kinematics_probe_points(z_pt, new_mm_at_pt_axis);
  5050. LOOP_XYZ(axis) LOOP_CAL_ALL(rad) diff_mm_at_pt_axis[rad][axis] -= new_mm_at_pt_axis[rad][axis] + delta_e[axis];
  5051. forward_kinematics_probe_points(diff_mm_at_pt_axis, z_pt);
  5052. LOOP_CAL_RAD(rad) z_pt[rad] -= z_pt[CEN] - z_center;
  5053. z_pt[CEN] = z_center;
  5054. delta_radius -= delta_r;
  5055. LOOP_XYZ(axis) delta_tower_angle_trim[axis] -= delta_t[axis];
  5056. recalc_delta_settings();
  5057. }
  5058. static float auto_tune_h() {
  5059. const float r_quot = delta_calibration_radius / delta_radius;
  5060. float h_fac = 0.0;
  5061. h_fac = r_quot / (2.0 / 3.0);
  5062. h_fac = 1.0f / h_fac; // (2/3)/CR
  5063. return h_fac;
  5064. }
  5065. static float auto_tune_r() {
  5066. const float diff = 0.01;
  5067. float r_fac = 0.0,
  5068. z_pt[NPP + 1] = { 0.0 },
  5069. delta_e[ABC] = {0.0},
  5070. delta_r = {0.0},
  5071. delta_t[ABC] = {0.0};
  5072. delta_r = diff;
  5073. calc_kinematics_diff_probe_points(z_pt, delta_e, delta_r, delta_t);
  5074. r_fac = -(z_pt[__A] + z_pt[__B] + z_pt[__C] + z_pt[_BC] + z_pt[_CA] + z_pt[_AB]) / 6.0;
  5075. r_fac = diff / r_fac / 3.0; // 1/(3*delta_Z)
  5076. return r_fac;
  5077. }
  5078. static float auto_tune_a() {
  5079. const float diff = 0.01;
  5080. float a_fac = 0.0,
  5081. z_pt[NPP + 1] = { 0.0 },
  5082. delta_e[ABC] = {0.0},
  5083. delta_r = {0.0},
  5084. delta_t[ABC] = {0.0};
  5085. LOOP_XYZ(axis) {
  5086. LOOP_XYZ(axis_2) delta_t[axis_2] = 0.0;
  5087. delta_t[axis] = diff;
  5088. calc_kinematics_diff_probe_points(z_pt, delta_e, delta_r, delta_t);
  5089. a_fac += z_pt[uint8_t((axis * _4P_STEP) - _7P_STEP + NPP) % NPP + 1] / 6.0;
  5090. a_fac -= z_pt[uint8_t((axis * _4P_STEP) + 1 + _7P_STEP)] / 6.0;
  5091. }
  5092. a_fac = diff / a_fac / 3.0; // 1/(3*delta_Z)
  5093. return a_fac;
  5094. }
  5095. /**
  5096. * G33 - Delta '1-4-7-point' Auto-Calibration
  5097. * Calibrate height, z_offset, endstops, delta radius, and tower angles.
  5098. *
  5099. * Parameters:
  5100. *
  5101. * Pn Number of probe points:
  5102. * P0 Normalizes calibration.
  5103. * P1 Calibrates height only with center probe.
  5104. * P2 Probe center and towers. Calibrate height, endstops and delta radius.
  5105. * P3 Probe all positions: center, towers and opposite towers. Calibrate all.
  5106. * P4-P10 Probe all positions at different intermediate locations and average them.
  5107. *
  5108. * T Don't calibrate tower angle corrections
  5109. *
  5110. * Cn.nn Calibration precision; when omitted calibrates to maximum precision
  5111. *
  5112. * Fn Force to run at least n iterations and take the best result
  5113. *
  5114. * Vn Verbose level:
  5115. * V0 Dry-run mode. Report settings and probe results. No calibration.
  5116. * V1 Report start and end settings only
  5117. * V2 Report settings at each iteration
  5118. * V3 Report settings and probe results
  5119. *
  5120. * E Engage the probe for each point
  5121. */
  5122. inline void gcode_G33() {
  5123. const int8_t probe_points = parser.intval('P', DELTA_CALIBRATION_DEFAULT_POINTS);
  5124. if (!WITHIN(probe_points, 0, 10)) {
  5125. SERIAL_PROTOCOLLNPGM("?(P)oints is implausible (0-10).");
  5126. return;
  5127. }
  5128. const bool towers_set = !parser.seen('T');
  5129. const float calibration_precision = parser.floatval('C', 0.0);
  5130. if (calibration_precision < 0) {
  5131. SERIAL_PROTOCOLLNPGM("?(C)alibration precision is implausible (>=0).");
  5132. return;
  5133. }
  5134. const int8_t force_iterations = parser.intval('F', 0);
  5135. if (!WITHIN(force_iterations, 0, 30)) {
  5136. SERIAL_PROTOCOLLNPGM("?(F)orce iteration is implausible (0-30).");
  5137. return;
  5138. }
  5139. const int8_t verbose_level = parser.byteval('V', 1);
  5140. if (!WITHIN(verbose_level, 0, 3)) {
  5141. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-3).");
  5142. return;
  5143. }
  5144. const bool stow_after_each = parser.seen('E');
  5145. const bool _0p_calibration = probe_points == 0,
  5146. _1p_calibration = probe_points == 1 || probe_points == -1,
  5147. _4p_calibration = probe_points == 2,
  5148. _4p_opposite_points = _4p_calibration && !towers_set,
  5149. _7p_9_center = probe_points >= 8,
  5150. _tower_results = (_4p_calibration && towers_set) || probe_points >= 3,
  5151. _opposite_results = (_4p_calibration && !towers_set) || probe_points >= 3,
  5152. _endstop_results = probe_points != 1 && probe_points != -1 && probe_points != 0,
  5153. _angle_results = probe_points >= 3 && towers_set;
  5154. static const char save_message[] PROGMEM = "Save with M500 and/or copy to Configuration.h";
  5155. int8_t iterations = 0;
  5156. float test_precision,
  5157. zero_std_dev = (verbose_level ? 999.0 : 0.0), // 0.0 in dry-run mode : forced end
  5158. zero_std_dev_min = zero_std_dev,
  5159. zero_std_dev_old = zero_std_dev,
  5160. h_factor,
  5161. r_factor,
  5162. a_factor,
  5163. e_old[ABC] = {
  5164. delta_endstop_adj[A_AXIS],
  5165. delta_endstop_adj[B_AXIS],
  5166. delta_endstop_adj[C_AXIS]
  5167. },
  5168. r_old = delta_radius,
  5169. h_old = delta_height,
  5170. a_old[ABC] = {
  5171. delta_tower_angle_trim[A_AXIS],
  5172. delta_tower_angle_trim[B_AXIS],
  5173. delta_tower_angle_trim[C_AXIS]
  5174. };
  5175. SERIAL_PROTOCOLLNPGM("G33 Auto Calibrate");
  5176. if (!_1p_calibration && !_0p_calibration) { // test if the outer radius is reachable
  5177. LOOP_CAL_RAD(axis) {
  5178. const float a = RADIANS(210 + (360 / NPP) * (axis - 1)),
  5179. r = delta_calibration_radius;
  5180. if (!position_is_reachable(cos(a) * r, sin(a) * r)) {
  5181. SERIAL_PROTOCOLLNPGM("?(M665 B)ed radius is implausible.");
  5182. return;
  5183. }
  5184. }
  5185. }
  5186. // Report settings
  5187. const char *checkingac = PSTR("Checking... AC");
  5188. serialprintPGM(checkingac);
  5189. if (verbose_level == 0) SERIAL_PROTOCOLPGM(" (DRY-RUN)");
  5190. SERIAL_EOL();
  5191. lcd_setstatusPGM(checkingac);
  5192. print_calibration_settings(_endstop_results, _angle_results);
  5193. ac_setup(!_0p_calibration && !_1p_calibration);
  5194. if (!_0p_calibration) ac_home();
  5195. do { // start iterations
  5196. float z_at_pt[NPP + 1] = { 0.0 };
  5197. test_precision = zero_std_dev_old != 999.0 ? (zero_std_dev + zero_std_dev_old) / 2 : zero_std_dev;
  5198. iterations++;
  5199. // Probe the points
  5200. zero_std_dev_old = zero_std_dev;
  5201. if (!probe_calibration_points(z_at_pt, probe_points, towers_set, stow_after_each)) {
  5202. SERIAL_PROTOCOLLNPGM("Correct delta settings with M665 and M666");
  5203. return AC_CLEANUP();
  5204. }
  5205. zero_std_dev = std_dev_points(z_at_pt, _0p_calibration, _1p_calibration, _4p_calibration, _4p_opposite_points);
  5206. // Solve matrices
  5207. if ((zero_std_dev < test_precision || iterations <= force_iterations) && zero_std_dev > calibration_precision) {
  5208. #if !HAS_BED_PROBE
  5209. test_precision = 0.00; // forced end
  5210. #endif
  5211. if (zero_std_dev < zero_std_dev_min) {
  5212. // set roll-back point
  5213. COPY(e_old, delta_endstop_adj);
  5214. r_old = delta_radius;
  5215. h_old = delta_height;
  5216. COPY(a_old, delta_tower_angle_trim);
  5217. }
  5218. float e_delta[ABC] = { 0.0 },
  5219. r_delta = 0.0,
  5220. t_delta[ABC] = { 0.0 };
  5221. /**
  5222. * convergence matrices:
  5223. * see https://github.com/LVD-AC/Marlin-AC/tree/1.1.x-AC/documentation for
  5224. * - definition of the matrix scaling parameters
  5225. * - matrices for 4 and 7 point calibration
  5226. */
  5227. #define ZP(N,I) ((N) * z_at_pt[I] / 4.0) // 4.0 = divider to normalize to integers
  5228. #define Z12(I) ZP(12, I)
  5229. #define Z4(I) ZP(4, I)
  5230. #define Z2(I) ZP(2, I)
  5231. #define Z1(I) ZP(1, I)
  5232. #define Z0(I) ZP(0, I)
  5233. // calculate factors
  5234. const float cr_old = delta_calibration_radius;
  5235. if (_7p_9_center) delta_calibration_radius *= 0.9;
  5236. h_factor = auto_tune_h();
  5237. r_factor = auto_tune_r();
  5238. a_factor = auto_tune_a();
  5239. delta_calibration_radius = cr_old;
  5240. switch (probe_points) {
  5241. case 0:
  5242. test_precision = 0.00; // forced end
  5243. break;
  5244. case 1:
  5245. test_precision = 0.00; // forced end
  5246. LOOP_XYZ(axis) e_delta[axis] = +Z4(CEN);
  5247. break;
  5248. case 2:
  5249. if (towers_set) { // see 4 point calibration (towers) matrix
  5250. e_delta[A_AXIS] = (+Z4(__A) -Z2(__B) -Z2(__C)) * h_factor +Z4(CEN);
  5251. e_delta[B_AXIS] = (-Z2(__A) +Z4(__B) -Z2(__C)) * h_factor +Z4(CEN);
  5252. e_delta[C_AXIS] = (-Z2(__A) -Z2(__B) +Z4(__C)) * h_factor +Z4(CEN);
  5253. r_delta = (+Z4(__A) +Z4(__B) +Z4(__C) -Z12(CEN)) * r_factor;
  5254. }
  5255. else { // see 4 point calibration (opposites) matrix
  5256. e_delta[A_AXIS] = (-Z4(_BC) +Z2(_CA) +Z2(_AB)) * h_factor +Z4(CEN);
  5257. e_delta[B_AXIS] = (+Z2(_BC) -Z4(_CA) +Z2(_AB)) * h_factor +Z4(CEN);
  5258. e_delta[C_AXIS] = (+Z2(_BC) +Z2(_CA) -Z4(_AB)) * h_factor +Z4(CEN);
  5259. r_delta = (+Z4(_BC) +Z4(_CA) +Z4(_AB) -Z12(CEN)) * r_factor;
  5260. }
  5261. break;
  5262. default: // see 7 point calibration (towers & opposites) matrix
  5263. e_delta[A_AXIS] = (+Z2(__A) -Z1(__B) -Z1(__C) -Z2(_BC) +Z1(_CA) +Z1(_AB)) * h_factor +Z4(CEN);
  5264. e_delta[B_AXIS] = (-Z1(__A) +Z2(__B) -Z1(__C) +Z1(_BC) -Z2(_CA) +Z1(_AB)) * h_factor +Z4(CEN);
  5265. e_delta[C_AXIS] = (-Z1(__A) -Z1(__B) +Z2(__C) +Z1(_BC) +Z1(_CA) -Z2(_AB)) * h_factor +Z4(CEN);
  5266. r_delta = (+Z2(__A) +Z2(__B) +Z2(__C) +Z2(_BC) +Z2(_CA) +Z2(_AB) -Z12(CEN)) * r_factor;
  5267. if (towers_set) { // see 7 point tower angle calibration (towers & opposites) matrix
  5268. t_delta[A_AXIS] = (+Z0(__A) -Z4(__B) +Z4(__C) +Z0(_BC) -Z4(_CA) +Z4(_AB) +Z0(CEN)) * a_factor;
  5269. t_delta[B_AXIS] = (+Z4(__A) +Z0(__B) -Z4(__C) +Z4(_BC) +Z0(_CA) -Z4(_AB) +Z0(CEN)) * a_factor;
  5270. t_delta[C_AXIS] = (-Z4(__A) +Z4(__B) +Z0(__C) -Z4(_BC) +Z4(_CA) +Z0(_AB) +Z0(CEN)) * a_factor;
  5271. }
  5272. break;
  5273. }
  5274. LOOP_XYZ(axis) delta_endstop_adj[axis] += e_delta[axis];
  5275. delta_radius += r_delta;
  5276. LOOP_XYZ(axis) delta_tower_angle_trim[axis] += t_delta[axis];
  5277. }
  5278. else if (zero_std_dev >= test_precision) {
  5279. // roll back
  5280. COPY(delta_endstop_adj, e_old);
  5281. delta_radius = r_old;
  5282. delta_height = h_old;
  5283. COPY(delta_tower_angle_trim, a_old);
  5284. }
  5285. if (verbose_level != 0) { // !dry run
  5286. // normalise angles to least squares
  5287. if (_angle_results) {
  5288. float a_sum = 0.0;
  5289. LOOP_XYZ(axis) a_sum += delta_tower_angle_trim[axis];
  5290. LOOP_XYZ(axis) delta_tower_angle_trim[axis] -= a_sum / 3.0;
  5291. }
  5292. // adjust delta_height and endstops by the max amount
  5293. const float z_temp = MAX3(delta_endstop_adj[A_AXIS], delta_endstop_adj[B_AXIS], delta_endstop_adj[C_AXIS]);
  5294. delta_height -= z_temp;
  5295. LOOP_XYZ(axis) delta_endstop_adj[axis] -= z_temp;
  5296. }
  5297. recalc_delta_settings();
  5298. NOMORE(zero_std_dev_min, zero_std_dev);
  5299. // print report
  5300. if (verbose_level == 3)
  5301. print_calibration_results(z_at_pt, _tower_results, _opposite_results);
  5302. if (verbose_level != 0) { // !dry run
  5303. if ((zero_std_dev >= test_precision && iterations > force_iterations) || zero_std_dev <= calibration_precision) { // end iterations
  5304. SERIAL_PROTOCOLPGM("Calibration OK");
  5305. SERIAL_PROTOCOL_SP(32);
  5306. #if HAS_BED_PROBE
  5307. if (zero_std_dev >= test_precision && !_1p_calibration && !_0p_calibration)
  5308. SERIAL_PROTOCOLPGM("rolling back.");
  5309. else
  5310. #endif
  5311. {
  5312. SERIAL_PROTOCOLPGM("std dev:");
  5313. SERIAL_PROTOCOL_F(zero_std_dev_min, 3);
  5314. }
  5315. SERIAL_EOL();
  5316. char mess[21];
  5317. strcpy_P(mess, PSTR("Calibration sd:"));
  5318. if (zero_std_dev_min < 1)
  5319. sprintf_P(&mess[15], PSTR("0.%03i"), int(LROUND(zero_std_dev_min * 1000.0)));
  5320. else
  5321. sprintf_P(&mess[15], PSTR("%03i.x"), int(LROUND(zero_std_dev_min)));
  5322. lcd_setstatus(mess);
  5323. print_calibration_settings(_endstop_results, _angle_results);
  5324. serialprintPGM(save_message);
  5325. SERIAL_EOL();
  5326. }
  5327. else { // !end iterations
  5328. char mess[15];
  5329. if (iterations < 31)
  5330. sprintf_P(mess, PSTR("Iteration : %02i"), int(iterations));
  5331. else
  5332. strcpy_P(mess, PSTR("No convergence"));
  5333. SERIAL_PROTOCOL(mess);
  5334. SERIAL_PROTOCOL_SP(32);
  5335. SERIAL_PROTOCOLPGM("std dev:");
  5336. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  5337. SERIAL_EOL();
  5338. lcd_setstatus(mess);
  5339. if (verbose_level > 1)
  5340. print_calibration_settings(_endstop_results, _angle_results);
  5341. }
  5342. }
  5343. else { // dry run
  5344. const char *enddryrun = PSTR("End DRY-RUN");
  5345. serialprintPGM(enddryrun);
  5346. SERIAL_PROTOCOL_SP(35);
  5347. SERIAL_PROTOCOLPGM("std dev:");
  5348. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  5349. SERIAL_EOL();
  5350. char mess[21];
  5351. strcpy_P(mess, enddryrun);
  5352. strcpy_P(&mess[11], PSTR(" sd:"));
  5353. if (zero_std_dev < 1)
  5354. sprintf_P(&mess[15], PSTR("0.%03i"), int(LROUND(zero_std_dev * 1000.0)));
  5355. else
  5356. sprintf_P(&mess[15], PSTR("%03i.x"), int(LROUND(zero_std_dev)));
  5357. lcd_setstatus(mess);
  5358. }
  5359. ac_home();
  5360. }
  5361. while (((zero_std_dev < test_precision && iterations < 31) || iterations <= force_iterations) && zero_std_dev > calibration_precision);
  5362. AC_CLEANUP();
  5363. }
  5364. #endif // DELTA_AUTO_CALIBRATION
  5365. #if ENABLED(G38_PROBE_TARGET)
  5366. static bool G38_run_probe() {
  5367. bool G38_pass_fail = false;
  5368. #if MULTIPLE_PROBING > 1
  5369. // Get direction of move and retract
  5370. float retract_mm[XYZ];
  5371. LOOP_XYZ(i) {
  5372. float dist = destination[i] - current_position[i];
  5373. retract_mm[i] = ABS(dist) < G38_MINIMUM_MOVE ? 0 : home_bump_mm((AxisEnum)i) * (dist > 0 ? -1 : 1);
  5374. }
  5375. #endif
  5376. // Move until destination reached or target hit
  5377. planner.synchronize();
  5378. endstops.enable(true);
  5379. G38_move = true;
  5380. G38_endstop_hit = false;
  5381. prepare_move_to_destination();
  5382. planner.synchronize();
  5383. G38_move = false;
  5384. endstops.hit_on_purpose();
  5385. set_current_from_steppers_for_axis(ALL_AXES);
  5386. SYNC_PLAN_POSITION_KINEMATIC();
  5387. if (G38_endstop_hit) {
  5388. G38_pass_fail = true;
  5389. #if MULTIPLE_PROBING > 1
  5390. // Move away by the retract distance
  5391. set_destination_from_current();
  5392. LOOP_XYZ(i) destination[i] += retract_mm[i];
  5393. endstops.enable(false);
  5394. prepare_move_to_destination();
  5395. feedrate_mm_s /= 4;
  5396. // Bump the target more slowly
  5397. LOOP_XYZ(i) destination[i] -= retract_mm[i] * 2;
  5398. planner.synchronize();
  5399. endstops.enable(true);
  5400. G38_move = true;
  5401. prepare_move_to_destination();
  5402. planner.synchronize();
  5403. G38_move = false;
  5404. set_current_from_steppers_for_axis(ALL_AXES);
  5405. SYNC_PLAN_POSITION_KINEMATIC();
  5406. #endif
  5407. }
  5408. endstops.hit_on_purpose();
  5409. endstops.not_homing();
  5410. return G38_pass_fail;
  5411. }
  5412. /**
  5413. * G38.2 - probe toward workpiece, stop on contact, signal error if failure
  5414. * G38.3 - probe toward workpiece, stop on contact
  5415. *
  5416. * Like G28 except uses Z min probe for all axes
  5417. */
  5418. inline void gcode_G38(bool is_38_2) {
  5419. // Get X Y Z E F
  5420. gcode_get_destination();
  5421. setup_for_endstop_or_probe_move();
  5422. // If any axis has enough movement, do the move
  5423. LOOP_XYZ(i)
  5424. if (ABS(destination[i] - current_position[i]) >= G38_MINIMUM_MOVE) {
  5425. if (!parser.seenval('F')) feedrate_mm_s = homing_feedrate((AxisEnum)i);
  5426. // If G38.2 fails throw an error
  5427. if (!G38_run_probe() && is_38_2) {
  5428. SERIAL_ERROR_START();
  5429. SERIAL_ERRORLNPGM("Failed to reach target");
  5430. }
  5431. break;
  5432. }
  5433. clean_up_after_endstop_or_probe_move();
  5434. }
  5435. #endif // G38_PROBE_TARGET
  5436. #if HAS_MESH
  5437. /**
  5438. * G42: Move X & Y axes to mesh coordinates (I & J)
  5439. */
  5440. inline void gcode_G42() {
  5441. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  5442. if (axis_unhomed_error()) return;
  5443. #endif
  5444. if (IsRunning()) {
  5445. const bool hasI = parser.seenval('I');
  5446. const int8_t ix = hasI ? parser.value_int() : 0;
  5447. const bool hasJ = parser.seenval('J');
  5448. const int8_t iy = hasJ ? parser.value_int() : 0;
  5449. if ((hasI && !WITHIN(ix, 0, GRID_MAX_POINTS_X - 1)) || (hasJ && !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1))) {
  5450. SERIAL_ECHOLNPGM(MSG_ERR_MESH_XY);
  5451. return;
  5452. }
  5453. set_destination_from_current();
  5454. if (hasI) destination[X_AXIS] = _GET_MESH_X(ix);
  5455. if (hasJ) destination[Y_AXIS] = _GET_MESH_Y(iy);
  5456. if (parser.boolval('P')) {
  5457. if (hasI) destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  5458. if (hasJ) destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  5459. }
  5460. const float fval = parser.linearval('F');
  5461. if (fval > 0.0) feedrate_mm_s = MMM_TO_MMS(fval);
  5462. // SCARA kinematic has "safe" XY raw moves
  5463. #if IS_SCARA
  5464. prepare_uninterpolated_move_to_destination();
  5465. #else
  5466. prepare_move_to_destination();
  5467. #endif
  5468. }
  5469. }
  5470. #endif // HAS_MESH
  5471. /**
  5472. * G92: Set current position to given X Y Z E
  5473. */
  5474. inline void gcode_G92() {
  5475. #if ENABLED(CNC_COORDINATE_SYSTEMS)
  5476. switch (parser.subcode) {
  5477. case 1:
  5478. // Zero the G92 values and restore current position
  5479. #if !IS_SCARA
  5480. LOOP_XYZ(i) {
  5481. const float v = position_shift[i];
  5482. if (v) {
  5483. position_shift[i] = 0;
  5484. update_software_endstops((AxisEnum)i);
  5485. }
  5486. }
  5487. #endif // Not SCARA
  5488. return;
  5489. }
  5490. #endif
  5491. #if ENABLED(CNC_COORDINATE_SYSTEMS)
  5492. #define IS_G92_0 (parser.subcode == 0)
  5493. #else
  5494. #define IS_G92_0 true
  5495. #endif
  5496. bool didE = false;
  5497. #if IS_SCARA || !HAS_POSITION_SHIFT || ENABLED(HANGPRINTER)
  5498. bool didXYZ = false;
  5499. #else
  5500. constexpr bool didXYZ = false;
  5501. #endif
  5502. if (IS_G92_0) LOOP_XYZE(i) {
  5503. if (parser.seenval(axis_codes[i])) {
  5504. const float l = parser.value_axis_units((AxisEnum)i),
  5505. v = i == E_CART ? l : LOGICAL_TO_NATIVE(l, i),
  5506. d = v - current_position[i];
  5507. if (!NEAR_ZERO(d)
  5508. #if ENABLED(HANGPRINTER)
  5509. || true // Hangprinter needs to update its line lengths whether current_position changed or not
  5510. #endif
  5511. ) {
  5512. #if IS_SCARA || !HAS_POSITION_SHIFT || ENABLED(HANGPRINTER)
  5513. if (i == E_CART) didE = true; else didXYZ = true;
  5514. current_position[i] = v; // Without workspaces revert to Marlin 1.0 behavior
  5515. #elif HAS_POSITION_SHIFT
  5516. if (i == E_CART) {
  5517. didE = true;
  5518. current_position[E_CART] = v; // When using coordinate spaces, only E is set directly
  5519. }
  5520. else {
  5521. position_shift[i] += d; // Other axes simply offset the coordinate space
  5522. update_software_endstops((AxisEnum)i);
  5523. }
  5524. #endif
  5525. }
  5526. }
  5527. }
  5528. #if ENABLED(CNC_COORDINATE_SYSTEMS)
  5529. // Apply workspace offset to the active coordinate system
  5530. if (WITHIN(active_coordinate_system, 0, MAX_COORDINATE_SYSTEMS - 1))
  5531. COPY(coordinate_system[active_coordinate_system], position_shift);
  5532. #endif
  5533. // Update planner/steppers only if the native coordinates changed
  5534. if (didXYZ) SYNC_PLAN_POSITION_KINEMATIC();
  5535. else if (didE) sync_plan_position_e();
  5536. report_current_position();
  5537. }
  5538. #if ENABLED(MECHADUINO_I2C_COMMANDS)
  5539. /**
  5540. * G95: Set torque mode
  5541. */
  5542. inline void gcode_G95() {
  5543. i2cFloat torques[NUM_AXIS]; // Assumes 4-byte floats here and in Mechaduino firmware
  5544. LOOP_NUM_AXIS(i)
  5545. torques[i].fval = parser.floatval(RAW_AXIS_CODES(i), 999.9); // 999.9 chosen to satisfy fabs(999.9) > 255.0
  5546. // 0x5f == 95
  5547. #define G95_SEND(LETTER) do { \
  5548. if (fabs(torques[_AXIS(LETTER)].fval) < 255.0){ \
  5549. torques[_AXIS(LETTER)].fval = -fabs(torques[_AXIS(LETTER)].fval); \
  5550. if(!INVERT_##LETTER##_DIR) torques[_AXIS(LETTER)].fval = -torques[_AXIS(LETTER)].fval; \
  5551. i2c.address(LETTER##_MOTOR_I2C_ADDR); \
  5552. i2c.reset(); \
  5553. i2c.addbyte(0x5f); \
  5554. i2c.addbytes(torques[_AXIS(LETTER)].bval, sizeof(float)); \
  5555. i2c.send(); \
  5556. }} while(0)
  5557. #if ENABLED(HANGPRINTER)
  5558. #if ENABLED(A_IS_MECHADUINO)
  5559. G95_SEND(A);
  5560. #endif
  5561. #if ENABLED(B_IS_MECHADUINO)
  5562. G95_SEND(B);
  5563. #endif
  5564. #if ENABLED(C_IS_MECHADUINO)
  5565. G95_SEND(C);
  5566. #endif
  5567. #if ENABLED(D_IS_MECHADUINO)
  5568. G95_SEND(D);
  5569. #endif
  5570. #else
  5571. #if ENABLED(X_IS_MECHADUINO)
  5572. G95_SEND(X);
  5573. #endif
  5574. #if ENABLED(Y_IS_MECHADUINO)
  5575. G95_SEND(Y);
  5576. #endif
  5577. #if ENABLED(Z_IS_MECHADUINO)
  5578. G95_SEND(Z);
  5579. #endif
  5580. #endif
  5581. #if ENABLED(E_IS_MECHADUINO)
  5582. G95_SEND(E);
  5583. #endif
  5584. }
  5585. /**
  5586. * G96: Mark encoder reference point
  5587. */
  5588. inline void gcode_G96() {
  5589. bool mark[NUM_AXIS] = { false };
  5590. if (!parser.seen_any())
  5591. LOOP_NUM_AXIS(i)
  5592. mark[i] = true;
  5593. else
  5594. LOOP_NUM_AXIS(i)
  5595. if (parser.seen(RAW_AXIS_CODES(i)))
  5596. mark[i] = true;
  5597. // 0x60 == 96
  5598. #define G96_SEND(LETTER) do {\
  5599. if (mark[LETTER##_AXIS]){ \
  5600. i2c.address(LETTER##_MOTOR_I2C_ADDR); \
  5601. i2c.reset(); \
  5602. i2c.addbyte(0x60); \
  5603. i2c.send(); \
  5604. }} while(0)
  5605. #if ENABLED(HANGPRINTER)
  5606. #if ENABLED(A_IS_MECHADUINO)
  5607. G96_SEND(A);
  5608. #endif
  5609. #if ENABLED(B_IS_MECHADUINO)
  5610. G96_SEND(B);
  5611. #endif
  5612. #if ENABLED(C_IS_MECHADUINO)
  5613. G96_SEND(C);
  5614. #endif
  5615. #if ENABLED(D_IS_MECHADUINO)
  5616. G96_SEND(D);
  5617. #endif
  5618. #else
  5619. #if ENABLED(X_IS_MECHADUINO)
  5620. G96_SEND(X);
  5621. #endif
  5622. #if ENABLED(Y_IS_MECHADUINO)
  5623. G96_SEND(Y);
  5624. #endif
  5625. #if ENABLED(Z_IS_MECHADUINO)
  5626. G96_SEND(Z);
  5627. #endif
  5628. #endif
  5629. #if ENABLED(E_IS_MECHADUINO)
  5630. G96_SEND(E); // E ref point not used by any other commands (Feb 7, 2018)
  5631. #endif
  5632. }
  5633. float ang_to_mm(float ang, const AxisEnum axis) {
  5634. const float abs_step_in_origin =
  5635. #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
  5636. planner.k0[axis] * (SQRT(planner.k1[axis] + planner.k2[axis] * line_lengths_origin[axis]) - planner.sqrtk1[axis])
  5637. #else
  5638. line_lengths_origin[axis] * planner.axis_steps_per_mm[axis]
  5639. #endif
  5640. ;
  5641. const float c = abs_step_in_origin + ang * float(STEPS_PER_MOTOR_REVOLUTION) / 360.0; // current step count
  5642. return
  5643. #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
  5644. // Inverse function found in planner.cpp, where target[AXIS_A] is calculated
  5645. ((c / planner.k0[axis] + planner.sqrtk1[axis]) * (c / planner.k0[axis] + planner.sqrtk1[axis]) - planner.k1[axis]) / planner.k2[axis] - line_lengths_origin[axis]
  5646. #else
  5647. c / planner.axis_steps_per_mm[axis] - line_lengths_origin[axis]
  5648. #endif
  5649. ;
  5650. }
  5651. void report_axis_position_from_encoder_data() {
  5652. i2cFloat ang;
  5653. #define M114_S1_RECEIVE(LETTER) do { \
  5654. i2c.address(LETTER##_MOTOR_I2C_ADDR); \
  5655. i2c.request(sizeof(float)); \
  5656. i2c.capture(ang.bval, sizeof(float)); \
  5657. if(LETTER##_INVERT_REPORTED_ANGLE == INVERT_##LETTER##_DIR) ang.fval = -ang.fval; \
  5658. SERIAL_PROTOCOL(ang_to_mm(ang.fval, LETTER##_AXIS)); \
  5659. } while(0)
  5660. SERIAL_CHAR('[');
  5661. #if ENABLED(HANGPRINTER)
  5662. #if ENABLED(A_IS_MECHADUINO)
  5663. M114_S1_RECEIVE(A);
  5664. #endif
  5665. #if ENABLED(B_IS_MECHADUINO)
  5666. SERIAL_PROTOCOLPGM(", ");
  5667. M114_S1_RECEIVE(B);
  5668. #endif
  5669. #if ENABLED(C_IS_MECHADUINO)
  5670. SERIAL_PROTOCOLPGM(", ");
  5671. M114_S1_RECEIVE(C);
  5672. #endif
  5673. #if ENABLED(D_IS_MECHADUINO)
  5674. SERIAL_PROTOCOLPGM(", ");
  5675. M114_S1_RECEIVE(D);
  5676. #endif
  5677. #else
  5678. #if ENABLED(X_IS_MECHADUINO)
  5679. M114_S1_RECEIVE(X);
  5680. #endif
  5681. #if ENABLED(Y_IS_MECHADUINO)
  5682. SERIAL_PROTOCOLPGM(", ");
  5683. M114_S1_RECEIVE(Y);
  5684. #endif
  5685. #if ENABLED(Z_IS_MECHADUINO)
  5686. SERIAL_PROTOCOLPGM(", ");
  5687. M114_S1_RECEIVE(Z);
  5688. #endif
  5689. #endif
  5690. SERIAL_CHAR(']');
  5691. SERIAL_EOL();
  5692. }
  5693. #endif // MECHADUINO_I2C_COMMANDS
  5694. void report_xyz_from_stepper_position() {
  5695. get_cartesian_from_steppers(); // writes to cartes[XYZ]
  5696. SERIAL_CHAR('[');
  5697. SERIAL_PROTOCOL(cartes[X_AXIS]);
  5698. SERIAL_PROTOCOLPAIR(", ", cartes[Y_AXIS]);
  5699. SERIAL_PROTOCOLPAIR(", ", cartes[Z_AXIS]);
  5700. SERIAL_CHAR(']');
  5701. SERIAL_EOL();
  5702. }
  5703. #if HAS_RESUME_CONTINUE
  5704. /**
  5705. * M0: Unconditional stop - Wait for user button press on LCD
  5706. * M1: Conditional stop - Wait for user button press on LCD
  5707. */
  5708. inline void gcode_M0_M1() {
  5709. const char * const args = parser.string_arg;
  5710. millis_t ms = 0;
  5711. bool hasP = false, hasS = false;
  5712. if (parser.seenval('P')) {
  5713. ms = parser.value_millis(); // milliseconds to wait
  5714. hasP = ms > 0;
  5715. }
  5716. if (parser.seenval('S')) {
  5717. ms = parser.value_millis_from_seconds(); // seconds to wait
  5718. hasS = ms > 0;
  5719. }
  5720. const bool has_message = !hasP && !hasS && args && *args;
  5721. planner.synchronize();
  5722. #if ENABLED(ULTIPANEL)
  5723. if (has_message)
  5724. lcd_setstatus(args, true);
  5725. else {
  5726. LCD_MESSAGEPGM(MSG_USERWAIT);
  5727. #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0
  5728. dontExpireStatus();
  5729. #endif
  5730. }
  5731. #else
  5732. if (has_message) {
  5733. SERIAL_ECHO_START();
  5734. SERIAL_ECHOLN(args);
  5735. }
  5736. #endif
  5737. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5738. wait_for_user = true;
  5739. if (ms > 0) {
  5740. ms += millis(); // wait until this time for a click
  5741. while (PENDING(millis(), ms) && wait_for_user) idle();
  5742. }
  5743. else
  5744. while (wait_for_user) idle();
  5745. #if ENABLED(PRINTER_EVENT_LEDS) && ENABLED(SDSUPPORT)
  5746. if (lights_off_after_print) {
  5747. leds.set_off();
  5748. lights_off_after_print = false;
  5749. }
  5750. #endif
  5751. lcd_reset_status();
  5752. wait_for_user = false;
  5753. KEEPALIVE_STATE(IN_HANDLER);
  5754. }
  5755. #endif // HAS_RESUME_CONTINUE
  5756. #if ENABLED(SPINDLE_LASER_ENABLE)
  5757. /**
  5758. * M3: Spindle Clockwise
  5759. * M4: Spindle Counter-clockwise
  5760. *
  5761. * S0 turns off spindle.
  5762. *
  5763. * If no speed PWM output is defined then M3/M4 just turns it on.
  5764. *
  5765. * At least 12.8KHz (50Hz * 256) is needed for spindle PWM.
  5766. * Hardware PWM is required. ISRs are too slow.
  5767. *
  5768. * NOTE: WGM for timers 3, 4, and 5 must be either Mode 1 or Mode 5.
  5769. * No other settings give a PWM signal that goes from 0 to 5 volts.
  5770. *
  5771. * The system automatically sets WGM to Mode 1, so no special
  5772. * initialization is needed.
  5773. *
  5774. * WGM bits for timer 2 are automatically set by the system to
  5775. * Mode 1. This produces an acceptable 0 to 5 volt signal.
  5776. * No special initialization is needed.
  5777. *
  5778. * NOTE: A minimum PWM frequency of 50 Hz is needed. All prescaler
  5779. * factors for timers 2, 3, 4, and 5 are acceptable.
  5780. *
  5781. * SPINDLE_LASER_ENABLE_PIN needs an external pullup or it may power on
  5782. * the spindle/laser during power-up or when connecting to the host
  5783. * (usually goes through a reset which sets all I/O pins to tri-state)
  5784. *
  5785. * PWM duty cycle goes from 0 (off) to 255 (always on).
  5786. */
  5787. // Wait for spindle to come up to speed
  5788. inline void delay_for_power_up() { dwell(SPINDLE_LASER_POWERUP_DELAY); }
  5789. // Wait for spindle to stop turning
  5790. inline void delay_for_power_down() { dwell(SPINDLE_LASER_POWERDOWN_DELAY); }
  5791. /**
  5792. * ocr_val_mode() is used for debugging and to get the points needed to compute the RPM vs ocr_val line
  5793. *
  5794. * it accepts inputs of 0-255
  5795. */
  5796. inline void ocr_val_mode() {
  5797. uint8_t spindle_laser_power = parser.value_byte();
  5798. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  5799. if (SPINDLE_LASER_PWM_INVERT) spindle_laser_power = 255 - spindle_laser_power;
  5800. analogWrite(SPINDLE_LASER_PWM_PIN, spindle_laser_power);
  5801. }
  5802. inline void gcode_M3_M4(bool is_M3) {
  5803. planner.synchronize(); // wait until previous movement commands (G0/G0/G2/G3) have completed before playing with the spindle
  5804. #if SPINDLE_DIR_CHANGE
  5805. const bool rotation_dir = (is_M3 && !SPINDLE_INVERT_DIR || !is_M3 && SPINDLE_INVERT_DIR) ? HIGH : LOW;
  5806. if (SPINDLE_STOP_ON_DIR_CHANGE \
  5807. && READ(SPINDLE_LASER_ENABLE_PIN) == SPINDLE_LASER_ENABLE_INVERT \
  5808. && READ(SPINDLE_DIR_PIN) != rotation_dir
  5809. ) {
  5810. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off
  5811. delay_for_power_down();
  5812. }
  5813. WRITE(SPINDLE_DIR_PIN, rotation_dir);
  5814. #endif
  5815. /**
  5816. * Our final value for ocr_val is an unsigned 8 bit value between 0 and 255 which usually means uint8_t.
  5817. * Went to uint16_t because some of the uint8_t calculations would sometimes give 1000 0000 rather than 1111 1111.
  5818. * Then needed to AND the uint16_t result with 0x00FF to make sure we only wrote the byte of interest.
  5819. */
  5820. #if ENABLED(SPINDLE_LASER_PWM)
  5821. if (parser.seen('O')) ocr_val_mode();
  5822. else {
  5823. const float spindle_laser_power = parser.floatval('S');
  5824. if (spindle_laser_power == 0) {
  5825. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off (active low)
  5826. analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0); // only write low byte
  5827. delay_for_power_down();
  5828. }
  5829. else {
  5830. int16_t ocr_val = (spindle_laser_power - (SPEED_POWER_INTERCEPT)) * (1.0f / (SPEED_POWER_SLOPE)); // convert RPM to PWM duty cycle
  5831. NOMORE(ocr_val, 255); // limit to max the Atmel PWM will support
  5832. if (spindle_laser_power <= SPEED_POWER_MIN)
  5833. ocr_val = (SPEED_POWER_MIN - (SPEED_POWER_INTERCEPT)) * (1.0f / (SPEED_POWER_SLOPE)); // minimum setting
  5834. if (spindle_laser_power >= SPEED_POWER_MAX)
  5835. ocr_val = (SPEED_POWER_MAX - (SPEED_POWER_INTERCEPT)) * (1.0f / (SPEED_POWER_SLOPE)); // limit to max RPM
  5836. if (SPINDLE_LASER_PWM_INVERT) ocr_val = 255 - ocr_val;
  5837. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  5838. analogWrite(SPINDLE_LASER_PWM_PIN, ocr_val & 0xFF); // only write low byte
  5839. delay_for_power_up();
  5840. }
  5841. }
  5842. #else
  5843. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low) if spindle speed option not enabled
  5844. delay_for_power_up();
  5845. #endif
  5846. }
  5847. /**
  5848. * M5 turn off spindle
  5849. */
  5850. inline void gcode_M5() {
  5851. planner.synchronize();
  5852. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT);
  5853. #if ENABLED(SPINDLE_LASER_PWM)
  5854. analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0);
  5855. #endif
  5856. delay_for_power_down();
  5857. }
  5858. #endif // SPINDLE_LASER_ENABLE
  5859. /**
  5860. * M17: Enable power on all stepper motors
  5861. */
  5862. inline void gcode_M17() {
  5863. LCD_MESSAGEPGM(MSG_NO_MOVE);
  5864. enable_all_steppers();
  5865. }
  5866. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  5867. void do_pause_e_move(const float &length, const float &fr) {
  5868. set_destination_from_current();
  5869. destination[E_CART] += length / planner.e_factor[active_extruder];
  5870. planner.buffer_line_kinematic(destination, fr, active_extruder);
  5871. set_current_from_destination();
  5872. planner.synchronize();
  5873. }
  5874. static float resume_position[XYZE];
  5875. int8_t did_pause_print = 0;
  5876. #if HAS_BUZZER
  5877. static void filament_change_beep(const int8_t max_beep_count, const bool init=false) {
  5878. static millis_t next_buzz = 0;
  5879. static int8_t runout_beep = 0;
  5880. if (init) next_buzz = runout_beep = 0;
  5881. const millis_t ms = millis();
  5882. if (ELAPSED(ms, next_buzz)) {
  5883. if (max_beep_count < 0 || runout_beep < max_beep_count + 5) { // Only beep as long as we're supposed to
  5884. next_buzz = ms + ((max_beep_count < 0 || runout_beep < max_beep_count) ? 1000 : 500);
  5885. BUZZ(50, 880 - (runout_beep & 1) * 220);
  5886. runout_beep++;
  5887. }
  5888. }
  5889. }
  5890. #endif
  5891. /**
  5892. * Ensure a safe temperature for extrusion
  5893. *
  5894. * - Fail if the TARGET temperature is too low
  5895. * - Display LCD placard with temperature status
  5896. * - Return when heating is done or aborted
  5897. *
  5898. * Returns 'true' if heating was completed, 'false' for abort
  5899. */
  5900. static bool ensure_safe_temperature(const AdvancedPauseMode mode=ADVANCED_PAUSE_MODE_PAUSE_PRINT) {
  5901. #if ENABLED(PREVENT_COLD_EXTRUSION)
  5902. if (!DEBUGGING(DRYRUN) && thermalManager.targetTooColdToExtrude(active_extruder)) {
  5903. SERIAL_ERROR_START();
  5904. SERIAL_ERRORLNPGM(MSG_HOTEND_TOO_COLD);
  5905. return false;
  5906. }
  5907. #endif
  5908. #if ENABLED(ULTIPANEL)
  5909. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_WAIT_FOR_NOZZLES_TO_HEAT, mode);
  5910. #else
  5911. UNUSED(mode);
  5912. #endif
  5913. wait_for_heatup = true; // M108 will clear this
  5914. while (wait_for_heatup && thermalManager.wait_for_heating(active_extruder)) idle();
  5915. const bool status = wait_for_heatup;
  5916. wait_for_heatup = false;
  5917. return status;
  5918. }
  5919. /**
  5920. * Load filament into the hotend
  5921. *
  5922. * - Fail if the a safe temperature was not reached
  5923. * - If pausing for confirmation, wait for a click or M108
  5924. * - Show "wait for load" placard
  5925. * - Load and purge filament
  5926. * - Show "Purge more" / "Continue" menu
  5927. * - Return when "Continue" is selected
  5928. *
  5929. * Returns 'true' if load was completed, 'false' for abort
  5930. */
  5931. static bool load_filament(const float &slow_load_length=0, const float &fast_load_length=0, const float &purge_length=0, const int8_t max_beep_count=0,
  5932. const bool show_lcd=false, const bool pause_for_user=false,
  5933. const AdvancedPauseMode mode=ADVANCED_PAUSE_MODE_PAUSE_PRINT
  5934. ) {
  5935. #if DISABLED(ULTIPANEL)
  5936. UNUSED(show_lcd);
  5937. #endif
  5938. if (!ensure_safe_temperature(mode)) {
  5939. #if ENABLED(ULTIPANEL)
  5940. if (show_lcd) // Show status screen
  5941. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  5942. #endif
  5943. return false;
  5944. }
  5945. if (pause_for_user) {
  5946. #if ENABLED(ULTIPANEL)
  5947. if (show_lcd) // Show "insert filament"
  5948. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT, mode);
  5949. #endif
  5950. SERIAL_ECHO_START();
  5951. SERIAL_ECHOLNPGM(MSG_FILAMENT_CHANGE_INSERT);
  5952. #if HAS_BUZZER
  5953. filament_change_beep(max_beep_count, true);
  5954. #else
  5955. UNUSED(max_beep_count);
  5956. #endif
  5957. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5958. wait_for_user = true; // LCD click or M108 will clear this
  5959. while (wait_for_user) {
  5960. #if HAS_BUZZER
  5961. filament_change_beep(max_beep_count);
  5962. #endif
  5963. idle(true);
  5964. }
  5965. KEEPALIVE_STATE(IN_HANDLER);
  5966. }
  5967. #if ENABLED(ULTIPANEL)
  5968. if (show_lcd) // Show "wait for load" message
  5969. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_LOAD, mode);
  5970. #endif
  5971. // Slow Load filament
  5972. if (slow_load_length) do_pause_e_move(slow_load_length, FILAMENT_CHANGE_SLOW_LOAD_FEEDRATE);
  5973. // Fast Load Filament
  5974. if (fast_load_length) {
  5975. #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0
  5976. const float saved_acceleration = planner.retract_acceleration;
  5977. planner.retract_acceleration = FILAMENT_CHANGE_FAST_LOAD_ACCEL;
  5978. #endif
  5979. do_pause_e_move(fast_load_length, FILAMENT_CHANGE_FAST_LOAD_FEEDRATE);
  5980. #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0
  5981. planner.retract_acceleration = saved_acceleration;
  5982. #endif
  5983. }
  5984. #if ENABLED(ADVANCED_PAUSE_CONTINUOUS_PURGE)
  5985. #if ENABLED(ULTIPANEL)
  5986. if (show_lcd)
  5987. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_CONTINUOUS_PURGE);
  5988. #endif
  5989. wait_for_user = true;
  5990. for (float purge_count = purge_length; purge_count > 0 && wait_for_user; --purge_count)
  5991. do_pause_e_move(1, ADVANCED_PAUSE_PURGE_FEEDRATE);
  5992. wait_for_user = false;
  5993. #else
  5994. do {
  5995. if (purge_length > 0) {
  5996. // "Wait for filament purge"
  5997. #if ENABLED(ULTIPANEL)
  5998. if (show_lcd)
  5999. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_PURGE, mode);
  6000. #endif
  6001. // Extrude filament to get into hotend
  6002. do_pause_e_move(purge_length, ADVANCED_PAUSE_PURGE_FEEDRATE);
  6003. }
  6004. // Show "Purge More" / "Resume" menu and wait for reply
  6005. #if ENABLED(ULTIPANEL)
  6006. if (show_lcd) {
  6007. KEEPALIVE_STATE(PAUSED_FOR_USER);
  6008. wait_for_user = false;
  6009. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_OPTION, mode);
  6010. while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_WAIT_FOR) idle(true);
  6011. KEEPALIVE_STATE(IN_HANDLER);
  6012. }
  6013. #endif
  6014. // Keep looping if "Purge More" was selected
  6015. } while (
  6016. #if ENABLED(ULTIPANEL)
  6017. show_lcd && advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_EXTRUDE_MORE
  6018. #else
  6019. 0
  6020. #endif
  6021. );
  6022. #endif
  6023. return true;
  6024. }
  6025. /**
  6026. * Unload filament from the hotend
  6027. *
  6028. * - Fail if the a safe temperature was not reached
  6029. * - Show "wait for unload" placard
  6030. * - Retract, pause, then unload filament
  6031. * - Disable E stepper (on most machines)
  6032. *
  6033. * Returns 'true' if unload was completed, 'false' for abort
  6034. */
  6035. static bool unload_filament(const float &unload_length, const bool show_lcd=false,
  6036. const AdvancedPauseMode mode=ADVANCED_PAUSE_MODE_PAUSE_PRINT
  6037. ) {
  6038. if (!ensure_safe_temperature(mode)) {
  6039. #if ENABLED(ULTIPANEL)
  6040. if (show_lcd) // Show status screen
  6041. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  6042. #endif
  6043. return false;
  6044. }
  6045. #if DISABLED(ULTIPANEL)
  6046. UNUSED(show_lcd);
  6047. #else
  6048. if (show_lcd)
  6049. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_UNLOAD, mode);
  6050. #endif
  6051. // Retract filament
  6052. do_pause_e_move(-FILAMENT_UNLOAD_RETRACT_LENGTH, PAUSE_PARK_RETRACT_FEEDRATE);
  6053. // Wait for filament to cool
  6054. safe_delay(FILAMENT_UNLOAD_DELAY);
  6055. // Quickly purge
  6056. do_pause_e_move(FILAMENT_UNLOAD_RETRACT_LENGTH + FILAMENT_UNLOAD_PURGE_LENGTH, planner.max_feedrate_mm_s[E_AXIS]);
  6057. // Unload filament
  6058. #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0
  6059. const float saved_acceleration = planner.retract_acceleration;
  6060. planner.retract_acceleration = FILAMENT_CHANGE_UNLOAD_ACCEL;
  6061. #endif
  6062. do_pause_e_move(unload_length, FILAMENT_CHANGE_UNLOAD_FEEDRATE);
  6063. #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0
  6064. planner.retract_acceleration = saved_acceleration;
  6065. #endif
  6066. // Disable extruders steppers for manual filament changing (only on boards that have separate ENABLE_PINS)
  6067. #if E0_ENABLE_PIN != X_ENABLE_PIN && E1_ENABLE_PIN != Y_ENABLE_PIN
  6068. disable_e_stepper(active_extruder);
  6069. safe_delay(100);
  6070. #endif
  6071. return true;
  6072. }
  6073. /**
  6074. * Pause procedure
  6075. *
  6076. * - Abort if already paused
  6077. * - Send host action for pause, if configured
  6078. * - Abort if TARGET temperature is too low
  6079. * - Display "wait for start of filament change" (if a length was specified)
  6080. * - Initial retract, if current temperature is hot enough
  6081. * - Park the nozzle at the given position
  6082. * - Call unload_filament (if a length was specified)
  6083. *
  6084. * Returns 'true' if pause was completed, 'false' for abort
  6085. */
  6086. static bool pause_print(const float &retract, const point_t &park_point, const float &unload_length=0, const bool show_lcd=false) {
  6087. if (did_pause_print) return false; // already paused
  6088. #ifdef ACTION_ON_PAUSE
  6089. SERIAL_ECHOLNPGM("//action:" ACTION_ON_PAUSE);
  6090. #endif
  6091. if (!DEBUGGING(DRYRUN) && unload_length && thermalManager.targetTooColdToExtrude(active_extruder)) {
  6092. SERIAL_ERROR_START();
  6093. SERIAL_ERRORLNPGM(MSG_HOTEND_TOO_COLD);
  6094. #if ENABLED(ULTIPANEL)
  6095. if (show_lcd) // Show status screen
  6096. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  6097. LCD_MESSAGEPGM(MSG_M600_TOO_COLD);
  6098. #endif
  6099. return false; // unable to reach safe temperature
  6100. }
  6101. // Indicate that the printer is paused
  6102. ++did_pause_print;
  6103. // Pause the print job and timer
  6104. #if ENABLED(SDSUPPORT)
  6105. if (card.sdprinting) {
  6106. card.pauseSDPrint();
  6107. ++did_pause_print; // Indicate SD pause also
  6108. }
  6109. #endif
  6110. print_job_timer.pause();
  6111. // Save current position
  6112. COPY(resume_position, current_position);
  6113. // Wait for synchronize steppers
  6114. planner.synchronize();
  6115. // Initial retract before move to filament change position
  6116. if (retract && thermalManager.hotEnoughToExtrude(active_extruder))
  6117. do_pause_e_move(retract, PAUSE_PARK_RETRACT_FEEDRATE);
  6118. // Park the nozzle by moving up by z_lift and then moving to (x_pos, y_pos)
  6119. if (!axis_unhomed_error())
  6120. Nozzle::park(2, park_point);
  6121. // Unload the filament
  6122. if (unload_length)
  6123. unload_filament(unload_length, show_lcd);
  6124. return true;
  6125. }
  6126. /**
  6127. * - Show "Insert filament and press button to continue"
  6128. * - Wait for a click before returning
  6129. * - Heaters can time out, reheated before accepting a click
  6130. *
  6131. * Used by M125 and M600
  6132. */
  6133. static void wait_for_filament_reload(const int8_t max_beep_count=0) {
  6134. bool nozzle_timed_out = false;
  6135. #if ENABLED(ULTIPANEL)
  6136. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  6137. #endif
  6138. SERIAL_ECHO_START();
  6139. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT);
  6140. #if HAS_BUZZER
  6141. filament_change_beep(max_beep_count, true);
  6142. #endif
  6143. // Start the heater idle timers
  6144. const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL;
  6145. HOTEND_LOOP()
  6146. thermalManager.start_heater_idle_timer(e, nozzle_timeout);
  6147. // Wait for filament insert by user and press button
  6148. KEEPALIVE_STATE(PAUSED_FOR_USER);
  6149. wait_for_user = true; // LCD click or M108 will clear this
  6150. while (wait_for_user) {
  6151. #if HAS_BUZZER
  6152. filament_change_beep(max_beep_count);
  6153. #endif
  6154. // If the nozzle has timed out, wait for the user to press the button to re-heat the nozzle, then
  6155. // re-heat the nozzle, re-show the insert screen, restart the idle timers, and start over
  6156. if (!nozzle_timed_out)
  6157. HOTEND_LOOP()
  6158. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  6159. if (nozzle_timed_out) {
  6160. #if ENABLED(ULTIPANEL)
  6161. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_CLICK_TO_HEAT_NOZZLE);
  6162. #endif
  6163. SERIAL_ECHO_START();
  6164. #if ENABLED(ULTIPANEL) && ENABLED(EMERGENCY_PARSER)
  6165. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_HEAT);
  6166. #elif ENABLED(EMERGENCY_PARSER)
  6167. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_HEAT_M108);
  6168. #else
  6169. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_HEAT_LCD);
  6170. #endif
  6171. // Wait for LCD click or M108
  6172. while (wait_for_user) idle(true);
  6173. // Re-enable the heaters if they timed out
  6174. HOTEND_LOOP() thermalManager.reset_heater_idle_timer(e);
  6175. // Wait for the heaters to reach the target temperatures
  6176. ensure_safe_temperature();
  6177. #if ENABLED(ULTIPANEL)
  6178. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  6179. #endif
  6180. SERIAL_ECHO_START();
  6181. #if ENABLED(ULTIPANEL) && ENABLED(EMERGENCY_PARSER)
  6182. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT);
  6183. #elif ENABLED(EMERGENCY_PARSER)
  6184. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT_M108);
  6185. #else
  6186. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT_LCD);
  6187. #endif
  6188. // Start the heater idle timers
  6189. const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL;
  6190. HOTEND_LOOP()
  6191. thermalManager.start_heater_idle_timer(e, nozzle_timeout);
  6192. wait_for_user = true; // Wait for user to load filament
  6193. nozzle_timed_out = false;
  6194. #if HAS_BUZZER
  6195. filament_change_beep(max_beep_count, true);
  6196. #endif
  6197. }
  6198. idle(true);
  6199. }
  6200. KEEPALIVE_STATE(IN_HANDLER);
  6201. }
  6202. /**
  6203. * Resume or Start print procedure
  6204. *
  6205. * - Abort if not paused
  6206. * - Reset heater idle timers
  6207. * - Load filament if specified, but only if:
  6208. * - a nozzle timed out, or
  6209. * - the nozzle is already heated.
  6210. * - Display "wait for print to resume"
  6211. * - Re-prime the nozzle...
  6212. * - FWRETRACT: Recover/prime from the prior G10.
  6213. * - !FWRETRACT: Retract by resume_position[E], if negative.
  6214. * Not sure how this logic comes into use.
  6215. * - Move the nozzle back to resume_position
  6216. * - Sync the planner E to resume_position[E]
  6217. * - Send host action for resume, if configured
  6218. * - Resume the current SD print job, if any
  6219. */
  6220. static void resume_print(const float &slow_load_length=0, const float &fast_load_length=0, const float &purge_length=ADVANCED_PAUSE_PURGE_LENGTH, const int8_t max_beep_count=0) {
  6221. if (!did_pause_print) return;
  6222. // Re-enable the heaters if they timed out
  6223. bool nozzle_timed_out = false;
  6224. HOTEND_LOOP() {
  6225. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  6226. thermalManager.reset_heater_idle_timer(e);
  6227. }
  6228. if (nozzle_timed_out || thermalManager.hotEnoughToExtrude(active_extruder)) {
  6229. // Load the new filament
  6230. load_filament(slow_load_length, fast_load_length, purge_length, max_beep_count, true, nozzle_timed_out);
  6231. }
  6232. #if ENABLED(ULTIPANEL)
  6233. // "Wait for print to resume"
  6234. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_RESUME);
  6235. #endif
  6236. // Intelligent resuming
  6237. #if ENABLED(FWRETRACT)
  6238. // If retracted before goto pause
  6239. if (fwretract.retracted[active_extruder])
  6240. do_pause_e_move(-fwretract.retract_length, fwretract.retract_feedrate_mm_s);
  6241. #endif
  6242. // If resume_position is negative
  6243. if (resume_position[E_CART] < 0) do_pause_e_move(resume_position[E_CART], PAUSE_PARK_RETRACT_FEEDRATE);
  6244. // Move XY to starting position, then Z
  6245. do_blocking_move_to_xy(resume_position[X_AXIS], resume_position[Y_AXIS], NOZZLE_PARK_XY_FEEDRATE);
  6246. // Set Z_AXIS to saved position
  6247. do_blocking_move_to_z(resume_position[Z_AXIS], NOZZLE_PARK_Z_FEEDRATE);
  6248. // Now all extrusion positions are resumed and ready to be confirmed
  6249. // Set extruder to saved position
  6250. planner.set_e_position_mm((destination[E_CART] = current_position[E_CART] = resume_position[E_CART]));
  6251. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  6252. runout.reset();
  6253. #endif
  6254. #if ENABLED(ULTIPANEL)
  6255. // Show status screen
  6256. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  6257. #endif
  6258. #ifdef ACTION_ON_RESUME
  6259. SERIAL_ECHOLNPGM("//action:" ACTION_ON_RESUME);
  6260. #endif
  6261. --did_pause_print;
  6262. #if ENABLED(SDSUPPORT)
  6263. if (did_pause_print) {
  6264. card.startFileprint();
  6265. --did_pause_print;
  6266. }
  6267. #endif
  6268. }
  6269. #endif // ADVANCED_PAUSE_FEATURE
  6270. #if ENABLED(SDSUPPORT)
  6271. /**
  6272. * M20: List SD card to serial output
  6273. */
  6274. inline void gcode_M20() {
  6275. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  6276. card.ls();
  6277. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  6278. }
  6279. /**
  6280. * M21: Init SD Card
  6281. */
  6282. inline void gcode_M21() { card.initsd(); }
  6283. /**
  6284. * M22: Release SD Card
  6285. */
  6286. inline void gcode_M22() { card.release(); }
  6287. /**
  6288. * M23: Open a file
  6289. */
  6290. inline void gcode_M23() {
  6291. #if ENABLED(POWER_LOSS_RECOVERY)
  6292. card.removeJobRecoveryFile();
  6293. #endif
  6294. // Simplify3D includes the size, so zero out all spaces (#7227)
  6295. for (char *fn = parser.string_arg; *fn; ++fn) if (*fn == ' ') *fn = '\0';
  6296. card.openFile(parser.string_arg, true);
  6297. }
  6298. /**
  6299. * M24: Start or Resume SD Print
  6300. */
  6301. inline void gcode_M24() {
  6302. #if ENABLED(PARK_HEAD_ON_PAUSE)
  6303. resume_print();
  6304. #endif
  6305. #if ENABLED(POWER_LOSS_RECOVERY)
  6306. if (parser.seenval('S')) card.setIndex(parser.value_long());
  6307. #endif
  6308. card.startFileprint();
  6309. #if ENABLED(POWER_LOSS_RECOVERY)
  6310. if (parser.seenval('T'))
  6311. print_job_timer.resume(parser.value_long());
  6312. else
  6313. #endif
  6314. print_job_timer.start();
  6315. }
  6316. /**
  6317. * M25: Pause SD Print
  6318. */
  6319. inline void gcode_M25() {
  6320. card.pauseSDPrint();
  6321. print_job_timer.pause();
  6322. #if ENABLED(PARK_HEAD_ON_PAUSE)
  6323. enqueue_and_echo_commands_P(PSTR("M125")); // Must be enqueued with pauseSDPrint set to be last in the buffer
  6324. #endif
  6325. }
  6326. /**
  6327. * M26: Set SD Card file index
  6328. */
  6329. inline void gcode_M26() {
  6330. if (card.cardOK && parser.seenval('S'))
  6331. card.setIndex(parser.value_long());
  6332. }
  6333. /**
  6334. * M27: Get SD Card status
  6335. * OR, with 'S<seconds>' set the SD status auto-report interval. (Requires AUTO_REPORT_SD_STATUS)
  6336. * OR, with 'C' get the current filename.
  6337. */
  6338. inline void gcode_M27() {
  6339. if (parser.seen('C')) {
  6340. SERIAL_ECHOPGM("Current file: ");
  6341. card.printFilename();
  6342. }
  6343. #if ENABLED(AUTO_REPORT_SD_STATUS)
  6344. else if (parser.seenval('S'))
  6345. card.set_auto_report_interval(parser.value_byte());
  6346. #endif
  6347. else
  6348. card.getStatus();
  6349. }
  6350. /**
  6351. * M28: Start SD Write
  6352. */
  6353. inline void gcode_M28() { card.openFile(parser.string_arg, false); }
  6354. /**
  6355. * M29: Stop SD Write
  6356. * Processed in write to file routine above
  6357. */
  6358. inline void gcode_M29() {
  6359. // card.saving = false;
  6360. }
  6361. /**
  6362. * M30 <filename>: Delete SD Card file
  6363. */
  6364. inline void gcode_M30() {
  6365. if (card.cardOK) {
  6366. card.closefile();
  6367. card.removeFile(parser.string_arg);
  6368. }
  6369. }
  6370. #endif // SDSUPPORT
  6371. /**
  6372. * M31: Get the time since the start of SD Print (or last M109)
  6373. */
  6374. inline void gcode_M31() {
  6375. char buffer[21];
  6376. duration_t elapsed = print_job_timer.duration();
  6377. elapsed.toString(buffer);
  6378. lcd_setstatus(buffer);
  6379. SERIAL_ECHO_START();
  6380. SERIAL_ECHOLNPAIR("Print time: ", buffer);
  6381. }
  6382. #if ENABLED(SDSUPPORT)
  6383. /**
  6384. * M32: Select file and start SD Print
  6385. *
  6386. * Examples:
  6387. *
  6388. * M32 !PATH/TO/FILE.GCO# ; Start FILE.GCO
  6389. * M32 P !PATH/TO/FILE.GCO# ; Start FILE.GCO as a procedure
  6390. * M32 S60 !PATH/TO/FILE.GCO# ; Start FILE.GCO at byte 60
  6391. *
  6392. */
  6393. inline void gcode_M32() {
  6394. if (card.sdprinting) planner.synchronize();
  6395. if (card.cardOK) {
  6396. const bool call_procedure = parser.boolval('P');
  6397. card.openFile(parser.string_arg, true, call_procedure);
  6398. if (parser.seenval('S')) card.setIndex(parser.value_long());
  6399. card.startFileprint();
  6400. // Procedure calls count as normal print time.
  6401. if (!call_procedure) print_job_timer.start();
  6402. }
  6403. }
  6404. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  6405. /**
  6406. * M33: Get the long full path of a file or folder
  6407. *
  6408. * Parameters:
  6409. * <dospath> Case-insensitive DOS-style path to a file or folder
  6410. *
  6411. * Example:
  6412. * M33 miscel~1/armchair/armcha~1.gco
  6413. *
  6414. * Output:
  6415. * /Miscellaneous/Armchair/Armchair.gcode
  6416. */
  6417. inline void gcode_M33() {
  6418. card.printLongPath(parser.string_arg);
  6419. }
  6420. #endif
  6421. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  6422. /**
  6423. * M34: Set SD Card Sorting Options
  6424. */
  6425. inline void gcode_M34() {
  6426. if (parser.seen('S')) card.setSortOn(parser.value_bool());
  6427. if (parser.seenval('F')) {
  6428. const int v = parser.value_long();
  6429. card.setSortFolders(v < 0 ? -1 : v > 0 ? 1 : 0);
  6430. }
  6431. //if (parser.seen('R')) card.setSortReverse(parser.value_bool());
  6432. }
  6433. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  6434. /**
  6435. * M928: Start SD Write
  6436. */
  6437. inline void gcode_M928() {
  6438. card.openLogFile(parser.string_arg);
  6439. }
  6440. #endif // SDSUPPORT
  6441. /**
  6442. * Sensitive pin test for M42, M226
  6443. */
  6444. static bool pin_is_protected(const pin_t pin) {
  6445. static const pin_t sensitive_pins[] PROGMEM = SENSITIVE_PINS;
  6446. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++)
  6447. if (pin == (pin_t)pgm_read_byte(&sensitive_pins[i])) return true;
  6448. return false;
  6449. }
  6450. inline void protected_pin_err() {
  6451. SERIAL_ERROR_START();
  6452. SERIAL_ERRORLNPGM(MSG_ERR_PROTECTED_PIN);
  6453. }
  6454. /**
  6455. * M42: Change pin status via GCode
  6456. *
  6457. * P<pin> Pin number (LED if omitted)
  6458. * S<byte> Pin status from 0 - 255
  6459. * I Flag to ignore Marlin's pin protection
  6460. */
  6461. inline void gcode_M42() {
  6462. if (!parser.seenval('S')) return;
  6463. const byte pin_status = parser.value_byte();
  6464. const pin_t pin_number = parser.byteval('P', LED_PIN);
  6465. if (pin_number < 0) return;
  6466. if (!parser.boolval('I') && pin_is_protected(pin_number)) return protected_pin_err();
  6467. pinMode(pin_number, OUTPUT);
  6468. digitalWrite(pin_number, pin_status);
  6469. analogWrite(pin_number, pin_status);
  6470. #if FAN_COUNT > 0
  6471. switch (pin_number) {
  6472. #if HAS_FAN0
  6473. case FAN_PIN: fanSpeeds[0] = pin_status; break;
  6474. #endif
  6475. #if HAS_FAN1
  6476. case FAN1_PIN: fanSpeeds[1] = pin_status; break;
  6477. #endif
  6478. #if HAS_FAN2
  6479. case FAN2_PIN: fanSpeeds[2] = pin_status; break;
  6480. #endif
  6481. }
  6482. #endif
  6483. }
  6484. #if ENABLED(PINS_DEBUGGING)
  6485. #include "pinsDebug.h"
  6486. inline void toggle_pins() {
  6487. const bool ignore_protection = parser.boolval('I');
  6488. const int repeat = parser.intval('R', 1),
  6489. start = parser.intval('S'),
  6490. end = parser.intval('L', NUM_DIGITAL_PINS - 1),
  6491. wait = parser.intval('W', 500);
  6492. for (uint8_t pin = start; pin <= end; pin++) {
  6493. //report_pin_state_extended(pin, ignore_protection, false);
  6494. if (!ignore_protection && pin_is_protected(pin)) {
  6495. report_pin_state_extended(pin, ignore_protection, true, "Untouched ");
  6496. SERIAL_EOL();
  6497. }
  6498. else {
  6499. report_pin_state_extended(pin, ignore_protection, true, "Pulsing ");
  6500. #if AVR_AT90USB1286_FAMILY // Teensy IDEs don't know about these pins so must use FASTIO
  6501. if (pin == TEENSY_E2) {
  6502. SET_OUTPUT(TEENSY_E2);
  6503. for (int16_t j = 0; j < repeat; j++) {
  6504. WRITE(TEENSY_E2, LOW); safe_delay(wait);
  6505. WRITE(TEENSY_E2, HIGH); safe_delay(wait);
  6506. WRITE(TEENSY_E2, LOW); safe_delay(wait);
  6507. }
  6508. }
  6509. else if (pin == TEENSY_E3) {
  6510. SET_OUTPUT(TEENSY_E3);
  6511. for (int16_t j = 0; j < repeat; j++) {
  6512. WRITE(TEENSY_E3, LOW); safe_delay(wait);
  6513. WRITE(TEENSY_E3, HIGH); safe_delay(wait);
  6514. WRITE(TEENSY_E3, LOW); safe_delay(wait);
  6515. }
  6516. }
  6517. else
  6518. #endif
  6519. {
  6520. pinMode(pin, OUTPUT);
  6521. for (int16_t j = 0; j < repeat; j++) {
  6522. digitalWrite(pin, 0); safe_delay(wait);
  6523. digitalWrite(pin, 1); safe_delay(wait);
  6524. digitalWrite(pin, 0); safe_delay(wait);
  6525. }
  6526. }
  6527. }
  6528. SERIAL_EOL();
  6529. }
  6530. SERIAL_ECHOLNPGM("Done.");
  6531. } // toggle_pins
  6532. inline void servo_probe_test() {
  6533. #if !(NUM_SERVOS > 0 && HAS_SERVO_0)
  6534. SERIAL_ERROR_START();
  6535. SERIAL_ERRORLNPGM("SERVO not setup");
  6536. #elif !HAS_Z_SERVO_PROBE
  6537. SERIAL_ERROR_START();
  6538. SERIAL_ERRORLNPGM("Z_PROBE_SERVO_NR not setup");
  6539. #else // HAS_Z_SERVO_PROBE
  6540. const uint8_t probe_index = parser.byteval('P', Z_PROBE_SERVO_NR);
  6541. SERIAL_PROTOCOLLNPGM("Servo probe test");
  6542. SERIAL_PROTOCOLLNPAIR(". using index: ", probe_index);
  6543. SERIAL_PROTOCOLLNPAIR(". deploy angle: ", z_servo_angle[0]);
  6544. SERIAL_PROTOCOLLNPAIR(". stow angle: ", z_servo_angle[1]);
  6545. bool probe_inverting;
  6546. #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN)
  6547. #define PROBE_TEST_PIN Z_MIN_PIN
  6548. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN pin: ", PROBE_TEST_PIN);
  6549. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_ENDSTOP_INVERTING (ignores Z_MIN_PROBE_ENDSTOP_INVERTING)");
  6550. SERIAL_PROTOCOLPGM(". Z_MIN_ENDSTOP_INVERTING: ");
  6551. #if Z_MIN_ENDSTOP_INVERTING
  6552. SERIAL_PROTOCOLLNPGM("true");
  6553. #else
  6554. SERIAL_PROTOCOLLNPGM("false");
  6555. #endif
  6556. probe_inverting = Z_MIN_ENDSTOP_INVERTING;
  6557. #elif ENABLED(Z_MIN_PROBE_ENDSTOP)
  6558. #define PROBE_TEST_PIN Z_MIN_PROBE_PIN
  6559. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN_PROBE_PIN: ", PROBE_TEST_PIN);
  6560. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_PROBE_ENDSTOP_INVERTING (ignores Z_MIN_ENDSTOP_INVERTING)");
  6561. SERIAL_PROTOCOLPGM(". Z_MIN_PROBE_ENDSTOP_INVERTING: ");
  6562. #if Z_MIN_PROBE_ENDSTOP_INVERTING
  6563. SERIAL_PROTOCOLLNPGM("true");
  6564. #else
  6565. SERIAL_PROTOCOLLNPGM("false");
  6566. #endif
  6567. probe_inverting = Z_MIN_PROBE_ENDSTOP_INVERTING;
  6568. #endif
  6569. SERIAL_PROTOCOLLNPGM(". deploy & stow 4 times");
  6570. SET_INPUT_PULLUP(PROBE_TEST_PIN);
  6571. bool deploy_state, stow_state;
  6572. for (uint8_t i = 0; i < 4; i++) {
  6573. MOVE_SERVO(probe_index, z_servo_angle[0]); //deploy
  6574. safe_delay(500);
  6575. deploy_state = READ(PROBE_TEST_PIN);
  6576. MOVE_SERVO(probe_index, z_servo_angle[1]); //stow
  6577. safe_delay(500);
  6578. stow_state = READ(PROBE_TEST_PIN);
  6579. }
  6580. if (probe_inverting != deploy_state) SERIAL_PROTOCOLLNPGM("WARNING - INVERTING setting probably backwards");
  6581. if (deploy_state != stow_state) {
  6582. SERIAL_PROTOCOLLNPGM("BLTouch clone detected");
  6583. if (deploy_state) {
  6584. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: HIGH (logic 1)");
  6585. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: LOW (logic 0)");
  6586. }
  6587. else {
  6588. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: LOW (logic 0)");
  6589. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: HIGH (logic 1)");
  6590. }
  6591. #if ENABLED(BLTOUCH)
  6592. SERIAL_PROTOCOLLNPGM("ERROR: BLTOUCH enabled - set this device up as a Z Servo Probe with inverting as true.");
  6593. #endif
  6594. }
  6595. else { // measure active signal length
  6596. MOVE_SERVO(probe_index, z_servo_angle[0]); // deploy
  6597. safe_delay(500);
  6598. SERIAL_PROTOCOLLNPGM("please trigger probe");
  6599. uint16_t probe_counter = 0;
  6600. // Allow 30 seconds max for operator to trigger probe
  6601. for (uint16_t j = 0; j < 500 * 30 && probe_counter == 0 ; j++) {
  6602. safe_delay(2);
  6603. if (0 == j % (500 * 1)) reset_stepper_timeout(); // Keep steppers powered
  6604. if (deploy_state != READ(PROBE_TEST_PIN)) { // probe triggered
  6605. for (probe_counter = 1; probe_counter < 50 && deploy_state != READ(PROBE_TEST_PIN); ++probe_counter)
  6606. safe_delay(2);
  6607. if (probe_counter == 50)
  6608. SERIAL_PROTOCOLLNPGM("Z Servo Probe detected"); // >= 100mS active time
  6609. else if (probe_counter >= 2)
  6610. SERIAL_PROTOCOLLNPAIR("BLTouch compatible probe detected - pulse width (+/- 4mS): ", probe_counter * 2); // allow 4 - 100mS pulse
  6611. else
  6612. SERIAL_PROTOCOLLNPGM("noise detected - please re-run test"); // less than 2mS pulse
  6613. MOVE_SERVO(probe_index, z_servo_angle[1]); //stow
  6614. } // pulse detected
  6615. } // for loop waiting for trigger
  6616. if (probe_counter == 0) SERIAL_PROTOCOLLNPGM("trigger not detected");
  6617. } // measure active signal length
  6618. #endif
  6619. } // servo_probe_test
  6620. /**
  6621. * M43: Pin debug - report pin state, watch pins, toggle pins and servo probe test/report
  6622. *
  6623. * M43 - report name and state of pin(s)
  6624. * P<pin> Pin to read or watch. If omitted, reads all pins.
  6625. * I Flag to ignore Marlin's pin protection.
  6626. *
  6627. * M43 W - Watch pins -reporting changes- until reset, click, or M108.
  6628. * P<pin> Pin to read or watch. If omitted, read/watch all pins.
  6629. * I Flag to ignore Marlin's pin protection.
  6630. *
  6631. * M43 E<bool> - Enable / disable background endstop monitoring
  6632. * - Machine continues to operate
  6633. * - Reports changes to endstops
  6634. * - Toggles LED_PIN when an endstop changes
  6635. * - Can not reliably catch the 5mS pulse from BLTouch type probes
  6636. *
  6637. * M43 T - Toggle pin(s) and report which pin is being toggled
  6638. * S<pin> - Start Pin number. If not given, will default to 0
  6639. * L<pin> - End Pin number. If not given, will default to last pin defined for this board
  6640. * I<bool> - Flag to ignore Marlin's pin protection. Use with caution!!!!
  6641. * R - Repeat pulses on each pin this number of times before continueing to next pin
  6642. * W - Wait time (in miliseconds) between pulses. If not given will default to 500
  6643. *
  6644. * M43 S - Servo probe test
  6645. * P<index> - Probe index (optional - defaults to 0
  6646. */
  6647. inline void gcode_M43() {
  6648. if (parser.seen('T')) { // must be first or else its "S" and "E" parameters will execute endstop or servo test
  6649. toggle_pins();
  6650. return;
  6651. }
  6652. // Enable or disable endstop monitoring
  6653. if (parser.seen('E')) {
  6654. endstops.monitor_flag = parser.value_bool();
  6655. SERIAL_PROTOCOLPGM("endstop monitor ");
  6656. serialprintPGM(endstops.monitor_flag ? PSTR("en") : PSTR("dis"));
  6657. SERIAL_PROTOCOLLNPGM("abled");
  6658. return;
  6659. }
  6660. if (parser.seen('S')) {
  6661. servo_probe_test();
  6662. return;
  6663. }
  6664. // Get the range of pins to test or watch
  6665. const pin_t first_pin = parser.byteval('P'),
  6666. last_pin = parser.seenval('P') ? first_pin : NUM_DIGITAL_PINS - 1;
  6667. if (first_pin > last_pin) return;
  6668. const bool ignore_protection = parser.boolval('I');
  6669. // Watch until click, M108, or reset
  6670. if (parser.boolval('W')) {
  6671. SERIAL_PROTOCOLLNPGM("Watching pins");
  6672. byte pin_state[last_pin - first_pin + 1];
  6673. for (pin_t pin = first_pin; pin <= last_pin; pin++) {
  6674. if (!ignore_protection && pin_is_protected(pin)) continue;
  6675. pinMode(pin, INPUT_PULLUP);
  6676. delay(1);
  6677. /*
  6678. if (IS_ANALOG(pin))
  6679. pin_state[pin - first_pin] = analogRead(pin - analogInputToDigitalPin(0)); // int16_t pin_state[...]
  6680. else
  6681. //*/
  6682. pin_state[pin - first_pin] = digitalRead(pin);
  6683. }
  6684. #if HAS_RESUME_CONTINUE
  6685. wait_for_user = true;
  6686. KEEPALIVE_STATE(PAUSED_FOR_USER);
  6687. #endif
  6688. for (;;) {
  6689. for (pin_t pin = first_pin; pin <= last_pin; pin++) {
  6690. if (!ignore_protection && pin_is_protected(pin)) continue;
  6691. const byte val =
  6692. /*
  6693. IS_ANALOG(pin)
  6694. ? analogRead(pin - analogInputToDigitalPin(0)) : // int16_t val
  6695. :
  6696. //*/
  6697. digitalRead(pin);
  6698. if (val != pin_state[pin - first_pin]) {
  6699. report_pin_state_extended(pin, ignore_protection, false);
  6700. pin_state[pin - first_pin] = val;
  6701. }
  6702. }
  6703. #if HAS_RESUME_CONTINUE
  6704. if (!wait_for_user) {
  6705. KEEPALIVE_STATE(IN_HANDLER);
  6706. break;
  6707. }
  6708. #endif
  6709. safe_delay(200);
  6710. }
  6711. return;
  6712. }
  6713. // Report current state of selected pin(s)
  6714. for (pin_t pin = first_pin; pin <= last_pin; pin++)
  6715. report_pin_state_extended(pin, ignore_protection, true);
  6716. }
  6717. #endif // PINS_DEBUGGING
  6718. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  6719. /**
  6720. * M48: Z probe repeatability measurement function.
  6721. *
  6722. * Usage:
  6723. * M48 <P#> <X#> <Y#> <V#> <E> <L#> <S>
  6724. * P = Number of sampled points (4-50, default 10)
  6725. * X = Sample X position
  6726. * Y = Sample Y position
  6727. * V = Verbose level (0-4, default=1)
  6728. * E = Engage Z probe for each reading
  6729. * L = Number of legs of movement before probe
  6730. * S = Schizoid (Or Star if you prefer)
  6731. *
  6732. * This function requires the machine to be homed before invocation.
  6733. */
  6734. inline void gcode_M48() {
  6735. if (axis_unhomed_error()) return;
  6736. const int8_t verbose_level = parser.byteval('V', 1);
  6737. if (!WITHIN(verbose_level, 0, 4)) {
  6738. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  6739. return;
  6740. }
  6741. if (verbose_level > 0)
  6742. SERIAL_PROTOCOLLNPGM("M48 Z-Probe Repeatability Test");
  6743. const int8_t n_samples = parser.byteval('P', 10);
  6744. if (!WITHIN(n_samples, 4, 50)) {
  6745. SERIAL_PROTOCOLLNPGM("?Sample size not plausible (4-50).");
  6746. return;
  6747. }
  6748. const ProbePtRaise raise_after = parser.boolval('E') ? PROBE_PT_STOW : PROBE_PT_RAISE;
  6749. float X_current = current_position[X_AXIS],
  6750. Y_current = current_position[Y_AXIS];
  6751. const float X_probe_location = parser.linearval('X', X_current + X_PROBE_OFFSET_FROM_EXTRUDER),
  6752. Y_probe_location = parser.linearval('Y', Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER);
  6753. if (!position_is_reachable_by_probe(X_probe_location, Y_probe_location)) {
  6754. SERIAL_PROTOCOLLNPGM("? (X,Y) out of bounds.");
  6755. return;
  6756. }
  6757. bool seen_L = parser.seen('L');
  6758. uint8_t n_legs = seen_L ? parser.value_byte() : 0;
  6759. if (n_legs > 15) {
  6760. SERIAL_PROTOCOLLNPGM("?Number of legs in movement not plausible (0-15).");
  6761. return;
  6762. }
  6763. if (n_legs == 1) n_legs = 2;
  6764. const bool schizoid_flag = parser.boolval('S');
  6765. if (schizoid_flag && !seen_L) n_legs = 7;
  6766. /**
  6767. * Now get everything to the specified probe point So we can safely do a
  6768. * probe to get us close to the bed. If the Z-Axis is far from the bed,
  6769. * we don't want to use that as a starting point for each probe.
  6770. */
  6771. if (verbose_level > 2)
  6772. SERIAL_PROTOCOLLNPGM("Positioning the probe...");
  6773. // Disable bed level correction in M48 because we want the raw data when we probe
  6774. #if HAS_LEVELING
  6775. const bool was_enabled = planner.leveling_active;
  6776. set_bed_leveling_enabled(false);
  6777. #endif
  6778. setup_for_endstop_or_probe_move();
  6779. float mean = 0.0, sigma = 0.0, min = 99999.9, max = -99999.9, sample_set[n_samples];
  6780. // Move to the first point, deploy, and probe
  6781. const float t = probe_pt(X_probe_location, Y_probe_location, raise_after, verbose_level);
  6782. bool probing_good = !isnan(t);
  6783. if (probing_good) {
  6784. randomSeed(millis());
  6785. for (uint8_t n = 0; n < n_samples; n++) {
  6786. if (n_legs) {
  6787. const int dir = (random(0, 10) > 5.0) ? -1 : 1; // clockwise or counter clockwise
  6788. float angle = random(0.0, 360.0);
  6789. const float radius = random(
  6790. #if ENABLED(DELTA)
  6791. 0.1250000000 * (DELTA_PRINTABLE_RADIUS),
  6792. 0.3333333333 * (DELTA_PRINTABLE_RADIUS)
  6793. #else
  6794. 5.0, 0.125 * MIN(X_BED_SIZE, Y_BED_SIZE)
  6795. #endif
  6796. );
  6797. if (verbose_level > 3) {
  6798. SERIAL_ECHOPAIR("Starting radius: ", radius);
  6799. SERIAL_ECHOPAIR(" angle: ", angle);
  6800. SERIAL_ECHOPGM(" Direction: ");
  6801. if (dir > 0) SERIAL_ECHOPGM("Counter-");
  6802. SERIAL_ECHOLNPGM("Clockwise");
  6803. }
  6804. for (uint8_t l = 0; l < n_legs - 1; l++) {
  6805. float delta_angle;
  6806. if (schizoid_flag)
  6807. // The points of a 5 point star are 72 degrees apart. We need to
  6808. // skip a point and go to the next one on the star.
  6809. delta_angle = dir * 2.0 * 72.0;
  6810. else
  6811. // If we do this line, we are just trying to move further
  6812. // around the circle.
  6813. delta_angle = dir * (float) random(25, 45);
  6814. angle += delta_angle;
  6815. while (angle > 360.0) // We probably do not need to keep the angle between 0 and 2*PI, but the
  6816. angle -= 360.0; // Arduino documentation says the trig functions should not be given values
  6817. while (angle < 0.0) // outside of this range. It looks like they behave correctly with
  6818. angle += 360.0; // numbers outside of the range, but just to be safe we clamp them.
  6819. X_current = X_probe_location - (X_PROBE_OFFSET_FROM_EXTRUDER) + cos(RADIANS(angle)) * radius;
  6820. Y_current = Y_probe_location - (Y_PROBE_OFFSET_FROM_EXTRUDER) + sin(RADIANS(angle)) * radius;
  6821. #if DISABLED(DELTA)
  6822. X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
  6823. Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
  6824. #else
  6825. // If we have gone out too far, we can do a simple fix and scale the numbers
  6826. // back in closer to the origin.
  6827. while (!position_is_reachable_by_probe(X_current, Y_current)) {
  6828. X_current *= 0.8;
  6829. Y_current *= 0.8;
  6830. if (verbose_level > 3) {
  6831. SERIAL_ECHOPAIR("Pulling point towards center:", X_current);
  6832. SERIAL_ECHOLNPAIR(", ", Y_current);
  6833. }
  6834. }
  6835. #endif
  6836. if (verbose_level > 3) {
  6837. SERIAL_PROTOCOLPGM("Going to:");
  6838. SERIAL_ECHOPAIR(" X", X_current);
  6839. SERIAL_ECHOPAIR(" Y", Y_current);
  6840. SERIAL_ECHOLNPAIR(" Z", current_position[Z_AXIS]);
  6841. }
  6842. do_blocking_move_to_xy(X_current, Y_current);
  6843. } // n_legs loop
  6844. } // n_legs
  6845. // Probe a single point
  6846. sample_set[n] = probe_pt(X_probe_location, Y_probe_location, raise_after);
  6847. // Break the loop if the probe fails
  6848. probing_good = !isnan(sample_set[n]);
  6849. if (!probing_good) break;
  6850. /**
  6851. * Get the current mean for the data points we have so far
  6852. */
  6853. float sum = 0.0;
  6854. for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
  6855. mean = sum / (n + 1);
  6856. NOMORE(min, sample_set[n]);
  6857. NOLESS(max, sample_set[n]);
  6858. /**
  6859. * Now, use that mean to calculate the standard deviation for the
  6860. * data points we have so far
  6861. */
  6862. sum = 0.0;
  6863. for (uint8_t j = 0; j <= n; j++)
  6864. sum += sq(sample_set[j] - mean);
  6865. sigma = SQRT(sum / (n + 1));
  6866. if (verbose_level > 0) {
  6867. if (verbose_level > 1) {
  6868. SERIAL_PROTOCOL(n + 1);
  6869. SERIAL_PROTOCOLPGM(" of ");
  6870. SERIAL_PROTOCOL(int(n_samples));
  6871. SERIAL_PROTOCOLPGM(": z: ");
  6872. SERIAL_PROTOCOL_F(sample_set[n], 3);
  6873. if (verbose_level > 2) {
  6874. SERIAL_PROTOCOLPGM(" mean: ");
  6875. SERIAL_PROTOCOL_F(mean, 4);
  6876. SERIAL_PROTOCOLPGM(" sigma: ");
  6877. SERIAL_PROTOCOL_F(sigma, 6);
  6878. SERIAL_PROTOCOLPGM(" min: ");
  6879. SERIAL_PROTOCOL_F(min, 3);
  6880. SERIAL_PROTOCOLPGM(" max: ");
  6881. SERIAL_PROTOCOL_F(max, 3);
  6882. SERIAL_PROTOCOLPGM(" range: ");
  6883. SERIAL_PROTOCOL_F(max-min, 3);
  6884. }
  6885. SERIAL_EOL();
  6886. }
  6887. }
  6888. } // n_samples loop
  6889. }
  6890. STOW_PROBE();
  6891. if (probing_good) {
  6892. SERIAL_PROTOCOLLNPGM("Finished!");
  6893. if (verbose_level > 0) {
  6894. SERIAL_PROTOCOLPGM("Mean: ");
  6895. SERIAL_PROTOCOL_F(mean, 6);
  6896. SERIAL_PROTOCOLPGM(" Min: ");
  6897. SERIAL_PROTOCOL_F(min, 3);
  6898. SERIAL_PROTOCOLPGM(" Max: ");
  6899. SERIAL_PROTOCOL_F(max, 3);
  6900. SERIAL_PROTOCOLPGM(" Range: ");
  6901. SERIAL_PROTOCOL_F(max-min, 3);
  6902. SERIAL_EOL();
  6903. }
  6904. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  6905. SERIAL_PROTOCOL_F(sigma, 6);
  6906. SERIAL_EOL();
  6907. SERIAL_EOL();
  6908. }
  6909. clean_up_after_endstop_or_probe_move();
  6910. // Re-enable bed level correction if it had been on
  6911. #if HAS_LEVELING
  6912. set_bed_leveling_enabled(was_enabled);
  6913. #endif
  6914. #ifdef Z_AFTER_PROBING
  6915. move_z_after_probing();
  6916. #endif
  6917. report_current_position();
  6918. }
  6919. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  6920. #if ENABLED(G26_MESH_VALIDATION)
  6921. inline void gcode_M49() {
  6922. g26_debug_flag ^= true;
  6923. SERIAL_PROTOCOLPGM("G26 Debug ");
  6924. serialprintPGM(g26_debug_flag ? PSTR("on.\n") : PSTR("off.\n"));
  6925. }
  6926. #endif // G26_MESH_VALIDATION
  6927. #if ENABLED(ULTRA_LCD) && ENABLED(LCD_SET_PROGRESS_MANUALLY)
  6928. /**
  6929. * M73: Set percentage complete (for display on LCD)
  6930. *
  6931. * Example:
  6932. * M73 P25 ; Set progress to 25%
  6933. *
  6934. * Notes:
  6935. * This has no effect during an SD print job
  6936. */
  6937. inline void gcode_M73() {
  6938. if (!IS_SD_PRINTING() && parser.seen('P')) {
  6939. progress_bar_percent = parser.value_byte();
  6940. NOMORE(progress_bar_percent, 100);
  6941. }
  6942. }
  6943. #endif // ULTRA_LCD && LCD_SET_PROGRESS_MANUALLY
  6944. /**
  6945. * M75: Start print timer
  6946. */
  6947. inline void gcode_M75() { print_job_timer.start(); }
  6948. /**
  6949. * M76: Pause print timer
  6950. */
  6951. inline void gcode_M76() { print_job_timer.pause(); }
  6952. /**
  6953. * M77: Stop print timer
  6954. */
  6955. inline void gcode_M77() { print_job_timer.stop(); }
  6956. #if ENABLED(PRINTCOUNTER)
  6957. /**
  6958. * M78: Show print statistics
  6959. */
  6960. inline void gcode_M78() {
  6961. // "M78 S78" will reset the statistics
  6962. if (parser.intval('S') == 78)
  6963. print_job_timer.initStats();
  6964. else
  6965. print_job_timer.showStats();
  6966. }
  6967. #endif
  6968. /**
  6969. * M104: Set hot end temperature
  6970. */
  6971. inline void gcode_M104() {
  6972. if (get_target_extruder_from_command(104)) return;
  6973. if (DEBUGGING(DRYRUN)) return;
  6974. #if ENABLED(SINGLENOZZLE)
  6975. if (target_extruder != active_extruder) return;
  6976. #endif
  6977. if (parser.seenval('S')) {
  6978. const int16_t temp = parser.value_celsius();
  6979. thermalManager.setTargetHotend(temp, target_extruder);
  6980. #if ENABLED(DUAL_X_CARRIAGE)
  6981. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  6982. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  6983. #endif
  6984. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  6985. /**
  6986. * Stop the timer at the end of print. Start is managed by 'heat and wait' M109.
  6987. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot
  6988. * standby mode, for instance in a dual extruder setup, without affecting
  6989. * the running print timer.
  6990. */
  6991. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  6992. print_job_timer.stop();
  6993. lcd_reset_status();
  6994. }
  6995. #endif
  6996. }
  6997. #if ENABLED(AUTOTEMP)
  6998. planner.autotemp_M104_M109();
  6999. #endif
  7000. }
  7001. /**
  7002. * M105: Read hot end and bed temperature
  7003. */
  7004. inline void gcode_M105() {
  7005. if (get_target_extruder_from_command(105)) return;
  7006. #if HAS_TEMP_SENSOR
  7007. SERIAL_PROTOCOLPGM(MSG_OK);
  7008. thermalManager.print_heaterstates();
  7009. #else // !HAS_TEMP_SENSOR
  7010. SERIAL_ERROR_START();
  7011. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  7012. #endif
  7013. SERIAL_EOL();
  7014. }
  7015. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  7016. /**
  7017. * M155: Set temperature auto-report interval. M155 S<seconds>
  7018. */
  7019. inline void gcode_M155() {
  7020. if (parser.seenval('S'))
  7021. thermalManager.set_auto_report_interval(parser.value_byte());
  7022. }
  7023. #endif // AUTO_REPORT_TEMPERATURES
  7024. #if FAN_COUNT > 0
  7025. /**
  7026. * M106: Set Fan Speed
  7027. *
  7028. * S<int> Speed between 0-255
  7029. * P<index> Fan index, if more than one fan
  7030. *
  7031. * With EXTRA_FAN_SPEED enabled:
  7032. *
  7033. * T<int> Restore/Use/Set Temporary Speed:
  7034. * 1 = Restore previous speed after T2
  7035. * 2 = Use temporary speed set with T3-255
  7036. * 3-255 = Set the speed for use with T2
  7037. */
  7038. inline void gcode_M106() {
  7039. const uint8_t p = parser.byteval('P');
  7040. if (p < FAN_COUNT) {
  7041. #if ENABLED(EXTRA_FAN_SPEED)
  7042. const int16_t t = parser.intval('T');
  7043. if (t > 0) {
  7044. switch (t) {
  7045. case 1:
  7046. fanSpeeds[p] = old_fanSpeeds[p];
  7047. break;
  7048. case 2:
  7049. old_fanSpeeds[p] = fanSpeeds[p];
  7050. fanSpeeds[p] = new_fanSpeeds[p];
  7051. break;
  7052. default:
  7053. new_fanSpeeds[p] = MIN(t, 255);
  7054. break;
  7055. }
  7056. return;
  7057. }
  7058. #endif // EXTRA_FAN_SPEED
  7059. const uint16_t s = parser.ushortval('S', 255);
  7060. fanSpeeds[p] = MIN(s, 255U);
  7061. }
  7062. }
  7063. /**
  7064. * M107: Fan Off
  7065. */
  7066. inline void gcode_M107() {
  7067. const uint16_t p = parser.ushortval('P');
  7068. if (p < FAN_COUNT) fanSpeeds[p] = 0;
  7069. }
  7070. #endif // FAN_COUNT > 0
  7071. #if DISABLED(EMERGENCY_PARSER)
  7072. /**
  7073. * M108: Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature.
  7074. */
  7075. inline void gcode_M108() { wait_for_heatup = false; }
  7076. /**
  7077. * M112: Emergency Stop
  7078. */
  7079. inline void gcode_M112() { kill(PSTR(MSG_KILLED)); }
  7080. /**
  7081. * M410: Quickstop - Abort all planned moves
  7082. *
  7083. * This will stop the carriages mid-move, so most likely they
  7084. * will be out of sync with the stepper position after this.
  7085. */
  7086. inline void gcode_M410() { quickstop_stepper(); }
  7087. #endif
  7088. /**
  7089. * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating.
  7090. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling.
  7091. */
  7092. #ifndef MIN_COOLING_SLOPE_DEG
  7093. #define MIN_COOLING_SLOPE_DEG 1.50
  7094. #endif
  7095. #ifndef MIN_COOLING_SLOPE_TIME
  7096. #define MIN_COOLING_SLOPE_TIME 60
  7097. #endif
  7098. inline void gcode_M109() {
  7099. if (get_target_extruder_from_command(109)) return;
  7100. if (DEBUGGING(DRYRUN)) return;
  7101. #if ENABLED(SINGLENOZZLE)
  7102. if (target_extruder != active_extruder) return;
  7103. #endif
  7104. const bool no_wait_for_cooling = parser.seenval('S'),
  7105. set_temp = no_wait_for_cooling || parser.seenval('R');
  7106. if (set_temp) {
  7107. const int16_t temp = parser.value_celsius();
  7108. thermalManager.setTargetHotend(temp, target_extruder);
  7109. #if ENABLED(DUAL_X_CARRIAGE)
  7110. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  7111. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  7112. #endif
  7113. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  7114. /**
  7115. * Use half EXTRUDE_MINTEMP to allow nozzles to be put into hot
  7116. * standby mode, (e.g., in a dual extruder setup) without affecting
  7117. * the running print timer.
  7118. */
  7119. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  7120. print_job_timer.stop();
  7121. lcd_reset_status();
  7122. }
  7123. else
  7124. print_job_timer.start();
  7125. #endif
  7126. #if ENABLED(ULTRA_LCD)
  7127. const bool heating = thermalManager.isHeatingHotend(target_extruder);
  7128. if (heating || !no_wait_for_cooling)
  7129. #if HOTENDS > 1
  7130. lcd_status_printf_P(0, heating ? PSTR("E%i " MSG_HEATING) : PSTR("E%i " MSG_COOLING), target_extruder + 1);
  7131. #else
  7132. lcd_setstatusPGM(heating ? PSTR("E " MSG_HEATING) : PSTR("E " MSG_COOLING));
  7133. #endif
  7134. #endif
  7135. }
  7136. #if ENABLED(AUTOTEMP)
  7137. planner.autotemp_M104_M109();
  7138. #endif
  7139. if (!set_temp) return;
  7140. #if TEMP_RESIDENCY_TIME > 0
  7141. millis_t residency_start_ms = 0;
  7142. // Loop until the temperature has stabilized
  7143. #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL))
  7144. #else
  7145. // Loop until the temperature is very close target
  7146. #define TEMP_CONDITIONS (wants_to_cool ? thermalManager.isCoolingHotend(target_extruder) : thermalManager.isHeatingHotend(target_extruder))
  7147. #endif
  7148. float target_temp = -1, old_temp = 9999;
  7149. bool wants_to_cool = false;
  7150. wait_for_heatup = true;
  7151. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  7152. #if DISABLED(BUSY_WHILE_HEATING)
  7153. KEEPALIVE_STATE(NOT_BUSY);
  7154. #endif
  7155. #if ENABLED(PRINTER_EVENT_LEDS)
  7156. const float start_temp = thermalManager.degHotend(target_extruder);
  7157. uint8_t old_blue = 0;
  7158. #endif
  7159. do {
  7160. // Target temperature might be changed during the loop
  7161. if (target_temp != thermalManager.degTargetHotend(target_extruder)) {
  7162. wants_to_cool = thermalManager.isCoolingHotend(target_extruder);
  7163. target_temp = thermalManager.degTargetHotend(target_extruder);
  7164. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  7165. if (no_wait_for_cooling && wants_to_cool) break;
  7166. }
  7167. now = millis();
  7168. if (ELAPSED(now, next_temp_ms)) { //Print temp & remaining time every 1s while waiting
  7169. next_temp_ms = now + 1000UL;
  7170. thermalManager.print_heaterstates();
  7171. #if TEMP_RESIDENCY_TIME > 0
  7172. SERIAL_PROTOCOLPGM(" W:");
  7173. if (residency_start_ms)
  7174. SERIAL_PROTOCOL(long((((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL));
  7175. else
  7176. SERIAL_PROTOCOLCHAR('?');
  7177. #endif
  7178. SERIAL_EOL();
  7179. }
  7180. idle();
  7181. reset_stepper_timeout(); // Keep steppers powered
  7182. const float temp = thermalManager.degHotend(target_extruder);
  7183. #if ENABLED(PRINTER_EVENT_LEDS)
  7184. // Gradually change LED strip from violet to red as nozzle heats up
  7185. if (!wants_to_cool) {
  7186. const uint8_t blue = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 255, 0);
  7187. if (blue != old_blue) {
  7188. old_blue = blue;
  7189. leds.set_color(
  7190. MakeLEDColor(255, 0, blue, 0, pixels.getBrightness())
  7191. #if ENABLED(NEOPIXEL_IS_SEQUENTIAL)
  7192. , true
  7193. #endif
  7194. );
  7195. }
  7196. }
  7197. #endif
  7198. #if TEMP_RESIDENCY_TIME > 0
  7199. const float temp_diff = ABS(target_temp - temp);
  7200. if (!residency_start_ms) {
  7201. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  7202. if (temp_diff < TEMP_WINDOW) residency_start_ms = now;
  7203. }
  7204. else if (temp_diff > TEMP_HYSTERESIS) {
  7205. // Restart the timer whenever the temperature falls outside the hysteresis.
  7206. residency_start_ms = now;
  7207. }
  7208. #endif
  7209. // Prevent a wait-forever situation if R is misused i.e. M109 R0
  7210. if (wants_to_cool) {
  7211. // break after MIN_COOLING_SLOPE_TIME seconds
  7212. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG
  7213. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  7214. if (old_temp - temp < float(MIN_COOLING_SLOPE_DEG)) break;
  7215. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME;
  7216. old_temp = temp;
  7217. }
  7218. }
  7219. } while (wait_for_heatup && TEMP_CONDITIONS);
  7220. if (wait_for_heatup) {
  7221. lcd_reset_status();
  7222. #if ENABLED(PRINTER_EVENT_LEDS)
  7223. leds.set_white();
  7224. #endif
  7225. }
  7226. #if DISABLED(BUSY_WHILE_HEATING)
  7227. KEEPALIVE_STATE(IN_HANDLER);
  7228. #endif
  7229. }
  7230. #if HAS_HEATED_BED
  7231. /**
  7232. * M140: Set bed temperature
  7233. */
  7234. inline void gcode_M140() {
  7235. if (DEBUGGING(DRYRUN)) return;
  7236. if (parser.seenval('S')) thermalManager.setTargetBed(parser.value_celsius());
  7237. }
  7238. #ifndef MIN_COOLING_SLOPE_DEG_BED
  7239. #define MIN_COOLING_SLOPE_DEG_BED 1.50
  7240. #endif
  7241. #ifndef MIN_COOLING_SLOPE_TIME_BED
  7242. #define MIN_COOLING_SLOPE_TIME_BED 60
  7243. #endif
  7244. /**
  7245. * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  7246. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  7247. */
  7248. inline void gcode_M190() {
  7249. if (DEBUGGING(DRYRUN)) return;
  7250. const bool no_wait_for_cooling = parser.seenval('S');
  7251. if (no_wait_for_cooling || parser.seenval('R')) {
  7252. thermalManager.setTargetBed(parser.value_celsius());
  7253. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  7254. if (parser.value_celsius() > BED_MINTEMP)
  7255. print_job_timer.start();
  7256. #endif
  7257. }
  7258. else return;
  7259. lcd_setstatusPGM(thermalManager.isHeatingBed() ? PSTR(MSG_BED_HEATING) : PSTR(MSG_BED_COOLING));
  7260. #if TEMP_BED_RESIDENCY_TIME > 0
  7261. millis_t residency_start_ms = 0;
  7262. // Loop until the temperature has stabilized
  7263. #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_BED_RESIDENCY_TIME) * 1000UL))
  7264. #else
  7265. // Loop until the temperature is very close target
  7266. #define TEMP_BED_CONDITIONS (wants_to_cool ? thermalManager.isCoolingBed() : thermalManager.isHeatingBed())
  7267. #endif
  7268. float target_temp = -1.0, old_temp = 9999.0;
  7269. bool wants_to_cool = false;
  7270. wait_for_heatup = true;
  7271. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  7272. #if DISABLED(BUSY_WHILE_HEATING)
  7273. KEEPALIVE_STATE(NOT_BUSY);
  7274. #endif
  7275. target_extruder = active_extruder; // for print_heaterstates
  7276. #if ENABLED(PRINTER_EVENT_LEDS)
  7277. const float start_temp = thermalManager.degBed();
  7278. uint8_t old_red = 127;
  7279. #endif
  7280. do {
  7281. // Target temperature might be changed during the loop
  7282. if (target_temp != thermalManager.degTargetBed()) {
  7283. wants_to_cool = thermalManager.isCoolingBed();
  7284. target_temp = thermalManager.degTargetBed();
  7285. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  7286. if (no_wait_for_cooling && wants_to_cool) break;
  7287. }
  7288. now = millis();
  7289. if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up.
  7290. next_temp_ms = now + 1000UL;
  7291. thermalManager.print_heaterstates();
  7292. #if TEMP_BED_RESIDENCY_TIME > 0
  7293. SERIAL_PROTOCOLPGM(" W:");
  7294. if (residency_start_ms)
  7295. SERIAL_PROTOCOL(long((((TEMP_BED_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL));
  7296. else
  7297. SERIAL_PROTOCOLCHAR('?');
  7298. #endif
  7299. SERIAL_EOL();
  7300. }
  7301. idle();
  7302. reset_stepper_timeout(); // Keep steppers powered
  7303. const float temp = thermalManager.degBed();
  7304. #if ENABLED(PRINTER_EVENT_LEDS)
  7305. // Gradually change LED strip from blue to violet as bed heats up
  7306. if (!wants_to_cool) {
  7307. const uint8_t red = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 0, 255);
  7308. if (red != old_red) {
  7309. old_red = red;
  7310. leds.set_color(
  7311. MakeLEDColor(red, 0, 255, 0, pixels.getBrightness())
  7312. #if ENABLED(NEOPIXEL_IS_SEQUENTIAL)
  7313. , true
  7314. #endif
  7315. );
  7316. }
  7317. }
  7318. #endif
  7319. #if TEMP_BED_RESIDENCY_TIME > 0
  7320. const float temp_diff = ABS(target_temp - temp);
  7321. if (!residency_start_ms) {
  7322. // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time.
  7323. if (temp_diff < TEMP_BED_WINDOW) residency_start_ms = now;
  7324. }
  7325. else if (temp_diff > TEMP_BED_HYSTERESIS) {
  7326. // Restart the timer whenever the temperature falls outside the hysteresis.
  7327. residency_start_ms = now;
  7328. }
  7329. #endif // TEMP_BED_RESIDENCY_TIME > 0
  7330. // Prevent a wait-forever situation if R is misused i.e. M190 R0
  7331. if (wants_to_cool) {
  7332. // Break after MIN_COOLING_SLOPE_TIME_BED seconds
  7333. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED
  7334. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  7335. if (old_temp - temp < float(MIN_COOLING_SLOPE_DEG_BED)) break;
  7336. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME_BED;
  7337. old_temp = temp;
  7338. }
  7339. }
  7340. } while (wait_for_heatup && TEMP_BED_CONDITIONS);
  7341. if (wait_for_heatup) lcd_reset_status();
  7342. #if DISABLED(BUSY_WHILE_HEATING)
  7343. KEEPALIVE_STATE(IN_HANDLER);
  7344. #endif
  7345. }
  7346. #endif // HAS_HEATED_BED
  7347. /**
  7348. * M110: Set Current Line Number
  7349. */
  7350. inline void gcode_M110() {
  7351. if (parser.seenval('N')) gcode_LastN = parser.value_long();
  7352. }
  7353. /**
  7354. * M111: Set the debug level
  7355. */
  7356. inline void gcode_M111() {
  7357. if (parser.seen('S')) marlin_debug_flags = parser.byteval('S');
  7358. static const char str_debug_1[] PROGMEM = MSG_DEBUG_ECHO,
  7359. str_debug_2[] PROGMEM = MSG_DEBUG_INFO,
  7360. str_debug_4[] PROGMEM = MSG_DEBUG_ERRORS,
  7361. str_debug_8[] PROGMEM = MSG_DEBUG_DRYRUN,
  7362. str_debug_16[] PROGMEM = MSG_DEBUG_COMMUNICATION
  7363. #if ENABLED(DEBUG_LEVELING_FEATURE)
  7364. , str_debug_32[] PROGMEM = MSG_DEBUG_LEVELING
  7365. #endif
  7366. ;
  7367. static const char* const debug_strings[] PROGMEM = {
  7368. str_debug_1, str_debug_2, str_debug_4, str_debug_8, str_debug_16
  7369. #if ENABLED(DEBUG_LEVELING_FEATURE)
  7370. , str_debug_32
  7371. #endif
  7372. };
  7373. SERIAL_ECHO_START();
  7374. SERIAL_ECHOPGM(MSG_DEBUG_PREFIX);
  7375. if (marlin_debug_flags) {
  7376. uint8_t comma = 0;
  7377. for (uint8_t i = 0; i < COUNT(debug_strings); i++) {
  7378. if (TEST(marlin_debug_flags, i)) {
  7379. if (comma++) SERIAL_CHAR(',');
  7380. serialprintPGM((char*)pgm_read_ptr(&debug_strings[i]));
  7381. }
  7382. }
  7383. }
  7384. else {
  7385. SERIAL_ECHOPGM(MSG_DEBUG_OFF);
  7386. #if !defined(__AVR__) || !defined(USBCON)
  7387. #if ENABLED(SERIAL_STATS_RX_BUFFER_OVERRUNS)
  7388. SERIAL_ECHOPAIR("\nBuffer Overruns: ", customizedSerial.buffer_overruns());
  7389. #endif
  7390. #if ENABLED(SERIAL_STATS_RX_FRAMING_ERRORS)
  7391. SERIAL_ECHOPAIR("\nFraming Errors: ", customizedSerial.framing_errors());
  7392. #endif
  7393. #if ENABLED(SERIAL_STATS_DROPPED_RX)
  7394. SERIAL_ECHOPAIR("\nDropped bytes: ", customizedSerial.dropped());
  7395. #endif
  7396. #if ENABLED(SERIAL_STATS_MAX_RX_QUEUED)
  7397. SERIAL_ECHOPAIR("\nMax RX Queue Size: ", customizedSerial.rxMaxEnqueued());
  7398. #endif
  7399. #endif // !__AVR__ || !USBCON
  7400. }
  7401. SERIAL_EOL();
  7402. }
  7403. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  7404. /**
  7405. * M113: Get or set Host Keepalive interval (0 to disable)
  7406. *
  7407. * S<seconds> Optional. Set the keepalive interval.
  7408. */
  7409. inline void gcode_M113() {
  7410. if (parser.seenval('S')) {
  7411. host_keepalive_interval = parser.value_byte();
  7412. NOMORE(host_keepalive_interval, 60);
  7413. }
  7414. else {
  7415. SERIAL_ECHO_START();
  7416. SERIAL_ECHOLNPAIR("M113 S", (unsigned long)host_keepalive_interval);
  7417. }
  7418. }
  7419. #endif
  7420. #if ENABLED(BARICUDA)
  7421. #if HAS_HEATER_1
  7422. /**
  7423. * M126: Heater 1 valve open
  7424. */
  7425. inline void gcode_M126() { baricuda_valve_pressure = parser.byteval('S', 255); }
  7426. /**
  7427. * M127: Heater 1 valve close
  7428. */
  7429. inline void gcode_M127() { baricuda_valve_pressure = 0; }
  7430. #endif
  7431. #if HAS_HEATER_2
  7432. /**
  7433. * M128: Heater 2 valve open
  7434. */
  7435. inline void gcode_M128() { baricuda_e_to_p_pressure = parser.byteval('S', 255); }
  7436. /**
  7437. * M129: Heater 2 valve close
  7438. */
  7439. inline void gcode_M129() { baricuda_e_to_p_pressure = 0; }
  7440. #endif
  7441. #endif // BARICUDA
  7442. #if ENABLED(ULTIPANEL)
  7443. /**
  7444. * M145: Set the heatup state for a material in the LCD menu
  7445. *
  7446. * S<material> (0=PLA, 1=ABS)
  7447. * H<hotend temp>
  7448. * B<bed temp>
  7449. * F<fan speed>
  7450. */
  7451. inline void gcode_M145() {
  7452. const uint8_t material = (uint8_t)parser.intval('S');
  7453. if (material >= COUNT(lcd_preheat_hotend_temp)) {
  7454. SERIAL_ERROR_START();
  7455. SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX);
  7456. }
  7457. else {
  7458. int v;
  7459. if (parser.seenval('H')) {
  7460. v = parser.value_int();
  7461. lcd_preheat_hotend_temp[material] = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  7462. }
  7463. if (parser.seenval('F')) {
  7464. v = parser.value_int();
  7465. lcd_preheat_fan_speed[material] = constrain(v, 0, 255);
  7466. }
  7467. #if TEMP_SENSOR_BED != 0
  7468. if (parser.seenval('B')) {
  7469. v = parser.value_int();
  7470. lcd_preheat_bed_temp[material] = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  7471. }
  7472. #endif
  7473. }
  7474. }
  7475. #endif // ULTIPANEL
  7476. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  7477. /**
  7478. * M149: Set temperature units
  7479. */
  7480. inline void gcode_M149() {
  7481. if (parser.seenval('C')) parser.set_input_temp_units(TEMPUNIT_C);
  7482. else if (parser.seenval('K')) parser.set_input_temp_units(TEMPUNIT_K);
  7483. else if (parser.seenval('F')) parser.set_input_temp_units(TEMPUNIT_F);
  7484. }
  7485. #endif
  7486. #if HAS_POWER_SWITCH
  7487. /**
  7488. * M80 : Turn on the Power Supply
  7489. * M80 S : Report the current state and exit
  7490. */
  7491. inline void gcode_M80() {
  7492. // S: Report the current power supply state and exit
  7493. if (parser.seen('S')) {
  7494. serialprintPGM(powersupply_on ? PSTR("PS:1\n") : PSTR("PS:0\n"));
  7495. return;
  7496. }
  7497. PSU_ON();
  7498. /**
  7499. * If you have a switch on suicide pin, this is useful
  7500. * if you want to start another print with suicide feature after
  7501. * a print without suicide...
  7502. */
  7503. #if HAS_SUICIDE
  7504. OUT_WRITE(SUICIDE_PIN, HIGH);
  7505. #endif
  7506. #if DISABLED(AUTO_POWER_CONTROL)
  7507. delay(100); // Wait for power to settle
  7508. restore_stepper_drivers();
  7509. #endif
  7510. #if ENABLED(ULTIPANEL)
  7511. lcd_reset_status();
  7512. #endif
  7513. }
  7514. #endif // HAS_POWER_SWITCH
  7515. /**
  7516. * M81: Turn off Power, including Power Supply, if there is one.
  7517. *
  7518. * This code should ALWAYS be available for EMERGENCY SHUTDOWN!
  7519. */
  7520. inline void gcode_M81() {
  7521. thermalManager.disable_all_heaters();
  7522. planner.finish_and_disable();
  7523. #if FAN_COUNT > 0
  7524. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  7525. #if ENABLED(PROBING_FANS_OFF)
  7526. fans_paused = false;
  7527. ZERO(paused_fanSpeeds);
  7528. #endif
  7529. #endif
  7530. safe_delay(1000); // Wait 1 second before switching off
  7531. #if HAS_SUICIDE
  7532. suicide();
  7533. #elif HAS_POWER_SWITCH
  7534. PSU_OFF();
  7535. #endif
  7536. #if ENABLED(ULTIPANEL)
  7537. LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF ".");
  7538. #endif
  7539. }
  7540. /**
  7541. * M82: Set E codes absolute (default)
  7542. */
  7543. inline void gcode_M82() { axis_relative_modes[E_CART] = false; }
  7544. /**
  7545. * M83: Set E codes relative while in Absolute Coordinates (G90) mode
  7546. */
  7547. inline void gcode_M83() { axis_relative_modes[E_CART] = true; }
  7548. /**
  7549. * M18, M84: Disable stepper motors
  7550. */
  7551. inline void gcode_M18_M84() {
  7552. if (parser.seenval('S')) {
  7553. stepper_inactive_time = parser.value_millis_from_seconds();
  7554. }
  7555. else {
  7556. bool all_axis = !(parser.seen('X') || parser.seen('Y') || parser.seen('Z') || parser.seen('E'));
  7557. if (all_axis) {
  7558. planner.finish_and_disable();
  7559. }
  7560. else {
  7561. planner.synchronize();
  7562. if (parser.seen('X')) disable_X();
  7563. if (parser.seen('Y')) disable_Y();
  7564. if (parser.seen('Z')) disable_Z();
  7565. #if E0_ENABLE_PIN != X_ENABLE_PIN && E1_ENABLE_PIN != Y_ENABLE_PIN // Only disable on boards that have separate ENABLE_PINS
  7566. if (parser.seen('E')) disable_e_steppers();
  7567. #endif
  7568. }
  7569. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(ULTIPANEL) // Only needed with an LCD
  7570. if (ubl.lcd_map_control) ubl.lcd_map_control = defer_return_to_status = false;
  7571. #endif
  7572. }
  7573. }
  7574. /**
  7575. * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  7576. */
  7577. inline void gcode_M85() {
  7578. if (parser.seen('S')) max_inactive_time = parser.value_millis_from_seconds();
  7579. }
  7580. /**
  7581. * Multi-stepper support for M92, M201, M203
  7582. */
  7583. #if ENABLED(DISTINCT_E_FACTORS)
  7584. #define GET_TARGET_EXTRUDER(CMD) if (get_target_extruder_from_command(CMD)) return
  7585. #define TARGET_EXTRUDER target_extruder
  7586. #else
  7587. #define GET_TARGET_EXTRUDER(CMD) NOOP
  7588. #define TARGET_EXTRUDER 0
  7589. #endif
  7590. /**
  7591. * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E.
  7592. * (for Hangprinter: A, B, C, D, and E)
  7593. * (Follows the same syntax as G92)
  7594. *
  7595. * With multiple extruders use T to specify which one.
  7596. */
  7597. inline void gcode_M92() {
  7598. GET_TARGET_EXTRUDER(92);
  7599. LOOP_NUM_AXIS(i) {
  7600. if (parser.seen(RAW_AXIS_CODES(i))) {
  7601. if (i == E_AXIS) {
  7602. const float value = parser.value_per_axis_unit((AxisEnum)(E_AXIS + TARGET_EXTRUDER));
  7603. if (value < 20) {
  7604. const float factor = planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] / value; // increase e constants if M92 E14 is given for netfab.
  7605. #if DISABLED(JUNCTION_DEVIATION)
  7606. planner.max_jerk[E_AXIS] *= factor;
  7607. #endif
  7608. planner.max_feedrate_mm_s[E_AXIS + TARGET_EXTRUDER] *= factor;
  7609. planner.max_acceleration_steps_per_s2[E_AXIS + TARGET_EXTRUDER] *= factor;
  7610. }
  7611. planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] = value;
  7612. }
  7613. else {
  7614. #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
  7615. SERIAL_ECHOLNPGM("Warning: "
  7616. "M92 A, B, C, and D only affect acceleration planning "
  7617. "when BUILDUP_COMPENSATION_FEATURE is enabled.");
  7618. #endif
  7619. planner.axis_steps_per_mm[i] = parser.value_per_axis_unit((AxisEnum)i);
  7620. }
  7621. }
  7622. }
  7623. planner.refresh_positioning();
  7624. }
  7625. /**
  7626. * Output the current position to serial
  7627. */
  7628. void report_current_position() {
  7629. SERIAL_PROTOCOLPAIR("X:", LOGICAL_X_POSITION(current_position[X_AXIS]));
  7630. SERIAL_PROTOCOLPAIR(" Y:", LOGICAL_Y_POSITION(current_position[Y_AXIS]));
  7631. SERIAL_PROTOCOLPAIR(" Z:", LOGICAL_Z_POSITION(current_position[Z_AXIS]));
  7632. SERIAL_PROTOCOLPAIR(" E:", current_position[E_CART]);
  7633. #if ENABLED(HANGPRINTER)
  7634. SERIAL_EOL();
  7635. SERIAL_PROTOCOLPAIR("A:", line_lengths[A_AXIS]);
  7636. SERIAL_PROTOCOLPAIR(" B:", line_lengths[B_AXIS]);
  7637. SERIAL_PROTOCOLPAIR(" C:", line_lengths[C_AXIS]);
  7638. SERIAL_PROTOCOLLNPAIR(" D:", line_lengths[D_AXIS]);
  7639. #endif
  7640. stepper.report_positions();
  7641. #if IS_SCARA
  7642. SERIAL_PROTOCOLPAIR("SCARA Theta:", planner.get_axis_position_degrees(A_AXIS));
  7643. SERIAL_PROTOCOLLNPAIR(" Psi+Theta:", planner.get_axis_position_degrees(B_AXIS));
  7644. SERIAL_EOL();
  7645. #endif
  7646. }
  7647. #ifdef M114_DETAIL
  7648. void report_xyze(const float pos[], const uint8_t n = 4, const uint8_t precision = 3) {
  7649. char str[12];
  7650. for (uint8_t i = 0; i < n; i++) {
  7651. SERIAL_CHAR(' ');
  7652. SERIAL_CHAR(axis_codes[i]);
  7653. SERIAL_CHAR(':');
  7654. SERIAL_PROTOCOL(dtostrf(pos[i], 8, precision, str));
  7655. }
  7656. SERIAL_EOL();
  7657. }
  7658. inline void report_xyz(const float pos[]) { report_xyze(pos, 3); }
  7659. void report_current_position_detail() {
  7660. SERIAL_PROTOCOLPGM("\nLogical:");
  7661. const float logical[XYZ] = {
  7662. LOGICAL_X_POSITION(current_position[X_AXIS]),
  7663. LOGICAL_Y_POSITION(current_position[Y_AXIS]),
  7664. LOGICAL_Z_POSITION(current_position[Z_AXIS])
  7665. };
  7666. report_xyz(logical);
  7667. SERIAL_PROTOCOLPGM("Raw: ");
  7668. report_xyz(current_position);
  7669. float leveled[XYZ] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  7670. #if PLANNER_LEVELING
  7671. SERIAL_PROTOCOLPGM("Leveled:");
  7672. planner.apply_leveling(leveled);
  7673. report_xyz(leveled);
  7674. SERIAL_PROTOCOLPGM("UnLevel:");
  7675. float unleveled[XYZ] = { leveled[X_AXIS], leveled[Y_AXIS], leveled[Z_AXIS] };
  7676. planner.unapply_leveling(unleveled);
  7677. report_xyz(unleveled);
  7678. #endif
  7679. #if IS_KINEMATIC
  7680. #if IS_SCARA
  7681. SERIAL_PROTOCOLPGM("ScaraK: ");
  7682. #else
  7683. SERIAL_PROTOCOLPGM("DeltaK: ");
  7684. #endif
  7685. inverse_kinematics(leveled); // writes delta[]
  7686. report_xyz(delta);
  7687. #endif
  7688. planner.synchronize();
  7689. SERIAL_PROTOCOLPGM("Stepper:");
  7690. LOOP_NUM_AXIS(i) {
  7691. SERIAL_CHAR(' ');
  7692. SERIAL_CHAR(RAW_AXIS_CODES(i));
  7693. SERIAL_CHAR(':');
  7694. SERIAL_PROTOCOL(stepper.position((AxisEnum)i));
  7695. }
  7696. SERIAL_EOL();
  7697. #if IS_SCARA
  7698. const float deg[XYZ] = {
  7699. planner.get_axis_position_degrees(A_AXIS),
  7700. planner.get_axis_position_degrees(B_AXIS)
  7701. };
  7702. SERIAL_PROTOCOLPGM("Degrees:");
  7703. report_xyze(deg, 2);
  7704. #endif
  7705. SERIAL_PROTOCOLPGM("FromStp:");
  7706. get_cartesian_from_steppers(); // writes cartes[XYZ] (with forward kinematics)
  7707. const float from_steppers[XYZE] = { cartes[X_AXIS], cartes[Y_AXIS], cartes[Z_AXIS], planner.get_axis_position_mm(E_AXIS) };
  7708. report_xyze(from_steppers);
  7709. const float diff[XYZE] = {
  7710. from_steppers[X_AXIS] - leveled[X_AXIS],
  7711. from_steppers[Y_AXIS] - leveled[Y_AXIS],
  7712. from_steppers[Z_AXIS] - leveled[Z_AXIS],
  7713. from_steppers[E_CART] - current_position[E_CART]
  7714. };
  7715. SERIAL_PROTOCOLPGM("Differ: ");
  7716. report_xyze(diff);
  7717. }
  7718. #endif // M114_DETAIL
  7719. /**
  7720. * M114: Report current position to host
  7721. */
  7722. inline void gcode_M114() {
  7723. #ifdef M114_DETAIL
  7724. if (parser.seen('D')) return report_current_position_detail();
  7725. #endif
  7726. planner.synchronize();
  7727. const uint16_t sval = parser.ushortval('S');
  7728. #if ENABLED(MECHADUINO_I2C_COMMANDS)
  7729. if (sval == 1) return report_axis_position_from_encoder_data();
  7730. #endif
  7731. if (sval == 2) return report_xyz_from_stepper_position();
  7732. report_current_position();
  7733. }
  7734. /**
  7735. * M115: Capabilities string
  7736. */
  7737. #if ENABLED(EXTENDED_CAPABILITIES_REPORT)
  7738. static void cap_line(const char * const name, bool ena=false) {
  7739. SERIAL_PROTOCOLPGM("Cap:");
  7740. serialprintPGM(name);
  7741. SERIAL_PROTOCOLPGM(":");
  7742. SERIAL_PROTOCOLLN(int(ena ? 1 : 0));
  7743. }
  7744. #endif
  7745. inline void gcode_M115() {
  7746. SERIAL_PROTOCOLLNPGM(MSG_M115_REPORT);
  7747. #if ENABLED(EXTENDED_CAPABILITIES_REPORT)
  7748. // SERIAL_XON_XOFF
  7749. cap_line(PSTR("SERIAL_XON_XOFF")
  7750. #if ENABLED(SERIAL_XON_XOFF)
  7751. , true
  7752. #endif
  7753. );
  7754. // EEPROM (M500, M501)
  7755. cap_line(PSTR("EEPROM")
  7756. #if ENABLED(EEPROM_SETTINGS)
  7757. , true
  7758. #endif
  7759. );
  7760. // Volumetric Extrusion (M200)
  7761. cap_line(PSTR("VOLUMETRIC")
  7762. #if DISABLED(NO_VOLUMETRICS)
  7763. , true
  7764. #endif
  7765. );
  7766. // AUTOREPORT_TEMP (M155)
  7767. cap_line(PSTR("AUTOREPORT_TEMP")
  7768. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  7769. , true
  7770. #endif
  7771. );
  7772. // PROGRESS (M530 S L, M531 <file>, M532 X L)
  7773. cap_line(PSTR("PROGRESS"));
  7774. // Print Job timer M75, M76, M77
  7775. cap_line(PSTR("PRINT_JOB"), true);
  7776. // AUTOLEVEL (G29)
  7777. cap_line(PSTR("AUTOLEVEL")
  7778. #if HAS_AUTOLEVEL
  7779. , true
  7780. #endif
  7781. );
  7782. // Z_PROBE (G30)
  7783. cap_line(PSTR("Z_PROBE")
  7784. #if HAS_BED_PROBE
  7785. , true
  7786. #endif
  7787. );
  7788. // MESH_REPORT (M420 V)
  7789. cap_line(PSTR("LEVELING_DATA")
  7790. #if HAS_LEVELING
  7791. , true
  7792. #endif
  7793. );
  7794. // BUILD_PERCENT (M73)
  7795. cap_line(PSTR("BUILD_PERCENT")
  7796. #if ENABLED(LCD_SET_PROGRESS_MANUALLY)
  7797. , true
  7798. #endif
  7799. );
  7800. // SOFTWARE_POWER (M80, M81)
  7801. cap_line(PSTR("SOFTWARE_POWER")
  7802. #if HAS_POWER_SWITCH
  7803. , true
  7804. #endif
  7805. );
  7806. // CASE LIGHTS (M355)
  7807. cap_line(PSTR("TOGGLE_LIGHTS")
  7808. #if HAS_CASE_LIGHT
  7809. , true
  7810. #endif
  7811. );
  7812. cap_line(PSTR("CASE_LIGHT_BRIGHTNESS")
  7813. #if HAS_CASE_LIGHT
  7814. , USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)
  7815. #endif
  7816. );
  7817. // EMERGENCY_PARSER (M108, M112, M410)
  7818. cap_line(PSTR("EMERGENCY_PARSER")
  7819. #if ENABLED(EMERGENCY_PARSER)
  7820. , true
  7821. #endif
  7822. );
  7823. // AUTOREPORT_SD_STATUS (M27 extension)
  7824. cap_line(PSTR("AUTOREPORT_SD_STATUS")
  7825. #if ENABLED(AUTO_REPORT_SD_STATUS)
  7826. , true
  7827. #endif
  7828. );
  7829. // THERMAL_PROTECTION
  7830. cap_line(PSTR("THERMAL_PROTECTION")
  7831. #if ENABLED(THERMAL_PROTECTION_HOTENDS) && ENABLED(THERMAL_PROTECTION_BED)
  7832. , true
  7833. #endif
  7834. );
  7835. #endif // EXTENDED_CAPABILITIES_REPORT
  7836. }
  7837. /**
  7838. * M117: Set LCD Status Message
  7839. */
  7840. inline void gcode_M117() {
  7841. if (parser.string_arg[0])
  7842. lcd_setstatus(parser.string_arg);
  7843. else
  7844. lcd_reset_status();
  7845. }
  7846. /**
  7847. * M118: Display a message in the host console.
  7848. *
  7849. * A1 Prepend '// ' for an action command, as in OctoPrint
  7850. * E1 Have the host 'echo:' the text
  7851. */
  7852. inline void gcode_M118() {
  7853. bool hasE = false, hasA = false;
  7854. char *p = parser.string_arg;
  7855. for (uint8_t i = 2; i--;)
  7856. if ((p[0] == 'A' || p[0] == 'E') && p[1] == '1') {
  7857. if (p[0] == 'A') hasA = true;
  7858. if (p[0] == 'E') hasE = true;
  7859. p += 2;
  7860. while (*p == ' ') ++p;
  7861. }
  7862. if (hasE) SERIAL_ECHO_START();
  7863. if (hasA) SERIAL_ECHOPGM("// ");
  7864. SERIAL_ECHOLN(p);
  7865. }
  7866. /**
  7867. * M119: Output endstop states to serial output
  7868. */
  7869. inline void gcode_M119() { endstops.M119(); }
  7870. /**
  7871. * M120: Enable endstops and set non-homing endstop state to "enabled"
  7872. */
  7873. inline void gcode_M120() { endstops.enable_globally(true); }
  7874. /**
  7875. * M121: Disable endstops and set non-homing endstop state to "disabled"
  7876. */
  7877. inline void gcode_M121() { endstops.enable_globally(false); }
  7878. #if ENABLED(PARK_HEAD_ON_PAUSE)
  7879. /**
  7880. * M125: Store current position and move to filament change position.
  7881. * Called on pause (by M25) to prevent material leaking onto the
  7882. * object. On resume (M24) the head will be moved back and the
  7883. * print will resume.
  7884. *
  7885. * If Marlin is compiled without SD Card support, M125 can be
  7886. * used directly to pause the print and move to park position,
  7887. * resuming with a button click or M108.
  7888. *
  7889. * L = override retract length
  7890. * X = override X
  7891. * Y = override Y
  7892. * Z = override Z raise
  7893. */
  7894. inline void gcode_M125() {
  7895. // Initial retract before move to filament change position
  7896. const float retract = -ABS(parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0
  7897. #ifdef PAUSE_PARK_RETRACT_LENGTH
  7898. + (PAUSE_PARK_RETRACT_LENGTH)
  7899. #endif
  7900. );
  7901. point_t park_point = NOZZLE_PARK_POINT;
  7902. // Move XY axes to filament change position or given position
  7903. if (parser.seenval('X')) park_point.x = parser.linearval('X');
  7904. if (parser.seenval('Y')) park_point.y = parser.linearval('Y');
  7905. // Lift Z axis
  7906. if (parser.seenval('Z')) park_point.z = parser.linearval('Z');
  7907. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE) && DISABLED(DELTA)
  7908. park_point.x += (active_extruder ? hotend_offset[X_AXIS][active_extruder] : 0);
  7909. park_point.y += (active_extruder ? hotend_offset[Y_AXIS][active_extruder] : 0);
  7910. #endif
  7911. #if DISABLED(SDSUPPORT)
  7912. const bool job_running = print_job_timer.isRunning();
  7913. #endif
  7914. if (pause_print(retract, park_point)) {
  7915. #if DISABLED(SDSUPPORT)
  7916. // Wait for lcd click or M108
  7917. wait_for_filament_reload();
  7918. // Return to print position and continue
  7919. resume_print();
  7920. if (job_running) print_job_timer.start();
  7921. #endif
  7922. }
  7923. }
  7924. #endif // PARK_HEAD_ON_PAUSE
  7925. #if HAS_COLOR_LEDS
  7926. /**
  7927. * M150: Set Status LED Color - Use R-U-B-W for R-G-B-W
  7928. * and Brightness - Use P (for NEOPIXEL only)
  7929. *
  7930. * Always sets all 3 or 4 components. If a component is left out, set to 0.
  7931. * If brightness is left out, no value changed
  7932. *
  7933. * Examples:
  7934. *
  7935. * M150 R255 ; Turn LED red
  7936. * M150 R255 U127 ; Turn LED orange (PWM only)
  7937. * M150 ; Turn LED off
  7938. * M150 R U B ; Turn LED white
  7939. * M150 W ; Turn LED white using a white LED
  7940. * M150 P127 ; Set LED 50% brightness
  7941. * M150 P ; Set LED full brightness
  7942. */
  7943. inline void gcode_M150() {
  7944. leds.set_color(MakeLEDColor(
  7945. parser.seen('R') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  7946. parser.seen('U') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  7947. parser.seen('B') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  7948. parser.seen('W') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  7949. parser.seen('P') ? (parser.has_value() ? parser.value_byte() : 255) : pixels.getBrightness()
  7950. ));
  7951. }
  7952. #endif // HAS_COLOR_LEDS
  7953. #if DISABLED(NO_VOLUMETRICS)
  7954. /**
  7955. * M200: Set filament diameter and set E axis units to cubic units
  7956. *
  7957. * T<extruder> - Optional extruder number. Current extruder if omitted.
  7958. * D<linear> - Diameter of the filament. Use "D0" to switch back to linear units on the E axis.
  7959. */
  7960. inline void gcode_M200() {
  7961. if (get_target_extruder_from_command(200)) return;
  7962. if (parser.seen('D')) {
  7963. // setting any extruder filament size disables volumetric on the assumption that
  7964. // slicers either generate in extruder values as cubic mm or as as filament feeds
  7965. // for all extruders
  7966. if ( (parser.volumetric_enabled = (parser.value_linear_units() != 0)) )
  7967. planner.set_filament_size(target_extruder, parser.value_linear_units());
  7968. }
  7969. planner.calculate_volumetric_multipliers();
  7970. }
  7971. #endif // !NO_VOLUMETRICS
  7972. /**
  7973. * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  7974. *
  7975. * With multiple extruders use T to specify which one.
  7976. */
  7977. inline void gcode_M201() {
  7978. GET_TARGET_EXTRUDER(201);
  7979. LOOP_NUM_AXIS(i) {
  7980. if (parser.seen(RAW_AXIS_CODES(i))) {
  7981. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  7982. planner.max_acceleration_mm_per_s2[a] = parser.value_axis_units((AxisEnum)a);
  7983. }
  7984. }
  7985. // 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)
  7986. planner.reset_acceleration_rates();
  7987. }
  7988. #if 0 // Not used for Sprinter/grbl gen6
  7989. inline void gcode_M202() {
  7990. LOOP_XYZE(i) {
  7991. if (parser.seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = parser.value_axis_units((AxisEnum)i) * planner.axis_steps_per_mm[i];
  7992. }
  7993. }
  7994. #endif
  7995. /**
  7996. * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec
  7997. *
  7998. * With multiple extruders use T to specify which one.
  7999. */
  8000. inline void gcode_M203() {
  8001. GET_TARGET_EXTRUDER(203);
  8002. LOOP_NUM_AXIS(i)
  8003. if (parser.seen(RAW_AXIS_CODES(i))) {
  8004. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  8005. planner.max_feedrate_mm_s[a] = parser.value_axis_units((AxisEnum)a);
  8006. }
  8007. }
  8008. /**
  8009. * M204: Set Accelerations in units/sec^2 (M204 P1200 R3000 T3000)
  8010. *
  8011. * P = Printing moves
  8012. * R = Retract only (no X, Y, Z) moves
  8013. * T = Travel (non printing) moves
  8014. */
  8015. inline void gcode_M204() {
  8016. bool report = true;
  8017. if (parser.seenval('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments.
  8018. planner.travel_acceleration = planner.acceleration = parser.value_linear_units();
  8019. report = false;
  8020. }
  8021. if (parser.seenval('P')) {
  8022. planner.acceleration = parser.value_linear_units();
  8023. report = false;
  8024. }
  8025. if (parser.seenval('R')) {
  8026. planner.retract_acceleration = parser.value_linear_units();
  8027. report = false;
  8028. }
  8029. if (parser.seenval('T')) {
  8030. planner.travel_acceleration = parser.value_linear_units();
  8031. report = false;
  8032. }
  8033. if (report) {
  8034. SERIAL_ECHOPAIR("Acceleration: P", planner.acceleration);
  8035. SERIAL_ECHOPAIR(" R", planner.retract_acceleration);
  8036. SERIAL_ECHOLNPAIR(" T", planner.travel_acceleration);
  8037. }
  8038. }
  8039. /**
  8040. * M205: Set Advanced Settings
  8041. *
  8042. * Q = Min Segment Time (µs)
  8043. * S = Min Feed Rate (units/s)
  8044. * T = Min Travel Feed Rate (units/s)
  8045. * X = Max X Jerk (units/sec^2)
  8046. * Y = Max Y Jerk (units/sec^2)
  8047. * Z = Max Z Jerk (units/sec^2)
  8048. * E = Max E Jerk (units/sec^2)
  8049. * J = Junction Deviation (mm) (Requires JUNCTION_DEVIATION)
  8050. */
  8051. inline void gcode_M205() {
  8052. if (parser.seen('Q')) planner.min_segment_time_us = parser.value_ulong();
  8053. if (parser.seen('S')) planner.min_feedrate_mm_s = parser.value_linear_units();
  8054. if (parser.seen('T')) planner.min_travel_feedrate_mm_s = parser.value_linear_units();
  8055. #if ENABLED(JUNCTION_DEVIATION)
  8056. if (parser.seen('J')) {
  8057. const float junc_dev = parser.value_linear_units();
  8058. if (WITHIN(junc_dev, 0.01f, 0.3f)) {
  8059. planner.junction_deviation_mm = junc_dev;
  8060. planner.recalculate_max_e_jerk();
  8061. }
  8062. else {
  8063. SERIAL_ERROR_START();
  8064. SERIAL_ERRORLNPGM("?J out of range (0.01 to 0.3)");
  8065. }
  8066. }
  8067. #else
  8068. #if ENABLED(HANGPRINTER)
  8069. if (parser.seen('A')) planner.max_jerk[A_AXIS] = parser.value_linear_units();
  8070. if (parser.seen('B')) planner.max_jerk[B_AXIS] = parser.value_linear_units();
  8071. if (parser.seen('C')) planner.max_jerk[C_AXIS] = parser.value_linear_units();
  8072. if (parser.seen('D')) planner.max_jerk[D_AXIS] = parser.value_linear_units();
  8073. #else
  8074. if (parser.seen('X')) planner.max_jerk[X_AXIS] = parser.value_linear_units();
  8075. if (parser.seen('Y')) planner.max_jerk[Y_AXIS] = parser.value_linear_units();
  8076. if (parser.seen('Z')) {
  8077. planner.max_jerk[Z_AXIS] = parser.value_linear_units();
  8078. #if HAS_MESH
  8079. if (planner.max_jerk[Z_AXIS] <= 0.1f)
  8080. SERIAL_ECHOLNPGM("WARNING! Low Z Jerk may lead to unwanted pauses.");
  8081. #endif
  8082. }
  8083. #endif
  8084. if (parser.seen('E')) planner.max_jerk[E_AXIS] = parser.value_linear_units();
  8085. #endif
  8086. }
  8087. #if HAS_M206_COMMAND
  8088. /**
  8089. * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y
  8090. *
  8091. * *** @thinkyhead: I recommend deprecating M206 for SCARA in favor of M665.
  8092. * *** M206 for SCARA will remain enabled in 1.1.x for compatibility.
  8093. * *** In the next 1.2 release, it will simply be disabled by default.
  8094. */
  8095. inline void gcode_M206() {
  8096. LOOP_XYZ(i)
  8097. if (parser.seen(axis_codes[i]))
  8098. set_home_offset((AxisEnum)i, parser.value_linear_units());
  8099. #if ENABLED(MORGAN_SCARA)
  8100. if (parser.seen('T')) set_home_offset(A_AXIS, parser.value_float()); // Theta
  8101. if (parser.seen('P')) set_home_offset(B_AXIS, parser.value_float()); // Psi
  8102. #endif
  8103. report_current_position();
  8104. }
  8105. #endif // HAS_M206_COMMAND
  8106. #if ENABLED(DELTA)
  8107. /**
  8108. * M665: Set delta configurations
  8109. *
  8110. * H = delta height
  8111. * L = diagonal rod
  8112. * R = delta radius
  8113. * S = segments per second
  8114. * B = delta calibration radius
  8115. * X = Alpha (Tower 1) angle trim
  8116. * Y = Beta (Tower 2) angle trim
  8117. * Z = Gamma (Tower 3) angle trim
  8118. */
  8119. inline void gcode_M665() {
  8120. if (parser.seen('H')) delta_height = parser.value_linear_units();
  8121. if (parser.seen('L')) delta_diagonal_rod = parser.value_linear_units();
  8122. if (parser.seen('R')) delta_radius = parser.value_linear_units();
  8123. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  8124. if (parser.seen('B')) delta_calibration_radius = parser.value_float();
  8125. if (parser.seen('X')) delta_tower_angle_trim[A_AXIS] = parser.value_float();
  8126. if (parser.seen('Y')) delta_tower_angle_trim[B_AXIS] = parser.value_float();
  8127. if (parser.seen('Z')) delta_tower_angle_trim[C_AXIS] = parser.value_float();
  8128. recalc_delta_settings();
  8129. }
  8130. /**
  8131. * M666: Set delta endstop adjustment
  8132. */
  8133. inline void gcode_M666() {
  8134. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8135. if (DEBUGGING(LEVELING)) {
  8136. SERIAL_ECHOLNPGM(">>> gcode_M666");
  8137. }
  8138. #endif
  8139. LOOP_XYZ(i) {
  8140. if (parser.seen(axis_codes[i])) {
  8141. if (parser.value_linear_units() * Z_HOME_DIR <= 0)
  8142. delta_endstop_adj[i] = parser.value_linear_units();
  8143. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8144. if (DEBUGGING(LEVELING)) {
  8145. SERIAL_ECHOPAIR("delta_endstop_adj[", axis_codes[i]);
  8146. SERIAL_ECHOLNPAIR("] = ", delta_endstop_adj[i]);
  8147. }
  8148. #endif
  8149. }
  8150. }
  8151. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8152. if (DEBUGGING(LEVELING)) {
  8153. SERIAL_ECHOLNPGM("<<< gcode_M666");
  8154. }
  8155. #endif
  8156. }
  8157. #elif IS_SCARA
  8158. /**
  8159. * M665: Set SCARA settings
  8160. *
  8161. * Parameters:
  8162. *
  8163. * S[segments-per-second] - Segments-per-second
  8164. * P[theta-psi-offset] - Theta-Psi offset, added to the shoulder (A/X) angle
  8165. * T[theta-offset] - Theta offset, added to the elbow (B/Y) angle
  8166. *
  8167. * A, P, and X are all aliases for the shoulder angle
  8168. * B, T, and Y are all aliases for the elbow angle
  8169. */
  8170. inline void gcode_M665() {
  8171. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  8172. const bool hasA = parser.seen('A'), hasP = parser.seen('P'), hasX = parser.seen('X');
  8173. const uint8_t sumAPX = hasA + hasP + hasX;
  8174. if (sumAPX == 1)
  8175. home_offset[A_AXIS] = parser.value_float();
  8176. else if (sumAPX > 1) {
  8177. SERIAL_ERROR_START();
  8178. SERIAL_ERRORLNPGM("Only one of A, P, or X is allowed.");
  8179. return;
  8180. }
  8181. const bool hasB = parser.seen('B'), hasT = parser.seen('T'), hasY = parser.seen('Y');
  8182. const uint8_t sumBTY = hasB + hasT + hasY;
  8183. if (sumBTY == 1)
  8184. home_offset[B_AXIS] = parser.value_float();
  8185. else if (sumBTY > 1) {
  8186. SERIAL_ERROR_START();
  8187. SERIAL_ERRORLNPGM("Only one of B, T, or Y is allowed.");
  8188. return;
  8189. }
  8190. }
  8191. #elif ENABLED(HANGPRINTER)
  8192. /**
  8193. * M665: Set HANGPRINTER settings
  8194. *
  8195. * Parameters:
  8196. *
  8197. * W[anchor_A_y] - A-anchor's y coordinate (see note)
  8198. * E[anchor_A_z] - A-anchor's z coordinate (see note)
  8199. * R[anchor_B_x] - B-anchor's x coordinate (see note)
  8200. * T[anchor_B_y] - B-anchor's y coordinate (see note)
  8201. * Y[anchor_B_z] - B-anchor's z coordinate (see note)
  8202. * U[anchor_C_x] - C-anchor's x coordinate (see note)
  8203. * I[anchor_C_y] - C-anchor's y coordinate (see note)
  8204. * O[anchor_C_z] - C-anchor's z coordinate (see note)
  8205. * P[anchor_D_z] - D-anchor's z coordinate (see note)
  8206. * S[segments-per-second] - Segments-per-second
  8207. *
  8208. * Note: All xyz coordinates are measured relative to the line's pivot point in the mover,
  8209. * when it is at its home position (nozzle in (0,0,0), and lines tight).
  8210. * The y-axis is defined to be horizontal right above/below the A-lines when mover is at home.
  8211. * The z-axis is along the vertical direction.
  8212. */
  8213. inline void gcode_M665() {
  8214. if (parser.seen('W')) anchor_A_y = parser.value_float();
  8215. if (parser.seen('E')) anchor_A_z = parser.value_float();
  8216. if (parser.seen('R')) anchor_B_x = parser.value_float();
  8217. if (parser.seen('T')) anchor_B_y = parser.value_float();
  8218. if (parser.seen('Y')) anchor_B_z = parser.value_float();
  8219. if (parser.seen('U')) anchor_C_x = parser.value_float();
  8220. if (parser.seen('I')) anchor_C_y = parser.value_float();
  8221. if (parser.seen('O')) anchor_C_z = parser.value_float();
  8222. if (parser.seen('P')) anchor_D_z = parser.value_float();
  8223. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  8224. recalc_hangprinter_settings();
  8225. }
  8226. #elif ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS)
  8227. /**
  8228. * M666: Set Dual Endstops offsets for X, Y, and/or Z.
  8229. * With no parameters report current offsets.
  8230. */
  8231. inline void gcode_M666() {
  8232. bool report = true;
  8233. #if ENABLED(X_DUAL_ENDSTOPS)
  8234. if (parser.seenval('X')) {
  8235. endstops.x_endstop_adj = parser.value_linear_units();
  8236. report = false;
  8237. }
  8238. #endif
  8239. #if ENABLED(Y_DUAL_ENDSTOPS)
  8240. if (parser.seenval('Y')) {
  8241. endstops.y_endstop_adj = parser.value_linear_units();
  8242. report = false;
  8243. }
  8244. #endif
  8245. #if ENABLED(Z_DUAL_ENDSTOPS)
  8246. if (parser.seenval('Z')) {
  8247. endstops.z_endstop_adj = parser.value_linear_units();
  8248. report = false;
  8249. }
  8250. #endif
  8251. if (report) {
  8252. SERIAL_ECHOPGM("Dual Endstop Adjustment (mm): ");
  8253. #if ENABLED(X_DUAL_ENDSTOPS)
  8254. SERIAL_ECHOPAIR(" X", endstops.x_endstop_adj);
  8255. #endif
  8256. #if ENABLED(Y_DUAL_ENDSTOPS)
  8257. SERIAL_ECHOPAIR(" Y", endstops.y_endstop_adj);
  8258. #endif
  8259. #if ENABLED(Z_DUAL_ENDSTOPS)
  8260. SERIAL_ECHOPAIR(" Z", endstops.z_endstop_adj);
  8261. #endif
  8262. SERIAL_EOL();
  8263. }
  8264. }
  8265. #endif // X_DUAL_ENDSTOPS || Y_DUAL_ENDSTOPS || Z_DUAL_ENDSTOPS
  8266. #if ENABLED(FWRETRACT)
  8267. /**
  8268. * M207: Set firmware retraction values
  8269. *
  8270. * S[+units] retract_length
  8271. * W[+units] swap_retract_length (multi-extruder)
  8272. * F[units/min] retract_feedrate_mm_s
  8273. * Z[units] retract_zlift
  8274. */
  8275. inline void gcode_M207() {
  8276. if (parser.seen('S')) fwretract.retract_length = parser.value_axis_units(E_AXIS);
  8277. if (parser.seen('F')) fwretract.retract_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  8278. if (parser.seen('Z')) fwretract.retract_zlift = parser.value_linear_units();
  8279. if (parser.seen('W')) fwretract.swap_retract_length = parser.value_axis_units(E_AXIS);
  8280. }
  8281. /**
  8282. * M208: Set firmware un-retraction values
  8283. *
  8284. * S[+units] retract_recover_length (in addition to M207 S*)
  8285. * W[+units] swap_retract_recover_length (multi-extruder)
  8286. * F[units/min] retract_recover_feedrate_mm_s
  8287. * R[units/min] swap_retract_recover_feedrate_mm_s
  8288. */
  8289. inline void gcode_M208() {
  8290. if (parser.seen('S')) fwretract.retract_recover_length = parser.value_axis_units(E_AXIS);
  8291. if (parser.seen('F')) fwretract.retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  8292. if (parser.seen('R')) fwretract.swap_retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  8293. if (parser.seen('W')) fwretract.swap_retract_recover_length = parser.value_axis_units(E_AXIS);
  8294. }
  8295. /**
  8296. * M209: Enable automatic retract (M209 S1)
  8297. * For slicers that don't support G10/11, reversed extrude-only
  8298. * moves will be classified as retraction.
  8299. */
  8300. inline void gcode_M209() {
  8301. if (MIN_AUTORETRACT <= MAX_AUTORETRACT) {
  8302. if (parser.seen('S')) {
  8303. fwretract.autoretract_enabled = parser.value_bool();
  8304. for (uint8_t i = 0; i < EXTRUDERS; i++) fwretract.retracted[i] = false;
  8305. }
  8306. }
  8307. }
  8308. #endif // FWRETRACT
  8309. /**
  8310. * M211: Enable, Disable, and/or Report software endstops
  8311. *
  8312. * Usage: M211 S1 to enable, M211 S0 to disable, M211 alone for report
  8313. */
  8314. inline void gcode_M211() {
  8315. SERIAL_ECHO_START();
  8316. #if HAS_SOFTWARE_ENDSTOPS
  8317. if (parser.seen('S')) soft_endstops_enabled = parser.value_bool();
  8318. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  8319. serialprintPGM(soft_endstops_enabled ? PSTR(MSG_ON) : PSTR(MSG_OFF));
  8320. #else
  8321. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  8322. SERIAL_ECHOPGM(MSG_OFF);
  8323. #endif
  8324. SERIAL_ECHOPGM(MSG_SOFT_MIN);
  8325. SERIAL_ECHOPAIR( MSG_X, LOGICAL_X_POSITION(soft_endstop_min[X_AXIS]));
  8326. SERIAL_ECHOPAIR(" " MSG_Y, LOGICAL_Y_POSITION(soft_endstop_min[Y_AXIS]));
  8327. SERIAL_ECHOPAIR(" " MSG_Z, LOGICAL_Z_POSITION(soft_endstop_min[Z_AXIS]));
  8328. SERIAL_ECHOPGM(MSG_SOFT_MAX);
  8329. SERIAL_ECHOPAIR( MSG_X, LOGICAL_X_POSITION(soft_endstop_max[X_AXIS]));
  8330. SERIAL_ECHOPAIR(" " MSG_Y, LOGICAL_Y_POSITION(soft_endstop_max[Y_AXIS]));
  8331. SERIAL_ECHOLNPAIR(" " MSG_Z, LOGICAL_Z_POSITION(soft_endstop_max[Z_AXIS]));
  8332. }
  8333. #if HOTENDS > 1
  8334. /**
  8335. * M218 - Set/get hotend offset (in linear units)
  8336. *
  8337. * T<tool>
  8338. * X<xoffset>
  8339. * Y<yoffset>
  8340. * Z<zoffset> - Available with DUAL_X_CARRIAGE, SWITCHING_NOZZLE, and PARKING_EXTRUDER
  8341. */
  8342. inline void gcode_M218() {
  8343. if (get_target_extruder_from_command(218) || target_extruder == 0) return;
  8344. bool report = true;
  8345. if (parser.seenval('X')) {
  8346. hotend_offset[X_AXIS][target_extruder] = parser.value_linear_units();
  8347. report = false;
  8348. }
  8349. if (parser.seenval('Y')) {
  8350. hotend_offset[Y_AXIS][target_extruder] = parser.value_linear_units();
  8351. report = false;
  8352. }
  8353. #if HAS_HOTEND_OFFSET_Z
  8354. if (parser.seenval('Z')) {
  8355. hotend_offset[Z_AXIS][target_extruder] = parser.value_linear_units();
  8356. report = false;
  8357. }
  8358. #endif
  8359. if (report) {
  8360. SERIAL_ECHO_START();
  8361. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  8362. HOTEND_LOOP() {
  8363. SERIAL_CHAR(' ');
  8364. SERIAL_ECHO(hotend_offset[X_AXIS][e]);
  8365. SERIAL_CHAR(',');
  8366. SERIAL_ECHO(hotend_offset[Y_AXIS][e]);
  8367. #if HAS_HOTEND_OFFSET_Z
  8368. SERIAL_CHAR(',');
  8369. SERIAL_ECHO(hotend_offset[Z_AXIS][e]);
  8370. #endif
  8371. }
  8372. SERIAL_EOL();
  8373. }
  8374. #if ENABLED(DELTA)
  8375. if (target_extruder == active_extruder)
  8376. do_blocking_move_to_xy(current_position[X_AXIS], current_position[Y_AXIS], planner.max_feedrate_mm_s[X_AXIS]);
  8377. #endif
  8378. }
  8379. #endif // HOTENDS > 1
  8380. /**
  8381. * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95)
  8382. */
  8383. inline void gcode_M220() {
  8384. if (parser.seenval('S')) feedrate_percentage = parser.value_int();
  8385. }
  8386. /**
  8387. * M221: Set extrusion percentage (M221 T0 S95)
  8388. */
  8389. inline void gcode_M221() {
  8390. if (get_target_extruder_from_command(221)) return;
  8391. if (parser.seenval('S')) {
  8392. planner.flow_percentage[target_extruder] = parser.value_int();
  8393. planner.refresh_e_factor(target_extruder);
  8394. }
  8395. else {
  8396. SERIAL_ECHO_START();
  8397. SERIAL_CHAR('E');
  8398. SERIAL_CHAR('0' + target_extruder);
  8399. SERIAL_ECHOPAIR(" Flow: ", planner.flow_percentage[target_extruder]);
  8400. SERIAL_CHAR('%');
  8401. SERIAL_EOL();
  8402. }
  8403. }
  8404. /**
  8405. * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>)
  8406. */
  8407. inline void gcode_M226() {
  8408. if (parser.seen('P')) {
  8409. const int pin = parser.value_int(), pin_state = parser.intval('S', -1);
  8410. if (WITHIN(pin_state, -1, 1) && pin > -1) {
  8411. if (pin_is_protected(pin))
  8412. protected_pin_err();
  8413. else {
  8414. int target = LOW;
  8415. planner.synchronize();
  8416. pinMode(pin, INPUT);
  8417. switch (pin_state) {
  8418. case 1: target = HIGH; break;
  8419. case 0: target = LOW; break;
  8420. case -1: target = !digitalRead(pin); break;
  8421. }
  8422. while (digitalRead(pin) != target) idle();
  8423. }
  8424. } // pin_state -1 0 1 && pin > -1
  8425. } // parser.seen('P')
  8426. }
  8427. #if ENABLED(EXPERIMENTAL_I2CBUS)
  8428. /**
  8429. * M260: Send data to a I2C slave device
  8430. *
  8431. * This is a PoC, the formating and arguments for the GCODE will
  8432. * change to be more compatible, the current proposal is:
  8433. *
  8434. * M260 A<slave device address base 10> ; Sets the I2C slave address the data will be sent to
  8435. *
  8436. * M260 B<byte-1 value in base 10>
  8437. * M260 B<byte-2 value in base 10>
  8438. * M260 B<byte-3 value in base 10>
  8439. *
  8440. * M260 S1 ; Send the buffered data and reset the buffer
  8441. * M260 R1 ; Reset the buffer without sending data
  8442. *
  8443. */
  8444. inline void gcode_M260() {
  8445. // Set the target address
  8446. if (parser.seen('A')) i2c.address(parser.value_byte());
  8447. // Add a new byte to the buffer
  8448. if (parser.seen('B')) i2c.addbyte(parser.value_byte());
  8449. // Flush the buffer to the bus
  8450. if (parser.seen('S')) i2c.send();
  8451. // Reset and rewind the buffer
  8452. else if (parser.seen('R')) i2c.reset();
  8453. }
  8454. /**
  8455. * M261: Request X bytes from I2C slave device
  8456. *
  8457. * Usage: M261 A<slave device address base 10> B<number of bytes>
  8458. */
  8459. inline void gcode_M261() {
  8460. if (parser.seen('A')) i2c.address(parser.value_byte());
  8461. uint8_t bytes = parser.byteval('B', 1);
  8462. if (i2c.addr && bytes && bytes <= TWIBUS_BUFFER_SIZE) {
  8463. i2c.relay(bytes);
  8464. }
  8465. else {
  8466. SERIAL_ERROR_START();
  8467. SERIAL_ERRORLNPGM("Bad i2c request");
  8468. }
  8469. }
  8470. #endif // EXPERIMENTAL_I2CBUS
  8471. #if HAS_SERVOS
  8472. /**
  8473. * M280: Get or set servo position. P<index> [S<angle>]
  8474. */
  8475. inline void gcode_M280() {
  8476. if (!parser.seen('P')) return;
  8477. const int servo_index = parser.value_int();
  8478. if (WITHIN(servo_index, 0, NUM_SERVOS - 1)) {
  8479. if (parser.seen('S'))
  8480. MOVE_SERVO(servo_index, parser.value_int());
  8481. else {
  8482. SERIAL_ECHO_START();
  8483. SERIAL_ECHOPAIR(" Servo ", servo_index);
  8484. SERIAL_ECHOLNPAIR(": ", servo[servo_index].read());
  8485. }
  8486. }
  8487. else {
  8488. SERIAL_ERROR_START();
  8489. SERIAL_ECHOPAIR("Servo ", servo_index);
  8490. SERIAL_ECHOLNPGM(" out of range");
  8491. }
  8492. }
  8493. #endif // HAS_SERVOS
  8494. #if ENABLED(BABYSTEPPING)
  8495. #if ENABLED(BABYSTEP_ZPROBE_OFFSET)
  8496. FORCE_INLINE void mod_zprobe_zoffset(const float &offs) {
  8497. zprobe_zoffset += offs;
  8498. SERIAL_ECHO_START();
  8499. SERIAL_ECHOLNPAIR(MSG_PROBE_Z_OFFSET ": ", zprobe_zoffset);
  8500. }
  8501. #endif
  8502. /**
  8503. * M290: Babystepping
  8504. */
  8505. inline void gcode_M290() {
  8506. #if ENABLED(BABYSTEP_XY)
  8507. for (uint8_t a = X_AXIS; a <= Z_AXIS; a++)
  8508. if (parser.seenval(axis_codes[a]) || (a == Z_AXIS && parser.seenval('S'))) {
  8509. const float offs = constrain(parser.value_axis_units((AxisEnum)a), -2, 2);
  8510. thermalManager.babystep_axis((AxisEnum)a, offs * planner.axis_steps_per_mm[a]);
  8511. #if ENABLED(BABYSTEP_ZPROBE_OFFSET)
  8512. if (a == Z_AXIS && (!parser.seen('P') || parser.value_bool())) mod_zprobe_zoffset(offs);
  8513. #endif
  8514. }
  8515. #else
  8516. if (parser.seenval('Z') || parser.seenval('S')) {
  8517. const float offs = constrain(parser.value_axis_units(Z_AXIS), -2, 2);
  8518. thermalManager.babystep_axis(Z_AXIS, offs * planner.axis_steps_per_mm[Z_AXIS]);
  8519. #if ENABLED(BABYSTEP_ZPROBE_OFFSET)
  8520. if (!parser.seen('P') || parser.value_bool()) mod_zprobe_zoffset(offs);
  8521. #endif
  8522. }
  8523. #endif
  8524. }
  8525. #endif // BABYSTEPPING
  8526. #if HAS_BUZZER
  8527. /**
  8528. * M300: Play beep sound S<frequency Hz> P<duration ms>
  8529. */
  8530. inline void gcode_M300() {
  8531. uint16_t const frequency = parser.ushortval('S', 260);
  8532. uint16_t duration = parser.ushortval('P', 1000);
  8533. // Limits the tone duration to 0-5 seconds.
  8534. NOMORE(duration, 5000);
  8535. BUZZ(duration, frequency);
  8536. }
  8537. #endif // HAS_BUZZER
  8538. #if ENABLED(PIDTEMP)
  8539. /**
  8540. * M301: Set PID parameters P I D (and optionally C, L)
  8541. *
  8542. * P[float] Kp term
  8543. * I[float] Ki term (unscaled)
  8544. * D[float] Kd term (unscaled)
  8545. *
  8546. * With PID_EXTRUSION_SCALING:
  8547. *
  8548. * C[float] Kc term
  8549. * L[int] LPQ length
  8550. */
  8551. inline void gcode_M301() {
  8552. // multi-extruder PID patch: M301 updates or prints a single extruder's PID values
  8553. // default behaviour (omitting E parameter) is to update for extruder 0 only
  8554. const uint8_t e = parser.byteval('E'); // extruder being updated
  8555. if (e < HOTENDS) { // catch bad input value
  8556. if (parser.seen('P')) PID_PARAM(Kp, e) = parser.value_float();
  8557. if (parser.seen('I')) PID_PARAM(Ki, e) = scalePID_i(parser.value_float());
  8558. if (parser.seen('D')) PID_PARAM(Kd, e) = scalePID_d(parser.value_float());
  8559. #if ENABLED(PID_EXTRUSION_SCALING)
  8560. if (parser.seen('C')) PID_PARAM(Kc, e) = parser.value_float();
  8561. if (parser.seen('L')) thermalManager.lpq_len = parser.value_float();
  8562. NOMORE(thermalManager.lpq_len, LPQ_MAX_LEN);
  8563. NOLESS(thermalManager.lpq_len, 0);
  8564. #endif
  8565. thermalManager.updatePID();
  8566. SERIAL_ECHO_START();
  8567. #if ENABLED(PID_PARAMS_PER_HOTEND)
  8568. SERIAL_ECHOPAIR(" e:", e); // specify extruder in serial output
  8569. #endif // PID_PARAMS_PER_HOTEND
  8570. SERIAL_ECHOPAIR(" p:", PID_PARAM(Kp, e));
  8571. SERIAL_ECHOPAIR(" i:", unscalePID_i(PID_PARAM(Ki, e)));
  8572. SERIAL_ECHOPAIR(" d:", unscalePID_d(PID_PARAM(Kd, e)));
  8573. #if ENABLED(PID_EXTRUSION_SCALING)
  8574. //Kc does not have scaling applied above, or in resetting defaults
  8575. SERIAL_ECHOPAIR(" c:", PID_PARAM(Kc, e));
  8576. #endif
  8577. SERIAL_EOL();
  8578. }
  8579. else {
  8580. SERIAL_ERROR_START();
  8581. SERIAL_ERRORLNPGM(MSG_INVALID_EXTRUDER);
  8582. }
  8583. }
  8584. #endif // PIDTEMP
  8585. #if ENABLED(PIDTEMPBED)
  8586. inline void gcode_M304() {
  8587. if (parser.seen('P')) thermalManager.bedKp = parser.value_float();
  8588. if (parser.seen('I')) thermalManager.bedKi = scalePID_i(parser.value_float());
  8589. if (parser.seen('D')) thermalManager.bedKd = scalePID_d(parser.value_float());
  8590. SERIAL_ECHO_START();
  8591. SERIAL_ECHOPAIR(" p:", thermalManager.bedKp);
  8592. SERIAL_ECHOPAIR(" i:", unscalePID_i(thermalManager.bedKi));
  8593. SERIAL_ECHOLNPAIR(" d:", unscalePID_d(thermalManager.bedKd));
  8594. }
  8595. #endif // PIDTEMPBED
  8596. #if defined(CHDK) || HAS_PHOTOGRAPH
  8597. /**
  8598. * M240: Trigger a camera by emulating a Canon RC-1
  8599. * See http://www.doc-diy.net/photo/rc-1_hacked/
  8600. */
  8601. inline void gcode_M240() {
  8602. #ifdef CHDK
  8603. OUT_WRITE(CHDK, HIGH);
  8604. chdkHigh = millis();
  8605. chdkActive = true;
  8606. #elif HAS_PHOTOGRAPH
  8607. const uint8_t NUM_PULSES = 16;
  8608. const float PULSE_LENGTH = 0.01524;
  8609. for (int i = 0; i < NUM_PULSES; i++) {
  8610. WRITE(PHOTOGRAPH_PIN, HIGH);
  8611. _delay_ms(PULSE_LENGTH);
  8612. WRITE(PHOTOGRAPH_PIN, LOW);
  8613. _delay_ms(PULSE_LENGTH);
  8614. }
  8615. delay(7.33);
  8616. for (int i = 0; i < NUM_PULSES; i++) {
  8617. WRITE(PHOTOGRAPH_PIN, HIGH);
  8618. _delay_ms(PULSE_LENGTH);
  8619. WRITE(PHOTOGRAPH_PIN, LOW);
  8620. _delay_ms(PULSE_LENGTH);
  8621. }
  8622. #endif // !CHDK && HAS_PHOTOGRAPH
  8623. }
  8624. #endif // CHDK || PHOTOGRAPH_PIN
  8625. #if HAS_LCD_CONTRAST
  8626. /**
  8627. * M250: Read and optionally set the LCD contrast
  8628. */
  8629. inline void gcode_M250() {
  8630. if (parser.seen('C')) set_lcd_contrast(parser.value_int());
  8631. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  8632. SERIAL_PROTOCOL(lcd_contrast);
  8633. SERIAL_EOL();
  8634. }
  8635. #endif // HAS_LCD_CONTRAST
  8636. #if ENABLED(PREVENT_COLD_EXTRUSION)
  8637. /**
  8638. * M302: Allow cold extrudes, or set the minimum extrude temperature
  8639. *
  8640. * S<temperature> sets the minimum extrude temperature
  8641. * P<bool> enables (1) or disables (0) cold extrusion
  8642. *
  8643. * Examples:
  8644. *
  8645. * M302 ; report current cold extrusion state
  8646. * M302 P0 ; enable cold extrusion checking
  8647. * M302 P1 ; disables cold extrusion checking
  8648. * M302 S0 ; always allow extrusion (disables checking)
  8649. * M302 S170 ; only allow extrusion above 170
  8650. * M302 S170 P1 ; set min extrude temp to 170 but leave disabled
  8651. */
  8652. inline void gcode_M302() {
  8653. const bool seen_S = parser.seen('S');
  8654. if (seen_S) {
  8655. thermalManager.extrude_min_temp = parser.value_celsius();
  8656. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0);
  8657. }
  8658. if (parser.seen('P'))
  8659. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0) || parser.value_bool();
  8660. else if (!seen_S) {
  8661. // Report current state
  8662. SERIAL_ECHO_START();
  8663. SERIAL_ECHOPAIR("Cold extrudes are ", (thermalManager.allow_cold_extrude ? "en" : "dis"));
  8664. SERIAL_ECHOPAIR("abled (min temp ", thermalManager.extrude_min_temp);
  8665. SERIAL_ECHOLNPGM("C)");
  8666. }
  8667. }
  8668. #endif // PREVENT_COLD_EXTRUSION
  8669. /**
  8670. * M303: PID relay autotune
  8671. *
  8672. * S<temperature> sets the target temperature. (default 150C / 70C)
  8673. * E<extruder> (-1 for the bed) (default 0)
  8674. * C<cycles>
  8675. * U<bool> with a non-zero value will apply the result to current settings
  8676. */
  8677. inline void gcode_M303() {
  8678. #if HAS_PID_HEATING
  8679. const int e = parser.intval('E'), c = parser.intval('C', 5);
  8680. const bool u = parser.boolval('U');
  8681. int16_t temp = parser.celsiusval('S', e < 0 ? 70 : 150);
  8682. if (WITHIN(e, 0, HOTENDS - 1))
  8683. target_extruder = e;
  8684. #if DISABLED(BUSY_WHILE_HEATING)
  8685. KEEPALIVE_STATE(NOT_BUSY);
  8686. #endif
  8687. thermalManager.PID_autotune(temp, e, c, u);
  8688. #if DISABLED(BUSY_WHILE_HEATING)
  8689. KEEPALIVE_STATE(IN_HANDLER);
  8690. #endif
  8691. #else
  8692. SERIAL_ERROR_START();
  8693. SERIAL_ERRORLNPGM(MSG_ERR_M303_DISABLED);
  8694. #endif
  8695. }
  8696. #if ENABLED(MORGAN_SCARA)
  8697. bool SCARA_move_to_cal(const uint8_t delta_a, const uint8_t delta_b) {
  8698. if (IsRunning()) {
  8699. forward_kinematics_SCARA(delta_a, delta_b);
  8700. destination[X_AXIS] = cartes[X_AXIS];
  8701. destination[Y_AXIS] = cartes[Y_AXIS];
  8702. destination[Z_AXIS] = current_position[Z_AXIS];
  8703. prepare_move_to_destination();
  8704. return true;
  8705. }
  8706. return false;
  8707. }
  8708. /**
  8709. * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  8710. */
  8711. inline bool gcode_M360() {
  8712. SERIAL_ECHOLNPGM(" Cal: Theta 0");
  8713. return SCARA_move_to_cal(0, 120);
  8714. }
  8715. /**
  8716. * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  8717. */
  8718. inline bool gcode_M361() {
  8719. SERIAL_ECHOLNPGM(" Cal: Theta 90");
  8720. return SCARA_move_to_cal(90, 130);
  8721. }
  8722. /**
  8723. * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  8724. */
  8725. inline bool gcode_M362() {
  8726. SERIAL_ECHOLNPGM(" Cal: Psi 0");
  8727. return SCARA_move_to_cal(60, 180);
  8728. }
  8729. /**
  8730. * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  8731. */
  8732. inline bool gcode_M363() {
  8733. SERIAL_ECHOLNPGM(" Cal: Psi 90");
  8734. return SCARA_move_to_cal(50, 90);
  8735. }
  8736. /**
  8737. * M364: SCARA calibration: Move to cal-position PsiC (90 deg to Theta calibration position)
  8738. */
  8739. inline bool gcode_M364() {
  8740. SERIAL_ECHOLNPGM(" Cal: Theta-Psi 90");
  8741. return SCARA_move_to_cal(45, 135);
  8742. }
  8743. #endif // SCARA
  8744. #if ENABLED(EXT_SOLENOID)
  8745. void enable_solenoid(const uint8_t num) {
  8746. switch (num) {
  8747. case 0:
  8748. OUT_WRITE(SOL0_PIN, HIGH);
  8749. break;
  8750. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  8751. case 1:
  8752. OUT_WRITE(SOL1_PIN, HIGH);
  8753. break;
  8754. #endif
  8755. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  8756. case 2:
  8757. OUT_WRITE(SOL2_PIN, HIGH);
  8758. break;
  8759. #endif
  8760. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  8761. case 3:
  8762. OUT_WRITE(SOL3_PIN, HIGH);
  8763. break;
  8764. #endif
  8765. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  8766. case 4:
  8767. OUT_WRITE(SOL4_PIN, HIGH);
  8768. break;
  8769. #endif
  8770. default:
  8771. SERIAL_ECHO_START();
  8772. SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID);
  8773. break;
  8774. }
  8775. }
  8776. void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); }
  8777. void disable_all_solenoids() {
  8778. OUT_WRITE(SOL0_PIN, LOW);
  8779. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  8780. OUT_WRITE(SOL1_PIN, LOW);
  8781. #endif
  8782. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  8783. OUT_WRITE(SOL2_PIN, LOW);
  8784. #endif
  8785. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  8786. OUT_WRITE(SOL3_PIN, LOW);
  8787. #endif
  8788. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  8789. OUT_WRITE(SOL4_PIN, LOW);
  8790. #endif
  8791. }
  8792. /**
  8793. * M380: Enable solenoid on the active extruder
  8794. */
  8795. inline void gcode_M380() { enable_solenoid_on_active_extruder(); }
  8796. /**
  8797. * M381: Disable all solenoids
  8798. */
  8799. inline void gcode_M381() { disable_all_solenoids(); }
  8800. #endif // EXT_SOLENOID
  8801. /**
  8802. * M400: Finish all moves
  8803. */
  8804. inline void gcode_M400() { planner.synchronize(); }
  8805. #if HAS_BED_PROBE
  8806. /**
  8807. * M401: Deploy and activate the Z probe
  8808. */
  8809. inline void gcode_M401() {
  8810. DEPLOY_PROBE();
  8811. report_current_position();
  8812. }
  8813. /**
  8814. * M402: Deactivate and stow the Z probe
  8815. */
  8816. inline void gcode_M402() {
  8817. STOW_PROBE();
  8818. #ifdef Z_AFTER_PROBING
  8819. move_z_after_probing();
  8820. #endif
  8821. report_current_position();
  8822. }
  8823. #endif // HAS_BED_PROBE
  8824. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  8825. /**
  8826. * M404: Display or set (in current units) the nominal filament width (3mm, 1.75mm ) W<3.0>
  8827. */
  8828. inline void gcode_M404() {
  8829. if (parser.seen('W')) {
  8830. filament_width_nominal = parser.value_linear_units();
  8831. planner.volumetric_area_nominal = CIRCLE_AREA(filament_width_nominal * 0.5);
  8832. }
  8833. else {
  8834. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  8835. SERIAL_PROTOCOLLN(filament_width_nominal);
  8836. }
  8837. }
  8838. /**
  8839. * M405: Turn on filament sensor for control
  8840. */
  8841. inline void gcode_M405() {
  8842. // This is technically a linear measurement, but since it's quantized to centimeters and is a different
  8843. // unit than everything else, it uses parser.value_byte() instead of parser.value_linear_units().
  8844. if (parser.seen('D')) {
  8845. meas_delay_cm = parser.value_byte();
  8846. NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY);
  8847. }
  8848. if (filwidth_delay_index[1] == -1) { // Initialize the ring buffer if not done since startup
  8849. const int8_t temp_ratio = thermalManager.widthFil_to_size_ratio();
  8850. for (uint8_t i = 0; i < COUNT(measurement_delay); ++i)
  8851. measurement_delay[i] = temp_ratio;
  8852. filwidth_delay_index[0] = filwidth_delay_index[1] = 0;
  8853. }
  8854. filament_sensor = true;
  8855. }
  8856. /**
  8857. * M406: Turn off filament sensor for control
  8858. */
  8859. inline void gcode_M406() {
  8860. filament_sensor = false;
  8861. planner.calculate_volumetric_multipliers(); // Restore correct 'volumetric_multiplier' value
  8862. }
  8863. /**
  8864. * M407: Get measured filament diameter on serial output
  8865. */
  8866. inline void gcode_M407() {
  8867. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  8868. SERIAL_PROTOCOLLN(filament_width_meas);
  8869. }
  8870. #endif // FILAMENT_WIDTH_SENSOR
  8871. void quickstop_stepper() {
  8872. planner.quick_stop();
  8873. planner.synchronize();
  8874. set_current_from_steppers_for_axis(ALL_AXES);
  8875. SYNC_PLAN_POSITION_KINEMATIC();
  8876. }
  8877. #if HAS_LEVELING
  8878. //#define M420_C_USE_MEAN
  8879. /**
  8880. * M420: Enable/Disable Bed Leveling and/or set the Z fade height.
  8881. *
  8882. * S[bool] Turns leveling on or off
  8883. * Z[height] Sets the Z fade height (0 or none to disable)
  8884. * V[bool] Verbose - Print the leveling grid
  8885. *
  8886. * With AUTO_BED_LEVELING_UBL only:
  8887. *
  8888. * L[index] Load UBL mesh from index (0 is default)
  8889. * T[map] 0:Human-readable 1:CSV 2:"LCD" 4:Compact
  8890. *
  8891. * With mesh-based leveling only:
  8892. *
  8893. * C Center mesh on the mean of the lowest and highest
  8894. */
  8895. inline void gcode_M420() {
  8896. const bool seen_S = parser.seen('S');
  8897. bool to_enable = seen_S ? parser.value_bool() : planner.leveling_active;
  8898. // If disabling leveling do it right away
  8899. // (Don't disable for just M420 or M420 V)
  8900. if (seen_S && !to_enable) set_bed_leveling_enabled(false);
  8901. const float oldpos[] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  8902. #if ENABLED(AUTO_BED_LEVELING_UBL)
  8903. // L to load a mesh from the EEPROM
  8904. if (parser.seen('L')) {
  8905. set_bed_leveling_enabled(false);
  8906. #if ENABLED(EEPROM_SETTINGS)
  8907. const int8_t storage_slot = parser.has_value() ? parser.value_int() : ubl.storage_slot;
  8908. const int16_t a = settings.calc_num_meshes();
  8909. if (!a) {
  8910. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  8911. return;
  8912. }
  8913. if (!WITHIN(storage_slot, 0, a - 1)) {
  8914. SERIAL_PROTOCOLLNPGM("?Invalid storage slot.");
  8915. SERIAL_PROTOCOLLNPAIR("?Use 0 to ", a - 1);
  8916. return;
  8917. }
  8918. settings.load_mesh(storage_slot);
  8919. ubl.storage_slot = storage_slot;
  8920. #else
  8921. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  8922. return;
  8923. #endif
  8924. }
  8925. // L or V display the map info
  8926. if (parser.seen('L') || parser.seen('V')) {
  8927. ubl.display_map(parser.byteval('T'));
  8928. SERIAL_ECHOPGM("Mesh is ");
  8929. if (!ubl.mesh_is_valid()) SERIAL_ECHOPGM("in");
  8930. SERIAL_ECHOLNPAIR("valid\nStorage slot: ", ubl.storage_slot);
  8931. }
  8932. #endif // AUTO_BED_LEVELING_UBL
  8933. #if HAS_MESH
  8934. #if ENABLED(MESH_BED_LEVELING)
  8935. #define Z_VALUES(X,Y) mbl.z_values[X][Y]
  8936. #else
  8937. #define Z_VALUES(X,Y) z_values[X][Y]
  8938. #endif
  8939. // Subtract the given value or the mean from all mesh values
  8940. if (leveling_is_valid() && parser.seen('C')) {
  8941. const float cval = parser.value_float();
  8942. #if ENABLED(AUTO_BED_LEVELING_UBL)
  8943. set_bed_leveling_enabled(false);
  8944. ubl.adjust_mesh_to_mean(true, cval);
  8945. #else
  8946. #if ENABLED(M420_C_USE_MEAN)
  8947. // Get the sum and average of all mesh values
  8948. float mesh_sum = 0;
  8949. for (uint8_t x = GRID_MAX_POINTS_X; x--;)
  8950. for (uint8_t y = GRID_MAX_POINTS_Y; y--;)
  8951. mesh_sum += Z_VALUES(x, y);
  8952. const float zmean = mesh_sum / float(GRID_MAX_POINTS);
  8953. #else
  8954. // Find the low and high mesh values
  8955. float lo_val = 100, hi_val = -100;
  8956. for (uint8_t x = GRID_MAX_POINTS_X; x--;)
  8957. for (uint8_t y = GRID_MAX_POINTS_Y; y--;) {
  8958. const float z = Z_VALUES(x, y);
  8959. NOMORE(lo_val, z);
  8960. NOLESS(hi_val, z);
  8961. }
  8962. // Take the mean of the lowest and highest
  8963. const float zmean = (lo_val + hi_val) / 2.0 + cval;
  8964. #endif
  8965. // If not very close to 0, adjust the mesh
  8966. if (!NEAR_ZERO(zmean)) {
  8967. set_bed_leveling_enabled(false);
  8968. // Subtract the mean from all values
  8969. for (uint8_t x = GRID_MAX_POINTS_X; x--;)
  8970. for (uint8_t y = GRID_MAX_POINTS_Y; y--;)
  8971. Z_VALUES(x, y) -= zmean;
  8972. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  8973. bed_level_virt_interpolate();
  8974. #endif
  8975. }
  8976. #endif
  8977. }
  8978. #endif // HAS_MESH
  8979. // V to print the matrix or mesh
  8980. if (parser.seen('V')) {
  8981. #if ABL_PLANAR
  8982. planner.bed_level_matrix.debug(PSTR("Bed Level Correction Matrix:"));
  8983. #else
  8984. if (leveling_is_valid()) {
  8985. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  8986. print_bilinear_leveling_grid();
  8987. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  8988. print_bilinear_leveling_grid_virt();
  8989. #endif
  8990. #elif ENABLED(MESH_BED_LEVELING)
  8991. SERIAL_ECHOLNPGM("Mesh Bed Level data:");
  8992. mbl.report_mesh();
  8993. #endif
  8994. }
  8995. #endif
  8996. }
  8997. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  8998. if (parser.seen('Z')) set_z_fade_height(parser.value_linear_units(), false);
  8999. #endif
  9000. // Enable leveling if specified, or if previously active
  9001. set_bed_leveling_enabled(to_enable);
  9002. // Error if leveling failed to enable or reenable
  9003. if (to_enable && !planner.leveling_active) {
  9004. SERIAL_ERROR_START();
  9005. SERIAL_ERRORLNPGM(MSG_ERR_M420_FAILED);
  9006. }
  9007. SERIAL_ECHO_START();
  9008. SERIAL_ECHOLNPAIR("Bed Leveling ", planner.leveling_active ? MSG_ON : MSG_OFF);
  9009. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  9010. SERIAL_ECHO_START();
  9011. SERIAL_ECHOPGM("Fade Height ");
  9012. if (planner.z_fade_height > 0.0)
  9013. SERIAL_ECHOLN(planner.z_fade_height);
  9014. else
  9015. SERIAL_ECHOLNPGM(MSG_OFF);
  9016. #endif
  9017. // Report change in position
  9018. if (memcmp(oldpos, current_position, sizeof(oldpos)))
  9019. report_current_position();
  9020. }
  9021. #endif // HAS_LEVELING
  9022. #if ENABLED(MESH_BED_LEVELING)
  9023. /**
  9024. * M421: Set a single Mesh Bed Leveling Z coordinate
  9025. *
  9026. * Usage:
  9027. * M421 X<linear> Y<linear> Z<linear>
  9028. * M421 X<linear> Y<linear> Q<offset>
  9029. * M421 I<xindex> J<yindex> Z<linear>
  9030. * M421 I<xindex> J<yindex> Q<offset>
  9031. */
  9032. inline void gcode_M421() {
  9033. const bool hasX = parser.seen('X'), hasI = parser.seen('I');
  9034. const int8_t ix = hasI ? parser.value_int() : hasX ? mbl.probe_index_x(parser.value_linear_units()) : -1;
  9035. const bool hasY = parser.seen('Y'), hasJ = parser.seen('J');
  9036. const int8_t iy = hasJ ? parser.value_int() : hasY ? mbl.probe_index_y(parser.value_linear_units()) : -1;
  9037. const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q');
  9038. if (int(hasI && hasJ) + int(hasX && hasY) != 1 || !(hasZ || hasQ)) {
  9039. SERIAL_ERROR_START();
  9040. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  9041. }
  9042. else if (ix < 0 || iy < 0) {
  9043. SERIAL_ERROR_START();
  9044. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  9045. }
  9046. else
  9047. mbl.set_z(ix, iy, parser.value_linear_units() + (hasQ ? mbl.z_values[ix][iy] : 0));
  9048. }
  9049. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9050. /**
  9051. * M421: Set a single Mesh Bed Leveling Z coordinate
  9052. *
  9053. * Usage:
  9054. * M421 I<xindex> J<yindex> Z<linear>
  9055. * M421 I<xindex> J<yindex> Q<offset>
  9056. */
  9057. inline void gcode_M421() {
  9058. int8_t ix = parser.intval('I', -1), iy = parser.intval('J', -1);
  9059. const bool hasI = ix >= 0,
  9060. hasJ = iy >= 0,
  9061. hasZ = parser.seen('Z'),
  9062. hasQ = !hasZ && parser.seen('Q');
  9063. if (!hasI || !hasJ || !(hasZ || hasQ)) {
  9064. SERIAL_ERROR_START();
  9065. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  9066. }
  9067. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  9068. SERIAL_ERROR_START();
  9069. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  9070. }
  9071. else {
  9072. z_values[ix][iy] = parser.value_linear_units() + (hasQ ? z_values[ix][iy] : 0);
  9073. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  9074. bed_level_virt_interpolate();
  9075. #endif
  9076. }
  9077. }
  9078. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  9079. /**
  9080. * M421: Set a single Mesh Bed Leveling Z coordinate
  9081. *
  9082. * Usage:
  9083. * M421 I<xindex> J<yindex> Z<linear>
  9084. * M421 I<xindex> J<yindex> Q<offset>
  9085. * M421 I<xindex> J<yindex> N
  9086. * M421 C Z<linear>
  9087. * M421 C Q<offset>
  9088. */
  9089. inline void gcode_M421() {
  9090. int8_t ix = parser.intval('I', -1), iy = parser.intval('J', -1);
  9091. const bool hasI = ix >= 0,
  9092. hasJ = iy >= 0,
  9093. hasC = parser.seen('C'),
  9094. hasN = parser.seen('N'),
  9095. hasZ = parser.seen('Z'),
  9096. hasQ = !hasZ && parser.seen('Q');
  9097. if (hasC) {
  9098. const mesh_index_pair location = ubl.find_closest_mesh_point_of_type(REAL, current_position[X_AXIS], current_position[Y_AXIS], USE_NOZZLE_AS_REFERENCE, NULL);
  9099. ix = location.x_index;
  9100. iy = location.y_index;
  9101. }
  9102. if (int(hasC) + int(hasI && hasJ) != 1 || !(hasZ || hasQ || hasN)) {
  9103. SERIAL_ERROR_START();
  9104. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  9105. }
  9106. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  9107. SERIAL_ERROR_START();
  9108. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  9109. }
  9110. else
  9111. ubl.z_values[ix][iy] = hasN ? NAN : parser.value_linear_units() + (hasQ ? ubl.z_values[ix][iy] : 0);
  9112. }
  9113. #endif // AUTO_BED_LEVELING_UBL
  9114. #if HAS_M206_COMMAND
  9115. /**
  9116. * M428: Set home_offset based on the distance between the
  9117. * current_position and the nearest "reference point."
  9118. * If an axis is past center its endstop position
  9119. * is the reference-point. Otherwise it uses 0. This allows
  9120. * the Z offset to be set near the bed when using a max endstop.
  9121. *
  9122. * M428 can't be used more than 2cm away from 0 or an endstop.
  9123. *
  9124. * Use M206 to set these values directly.
  9125. */
  9126. inline void gcode_M428() {
  9127. if (axis_unhomed_error()) return;
  9128. float diff[XYZ];
  9129. LOOP_XYZ(i) {
  9130. diff[i] = base_home_pos((AxisEnum)i) - current_position[i];
  9131. if (!WITHIN(diff[i], -20, 20) && home_dir((AxisEnum)i) > 0)
  9132. diff[i] = -current_position[i];
  9133. if (!WITHIN(diff[i], -20, 20)) {
  9134. SERIAL_ERROR_START();
  9135. SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR);
  9136. LCD_ALERTMESSAGEPGM("Err: Too far!");
  9137. BUZZ(200, 40);
  9138. return;
  9139. }
  9140. }
  9141. LOOP_XYZ(i) set_home_offset((AxisEnum)i, diff[i]);
  9142. report_current_position();
  9143. LCD_MESSAGEPGM(MSG_HOME_OFFSETS_APPLIED);
  9144. BUZZ(100, 659);
  9145. BUZZ(100, 698);
  9146. }
  9147. #endif // HAS_M206_COMMAND
  9148. /**
  9149. * M500: Store settings in EEPROM
  9150. */
  9151. inline void gcode_M500() {
  9152. (void)settings.save();
  9153. }
  9154. /**
  9155. * M501: Read settings from EEPROM
  9156. */
  9157. inline void gcode_M501() {
  9158. (void)settings.load();
  9159. }
  9160. /**
  9161. * M502: Revert to default settings
  9162. */
  9163. inline void gcode_M502() {
  9164. (void)settings.reset();
  9165. }
  9166. #if DISABLED(DISABLE_M503)
  9167. /**
  9168. * M503: print settings currently in memory
  9169. */
  9170. inline void gcode_M503() {
  9171. (void)settings.report(parser.seen('S') && !parser.value_bool());
  9172. }
  9173. #endif
  9174. #if ENABLED(EEPROM_SETTINGS)
  9175. /**
  9176. * M504: Validate EEPROM Contents
  9177. */
  9178. inline void gcode_M504() {
  9179. if (settings.validate()) {
  9180. SERIAL_ECHO_START();
  9181. SERIAL_ECHOLNPGM("EEPROM OK");
  9182. }
  9183. }
  9184. #endif
  9185. #if ENABLED(SDSUPPORT)
  9186. /**
  9187. * M524: Abort the current SD print job (started with M24)
  9188. */
  9189. inline void gcode_M524() {
  9190. if (IS_SD_PRINTING()) card.abort_sd_printing = true;
  9191. }
  9192. #endif // SDSUPPORT
  9193. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  9194. /**
  9195. * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>)
  9196. */
  9197. inline void gcode_M540() {
  9198. if (parser.seen('S')) planner.abort_on_endstop_hit = parser.value_bool();
  9199. }
  9200. #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  9201. #if HAS_BED_PROBE
  9202. inline void gcode_M851() {
  9203. if (parser.seenval('Z')) {
  9204. const float value = parser.value_linear_units();
  9205. if (WITHIN(value, Z_PROBE_OFFSET_RANGE_MIN, Z_PROBE_OFFSET_RANGE_MAX))
  9206. zprobe_zoffset = value;
  9207. else {
  9208. SERIAL_ERROR_START();
  9209. SERIAL_ERRORLNPGM("?Z out of range (" STRINGIFY(Z_PROBE_OFFSET_RANGE_MIN) " to " STRINGIFY(Z_PROBE_OFFSET_RANGE_MAX) ")");
  9210. }
  9211. return;
  9212. }
  9213. SERIAL_ECHO_START();
  9214. SERIAL_ECHOPGM(MSG_PROBE_Z_OFFSET);
  9215. SERIAL_ECHOLNPAIR(": ", zprobe_zoffset);
  9216. }
  9217. #endif // HAS_BED_PROBE
  9218. #if ENABLED(SKEW_CORRECTION_GCODE)
  9219. /**
  9220. * M852: Get or set the machine skew factors. Reports current values with no arguments.
  9221. *
  9222. * S[xy_factor] - Alias for 'I'
  9223. * I[xy_factor] - New XY skew factor
  9224. * J[xz_factor] - New XZ skew factor
  9225. * K[yz_factor] - New YZ skew factor
  9226. */
  9227. inline void gcode_M852() {
  9228. uint8_t ijk = 0, badval = 0, setval = 0;
  9229. if (parser.seen('I') || parser.seen('S')) {
  9230. ++ijk;
  9231. const float value = parser.value_linear_units();
  9232. if (WITHIN(value, SKEW_FACTOR_MIN, SKEW_FACTOR_MAX)) {
  9233. if (planner.xy_skew_factor != value) {
  9234. planner.xy_skew_factor = value;
  9235. ++setval;
  9236. }
  9237. }
  9238. else
  9239. ++badval;
  9240. }
  9241. #if ENABLED(SKEW_CORRECTION_FOR_Z)
  9242. if (parser.seen('J')) {
  9243. ++ijk;
  9244. const float value = parser.value_linear_units();
  9245. if (WITHIN(value, SKEW_FACTOR_MIN, SKEW_FACTOR_MAX)) {
  9246. if (planner.xz_skew_factor != value) {
  9247. planner.xz_skew_factor = value;
  9248. ++setval;
  9249. }
  9250. }
  9251. else
  9252. ++badval;
  9253. }
  9254. if (parser.seen('K')) {
  9255. ++ijk;
  9256. const float value = parser.value_linear_units();
  9257. if (WITHIN(value, SKEW_FACTOR_MIN, SKEW_FACTOR_MAX)) {
  9258. if (planner.yz_skew_factor != value) {
  9259. planner.yz_skew_factor = value;
  9260. ++setval;
  9261. }
  9262. }
  9263. else
  9264. ++badval;
  9265. }
  9266. #endif
  9267. if (badval)
  9268. SERIAL_ECHOLNPGM(MSG_SKEW_MIN " " STRINGIFY(SKEW_FACTOR_MIN) " " MSG_SKEW_MAX " " STRINGIFY(SKEW_FACTOR_MAX));
  9269. // When skew is changed the current position changes
  9270. if (setval) {
  9271. set_current_from_steppers_for_axis(ALL_AXES);
  9272. SYNC_PLAN_POSITION_KINEMATIC();
  9273. report_current_position();
  9274. }
  9275. if (!ijk) {
  9276. SERIAL_ECHO_START();
  9277. SERIAL_ECHOPGM(MSG_SKEW_FACTOR " XY: ");
  9278. SERIAL_ECHO_F(planner.xy_skew_factor, 6);
  9279. SERIAL_EOL();
  9280. #if ENABLED(SKEW_CORRECTION_FOR_Z)
  9281. SERIAL_ECHOPAIR(" XZ: ", planner.xz_skew_factor);
  9282. SERIAL_ECHOLNPAIR(" YZ: ", planner.yz_skew_factor);
  9283. #else
  9284. SERIAL_EOL();
  9285. #endif
  9286. }
  9287. }
  9288. #endif // SKEW_CORRECTION_GCODE
  9289. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  9290. /**
  9291. * M600: Pause for filament change
  9292. *
  9293. * E[distance] - Retract the filament this far
  9294. * Z[distance] - Move the Z axis by this distance
  9295. * X[position] - Move to this X position, with Y
  9296. * Y[position] - Move to this Y position, with X
  9297. * U[distance] - Retract distance for removal (manual reload)
  9298. * L[distance] - Extrude distance for insertion (manual reload)
  9299. * B[count] - Number of times to beep, -1 for indefinite (if equipped with a buzzer)
  9300. * T[toolhead] - Select extruder for filament change
  9301. *
  9302. * Default values are used for omitted arguments.
  9303. */
  9304. inline void gcode_M600() {
  9305. point_t park_point = NOZZLE_PARK_POINT;
  9306. if (get_target_extruder_from_command(600)) return;
  9307. // Show initial message
  9308. #if ENABLED(ULTIPANEL)
  9309. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INIT, ADVANCED_PAUSE_MODE_PAUSE_PRINT, target_extruder);
  9310. #endif
  9311. #if ENABLED(HOME_BEFORE_FILAMENT_CHANGE)
  9312. // Don't allow filament change without homing first
  9313. if (axis_unhomed_error()) home_all_axes();
  9314. #endif
  9315. #if EXTRUDERS > 1
  9316. // Change toolhead if specified
  9317. uint8_t active_extruder_before_filament_change = active_extruder;
  9318. if (active_extruder != target_extruder)
  9319. tool_change(target_extruder, 0, true);
  9320. #endif
  9321. // Initial retract before move to filament change position
  9322. const float retract = -ABS(parser.seen('E') ? parser.value_axis_units(E_AXIS) : 0
  9323. #ifdef PAUSE_PARK_RETRACT_LENGTH
  9324. + (PAUSE_PARK_RETRACT_LENGTH)
  9325. #endif
  9326. );
  9327. // Lift Z axis
  9328. if (parser.seenval('Z')) park_point.z = parser.linearval('Z');
  9329. // Move XY axes to filament change position or given position
  9330. if (parser.seenval('X')) park_point.x = parser.linearval('X');
  9331. if (parser.seenval('Y')) park_point.y = parser.linearval('Y');
  9332. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE) && DISABLED(DELTA)
  9333. park_point.x += (active_extruder ? hotend_offset[X_AXIS][active_extruder] : 0);
  9334. park_point.y += (active_extruder ? hotend_offset[Y_AXIS][active_extruder] : 0);
  9335. #endif
  9336. // Unload filament
  9337. const float unload_length = -ABS(parser.seen('U') ? parser.value_axis_units(E_AXIS) :
  9338. filament_change_unload_length[active_extruder]);
  9339. // Slow load filament
  9340. constexpr float slow_load_length = FILAMENT_CHANGE_SLOW_LOAD_LENGTH;
  9341. // Fast load filament
  9342. const float fast_load_length = ABS(parser.seen('L') ? parser.value_axis_units(E_AXIS) :
  9343. filament_change_load_length[active_extruder]);
  9344. const int beep_count = parser.intval('B',
  9345. #ifdef FILAMENT_CHANGE_ALERT_BEEPS
  9346. FILAMENT_CHANGE_ALERT_BEEPS
  9347. #else
  9348. -1
  9349. #endif
  9350. );
  9351. const bool job_running = print_job_timer.isRunning();
  9352. if (pause_print(retract, park_point, unload_length, true)) {
  9353. wait_for_filament_reload(beep_count);
  9354. resume_print(slow_load_length, fast_load_length, ADVANCED_PAUSE_PURGE_LENGTH, beep_count);
  9355. }
  9356. #if EXTRUDERS > 1
  9357. // Restore toolhead if it was changed
  9358. if (active_extruder_before_filament_change != active_extruder)
  9359. tool_change(active_extruder_before_filament_change, 0, true);
  9360. #endif
  9361. // Resume the print job timer if it was running
  9362. if (job_running) print_job_timer.start();
  9363. }
  9364. /**
  9365. * M603: Configure filament change
  9366. *
  9367. * T[toolhead] - Select extruder to configure, active extruder if not specified
  9368. * U[distance] - Retract distance for removal, for the specified extruder
  9369. * L[distance] - Extrude distance for insertion, for the specified extruder
  9370. *
  9371. */
  9372. inline void gcode_M603() {
  9373. if (get_target_extruder_from_command(603)) return;
  9374. // Unload length
  9375. if (parser.seen('U')) {
  9376. filament_change_unload_length[target_extruder] = ABS(parser.value_axis_units(E_AXIS));
  9377. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  9378. NOMORE(filament_change_unload_length[target_extruder], EXTRUDE_MAXLENGTH);
  9379. #endif
  9380. }
  9381. // Load length
  9382. if (parser.seen('L')) {
  9383. filament_change_load_length[target_extruder] = ABS(parser.value_axis_units(E_AXIS));
  9384. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  9385. NOMORE(filament_change_load_length[target_extruder], EXTRUDE_MAXLENGTH);
  9386. #endif
  9387. }
  9388. }
  9389. #endif // ADVANCED_PAUSE_FEATURE
  9390. #if ENABLED(MK2_MULTIPLEXER)
  9391. inline void select_multiplexed_stepper(const uint8_t e) {
  9392. planner.synchronize();
  9393. disable_e_steppers();
  9394. WRITE(E_MUX0_PIN, TEST(e, 0) ? HIGH : LOW);
  9395. WRITE(E_MUX1_PIN, TEST(e, 1) ? HIGH : LOW);
  9396. WRITE(E_MUX2_PIN, TEST(e, 2) ? HIGH : LOW);
  9397. safe_delay(100);
  9398. }
  9399. #endif // MK2_MULTIPLEXER
  9400. #if ENABLED(DUAL_X_CARRIAGE)
  9401. /**
  9402. * M605: Set dual x-carriage movement mode
  9403. *
  9404. * M605 S0: Full control mode. The slicer has full control over x-carriage movement
  9405. * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  9406. * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  9407. * units x-offset and an optional differential hotend temperature of
  9408. * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  9409. * the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  9410. *
  9411. * Note: the X axis should be homed after changing dual x-carriage mode.
  9412. */
  9413. inline void gcode_M605() {
  9414. planner.synchronize();
  9415. if (parser.seen('S')) dual_x_carriage_mode = (DualXMode)parser.value_byte();
  9416. switch (dual_x_carriage_mode) {
  9417. case DXC_FULL_CONTROL_MODE:
  9418. case DXC_AUTO_PARK_MODE:
  9419. break;
  9420. case DXC_DUPLICATION_MODE:
  9421. if (parser.seen('X')) duplicate_extruder_x_offset = MAX(parser.value_linear_units(), X2_MIN_POS - x_home_pos(0));
  9422. if (parser.seen('R')) duplicate_extruder_temp_offset = parser.value_celsius_diff();
  9423. SERIAL_ECHO_START();
  9424. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  9425. SERIAL_CHAR(' ');
  9426. SERIAL_ECHO(hotend_offset[X_AXIS][0]);
  9427. SERIAL_CHAR(',');
  9428. SERIAL_ECHO(hotend_offset[Y_AXIS][0]);
  9429. SERIAL_CHAR(' ');
  9430. SERIAL_ECHO(duplicate_extruder_x_offset);
  9431. SERIAL_CHAR(',');
  9432. SERIAL_ECHOLN(hotend_offset[Y_AXIS][1]);
  9433. break;
  9434. default:
  9435. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  9436. break;
  9437. }
  9438. active_extruder_parked = false;
  9439. extruder_duplication_enabled = false;
  9440. delayed_move_time = 0;
  9441. }
  9442. #elif ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  9443. inline void gcode_M605() {
  9444. planner.synchronize();
  9445. extruder_duplication_enabled = parser.intval('S') == int(DXC_DUPLICATION_MODE);
  9446. SERIAL_ECHO_START();
  9447. SERIAL_ECHOLNPAIR(MSG_DUPLICATION_MODE, extruder_duplication_enabled ? MSG_ON : MSG_OFF);
  9448. }
  9449. #endif // DUAL_NOZZLE_DUPLICATION_MODE
  9450. #if ENABLED(FILAMENT_LOAD_UNLOAD_GCODES)
  9451. /**
  9452. * M701: Load filament
  9453. *
  9454. * T<extruder> - Optional extruder number. Current extruder if omitted.
  9455. * Z<distance> - Move the Z axis by this distance
  9456. * L<distance> - Extrude distance for insertion (positive value) (manual reload)
  9457. *
  9458. * Default values are used for omitted arguments.
  9459. */
  9460. inline void gcode_M701() {
  9461. point_t park_point = NOZZLE_PARK_POINT;
  9462. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  9463. // Only raise Z if the machine is homed
  9464. if (axis_unhomed_error()) park_point.z = 0;
  9465. #endif
  9466. if (get_target_extruder_from_command(701)) return;
  9467. // Z axis lift
  9468. if (parser.seenval('Z')) park_point.z = parser.linearval('Z');
  9469. // Show initial "wait for load" message
  9470. #if ENABLED(ULTIPANEL)
  9471. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_LOAD, ADVANCED_PAUSE_MODE_LOAD_FILAMENT, target_extruder);
  9472. #endif
  9473. #if EXTRUDERS > 1
  9474. // Change toolhead if specified
  9475. uint8_t active_extruder_before_filament_change = active_extruder;
  9476. if (active_extruder != target_extruder)
  9477. tool_change(target_extruder, 0, true);
  9478. #endif
  9479. // Lift Z axis
  9480. if (park_point.z > 0)
  9481. do_blocking_move_to_z(MIN(current_position[Z_AXIS] + park_point.z, Z_MAX_POS), NOZZLE_PARK_Z_FEEDRATE);
  9482. constexpr float slow_load_length = FILAMENT_CHANGE_SLOW_LOAD_LENGTH;
  9483. const float fast_load_length = ABS(parser.seen('L') ? parser.value_axis_units(E_AXIS) : filament_change_load_length[active_extruder]);
  9484. load_filament(slow_load_length, fast_load_length, ADVANCED_PAUSE_PURGE_LENGTH, FILAMENT_CHANGE_ALERT_BEEPS,
  9485. true, thermalManager.wait_for_heating(target_extruder), ADVANCED_PAUSE_MODE_LOAD_FILAMENT);
  9486. // Restore Z axis
  9487. if (park_point.z > 0)
  9488. do_blocking_move_to_z(MAX(current_position[Z_AXIS] - park_point.z, 0), NOZZLE_PARK_Z_FEEDRATE);
  9489. #if EXTRUDERS > 1
  9490. // Restore toolhead if it was changed
  9491. if (active_extruder_before_filament_change != active_extruder)
  9492. tool_change(active_extruder_before_filament_change, 0, true);
  9493. #endif
  9494. // Show status screen
  9495. #if ENABLED(ULTIPANEL)
  9496. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  9497. #endif
  9498. }
  9499. /**
  9500. * M702: Unload filament
  9501. *
  9502. * T<extruder> - Optional extruder number. If omitted, current extruder
  9503. * (or ALL extruders with FILAMENT_UNLOAD_ALL_EXTRUDERS).
  9504. * Z<distance> - Move the Z axis by this distance
  9505. * U<distance> - Retract distance for removal (manual reload)
  9506. *
  9507. * Default values are used for omitted arguments.
  9508. */
  9509. inline void gcode_M702() {
  9510. point_t park_point = NOZZLE_PARK_POINT;
  9511. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  9512. // Only raise Z if the machine is homed
  9513. if (axis_unhomed_error()) park_point.z = 0;
  9514. #endif
  9515. if (get_target_extruder_from_command(702)) return;
  9516. // Z axis lift
  9517. if (parser.seenval('Z')) park_point.z = parser.linearval('Z');
  9518. // Show initial message
  9519. #if ENABLED(ULTIPANEL)
  9520. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_UNLOAD, ADVANCED_PAUSE_MODE_UNLOAD_FILAMENT, target_extruder);
  9521. #endif
  9522. #if EXTRUDERS > 1
  9523. // Change toolhead if specified
  9524. uint8_t active_extruder_before_filament_change = active_extruder;
  9525. if (active_extruder != target_extruder)
  9526. tool_change(target_extruder, 0, true);
  9527. #endif
  9528. // Lift Z axis
  9529. if (park_point.z > 0)
  9530. do_blocking_move_to_z(MIN(current_position[Z_AXIS] + park_point.z, Z_MAX_POS), NOZZLE_PARK_Z_FEEDRATE);
  9531. // Unload filament
  9532. #if EXTRUDERS > 1 && ENABLED(FILAMENT_UNLOAD_ALL_EXTRUDERS)
  9533. if (!parser.seenval('T')) {
  9534. HOTEND_LOOP() {
  9535. if (e != active_extruder) tool_change(e, 0, true);
  9536. unload_filament(-filament_change_unload_length[e], true, ADVANCED_PAUSE_MODE_UNLOAD_FILAMENT);
  9537. }
  9538. }
  9539. else
  9540. #endif
  9541. {
  9542. // Unload length
  9543. const float unload_length = -ABS(parser.seen('U') ? parser.value_axis_units(E_AXIS) :
  9544. filament_change_unload_length[target_extruder]);
  9545. unload_filament(unload_length, true, ADVANCED_PAUSE_MODE_UNLOAD_FILAMENT);
  9546. }
  9547. // Restore Z axis
  9548. if (park_point.z > 0)
  9549. do_blocking_move_to_z(MAX(current_position[Z_AXIS] - park_point.z, 0), NOZZLE_PARK_Z_FEEDRATE);
  9550. #if EXTRUDERS > 1
  9551. // Restore toolhead if it was changed
  9552. if (active_extruder_before_filament_change != active_extruder)
  9553. tool_change(active_extruder_before_filament_change, 0, true);
  9554. #endif
  9555. // Show status screen
  9556. #if ENABLED(ULTIPANEL)
  9557. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  9558. #endif
  9559. }
  9560. #endif // FILAMENT_LOAD_UNLOAD_GCODES
  9561. #if ENABLED(MAX7219_GCODE)
  9562. /**
  9563. * M7219: Control the Max7219 LED matrix
  9564. *
  9565. * I - Initialize (clear) the matrix
  9566. * F - Fill the matrix (set all bits)
  9567. * P - Dump the LEDs[] array values
  9568. * C<column> - Set a column to the 8-bit value V
  9569. * R<row> - Set a row to the 8-bit value V
  9570. * X<pos> - X position of an LED to set or toggle
  9571. * Y<pos> - Y position of an LED to set or toggle
  9572. * V<value> - The potentially 32-bit value or on/off state to set
  9573. * (for example: a chain of 4 Max7219 devices can have 32 bit
  9574. * rows or columns depending upon rotation)
  9575. */
  9576. inline void gcode_M7219() {
  9577. if (parser.seen('I')) {
  9578. max7219.register_setup();
  9579. max7219.clear();
  9580. }
  9581. if (parser.seen('F')) max7219.fill();
  9582. const uint32_t v = parser.ulongval('V');
  9583. if (parser.seenval('R')) {
  9584. const uint8_t r = parser.value_byte();
  9585. max7219.set_row(r, v);
  9586. }
  9587. else if (parser.seenval('C')) {
  9588. const uint8_t c = parser.value_byte();
  9589. max7219.set_column(c, v);
  9590. }
  9591. else if (parser.seenval('X') || parser.seenval('Y')) {
  9592. const uint8_t x = parser.byteval('X'), y = parser.byteval('Y');
  9593. if (parser.seenval('V'))
  9594. max7219.led_set(x, y, parser.boolval('V'));
  9595. else
  9596. max7219.led_toggle(x, y);
  9597. }
  9598. else if (parser.seen('D')) {
  9599. const uint8_t line = parser.byteval('D') + (parser.byteval('U') << 3);
  9600. if (line < MAX7219_LINES) {
  9601. max7219.led_line[line] = v;
  9602. return max7219.refresh_line(line);
  9603. }
  9604. }
  9605. if (parser.seen('P')) {
  9606. for (uint8_t r = 0; r < MAX7219_LINES; r++) {
  9607. SERIAL_ECHOPGM("led_line[");
  9608. if (r < 10) SERIAL_CHAR(' ');
  9609. SERIAL_ECHO(int(r));
  9610. SERIAL_ECHOPGM("]=");
  9611. for (uint8_t b = 8; b--;) SERIAL_CHAR('0' + TEST(max7219.led_line[r], b));
  9612. SERIAL_EOL();
  9613. }
  9614. }
  9615. }
  9616. #endif // MAX7219_GCODE
  9617. #if ENABLED(LIN_ADVANCE)
  9618. /**
  9619. * M900: Get or Set Linear Advance K-factor
  9620. *
  9621. * K<factor> Set advance K factor
  9622. */
  9623. inline void gcode_M900() {
  9624. if (parser.seenval('K')) {
  9625. const float newK = parser.floatval('K');
  9626. if (WITHIN(newK, 0, 10)) {
  9627. planner.synchronize();
  9628. planner.extruder_advance_K = newK;
  9629. }
  9630. else
  9631. SERIAL_PROTOCOLLNPGM("?K value out of range (0-10).");
  9632. }
  9633. else {
  9634. SERIAL_ECHO_START();
  9635. SERIAL_ECHOLNPAIR("Advance K=", planner.extruder_advance_K);
  9636. }
  9637. }
  9638. #endif // LIN_ADVANCE
  9639. #if HAS_TRINAMIC
  9640. #if ENABLED(TMC_DEBUG)
  9641. inline void gcode_M122() {
  9642. if (parser.seen('S'))
  9643. tmc_set_report_status(parser.value_bool());
  9644. else
  9645. tmc_report_all();
  9646. }
  9647. #endif // TMC_DEBUG
  9648. /**
  9649. * M906: Set motor current in milliamps using axis codes X, Y, Z, E
  9650. * Uses axis codes A, B, C, D, E for Hangprinter
  9651. * Report driver currents when no axis specified
  9652. */
  9653. inline void gcode_M906() {
  9654. #define TMC_SAY_CURRENT(Q) tmc_get_current(stepper##Q, TMC_##Q)
  9655. #define TMC_SET_CURRENT(Q) tmc_set_current(stepper##Q, value)
  9656. bool report = true;
  9657. const uint8_t index = parser.byteval('I');
  9658. LOOP_NUM_AXIS(i) if (uint16_t value = parser.intval(RAW_AXIS_CODES(i))) {
  9659. report = false;
  9660. switch (i) {
  9661. // Assumes {A_AXIS, B_AXIS, C_AXIS} == {X_AXIS, Y_AXIS, Z_AXIS}
  9662. case X_AXIS:
  9663. #if AXIS_IS_TMC(X)
  9664. if (index < 2) TMC_SET_CURRENT(X);
  9665. #endif
  9666. #if AXIS_IS_TMC(X2)
  9667. if (!(index & 1)) TMC_SET_CURRENT(X2);
  9668. #endif
  9669. break;
  9670. case Y_AXIS:
  9671. #if AXIS_IS_TMC(Y)
  9672. if (index < 2) TMC_SET_CURRENT(Y);
  9673. #endif
  9674. #if AXIS_IS_TMC(Y2)
  9675. if (!(index & 1)) TMC_SET_CURRENT(Y2);
  9676. #endif
  9677. break;
  9678. case Z_AXIS:
  9679. #if AXIS_IS_TMC(Z)
  9680. if (index < 2) TMC_SET_CURRENT(Z);
  9681. #endif
  9682. #if AXIS_IS_TMC(Z2)
  9683. if (!(index & 1)) TMC_SET_CURRENT(Z2);
  9684. #endif
  9685. break;
  9686. case E_AXIS: {
  9687. if (get_target_extruder_from_command(906)) return;
  9688. switch (target_extruder) {
  9689. #if AXIS_IS_TMC(E0)
  9690. case 0: TMC_SET_CURRENT(E0); break;
  9691. #endif
  9692. #if ENABLED(HANGPRINTER)
  9693. // Avoid setting the D-current
  9694. #if AXIS_IS_TMC(E1) && EXTRUDERS > 1
  9695. case 1: TMC_SET_CURRENT(E1); break;
  9696. #endif
  9697. #if AXIS_IS_TMC(E2) && EXTRUDERS > 2
  9698. case 2: TMC_SET_CURRENT(E2); break;
  9699. #endif
  9700. #if AXIS_IS_TMC(E3) && EXTRUDERS > 3
  9701. case 3: TMC_SET_CURRENT(E3); break;
  9702. #endif
  9703. #if AXIS_IS_TMC(E4) && EXTRUDERS > 4
  9704. case 4: TMC_SET_CURRENT(E4); break;
  9705. #endif
  9706. #else
  9707. #if AXIS_IS_TMC(E1)
  9708. case 1: TMC_SET_CURRENT(E1); break;
  9709. #endif
  9710. #if AXIS_IS_TMC(E2)
  9711. case 2: TMC_SET_CURRENT(E2); break;
  9712. #endif
  9713. #if AXIS_IS_TMC(E3)
  9714. case 3: TMC_SET_CURRENT(E3); break;
  9715. #endif
  9716. #if AXIS_IS_TMC(E4)
  9717. case 4: TMC_SET_CURRENT(E4); break;
  9718. #endif
  9719. #endif
  9720. }
  9721. } break;
  9722. #if ENABLED(HANGPRINTER)
  9723. case D_AXIS:
  9724. // D is connected on the first of E1, E2, E3, E4 output that is not an extruder
  9725. #if AXIS_IS_TMC(E1) && EXTRUDERS == 1
  9726. TMC_SET_CURRENT(E1); break;
  9727. #endif
  9728. #if AXIS_IS_TMC(E2) && EXTRUDERS == 2
  9729. TMC_SET_CURRENT(E2); break;
  9730. #endif
  9731. #if AXIS_IS_TMC(E3) && EXTRUDERS == 3
  9732. TMC_SET_CURRENT(E3); break;
  9733. #endif
  9734. #if AXIS_IS_TMC(E4) && EXTRUDERS == 4
  9735. TMC_SET_CURRENT(E4); break;
  9736. #endif
  9737. #endif
  9738. }
  9739. }
  9740. if (report) {
  9741. #if AXIS_IS_TMC(X)
  9742. TMC_SAY_CURRENT(X);
  9743. #endif
  9744. #if AXIS_IS_TMC(X2)
  9745. TMC_SAY_CURRENT(X2);
  9746. #endif
  9747. #if AXIS_IS_TMC(Y)
  9748. TMC_SAY_CURRENT(Y);
  9749. #endif
  9750. #if AXIS_IS_TMC(Y2)
  9751. TMC_SAY_CURRENT(Y2);
  9752. #endif
  9753. #if AXIS_IS_TMC(Z)
  9754. TMC_SAY_CURRENT(Z);
  9755. #endif
  9756. #if AXIS_IS_TMC(Z2)
  9757. TMC_SAY_CURRENT(Z2);
  9758. #endif
  9759. #if AXIS_IS_TMC(E0)
  9760. TMC_SAY_CURRENT(E0);
  9761. #endif
  9762. #if ENABLED(HANGPRINTER)
  9763. // D is connected on the first of E1, E2, E3, E4 output that is not an extruder
  9764. #if AXIS_IS_TMC(E1) && EXTRUDERS == 1
  9765. TMC_SAY_CURRENT(E1);
  9766. #endif
  9767. #if AXIS_IS_TMC(E2) && EXTRUDERS == 2
  9768. TMC_SAY_CURRENT(E2);
  9769. #endif
  9770. #if AXIS_IS_TMC(E3) && EXTRUDERS == 3
  9771. TMC_SAY_CURRENT(E3);
  9772. #endif
  9773. #if AXIS_IS_TMC(E4) && EXTRUDERS == 4
  9774. TMC_SAY_CURRENT(E4);
  9775. #endif
  9776. #else
  9777. #if AXIS_IS_TMC(E1)
  9778. TMC_SAY_CURRENT(E1);
  9779. #endif
  9780. #if AXIS_IS_TMC(E2)
  9781. TMC_SAY_CURRENT(E2);
  9782. #endif
  9783. #if AXIS_IS_TMC(E3)
  9784. TMC_SAY_CURRENT(E3);
  9785. #endif
  9786. #if AXIS_IS_TMC(E4)
  9787. TMC_SAY_CURRENT(E4);
  9788. #endif
  9789. #endif
  9790. }
  9791. }
  9792. #define M91x_USE(ST) (AXIS_DRIVER_TYPE(ST, TMC2130) || (AXIS_DRIVER_TYPE(ST, TMC2208) && PIN_EXISTS(ST##_SERIAL_RX)))
  9793. #define M91x_USE_E(N) (E_STEPPERS > N && M91x_USE(E##N))
  9794. /**
  9795. * M911: Report TMC stepper driver overtemperature pre-warn flag
  9796. * This flag is held by the library, persisting until cleared by M912
  9797. */
  9798. inline void gcode_M911() {
  9799. #if M91x_USE(X)
  9800. tmc_report_otpw(stepperX, TMC_X);
  9801. #endif
  9802. #if M91x_USE(X2)
  9803. tmc_report_otpw(stepperX2, TMC_X2);
  9804. #endif
  9805. #if M91x_USE(Y)
  9806. tmc_report_otpw(stepperY, TMC_Y);
  9807. #endif
  9808. #if M91x_USE(Y2)
  9809. tmc_report_otpw(stepperY2, TMC_Y2);
  9810. #endif
  9811. #if M91x_USE(Z)
  9812. tmc_report_otpw(stepperZ, TMC_Z);
  9813. #endif
  9814. #if M91x_USE(Z2)
  9815. tmc_report_otpw(stepperZ2, TMC_Z2);
  9816. #endif
  9817. #if M91x_USE_E(0)
  9818. tmc_report_otpw(stepperE0, TMC_E0);
  9819. #endif
  9820. #if M91x_USE_E(1)
  9821. tmc_report_otpw(stepperE1, TMC_E1);
  9822. #endif
  9823. #if M91x_USE_E(2)
  9824. tmc_report_otpw(stepperE2, TMC_E2);
  9825. #endif
  9826. #if M91x_USE_E(3)
  9827. tmc_report_otpw(stepperE3, TMC_E3);
  9828. #endif
  9829. #if M91x_USE_E(4)
  9830. tmc_report_otpw(stepperE4, TMC_E4);
  9831. #endif
  9832. }
  9833. /**
  9834. * M912: Clear TMC stepper driver overtemperature pre-warn flag held by the library
  9835. * Specify one or more axes with X, Y, Z, X1, Y1, Z1, X2, Y2, Z2, and E[index].
  9836. * If no axes are given, clear all.
  9837. *
  9838. * Examples:
  9839. * M912 X ; clear X and X2
  9840. * M912 X1 ; clear X1 only
  9841. * M912 X2 ; clear X2 only
  9842. * M912 X E ; clear X, X2, and all E
  9843. * M912 E1 ; clear E1 only
  9844. */
  9845. inline void gcode_M912() {
  9846. const bool hasX = parser.seen(axis_codes[X_AXIS]),
  9847. hasY = parser.seen(axis_codes[Y_AXIS]),
  9848. hasZ = parser.seen(axis_codes[Z_AXIS]),
  9849. hasE = parser.seen(axis_codes[E_CART]),
  9850. hasNone = !hasX && !hasY && !hasZ && !hasE;
  9851. #if M91x_USE(X) || M91x_USE(X2)
  9852. const uint8_t xval = parser.byteval(axis_codes[X_AXIS], 10);
  9853. #if M91x_USE(X)
  9854. if (hasNone || xval == 1 || (hasX && xval == 10)) tmc_clear_otpw(stepperX, TMC_X);
  9855. #endif
  9856. #if M91x_USE(X2)
  9857. if (hasNone || xval == 2 || (hasX && xval == 10)) tmc_clear_otpw(stepperX2, TMC_X2);
  9858. #endif
  9859. #endif
  9860. #if M91x_USE(Y) || M91x_USE(Y2)
  9861. const uint8_t yval = parser.byteval(axis_codes[Y_AXIS], 10);
  9862. #if M91x_USE(Y)
  9863. if (hasNone || yval == 1 || (hasY && yval == 10)) tmc_clear_otpw(stepperY, TMC_Y);
  9864. #endif
  9865. #if M91x_USE(Y2)
  9866. if (hasNone || yval == 2 || (hasY && yval == 10)) tmc_clear_otpw(stepperY2, TMC_Y2);
  9867. #endif
  9868. #endif
  9869. #if M91x_USE(Z) || M91x_USE(Z2)
  9870. const uint8_t zval = parser.byteval(axis_codes[Z_AXIS], 10);
  9871. #if M91x_USE(Z)
  9872. if (hasNone || zval == 1 || (hasZ && zval == 10)) tmc_clear_otpw(stepperZ, TMC_Z);
  9873. #endif
  9874. #if M91x_USE(Z2)
  9875. if (hasNone || zval == 2 || (hasZ && zval == 10)) tmc_clear_otpw(stepperZ2, TMC_Z2);
  9876. #endif
  9877. #endif
  9878. // TODO: If this is a Hangprinter, E_AXIS will not correspond to E0, E1, etc in this way
  9879. #if M91x_USE_E(0) || M91x_USE_E(1) || M91x_USE_E(2) || M91x_USE_E(3) || M91x_USE_E(4)
  9880. const uint8_t eval = parser.byteval(axis_codes[E_AXIS], 10);
  9881. #if M91x_USE_E(0)
  9882. if (hasNone || eval == 0 || (hasE && eval == 10)) tmc_clear_otpw(stepperE0, TMC_E0);
  9883. #endif
  9884. #if M91x_USE_E(1)
  9885. if (hasNone || eval == 1 || (hasE && eval == 10)) tmc_clear_otpw(stepperE1, TMC_E1);
  9886. #endif
  9887. #if M91x_USE_E(2)
  9888. if (hasNone || eval == 2 || (hasE && eval == 10)) tmc_clear_otpw(stepperE2, TMC_E2);
  9889. #endif
  9890. #if M91x_USE_E(3)
  9891. if (hasNone || eval == 3 || (hasE && eval == 10)) tmc_clear_otpw(stepperE3, TMC_E3);
  9892. #endif
  9893. #if M91x_USE_E(4)
  9894. if (hasNone || eval == 4 || (hasE && eval == 10)) tmc_clear_otpw(stepperE4, TMC_E4);
  9895. #endif
  9896. #endif
  9897. }
  9898. /**
  9899. * M913: Set HYBRID_THRESHOLD speed.
  9900. */
  9901. #if ENABLED(HYBRID_THRESHOLD)
  9902. inline void gcode_M913() {
  9903. #define TMC_SAY_PWMTHRS(A,Q) tmc_get_pwmthrs(stepper##Q, TMC_##Q, planner.axis_steps_per_mm[_AXIS(A)])
  9904. #define TMC_SET_PWMTHRS(A,Q) tmc_set_pwmthrs(stepper##Q, value, planner.axis_steps_per_mm[_AXIS(A)])
  9905. #define TMC_SAY_PWMTHRS_E(E) do{ const uint8_t extruder = E; tmc_get_pwmthrs(stepperE##E, TMC_E##E, planner.axis_steps_per_mm[E_AXIS_N]); }while(0)
  9906. #define TMC_SET_PWMTHRS_E(E) do{ const uint8_t extruder = E; tmc_set_pwmthrs(stepperE##E, value, planner.axis_steps_per_mm[E_AXIS_N]); }while(0)
  9907. bool report = true;
  9908. const uint8_t index = parser.byteval('I');
  9909. LOOP_XYZE(i) if (int32_t value = parser.longval(axis_codes[i])) {
  9910. report = false;
  9911. switch (i) {
  9912. case X_AXIS:
  9913. #if AXIS_HAS_STEALTHCHOP(X)
  9914. if (index < 2) TMC_SET_PWMTHRS(X,X);
  9915. #endif
  9916. #if AXIS_HAS_STEALTHCHOP(X2)
  9917. if (!(index & 1)) TMC_SET_PWMTHRS(X,X2);
  9918. #endif
  9919. break;
  9920. case Y_AXIS:
  9921. #if AXIS_HAS_STEALTHCHOP(Y)
  9922. if (index < 2) TMC_SET_PWMTHRS(Y,Y);
  9923. #endif
  9924. #if AXIS_HAS_STEALTHCHOP(Y2)
  9925. if (!(index & 1)) TMC_SET_PWMTHRS(Y,Y2);
  9926. #endif
  9927. break;
  9928. case Z_AXIS:
  9929. #if AXIS_HAS_STEALTHCHOP(Z)
  9930. if (index < 2) TMC_SET_PWMTHRS(Z,Z);
  9931. #endif
  9932. #if AXIS_HAS_STEALTHCHOP(Z2)
  9933. if (!(index & 1)) TMC_SET_PWMTHRS(Z,Z2);
  9934. #endif
  9935. break;
  9936. case E_CART: {
  9937. if (get_target_extruder_from_command(913)) return;
  9938. switch (target_extruder) {
  9939. #if AXIS_HAS_STEALTHCHOP(E0)
  9940. case 0: TMC_SET_PWMTHRS_E(0); break;
  9941. #endif
  9942. #if E_STEPPERS > 1 && AXIS_HAS_STEALTHCHOP(E1)
  9943. case 1: TMC_SET_PWMTHRS_E(1); break;
  9944. #endif
  9945. #if E_STEPPERS > 2 && AXIS_HAS_STEALTHCHOP(E2)
  9946. case 2: TMC_SET_PWMTHRS_E(2); break;
  9947. #endif
  9948. #if E_STEPPERS > 3 && AXIS_HAS_STEALTHCHOP(E3)
  9949. case 3: TMC_SET_PWMTHRS_E(3); break;
  9950. #endif
  9951. #if E_STEPPERS > 4 && AXIS_HAS_STEALTHCHOP(E4)
  9952. case 4: TMC_SET_PWMTHRS_E(4); break;
  9953. #endif
  9954. }
  9955. } break;
  9956. }
  9957. }
  9958. if (report) {
  9959. #if AXIS_HAS_STEALTHCHOP(X)
  9960. TMC_SAY_PWMTHRS(X,X);
  9961. #endif
  9962. #if AXIS_HAS_STEALTHCHOP(X2)
  9963. TMC_SAY_PWMTHRS(X,X2);
  9964. #endif
  9965. #if AXIS_HAS_STEALTHCHOP(Y)
  9966. TMC_SAY_PWMTHRS(Y,Y);
  9967. #endif
  9968. #if AXIS_HAS_STEALTHCHOP(Y2)
  9969. TMC_SAY_PWMTHRS(Y,Y2);
  9970. #endif
  9971. #if AXIS_HAS_STEALTHCHOP(Z)
  9972. TMC_SAY_PWMTHRS(Z,Z);
  9973. #endif
  9974. #if AXIS_HAS_STEALTHCHOP(Z2)
  9975. TMC_SAY_PWMTHRS(Z,Z2);
  9976. #endif
  9977. #if AXIS_HAS_STEALTHCHOP(E0)
  9978. TMC_SAY_PWMTHRS_E(0);
  9979. #endif
  9980. #if E_STEPPERS > 1 && AXIS_HAS_STEALTHCHOP(E1)
  9981. TMC_SAY_PWMTHRS_E(1);
  9982. #endif
  9983. #if E_STEPPERS > 2 && AXIS_HAS_STEALTHCHOP(E2)
  9984. TMC_SAY_PWMTHRS_E(2);
  9985. #endif
  9986. #if E_STEPPERS > 3 && AXIS_HAS_STEALTHCHOP(E3)
  9987. TMC_SAY_PWMTHRS_E(3);
  9988. #endif
  9989. #if E_STEPPERS > 4 && AXIS_HAS_STEALTHCHOP(E4)
  9990. TMC_SAY_PWMTHRS_E(4);
  9991. #endif
  9992. }
  9993. }
  9994. #endif // HYBRID_THRESHOLD
  9995. /**
  9996. * M914: Set SENSORLESS_HOMING sensitivity.
  9997. */
  9998. #if ENABLED(SENSORLESS_HOMING)
  9999. inline void gcode_M914() {
  10000. #define TMC_SAY_SGT(Q) tmc_get_sgt(stepper##Q, TMC_##Q)
  10001. #define TMC_SET_SGT(Q) tmc_set_sgt(stepper##Q, value)
  10002. bool report = true;
  10003. const uint8_t index = parser.byteval('I');
  10004. LOOP_XYZ(i) if (parser.seen(axis_codes[i])) {
  10005. const int8_t value = (int8_t)constrain(parser.value_int(), -64, 63);
  10006. report = false;
  10007. switch (i) {
  10008. #if X_SENSORLESS
  10009. case X_AXIS:
  10010. #if AXIS_HAS_STALLGUARD(X)
  10011. if (index < 2) TMC_SET_SGT(X);
  10012. #endif
  10013. #if AXIS_HAS_STALLGUARD(X2)
  10014. if (!(index & 1)) TMC_SET_SGT(X2);
  10015. #endif
  10016. break;
  10017. #endif
  10018. #if Y_SENSORLESS
  10019. case Y_AXIS:
  10020. #if AXIS_HAS_STALLGUARD(Y)
  10021. if (index < 2) TMC_SET_SGT(Y);
  10022. #endif
  10023. #if AXIS_HAS_STALLGUARD(Y2)
  10024. if (!(index & 1)) TMC_SET_SGT(Y2);
  10025. #endif
  10026. break;
  10027. #endif
  10028. #if Z_SENSORLESS
  10029. case Z_AXIS:
  10030. #if AXIS_HAS_STALLGUARD(Z)
  10031. if (index < 2) TMC_SET_SGT(Z);
  10032. #endif
  10033. #if AXIS_HAS_STALLGUARD(Z2)
  10034. if (!(index & 1)) TMC_SET_SGT(Z2);
  10035. #endif
  10036. break;
  10037. #endif
  10038. }
  10039. }
  10040. if (report) {
  10041. #if X_SENSORLESS
  10042. #if AXIS_HAS_STALLGUARD(X)
  10043. TMC_SAY_SGT(X);
  10044. #endif
  10045. #if AXIS_HAS_STALLGUARD(X2)
  10046. TMC_SAY_SGT(X2);
  10047. #endif
  10048. #endif
  10049. #if Y_SENSORLESS
  10050. #if AXIS_HAS_STALLGUARD(Y)
  10051. TMC_SAY_SGT(Y);
  10052. #endif
  10053. #if AXIS_HAS_STALLGUARD(Y2)
  10054. TMC_SAY_SGT(Y2);
  10055. #endif
  10056. #endif
  10057. #if Z_SENSORLESS
  10058. #if AXIS_HAS_STALLGUARD(Z)
  10059. TMC_SAY_SGT(Z);
  10060. #endif
  10061. #if AXIS_HAS_STALLGUARD(Z2)
  10062. TMC_SAY_SGT(Z2);
  10063. #endif
  10064. #endif
  10065. }
  10066. }
  10067. #endif // SENSORLESS_HOMING
  10068. /**
  10069. * TMC Z axis calibration routine
  10070. */
  10071. #if ENABLED(TMC_Z_CALIBRATION)
  10072. inline void gcode_M915() {
  10073. const uint16_t _rms = parser.seenval('S') ? parser.value_int() : CALIBRATION_CURRENT,
  10074. _z = parser.seenval('Z') ? parser.value_linear_units() : CALIBRATION_EXTRA_HEIGHT;
  10075. if (!TEST(axis_known_position, Z_AXIS)) {
  10076. SERIAL_ECHOLNPGM("\nPlease home Z axis first");
  10077. return;
  10078. }
  10079. #if AXIS_IS_TMC(Z)
  10080. const uint16_t Z_current_1 = stepperZ.getCurrent();
  10081. stepperZ.setCurrent(_rms, R_SENSE, HOLD_MULTIPLIER);
  10082. #endif
  10083. #if AXIS_IS_TMC(Z2)
  10084. const uint16_t Z2_current_1 = stepperZ2.getCurrent();
  10085. stepperZ2.setCurrent(_rms, R_SENSE, HOLD_MULTIPLIER);
  10086. #endif
  10087. SERIAL_ECHOPAIR("\nCalibration current: Z", _rms);
  10088. soft_endstops_enabled = false;
  10089. do_blocking_move_to_z(Z_MAX_POS+_z);
  10090. #if AXIS_IS_TMC(Z)
  10091. stepperZ.setCurrent(Z_current_1, R_SENSE, HOLD_MULTIPLIER);
  10092. #endif
  10093. #if AXIS_IS_TMC(Z2)
  10094. stepperZ2.setCurrent(Z2_current_1, R_SENSE, HOLD_MULTIPLIER);
  10095. #endif
  10096. do_blocking_move_to_z(Z_MAX_POS);
  10097. soft_endstops_enabled = true;
  10098. SERIAL_ECHOLNPGM("\nHoming Z due to lost steps");
  10099. enqueue_and_echo_commands_P(PSTR("G28 Z"));
  10100. }
  10101. #endif
  10102. #endif // HAS_TRINAMIC
  10103. /**
  10104. * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S
  10105. */
  10106. inline void gcode_M907() {
  10107. #if HAS_DIGIPOTSS
  10108. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.digipot_current(i, parser.value_int());
  10109. if (parser.seen('B')) stepper.digipot_current(4, parser.value_int());
  10110. if (parser.seen('S')) for (uint8_t i = 0; i <= 4; i++) stepper.digipot_current(i, parser.value_int());
  10111. #elif HAS_MOTOR_CURRENT_PWM
  10112. #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY)
  10113. if (parser.seen('X')) stepper.digipot_current(0, parser.value_int());
  10114. #endif
  10115. #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z)
  10116. if (parser.seen('Z')) stepper.digipot_current(1, parser.value_int());
  10117. #endif
  10118. #if PIN_EXISTS(MOTOR_CURRENT_PWM_E)
  10119. if (parser.seen('E')) stepper.digipot_current(2, parser.value_int());
  10120. #endif
  10121. #endif
  10122. #if ENABLED(DIGIPOT_I2C)
  10123. // this one uses actual amps in floating point
  10124. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) digipot_i2c_set_current(i, parser.value_float());
  10125. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  10126. for (uint8_t i = NUM_AXIS; i < DIGIPOT_I2C_NUM_CHANNELS; i++) if (parser.seen('B' + i - (NUM_AXIS))) digipot_i2c_set_current(i, parser.value_float());
  10127. #endif
  10128. #if ENABLED(DAC_STEPPER_CURRENT)
  10129. if (parser.seen('S')) {
  10130. const float dac_percent = parser.value_float();
  10131. for (uint8_t i = 0; i <= 4; i++) dac_current_percent(i, dac_percent);
  10132. }
  10133. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) dac_current_percent(i, parser.value_float());
  10134. #endif
  10135. }
  10136. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  10137. /**
  10138. * M908: Control digital trimpot directly (M908 P<pin> S<current>)
  10139. */
  10140. inline void gcode_M908() {
  10141. #if HAS_DIGIPOTSS
  10142. stepper.digitalPotWrite(
  10143. parser.intval('P'),
  10144. parser.intval('S')
  10145. );
  10146. #endif
  10147. #ifdef DAC_STEPPER_CURRENT
  10148. dac_current_raw(
  10149. parser.byteval('P', -1),
  10150. parser.ushortval('S', 0)
  10151. );
  10152. #endif
  10153. }
  10154. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  10155. inline void gcode_M909() { dac_print_values(); }
  10156. inline void gcode_M910() { dac_commit_eeprom(); }
  10157. #endif
  10158. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  10159. #if HAS_MICROSTEPS
  10160. // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  10161. inline void gcode_M350() {
  10162. if (parser.seen('S')) for (int i = 0; i <= 4; i++) stepper.microstep_mode(i, parser.value_byte());
  10163. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_mode(i, parser.value_byte());
  10164. if (parser.seen('B')) stepper.microstep_mode(4, parser.value_byte());
  10165. stepper.microstep_readings();
  10166. }
  10167. /**
  10168. * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B
  10169. * S# determines MS1 or MS2, X# sets the pin high/low.
  10170. */
  10171. inline void gcode_M351() {
  10172. if (parser.seenval('S')) switch (parser.value_byte()) {
  10173. case 1:
  10174. LOOP_XYZE(i) if (parser.seenval(axis_codes[i])) stepper.microstep_ms(i, parser.value_byte(), -1);
  10175. if (parser.seenval('B')) stepper.microstep_ms(4, parser.value_byte(), -1);
  10176. break;
  10177. case 2:
  10178. LOOP_XYZE(i) if (parser.seenval(axis_codes[i])) stepper.microstep_ms(i, -1, parser.value_byte());
  10179. if (parser.seenval('B')) stepper.microstep_ms(4, -1, parser.value_byte());
  10180. break;
  10181. }
  10182. stepper.microstep_readings();
  10183. }
  10184. #endif // HAS_MICROSTEPS
  10185. #if HAS_CASE_LIGHT
  10186. #ifndef INVERT_CASE_LIGHT
  10187. #define INVERT_CASE_LIGHT false
  10188. #endif
  10189. uint8_t case_light_brightness; // LCD routine wants INT
  10190. bool case_light_on;
  10191. #if ENABLED(CASE_LIGHT_USE_NEOPIXEL)
  10192. LEDColor case_light_color =
  10193. #ifdef CASE_LIGHT_NEOPIXEL_COLOR
  10194. CASE_LIGHT_NEOPIXEL_COLOR
  10195. #else
  10196. { 255, 255, 255, 255 }
  10197. #endif
  10198. ;
  10199. #endif
  10200. void update_case_light() {
  10201. const uint8_t i = case_light_on ? case_light_brightness : 0, n10ct = INVERT_CASE_LIGHT ? 255 - i : i;
  10202. #if ENABLED(CASE_LIGHT_USE_NEOPIXEL)
  10203. leds.set_color(
  10204. MakeLEDColor(case_light_color.r, case_light_color.g, case_light_color.b, case_light_color.w, n10ct),
  10205. false
  10206. );
  10207. #else // !CASE_LIGHT_USE_NEOPIXEL
  10208. SET_OUTPUT(CASE_LIGHT_PIN);
  10209. if (USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN))
  10210. analogWrite(CASE_LIGHT_PIN, n10ct);
  10211. else {
  10212. const bool s = case_light_on ? !INVERT_CASE_LIGHT : INVERT_CASE_LIGHT;
  10213. WRITE(CASE_LIGHT_PIN, s ? HIGH : LOW);
  10214. }
  10215. #endif // !CASE_LIGHT_USE_NEOPIXEL
  10216. }
  10217. #endif // HAS_CASE_LIGHT
  10218. /**
  10219. * M355: Turn case light on/off and set brightness
  10220. *
  10221. * P<byte> Set case light brightness (PWM pin required - ignored otherwise)
  10222. *
  10223. * S<bool> Set case light on/off
  10224. *
  10225. * When S turns on the light on a PWM pin then the current brightness level is used/restored
  10226. *
  10227. * M355 P200 S0 turns off the light & sets the brightness level
  10228. * M355 S1 turns on the light with a brightness of 200 (assuming a PWM pin)
  10229. */
  10230. inline void gcode_M355() {
  10231. #if HAS_CASE_LIGHT
  10232. uint8_t args = 0;
  10233. if (parser.seenval('P')) ++args, case_light_brightness = parser.value_byte();
  10234. if (parser.seenval('S')) ++args, case_light_on = parser.value_bool();
  10235. if (args) update_case_light();
  10236. // always report case light status
  10237. SERIAL_ECHO_START();
  10238. if (!case_light_on) {
  10239. SERIAL_ECHOLNPGM("Case light: off");
  10240. }
  10241. else {
  10242. if (!USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) SERIAL_ECHOLNPGM("Case light: on");
  10243. else SERIAL_ECHOLNPAIR("Case light: ", int(case_light_brightness));
  10244. }
  10245. #else
  10246. SERIAL_ERROR_START();
  10247. SERIAL_ERRORLNPGM(MSG_ERR_M355_NONE);
  10248. #endif // HAS_CASE_LIGHT
  10249. }
  10250. #if ENABLED(MIXING_EXTRUDER)
  10251. /**
  10252. * M163: Set a single mix factor for a mixing extruder
  10253. * This is called "weight" by some systems.
  10254. * The 'P' values must sum to 1.0 or must be followed by M164 to normalize them.
  10255. *
  10256. * S[index] The channel index to set
  10257. * P[float] The mix value
  10258. */
  10259. inline void gcode_M163() {
  10260. const int mix_index = parser.intval('S');
  10261. if (mix_index < MIXING_STEPPERS)
  10262. mixing_factor[mix_index] = MAX(parser.floatval('P'), 0.0);
  10263. }
  10264. /**
  10265. * M164: Normalize and commit the mix.
  10266. * If 'S' is given store as a virtual tool. (Requires MIXING_VIRTUAL_TOOLS > 1)
  10267. *
  10268. * S[index] The virtual tool to store
  10269. */
  10270. inline void gcode_M164() {
  10271. normalize_mix();
  10272. #if MIXING_VIRTUAL_TOOLS > 1
  10273. const int tool_index = parser.intval('S', -1);
  10274. if (WITHIN(tool_index, 0, MIXING_VIRTUAL_TOOLS - 1)) {
  10275. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  10276. mixing_virtual_tool_mix[tool_index][i] = mixing_factor[i];
  10277. }
  10278. #endif
  10279. }
  10280. #if ENABLED(DIRECT_MIXING_IN_G1)
  10281. /**
  10282. * M165: Set multiple mix factors for a mixing extruder.
  10283. * Factors that are left out will be set to 0.
  10284. * All factors should sum to 1.0, but they will be normalized regardless.
  10285. *
  10286. * A[factor] Mix factor for extruder stepper 1
  10287. * B[factor] Mix factor for extruder stepper 2
  10288. * C[factor] Mix factor for extruder stepper 3
  10289. * D[factor] Mix factor for extruder stepper 4
  10290. * H[factor] Mix factor for extruder stepper 5
  10291. * I[factor] Mix factor for extruder stepper 6
  10292. */
  10293. inline void gcode_M165() { gcode_get_mix(); }
  10294. #endif
  10295. #endif // MIXING_EXTRUDER
  10296. /**
  10297. * M999: Restart after being stopped
  10298. *
  10299. * Default behaviour is to flush the serial buffer and request
  10300. * a resend to the host starting on the last N line received.
  10301. *
  10302. * Sending "M999 S1" will resume printing without flushing the
  10303. * existing command buffer.
  10304. *
  10305. */
  10306. inline void gcode_M999() {
  10307. Running = true;
  10308. lcd_reset_alert_level();
  10309. if (parser.boolval('S')) return;
  10310. // gcode_LastN = Stopped_gcode_LastN;
  10311. flush_and_request_resend();
  10312. }
  10313. #if DO_SWITCH_EXTRUDER
  10314. #if EXTRUDERS > 3
  10315. #define REQ_ANGLES 4
  10316. #define _SERVO_NR (e < 2 ? SWITCHING_EXTRUDER_SERVO_NR : SWITCHING_EXTRUDER_E23_SERVO_NR)
  10317. #else
  10318. #define REQ_ANGLES 2
  10319. #define _SERVO_NR SWITCHING_EXTRUDER_SERVO_NR
  10320. #endif
  10321. inline void move_extruder_servo(const uint8_t e) {
  10322. constexpr int16_t angles[] = SWITCHING_EXTRUDER_SERVO_ANGLES;
  10323. static_assert(COUNT(angles) == REQ_ANGLES, "SWITCHING_EXTRUDER_SERVO_ANGLES needs " STRINGIFY(REQ_ANGLES) " angles.");
  10324. planner.synchronize();
  10325. #if EXTRUDERS & 1
  10326. if (e < EXTRUDERS - 1)
  10327. #endif
  10328. {
  10329. MOVE_SERVO(_SERVO_NR, angles[e]);
  10330. safe_delay(500);
  10331. }
  10332. }
  10333. #endif // DO_SWITCH_EXTRUDER
  10334. #if ENABLED(SWITCHING_NOZZLE)
  10335. inline void move_nozzle_servo(const uint8_t e) {
  10336. const int16_t angles[2] = SWITCHING_NOZZLE_SERVO_ANGLES;
  10337. planner.synchronize();
  10338. MOVE_SERVO(SWITCHING_NOZZLE_SERVO_NR, angles[e]);
  10339. safe_delay(500);
  10340. }
  10341. #endif
  10342. inline void invalid_extruder_error(const uint8_t e) {
  10343. SERIAL_ECHO_START();
  10344. SERIAL_CHAR('T');
  10345. SERIAL_ECHO_F(e, DEC);
  10346. SERIAL_CHAR(' ');
  10347. SERIAL_ECHOLNPGM(MSG_INVALID_EXTRUDER);
  10348. }
  10349. #if ENABLED(PARKING_EXTRUDER)
  10350. #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT)
  10351. #define PE_MAGNET_ON_STATE !PARKING_EXTRUDER_SOLENOIDS_PINS_ACTIVE
  10352. #else
  10353. #define PE_MAGNET_ON_STATE PARKING_EXTRUDER_SOLENOIDS_PINS_ACTIVE
  10354. #endif
  10355. void pe_set_magnet(const uint8_t extruder_num, const uint8_t state) {
  10356. switch (extruder_num) {
  10357. case 1: OUT_WRITE(SOL1_PIN, state); break;
  10358. default: OUT_WRITE(SOL0_PIN, state); break;
  10359. }
  10360. #if PARKING_EXTRUDER_SOLENOIDS_DELAY > 0
  10361. dwell(PARKING_EXTRUDER_SOLENOIDS_DELAY);
  10362. #endif
  10363. }
  10364. inline void pe_activate_magnet(const uint8_t extruder_num) { pe_set_magnet(extruder_num, PE_MAGNET_ON_STATE); }
  10365. inline void pe_deactivate_magnet(const uint8_t extruder_num) { pe_set_magnet(extruder_num, !PE_MAGNET_ON_STATE); }
  10366. #endif // PARKING_EXTRUDER
  10367. #if HAS_FANMUX
  10368. void fanmux_switch(const uint8_t e) {
  10369. WRITE(FANMUX0_PIN, TEST(e, 0) ? HIGH : LOW);
  10370. #if PIN_EXISTS(FANMUX1)
  10371. WRITE(FANMUX1_PIN, TEST(e, 1) ? HIGH : LOW);
  10372. #if PIN_EXISTS(FANMUX2)
  10373. WRITE(FANMUX2, TEST(e, 2) ? HIGH : LOW);
  10374. #endif
  10375. #endif
  10376. }
  10377. FORCE_INLINE void fanmux_init(void) {
  10378. SET_OUTPUT(FANMUX0_PIN);
  10379. #if PIN_EXISTS(FANMUX1)
  10380. SET_OUTPUT(FANMUX1_PIN);
  10381. #if PIN_EXISTS(FANMUX2)
  10382. SET_OUTPUT(FANMUX2_PIN);
  10383. #endif
  10384. #endif
  10385. fanmux_switch(0);
  10386. }
  10387. #endif // HAS_FANMUX
  10388. /**
  10389. * Tool Change functions
  10390. */
  10391. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  10392. inline void mixing_tool_change(const uint8_t tmp_extruder) {
  10393. if (tmp_extruder >= MIXING_VIRTUAL_TOOLS)
  10394. return invalid_extruder_error(tmp_extruder);
  10395. // T0-Tnnn: Switch virtual tool by changing the mix
  10396. for (uint8_t j = 0; j < MIXING_STEPPERS; j++)
  10397. mixing_factor[j] = mixing_virtual_tool_mix[tmp_extruder][j];
  10398. }
  10399. #endif // MIXING_EXTRUDER && MIXING_VIRTUAL_TOOLS > 1
  10400. #if ENABLED(DUAL_X_CARRIAGE)
  10401. inline void dualx_tool_change(const uint8_t tmp_extruder, bool &no_move) {
  10402. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10403. if (DEBUGGING(LEVELING)) {
  10404. SERIAL_ECHOPGM("Dual X Carriage Mode ");
  10405. switch (dual_x_carriage_mode) {
  10406. case DXC_FULL_CONTROL_MODE: SERIAL_ECHOLNPGM("DXC_FULL_CONTROL_MODE"); break;
  10407. case DXC_AUTO_PARK_MODE: SERIAL_ECHOLNPGM("DXC_AUTO_PARK_MODE"); break;
  10408. case DXC_DUPLICATION_MODE: SERIAL_ECHOLNPGM("DXC_DUPLICATION_MODE"); break;
  10409. }
  10410. }
  10411. #endif
  10412. const float xhome = x_home_pos(active_extruder);
  10413. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE
  10414. && IsRunning()
  10415. && (delayed_move_time || current_position[X_AXIS] != xhome)
  10416. ) {
  10417. float raised_z = current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT;
  10418. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  10419. NOMORE(raised_z, soft_endstop_max[Z_AXIS]);
  10420. #endif
  10421. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10422. if (DEBUGGING(LEVELING)) {
  10423. SERIAL_ECHOLNPAIR("Raise to ", raised_z);
  10424. SERIAL_ECHOLNPAIR("MoveX to ", xhome);
  10425. SERIAL_ECHOLNPAIR("Lower to ", current_position[Z_AXIS]);
  10426. }
  10427. #endif
  10428. // Park old head: 1) raise 2) move to park position 3) lower
  10429. for (uint8_t i = 0; i < 3; i++)
  10430. planner.buffer_line(
  10431. i == 0 ? current_position[X_AXIS] : xhome,
  10432. current_position[Y_AXIS],
  10433. i == 2 ? current_position[Z_AXIS] : raised_z,
  10434. current_position[E_CART],
  10435. planner.max_feedrate_mm_s[i == 1 ? X_AXIS : Z_AXIS],
  10436. active_extruder
  10437. );
  10438. planner.synchronize();
  10439. }
  10440. // Apply Y & Z extruder offset (X offset is used as home pos with Dual X)
  10441. current_position[Y_AXIS] -= hotend_offset[Y_AXIS][active_extruder] - hotend_offset[Y_AXIS][tmp_extruder];
  10442. current_position[Z_AXIS] -= hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  10443. // Activate the new extruder ahead of calling set_axis_is_at_home!
  10444. active_extruder = tmp_extruder;
  10445. // This function resets the max/min values - the current position may be overwritten below.
  10446. set_axis_is_at_home(X_AXIS);
  10447. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10448. if (DEBUGGING(LEVELING)) DEBUG_POS("New Extruder", current_position);
  10449. #endif
  10450. // Only when auto-parking are carriages safe to move
  10451. if (dual_x_carriage_mode != DXC_AUTO_PARK_MODE) no_move = true;
  10452. switch (dual_x_carriage_mode) {
  10453. case DXC_FULL_CONTROL_MODE:
  10454. // New current position is the position of the activated extruder
  10455. current_position[X_AXIS] = inactive_extruder_x_pos;
  10456. // Save the inactive extruder's position (from the old current_position)
  10457. inactive_extruder_x_pos = destination[X_AXIS];
  10458. break;
  10459. case DXC_AUTO_PARK_MODE:
  10460. // record raised toolhead position for use by unpark
  10461. COPY(raised_parked_position, current_position);
  10462. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  10463. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  10464. NOMORE(raised_parked_position[Z_AXIS], soft_endstop_max[Z_AXIS]);
  10465. #endif
  10466. active_extruder_parked = true;
  10467. delayed_move_time = 0;
  10468. break;
  10469. case DXC_DUPLICATION_MODE:
  10470. // If the new extruder is the left one, set it "parked"
  10471. // This triggers the second extruder to move into the duplication position
  10472. active_extruder_parked = (active_extruder == 0);
  10473. current_position[X_AXIS] = active_extruder_parked ? inactive_extruder_x_pos : destination[X_AXIS] + duplicate_extruder_x_offset;
  10474. inactive_extruder_x_pos = destination[X_AXIS];
  10475. extruder_duplication_enabled = false;
  10476. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10477. if (DEBUGGING(LEVELING)) {
  10478. SERIAL_ECHOLNPAIR("Set inactive_extruder_x_pos=", inactive_extruder_x_pos);
  10479. SERIAL_ECHOLNPGM("Clear extruder_duplication_enabled");
  10480. }
  10481. #endif
  10482. break;
  10483. }
  10484. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10485. if (DEBUGGING(LEVELING)) {
  10486. SERIAL_ECHOLNPAIR("Active extruder parked: ", active_extruder_parked ? "yes" : "no");
  10487. DEBUG_POS("New extruder (parked)", current_position);
  10488. }
  10489. #endif
  10490. // No extra case for HAS_ABL in DUAL_X_CARRIAGE. Does that mean they don't work together?
  10491. }
  10492. #endif // DUAL_X_CARRIAGE
  10493. #if ENABLED(PARKING_EXTRUDER)
  10494. inline void parking_extruder_tool_change(const uint8_t tmp_extruder, bool no_move) {
  10495. constexpr float z_raise = PARKING_EXTRUDER_SECURITY_RAISE;
  10496. if (!no_move) {
  10497. const float parkingposx[] = PARKING_EXTRUDER_PARKING_X,
  10498. midpos = (parkingposx[0] + parkingposx[1]) * 0.5 + hotend_offset[X_AXIS][active_extruder],
  10499. grabpos = parkingposx[tmp_extruder] + hotend_offset[X_AXIS][active_extruder]
  10500. + (tmp_extruder == 0 ? -(PARKING_EXTRUDER_GRAB_DISTANCE) : PARKING_EXTRUDER_GRAB_DISTANCE);
  10501. /**
  10502. * Steps:
  10503. * 1. Raise Z-Axis to give enough clearance
  10504. * 2. Move to park position of old extruder
  10505. * 3. Disengage magnetic field, wait for delay
  10506. * 4. Move near new extruder
  10507. * 5. Engage magnetic field for new extruder
  10508. * 6. Move to parking incl. offset of new extruder
  10509. * 7. Lower Z-Axis
  10510. */
  10511. // STEP 1
  10512. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10513. SERIAL_ECHOLNPGM("Starting Autopark");
  10514. if (DEBUGGING(LEVELING)) DEBUG_POS("current position:", current_position);
  10515. #endif
  10516. current_position[Z_AXIS] += z_raise;
  10517. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10518. SERIAL_ECHOLNPGM("(1) Raise Z-Axis ");
  10519. if (DEBUGGING(LEVELING)) DEBUG_POS("Moving to Raised Z-Position", current_position);
  10520. #endif
  10521. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  10522. planner.synchronize();
  10523. // STEP 2
  10524. current_position[X_AXIS] = parkingposx[active_extruder] + hotend_offset[X_AXIS][active_extruder];
  10525. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10526. SERIAL_ECHOLNPAIR("(2) Park extruder ", active_extruder);
  10527. if (DEBUGGING(LEVELING)) DEBUG_POS("Moving ParkPos", current_position);
  10528. #endif
  10529. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder);
  10530. planner.synchronize();
  10531. // STEP 3
  10532. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10533. SERIAL_ECHOLNPGM("(3) Disengage magnet ");
  10534. #endif
  10535. pe_deactivate_magnet(active_extruder);
  10536. // STEP 4
  10537. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10538. SERIAL_ECHOLNPGM("(4) Move to position near new extruder");
  10539. #endif
  10540. current_position[X_AXIS] += (active_extruder == 0 ? 10 : -10); // move 10mm away from parked extruder
  10541. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10542. if (DEBUGGING(LEVELING)) DEBUG_POS("Moving away from parked extruder", current_position);
  10543. #endif
  10544. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder);
  10545. planner.synchronize();
  10546. // STEP 5
  10547. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10548. SERIAL_ECHOLNPGM("(5) Engage magnetic field");
  10549. #endif
  10550. #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT)
  10551. pe_activate_magnet(active_extruder); //just save power for inverted magnets
  10552. #endif
  10553. pe_activate_magnet(tmp_extruder);
  10554. // STEP 6
  10555. current_position[X_AXIS] = grabpos + (tmp_extruder == 0 ? (+10) : (-10));
  10556. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder);
  10557. current_position[X_AXIS] = grabpos;
  10558. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10559. SERIAL_ECHOLNPAIR("(6) Unpark extruder ", tmp_extruder);
  10560. if (DEBUGGING(LEVELING)) DEBUG_POS("Move UnparkPos", current_position);
  10561. #endif
  10562. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS]/2, active_extruder);
  10563. planner.synchronize();
  10564. // Step 7
  10565. current_position[X_AXIS] = midpos - hotend_offset[X_AXIS][tmp_extruder];
  10566. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10567. SERIAL_ECHOLNPGM("(7) Move midway between hotends");
  10568. if (DEBUGGING(LEVELING)) DEBUG_POS("Move midway to new extruder", current_position);
  10569. #endif
  10570. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder);
  10571. planner.synchronize();
  10572. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10573. SERIAL_ECHOLNPGM("Autopark done.");
  10574. #endif
  10575. }
  10576. else { // nomove == true
  10577. // Only engage magnetic field for new extruder
  10578. pe_activate_magnet(tmp_extruder);
  10579. #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT)
  10580. pe_activate_magnet(active_extruder); // Just save power for inverted magnets
  10581. #endif
  10582. }
  10583. current_position[Z_AXIS] += hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  10584. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10585. if (DEBUGGING(LEVELING)) DEBUG_POS("Applying Z-offset", current_position);
  10586. #endif
  10587. }
  10588. #endif // PARKING_EXTRUDER
  10589. /**
  10590. * Perform a tool-change, which may result in moving the
  10591. * previous tool out of the way and the new tool into place.
  10592. */
  10593. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s/*=0.0*/, bool no_move/*=false*/) {
  10594. planner.synchronize();
  10595. #if HAS_LEVELING
  10596. // Set current position to the physical position
  10597. const bool leveling_was_active = planner.leveling_active;
  10598. set_bed_leveling_enabled(false);
  10599. #endif
  10600. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  10601. mixing_tool_change(tmp_extruder);
  10602. #else // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  10603. if (tmp_extruder >= EXTRUDERS)
  10604. return invalid_extruder_error(tmp_extruder);
  10605. #if HOTENDS > 1
  10606. const float old_feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : feedrate_mm_s;
  10607. feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  10608. if (tmp_extruder != active_extruder) {
  10609. if (!no_move && axis_unhomed_error()) {
  10610. no_move = true;
  10611. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10612. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("No move on toolchange");
  10613. #endif
  10614. }
  10615. #if ENABLED(DUAL_X_CARRIAGE)
  10616. #if HAS_SOFTWARE_ENDSTOPS
  10617. // Update the X software endstops early
  10618. active_extruder = tmp_extruder;
  10619. update_software_endstops(X_AXIS);
  10620. active_extruder = !tmp_extruder;
  10621. #endif
  10622. // Don't move the new extruder out of bounds
  10623. if (!WITHIN(current_position[X_AXIS], soft_endstop_min[X_AXIS], soft_endstop_max[X_AXIS]))
  10624. no_move = true;
  10625. if (!no_move) set_destination_from_current();
  10626. dualx_tool_change(tmp_extruder, no_move); // Can modify no_move
  10627. #else // !DUAL_X_CARRIAGE
  10628. set_destination_from_current();
  10629. #if ENABLED(PARKING_EXTRUDER)
  10630. parking_extruder_tool_change(tmp_extruder, no_move);
  10631. #endif
  10632. #if ENABLED(SWITCHING_NOZZLE)
  10633. // Always raise by at least 1 to avoid workpiece
  10634. const float zdiff = hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  10635. current_position[Z_AXIS] += (zdiff > 0.0 ? zdiff : 0.0) + 1;
  10636. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  10637. move_nozzle_servo(tmp_extruder);
  10638. #endif
  10639. const float xdiff = hotend_offset[X_AXIS][tmp_extruder] - hotend_offset[X_AXIS][active_extruder],
  10640. ydiff = hotend_offset[Y_AXIS][tmp_extruder] - hotend_offset[Y_AXIS][active_extruder];
  10641. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10642. if (DEBUGGING(LEVELING)) {
  10643. SERIAL_ECHOPAIR("Offset Tool XY by { ", xdiff);
  10644. SERIAL_ECHOPAIR(", ", ydiff);
  10645. SERIAL_ECHOLNPGM(" }");
  10646. }
  10647. #endif
  10648. // The newly-selected extruder XY is actually at...
  10649. current_position[X_AXIS] += xdiff;
  10650. current_position[Y_AXIS] += ydiff;
  10651. // Set the new active extruder
  10652. active_extruder = tmp_extruder;
  10653. #endif // !DUAL_X_CARRIAGE
  10654. #if ENABLED(SWITCHING_NOZZLE)
  10655. // The newly-selected extruder Z is actually at...
  10656. current_position[Z_AXIS] -= zdiff;
  10657. #endif
  10658. // Tell the planner the new "current position"
  10659. SYNC_PLAN_POSITION_KINEMATIC();
  10660. #if ENABLED(DELTA)
  10661. //LOOP_XYZ(i) update_software_endstops(i); // or modify the constrain function
  10662. const bool safe_to_move = current_position[Z_AXIS] < delta_clip_start_height - 1;
  10663. #else
  10664. constexpr bool safe_to_move = true;
  10665. #endif
  10666. // Raise, move, and lower again
  10667. if (safe_to_move && !no_move && IsRunning()) {
  10668. #if DISABLED(SWITCHING_NOZZLE)
  10669. // Do a small lift to avoid the workpiece in the move back (below)
  10670. current_position[Z_AXIS] += 1.0;
  10671. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  10672. #endif
  10673. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10674. if (DEBUGGING(LEVELING)) DEBUG_POS("Move back", destination);
  10675. #endif
  10676. // Move back to the original (or tweaked) position
  10677. do_blocking_move_to(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS]);
  10678. #if ENABLED(DUAL_X_CARRIAGE)
  10679. active_extruder_parked = false;
  10680. #endif
  10681. }
  10682. #if ENABLED(SWITCHING_NOZZLE)
  10683. else {
  10684. // Move back down. (Including when the new tool is higher.)
  10685. do_blocking_move_to_z(destination[Z_AXIS], planner.max_feedrate_mm_s[Z_AXIS]);
  10686. }
  10687. #endif
  10688. } // (tmp_extruder != active_extruder)
  10689. planner.synchronize();
  10690. #if ENABLED(EXT_SOLENOID) && !ENABLED(PARKING_EXTRUDER)
  10691. disable_all_solenoids();
  10692. enable_solenoid_on_active_extruder();
  10693. #endif
  10694. feedrate_mm_s = old_feedrate_mm_s;
  10695. #if HAS_SOFTWARE_ENDSTOPS && ENABLED(DUAL_X_CARRIAGE)
  10696. update_software_endstops(X_AXIS);
  10697. #endif
  10698. #else // HOTENDS <= 1
  10699. UNUSED(fr_mm_s);
  10700. UNUSED(no_move);
  10701. #if ENABLED(MK2_MULTIPLEXER)
  10702. if (tmp_extruder >= E_STEPPERS)
  10703. return invalid_extruder_error(tmp_extruder);
  10704. select_multiplexed_stepper(tmp_extruder);
  10705. #endif
  10706. // Set the new active extruder
  10707. active_extruder = tmp_extruder;
  10708. #endif // HOTENDS <= 1
  10709. #if DO_SWITCH_EXTRUDER
  10710. planner.synchronize();
  10711. move_extruder_servo(active_extruder);
  10712. #endif
  10713. #if HAS_FANMUX
  10714. fanmux_switch(active_extruder);
  10715. #endif
  10716. #if HAS_LEVELING
  10717. // Restore leveling to re-establish the logical position
  10718. set_bed_leveling_enabled(leveling_was_active);
  10719. #endif
  10720. SERIAL_ECHO_START();
  10721. SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, int(active_extruder));
  10722. #endif // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  10723. }
  10724. /**
  10725. * T0-T3: Switch tool, usually switching extruders
  10726. *
  10727. * F[units/min] Set the movement feedrate
  10728. * S1 Don't move the tool in XY after change
  10729. */
  10730. inline void gcode_T(const uint8_t tmp_extruder) {
  10731. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10732. if (DEBUGGING(LEVELING)) {
  10733. SERIAL_ECHOPAIR(">>> gcode_T(", tmp_extruder);
  10734. SERIAL_CHAR(')');
  10735. SERIAL_EOL();
  10736. DEBUG_POS("BEFORE", current_position);
  10737. }
  10738. #endif
  10739. #if HOTENDS == 1 || (ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1)
  10740. tool_change(tmp_extruder);
  10741. #elif HOTENDS > 1
  10742. tool_change(
  10743. tmp_extruder,
  10744. MMM_TO_MMS(parser.linearval('F')),
  10745. (tmp_extruder == active_extruder) || parser.boolval('S')
  10746. );
  10747. #endif
  10748. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10749. if (DEBUGGING(LEVELING)) {
  10750. DEBUG_POS("AFTER", current_position);
  10751. SERIAL_ECHOLNPGM("<<< gcode_T");
  10752. }
  10753. #endif
  10754. }
  10755. /**
  10756. * Process the parsed command and dispatch it to its handler
  10757. */
  10758. void process_parsed_command() {
  10759. KEEPALIVE_STATE(IN_HANDLER);
  10760. // Handle a known G, M, or T
  10761. switch (parser.command_letter) {
  10762. case 'G': switch (parser.codenum) {
  10763. case 0: case 1: gcode_G0_G1( // G0: Fast Move, G1: Linear Move
  10764. #if IS_SCARA
  10765. parser.codenum == 0
  10766. #endif
  10767. ); break;
  10768. #if ENABLED(ARC_SUPPORT) && DISABLED(SCARA)
  10769. case 2: case 3: gcode_G2_G3(parser.codenum == 2); break; // G2: CW ARC, G3: CCW ARC
  10770. #endif
  10771. case 4: gcode_G4(); break; // G4: Dwell
  10772. #if ENABLED(BEZIER_CURVE_SUPPORT)
  10773. case 5: gcode_G5(); break; // G5: Cubic B_spline
  10774. #endif
  10775. #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
  10776. case 6: gcode_G6(); break; // G6: Direct stepper move
  10777. #endif
  10778. #if ENABLED(FWRETRACT)
  10779. case 10: gcode_G10(); break; // G10: Retract
  10780. case 11: gcode_G11(); break; // G11: Prime
  10781. #endif
  10782. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  10783. case 12: gcode_G12(); break; // G12: Clean Nozzle
  10784. #endif
  10785. #if ENABLED(CNC_WORKSPACE_PLANES)
  10786. case 17: gcode_G17(); break; // G17: Select Plane XY
  10787. case 18: gcode_G18(); break; // G18: Select Plane ZX
  10788. case 19: gcode_G19(); break; // G19: Select Plane YZ
  10789. #endif
  10790. #if ENABLED(INCH_MODE_SUPPORT)
  10791. case 20: gcode_G20(); break; // G20: Inch Units
  10792. case 21: gcode_G21(); break; // G21: Millimeter Units
  10793. #endif
  10794. #if ENABLED(G26_MESH_VALIDATION)
  10795. case 26: gcode_G26(); break; // G26: Mesh Validation Pattern
  10796. #endif
  10797. #if ENABLED(NOZZLE_PARK_FEATURE)
  10798. case 27: gcode_G27(); break; // G27: Park Nozzle
  10799. #endif
  10800. case 28: gcode_G28(false); break; // G28: Home one or more axes
  10801. #if HAS_LEVELING
  10802. case 29: gcode_G29(); break; // G29: Detailed Z probe
  10803. #endif
  10804. #if HAS_BED_PROBE
  10805. case 30: gcode_G30(); break; // G30: Single Z probe
  10806. #endif
  10807. #if ENABLED(Z_PROBE_SLED)
  10808. case 31: gcode_G31(); break; // G31: Dock sled
  10809. case 32: gcode_G32(); break; // G32: Undock sled
  10810. #endif
  10811. #if ENABLED(DELTA_AUTO_CALIBRATION)
  10812. case 33: gcode_G33(); break; // G33: Delta Auto-Calibration
  10813. #endif
  10814. #if ENABLED(G38_PROBE_TARGET)
  10815. case 38:
  10816. if (parser.subcode == 2 || parser.subcode == 3)
  10817. gcode_G38(parser.subcode == 2); // G38.2, G38.3: Probe towards object
  10818. break;
  10819. #endif
  10820. #if HAS_MESH
  10821. case 42: gcode_G42(); break; // G42: Move to mesh point
  10822. #endif
  10823. case 90: relative_mode = false; break; // G90: Absolute coordinates
  10824. case 91: relative_mode = true; break; // G91: Relative coordinates
  10825. case 92: gcode_G92(); break; // G92: Set Position
  10826. #if ENABLED(MECHADUINO_I2C_COMMANDS)
  10827. case 95: gcode_G95(); break; // G95: Set torque mode
  10828. case 96: gcode_G96(); break; // G96: Mark encoder reference point
  10829. #endif
  10830. #if ENABLED(DEBUG_GCODE_PARSER)
  10831. case 800: parser.debug(); break; // G800: GCode Parser Test for G
  10832. #endif
  10833. default: parser.unknown_command_error();
  10834. }
  10835. break;
  10836. case 'M': switch (parser.codenum) {
  10837. #if HAS_RESUME_CONTINUE
  10838. case 0: case 1: gcode_M0_M1(); break; // M0: Unconditional stop, M1: Conditional stop
  10839. #endif
  10840. #if ENABLED(SPINDLE_LASER_ENABLE)
  10841. case 3: gcode_M3_M4(true); break; // M3: Laser/CW-Spindle Power
  10842. case 4: gcode_M3_M4(false); break; // M4: Laser/CCW-Spindle Power
  10843. case 5: gcode_M5(); break; // M5: Laser/Spindle OFF
  10844. #endif
  10845. case 17: gcode_M17(); break; // M17: Enable all steppers
  10846. #if ENABLED(SDSUPPORT)
  10847. case 20: gcode_M20(); break; // M20: List SD Card
  10848. case 21: gcode_M21(); break; // M21: Init SD Card
  10849. case 22: gcode_M22(); break; // M22: Release SD Card
  10850. case 23: gcode_M23(); break; // M23: Select File
  10851. case 24: gcode_M24(); break; // M24: Start SD Print
  10852. case 25: gcode_M25(); break; // M25: Pause SD Print
  10853. case 26: gcode_M26(); break; // M26: Set SD Index
  10854. case 27: gcode_M27(); break; // M27: Get SD Status
  10855. case 28: gcode_M28(); break; // M28: Start SD Write
  10856. case 29: gcode_M29(); break; // M29: Stop SD Write
  10857. case 30: gcode_M30(); break; // M30: Delete File
  10858. case 32: gcode_M32(); break; // M32: Select file, Start SD Print
  10859. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  10860. case 33: gcode_M33(); break; // M33: Report longname path
  10861. #endif
  10862. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  10863. case 34: gcode_M34(); break; // M34: Set SD card sorting options
  10864. #endif
  10865. case 928: gcode_M928(); break; // M928: Start SD write
  10866. #endif // SDSUPPORT
  10867. case 31: gcode_M31(); break; // M31: Report print job elapsed time
  10868. case 42: gcode_M42(); break; // M42: Change pin state
  10869. #if ENABLED(PINS_DEBUGGING)
  10870. case 43: gcode_M43(); break; // M43: Read/monitor pin and endstop states
  10871. #endif
  10872. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  10873. case 48: gcode_M48(); break; // M48: Z probe repeatability test
  10874. #endif
  10875. #if ENABLED(G26_MESH_VALIDATION)
  10876. case 49: gcode_M49(); break; // M49: Toggle the G26 Debug Flag
  10877. #endif
  10878. #if ENABLED(ULTRA_LCD) && ENABLED(LCD_SET_PROGRESS_MANUALLY)
  10879. case 73: gcode_M73(); break; // M73: Set Print Progress %
  10880. #endif
  10881. case 75: gcode_M75(); break; // M75: Start Print Job Timer
  10882. case 76: gcode_M76(); break; // M76: Pause Print Job Timer
  10883. case 77: gcode_M77(); break; // M77: Stop Print Job Timer
  10884. #if ENABLED(PRINTCOUNTER)
  10885. case 78: gcode_M78(); break; // M78: Report Print Statistics
  10886. #endif
  10887. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  10888. case 100: gcode_M100(); break; // M100: Free Memory Report
  10889. #endif
  10890. case 104: gcode_M104(); break; // M104: Set Hotend Temperature
  10891. case 110: gcode_M110(); break; // M110: Set Current Line Number
  10892. case 111: gcode_M111(); break; // M111: Set Debug Flags
  10893. #if DISABLED(EMERGENCY_PARSER)
  10894. case 108: gcode_M108(); break; // M108: Cancel Waiting
  10895. case 112: gcode_M112(); break; // M112: Emergency Stop
  10896. case 410: gcode_M410(); break; // M410: Quickstop. Abort all planned moves
  10897. #else
  10898. case 108: case 112: case 410: break; // Silently drop as handled by emergency parser
  10899. #endif
  10900. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  10901. case 113: gcode_M113(); break; // M113: Set Host Keepalive Interval
  10902. #endif
  10903. case 105: gcode_M105(); KEEPALIVE_STATE(NOT_BUSY); return; // M105: Report Temperatures (and say "ok")
  10904. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  10905. case 155: gcode_M155(); break; // M155: Set Temperature Auto-report Interval
  10906. #endif
  10907. case 109: gcode_M109(); break; // M109: Set Hotend Temperature. Wait for target.
  10908. #if HAS_HEATED_BED
  10909. case 140: gcode_M140(); break; // M140: Set Bed Temperature
  10910. case 190: gcode_M190(); break; // M190: Set Bed Temperature. Wait for target.
  10911. #endif
  10912. #if FAN_COUNT > 0
  10913. case 106: gcode_M106(); break; // M106: Set Fan Speed
  10914. case 107: gcode_M107(); break; // M107: Fan Off
  10915. #endif
  10916. #if ENABLED(PARK_HEAD_ON_PAUSE)
  10917. case 125: gcode_M125(); break; // M125: Park (for Filament Change)
  10918. #endif
  10919. #if ENABLED(BARICUDA)
  10920. #if HAS_HEATER_1
  10921. case 126: gcode_M126(); break; // M126: Valve 1 Open
  10922. case 127: gcode_M127(); break; // M127: Valve 1 Closed
  10923. #endif
  10924. #if HAS_HEATER_2
  10925. case 128: gcode_M128(); break; // M128: Valve 2 Open
  10926. case 129: gcode_M129(); break; // M129: Valve 2 Closed
  10927. #endif
  10928. #endif
  10929. #if HAS_POWER_SWITCH
  10930. case 80: gcode_M80(); break; // M80: Turn on Power Supply
  10931. #endif
  10932. case 81: gcode_M81(); break; // M81: Turn off Power and Power Supply
  10933. case 82: gcode_M82(); break; // M82: Disable Relative E-Axis
  10934. case 83: gcode_M83(); break; // M83: Set Relative E-Axis
  10935. case 18: case 84: gcode_M18_M84(); break; // M18/M84: Disable Steppers / Set Timeout
  10936. case 85: gcode_M85(); break; // M85: Set inactivity stepper shutdown timeout
  10937. case 92: gcode_M92(); break; // M92: Set steps-per-unit
  10938. case 114: gcode_M114(); break; // M114: Report Current Position
  10939. case 115: gcode_M115(); break; // M115: Capabilities Report
  10940. case 117: gcode_M117(); break; // M117: Set LCD message text
  10941. case 118: gcode_M118(); break; // M118: Print a message in the host console
  10942. case 119: gcode_M119(); break; // M119: Report Endstop states
  10943. case 120: gcode_M120(); break; // M120: Enable Endstops
  10944. case 121: gcode_M121(); break; // M121: Disable Endstops
  10945. #if ENABLED(ULTIPANEL)
  10946. case 145: gcode_M145(); break; // M145: Set material heatup parameters
  10947. #endif
  10948. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  10949. case 149: gcode_M149(); break; // M149: Set Temperature Units, C F K
  10950. #endif
  10951. #if HAS_COLOR_LEDS
  10952. case 150: gcode_M150(); break; // M150: Set Status LED Color
  10953. #endif
  10954. #if ENABLED(MIXING_EXTRUDER)
  10955. case 163: gcode_M163(); break; // M163: Set Mixing Component
  10956. #if MIXING_VIRTUAL_TOOLS > 1
  10957. case 164: gcode_M164(); break; // M164: Save Current Mix
  10958. #endif
  10959. #if ENABLED(DIRECT_MIXING_IN_G1)
  10960. case 165: gcode_M165(); break; // M165: Set Multiple Mixing Components
  10961. #endif
  10962. #endif
  10963. #if DISABLED(NO_VOLUMETRICS)
  10964. case 200: gcode_M200(); break; // M200: Set Filament Diameter, Volumetric Extrusion
  10965. #endif
  10966. case 201: gcode_M201(); break; // M201: Set Max Printing Acceleration (units/sec^2)
  10967. #if 0
  10968. case 202: gcode_M202(); break; // M202: Not used for Sprinter/grbl gen6
  10969. #endif
  10970. case 203: gcode_M203(); break; // M203: Set Max Feedrate (units/sec)
  10971. case 204: gcode_M204(); break; // M204: Set Acceleration
  10972. case 205: gcode_M205(); break; // M205: Set Advanced settings
  10973. #if HAS_M206_COMMAND
  10974. case 206: gcode_M206(); break; // M206: Set Home Offsets
  10975. case 428: gcode_M428(); break; // M428: Set Home Offsets based on current position
  10976. #endif
  10977. #if ENABLED(FWRETRACT)
  10978. case 207: gcode_M207(); break; // M207: Set Retract Length, Feedrate, Z lift
  10979. case 208: gcode_M208(); break; // M208: Set Additional Prime Length and Feedrate
  10980. case 209:
  10981. if (MIN_AUTORETRACT <= MAX_AUTORETRACT) gcode_M209(); // M209: Turn Auto-Retract on/off
  10982. break;
  10983. #endif
  10984. case 211: gcode_M211(); break; // M211: Enable/Disable/Report Software Endstops
  10985. #if HOTENDS > 1
  10986. case 218: gcode_M218(); break; // M218: Set Tool Offset
  10987. #endif
  10988. case 220: gcode_M220(); break; // M220: Set Feedrate Percentage
  10989. case 221: gcode_M221(); break; // M221: Set Flow Percentage
  10990. case 226: gcode_M226(); break; // M226: Wait for Pin State
  10991. #if defined(CHDK) || HAS_PHOTOGRAPH
  10992. case 240: gcode_M240(); break; // M240: Trigger Camera
  10993. #endif
  10994. #if HAS_LCD_CONTRAST
  10995. case 250: gcode_M250(); break; // M250: Set LCD Contrast
  10996. #endif
  10997. #if ENABLED(EXPERIMENTAL_I2CBUS)
  10998. case 260: gcode_M260(); break; // M260: Send Data to i2c slave
  10999. case 261: gcode_M261(); break; // M261: Request Data from i2c slave
  11000. #endif
  11001. #if HAS_SERVOS
  11002. case 280: gcode_M280(); break; // M280: Set Servo Position
  11003. #endif
  11004. #if ENABLED(BABYSTEPPING)
  11005. case 290: gcode_M290(); break; // M290: Babystepping
  11006. #endif
  11007. #if HAS_BUZZER
  11008. case 300: gcode_M300(); break; // M300: Add Tone/Buzz to Queue
  11009. #endif
  11010. #if ENABLED(PIDTEMP)
  11011. case 301: gcode_M301(); break; // M301: Set Hotend PID parameters
  11012. #endif
  11013. #if ENABLED(PREVENT_COLD_EXTRUSION)
  11014. case 302: gcode_M302(); break; // M302: Set Minimum Extrusion Temp
  11015. #endif
  11016. case 303: gcode_M303(); break; // M303: PID Autotune
  11017. #if ENABLED(PIDTEMPBED)
  11018. case 304: gcode_M304(); break; // M304: Set Bed PID parameters
  11019. #endif
  11020. #if HAS_MICROSTEPS
  11021. case 350: gcode_M350(); break; // M350: Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  11022. case 351: gcode_M351(); break; // M351: Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  11023. #endif
  11024. case 355: gcode_M355(); break; // M355: Set Case Light brightness
  11025. #if ENABLED(MORGAN_SCARA)
  11026. case 360: if (gcode_M360()) return; break; // M360: SCARA Theta pos1
  11027. case 361: if (gcode_M361()) return; break; // M361: SCARA Theta pos2
  11028. case 362: if (gcode_M362()) return; break; // M362: SCARA Psi pos1
  11029. case 363: if (gcode_M363()) return; break; // M363: SCARA Psi pos2
  11030. case 364: if (gcode_M364()) return; break; // M364: SCARA Psi pos3 (90 deg to Theta)
  11031. #endif
  11032. case 400: gcode_M400(); break; // M400: Synchronize. Wait for moves to finish.
  11033. #if HAS_BED_PROBE
  11034. case 401: gcode_M401(); break; // M401: Deploy Probe
  11035. case 402: gcode_M402(); break; // M402: Stow Probe
  11036. #endif
  11037. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  11038. case 404: gcode_M404(); break; // M404: Set/Report Nominal Filament Width
  11039. case 405: gcode_M405(); break; // M405: Enable Filament Width Sensor
  11040. case 406: gcode_M406(); break; // M406: Disable Filament Width Sensor
  11041. case 407: gcode_M407(); break; // M407: Report Measured Filament Width
  11042. #endif
  11043. #if HAS_LEVELING
  11044. case 420: gcode_M420(); break; // M420: Set Bed Leveling Enabled / Fade
  11045. #endif
  11046. #if HAS_MESH
  11047. case 421: gcode_M421(); break; // M421: Set a Mesh Z value
  11048. #endif
  11049. case 500: gcode_M500(); break; // M500: Store Settings in EEPROM
  11050. case 501: gcode_M501(); break; // M501: Read Settings from EEPROM
  11051. case 502: gcode_M502(); break; // M502: Revert Settings to defaults
  11052. #if DISABLED(DISABLE_M503)
  11053. case 503: gcode_M503(); break; // M503: Report Settings (in SRAM)
  11054. #endif
  11055. #if ENABLED(EEPROM_SETTINGS)
  11056. case 504: gcode_M504(); break; // M504: Validate EEPROM
  11057. #endif
  11058. #if ENABLED(SDSUPPORT)
  11059. case 524: gcode_M524(); break; // M524: Abort SD print job
  11060. #endif
  11061. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  11062. case 540: gcode_M540(); break; // M540: Set Abort on Endstop Hit for SD Printing
  11063. #endif
  11064. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  11065. case 600: gcode_M600(); break; // M600: Pause for Filament Change
  11066. case 603: gcode_M603(); break; // M603: Configure Filament Change
  11067. #endif
  11068. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  11069. case 605: gcode_M605(); break; // M605: Set Dual X Carriage movement mode
  11070. #endif
  11071. #if ENABLED(DELTA) || ENABLED(HANGPRINTER)
  11072. case 665: gcode_M665(); break; // M665: Delta / Hangprinter Configuration
  11073. #endif
  11074. #if ENABLED(DELTA) || ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS)
  11075. case 666: gcode_M666(); break; // M666: DELTA/Dual Endstop Adjustment
  11076. #endif
  11077. #if ENABLED(FILAMENT_LOAD_UNLOAD_GCODES)
  11078. case 701: gcode_M701(); break; // M701: Load Filament
  11079. case 702: gcode_M702(); break; // M702: Unload Filament
  11080. #endif
  11081. #if ENABLED(MAX7219_GCODE)
  11082. case 7219: gcode_M7219(); break; // M7219: Set LEDs, columns, and rows
  11083. #endif
  11084. #if ENABLED(DEBUG_GCODE_PARSER)
  11085. case 800: parser.debug(); break; // M800: GCode Parser Test for M
  11086. #endif
  11087. #if HAS_BED_PROBE
  11088. case 851: gcode_M851(); break; // M851: Set Z Probe Z Offset
  11089. #endif
  11090. #if ENABLED(SKEW_CORRECTION_GCODE)
  11091. case 852: gcode_M852(); break; // M852: Set Skew factors
  11092. #endif
  11093. #if ENABLED(I2C_POSITION_ENCODERS)
  11094. case 860: gcode_M860(); break; // M860: Report encoder module position
  11095. case 861: gcode_M861(); break; // M861: Report encoder module status
  11096. case 862: gcode_M862(); break; // M862: Perform axis test
  11097. case 863: gcode_M863(); break; // M863: Calibrate steps/mm
  11098. case 864: gcode_M864(); break; // M864: Change module address
  11099. case 865: gcode_M865(); break; // M865: Check module firmware version
  11100. case 866: gcode_M866(); break; // M866: Report axis error count
  11101. case 867: gcode_M867(); break; // M867: Toggle error correction
  11102. case 868: gcode_M868(); break; // M868: Set error correction threshold
  11103. case 869: gcode_M869(); break; // M869: Report axis error
  11104. #endif
  11105. #if ENABLED(LIN_ADVANCE)
  11106. case 900: gcode_M900(); break; // M900: Set Linear Advance K factor
  11107. #endif
  11108. case 907: gcode_M907(); break; // M907: Set Digital Trimpot Motor Current using axis codes.
  11109. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  11110. case 908: gcode_M908(); break; // M908: Direct Control Digital Trimpot
  11111. #if ENABLED(DAC_STEPPER_CURRENT)
  11112. case 909: gcode_M909(); break; // M909: Print Digipot/DAC current value (As with Printrbot RevF)
  11113. case 910: gcode_M910(); break; // M910: Commit Digipot/DAC value to External EEPROM (As with Printrbot RevF)
  11114. #endif
  11115. #endif
  11116. #if HAS_DRIVER(TMC2130) || HAS_DRIVER(TMC2208)
  11117. #if ENABLED(TMC_DEBUG)
  11118. case 122: gcode_M122(); break; // M122: Debug TMC steppers
  11119. #endif
  11120. case 906: gcode_M906(); break; // M906: Set motor current in milliamps using axis codes X, Y, Z, E
  11121. case 911: gcode_M911(); break; // M911: Report TMC prewarn triggered flags
  11122. case 912: gcode_M912(); break; // M911: Clear TMC prewarn triggered flags
  11123. #if ENABLED(HYBRID_THRESHOLD)
  11124. case 913: gcode_M913(); break; // M913: Set HYBRID_THRESHOLD speed.
  11125. #endif
  11126. #if ENABLED(SENSORLESS_HOMING)
  11127. case 914: gcode_M914(); break; // M914: Set SENSORLESS_HOMING sensitivity.
  11128. #endif
  11129. #if ENABLED(TMC_Z_CALIBRATION)
  11130. case 915: gcode_M915(); break; // M915: TMC Z axis calibration routine
  11131. #endif
  11132. #endif
  11133. case 999: gcode_M999(); break; // M999: Restart after being Stopped
  11134. default: parser.unknown_command_error();
  11135. }
  11136. break;
  11137. case 'T': gcode_T(parser.codenum); break; // T: Tool Select
  11138. default: parser.unknown_command_error();
  11139. }
  11140. KEEPALIVE_STATE(NOT_BUSY);
  11141. ok_to_send();
  11142. }
  11143. void process_next_command() {
  11144. char * const current_command = command_queue[cmd_queue_index_r];
  11145. if (DEBUGGING(ECHO)) {
  11146. SERIAL_ECHO_START();
  11147. SERIAL_ECHOLN(current_command);
  11148. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  11149. SERIAL_ECHOPAIR("slot:", cmd_queue_index_r);
  11150. M100_dump_routine(" Command Queue:", (const char*)command_queue, (const char*)(command_queue + sizeof(command_queue)));
  11151. #endif
  11152. }
  11153. // Parse the next command in the queue
  11154. parser.parse(current_command);
  11155. process_parsed_command();
  11156. }
  11157. /**
  11158. * Send a "Resend: nnn" message to the host to
  11159. * indicate that a command needs to be re-sent.
  11160. */
  11161. void flush_and_request_resend() {
  11162. //char command_queue[cmd_queue_index_r][100]="Resend:";
  11163. SERIAL_FLUSH();
  11164. SERIAL_PROTOCOLPGM(MSG_RESEND);
  11165. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  11166. ok_to_send();
  11167. }
  11168. /**
  11169. * Send an "ok" message to the host, indicating
  11170. * that a command was successfully processed.
  11171. *
  11172. * If ADVANCED_OK is enabled also include:
  11173. * N<int> Line number of the command, if any
  11174. * P<int> Planner space remaining
  11175. * B<int> Block queue space remaining
  11176. */
  11177. void ok_to_send() {
  11178. if (!send_ok[cmd_queue_index_r]) return;
  11179. SERIAL_PROTOCOLPGM(MSG_OK);
  11180. #if ENABLED(ADVANCED_OK)
  11181. char* p = command_queue[cmd_queue_index_r];
  11182. if (*p == 'N') {
  11183. SERIAL_PROTOCOL(' ');
  11184. SERIAL_ECHO(*p++);
  11185. while (NUMERIC_SIGNED(*p))
  11186. SERIAL_ECHO(*p++);
  11187. }
  11188. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1));
  11189. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  11190. #endif
  11191. SERIAL_EOL();
  11192. }
  11193. #if HAS_SOFTWARE_ENDSTOPS
  11194. /**
  11195. * Constrain the given coordinates to the software endstops.
  11196. *
  11197. * For DELTA/SCARA the XY constraint is based on the smallest
  11198. * radius within the set software endstops.
  11199. */
  11200. void clamp_to_software_endstops(float target[XYZ]) {
  11201. if (!soft_endstops_enabled) return;
  11202. #if IS_KINEMATIC
  11203. const float dist_2 = HYPOT2(target[X_AXIS], target[Y_AXIS]);
  11204. if (dist_2 > soft_endstop_radius_2) {
  11205. const float ratio = soft_endstop_radius / SQRT(dist_2); // 200 / 300 = 0.66
  11206. target[X_AXIS] *= ratio;
  11207. target[Y_AXIS] *= ratio;
  11208. }
  11209. #else
  11210. #if ENABLED(MIN_SOFTWARE_ENDSTOP_X)
  11211. NOLESS(target[X_AXIS], soft_endstop_min[X_AXIS]);
  11212. #endif
  11213. #if ENABLED(MIN_SOFTWARE_ENDSTOP_Y)
  11214. NOLESS(target[Y_AXIS], soft_endstop_min[Y_AXIS]);
  11215. #endif
  11216. #if ENABLED(MAX_SOFTWARE_ENDSTOP_X)
  11217. NOMORE(target[X_AXIS], soft_endstop_max[X_AXIS]);
  11218. #endif
  11219. #if ENABLED(MAX_SOFTWARE_ENDSTOP_Y)
  11220. NOMORE(target[Y_AXIS], soft_endstop_max[Y_AXIS]);
  11221. #endif
  11222. #endif
  11223. #if ENABLED(MIN_SOFTWARE_ENDSTOP_Z)
  11224. NOLESS(target[Z_AXIS], soft_endstop_min[Z_AXIS]);
  11225. #endif
  11226. #if ENABLED(MAX_SOFTWARE_ENDSTOP_Z)
  11227. NOMORE(target[Z_AXIS], soft_endstop_max[Z_AXIS]);
  11228. #endif
  11229. }
  11230. #endif
  11231. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  11232. // Get the Z adjustment for non-linear bed leveling
  11233. float bilinear_z_offset(const float raw[XYZ]) {
  11234. static float z1, d2, z3, d4, L, D, ratio_x, ratio_y,
  11235. last_x = -999.999, last_y = -999.999;
  11236. // Whole units for the grid line indices. Constrained within bounds.
  11237. static int8_t gridx, gridy, nextx, nexty,
  11238. last_gridx = -99, last_gridy = -99;
  11239. // XY relative to the probed area
  11240. const float rx = raw[X_AXIS] - bilinear_start[X_AXIS],
  11241. ry = raw[Y_AXIS] - bilinear_start[Y_AXIS];
  11242. #if ENABLED(EXTRAPOLATE_BEYOND_GRID)
  11243. // Keep using the last grid box
  11244. #define FAR_EDGE_OR_BOX 2
  11245. #else
  11246. // Just use the grid far edge
  11247. #define FAR_EDGE_OR_BOX 1
  11248. #endif
  11249. if (last_x != rx) {
  11250. last_x = rx;
  11251. ratio_x = rx * ABL_BG_FACTOR(X_AXIS);
  11252. const float gx = constrain(FLOOR(ratio_x), 0, ABL_BG_POINTS_X - FAR_EDGE_OR_BOX);
  11253. ratio_x -= gx; // Subtract whole to get the ratio within the grid box
  11254. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  11255. // Beyond the grid maintain height at grid edges
  11256. NOLESS(ratio_x, 0); // Never < 0.0. (> 1.0 is ok when nextx==gridx.)
  11257. #endif
  11258. gridx = gx;
  11259. nextx = MIN(gridx + 1, ABL_BG_POINTS_X - 1);
  11260. }
  11261. if (last_y != ry || last_gridx != gridx) {
  11262. if (last_y != ry) {
  11263. last_y = ry;
  11264. ratio_y = ry * ABL_BG_FACTOR(Y_AXIS);
  11265. const float gy = constrain(FLOOR(ratio_y), 0, ABL_BG_POINTS_Y - FAR_EDGE_OR_BOX);
  11266. ratio_y -= gy;
  11267. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  11268. // Beyond the grid maintain height at grid edges
  11269. NOLESS(ratio_y, 0); // Never < 0.0. (> 1.0 is ok when nexty==gridy.)
  11270. #endif
  11271. gridy = gy;
  11272. nexty = MIN(gridy + 1, ABL_BG_POINTS_Y - 1);
  11273. }
  11274. if (last_gridx != gridx || last_gridy != gridy) {
  11275. last_gridx = gridx;
  11276. last_gridy = gridy;
  11277. // Z at the box corners
  11278. z1 = ABL_BG_GRID(gridx, gridy); // left-front
  11279. d2 = ABL_BG_GRID(gridx, nexty) - z1; // left-back (delta)
  11280. z3 = ABL_BG_GRID(nextx, gridy); // right-front
  11281. d4 = ABL_BG_GRID(nextx, nexty) - z3; // right-back (delta)
  11282. }
  11283. // Bilinear interpolate. Needed since ry or gridx has changed.
  11284. L = z1 + d2 * ratio_y; // Linear interp. LF -> LB
  11285. const float R = z3 + d4 * ratio_y; // Linear interp. RF -> RB
  11286. D = R - L;
  11287. }
  11288. const float offset = L + ratio_x * D; // the offset almost always changes
  11289. /*
  11290. static float last_offset = 0;
  11291. if (ABS(last_offset - offset) > 0.2) {
  11292. SERIAL_ECHOPGM("Sudden Shift at ");
  11293. SERIAL_ECHOPAIR("x=", rx);
  11294. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[X_AXIS]);
  11295. SERIAL_ECHOLNPAIR(" -> gridx=", gridx);
  11296. SERIAL_ECHOPAIR(" y=", ry);
  11297. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[Y_AXIS]);
  11298. SERIAL_ECHOLNPAIR(" -> gridy=", gridy);
  11299. SERIAL_ECHOPAIR(" ratio_x=", ratio_x);
  11300. SERIAL_ECHOLNPAIR(" ratio_y=", ratio_y);
  11301. SERIAL_ECHOPAIR(" z1=", z1);
  11302. SERIAL_ECHOPAIR(" z2=", z2);
  11303. SERIAL_ECHOPAIR(" z3=", z3);
  11304. SERIAL_ECHOLNPAIR(" z4=", z4);
  11305. SERIAL_ECHOPAIR(" L=", L);
  11306. SERIAL_ECHOPAIR(" R=", R);
  11307. SERIAL_ECHOLNPAIR(" offset=", offset);
  11308. }
  11309. last_offset = offset;
  11310. //*/
  11311. return offset;
  11312. }
  11313. #endif // AUTO_BED_LEVELING_BILINEAR
  11314. #if ENABLED(DELTA)
  11315. /**
  11316. * Recalculate factors used for delta kinematics whenever
  11317. * settings have been changed (e.g., by M665).
  11318. */
  11319. void recalc_delta_settings() {
  11320. const float trt[ABC] = DELTA_RADIUS_TRIM_TOWER,
  11321. drt[ABC] = DELTA_DIAGONAL_ROD_TRIM_TOWER;
  11322. delta_tower[A_AXIS][X_AXIS] = cos(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (delta_radius + trt[A_AXIS]); // front left tower
  11323. delta_tower[A_AXIS][Y_AXIS] = sin(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (delta_radius + trt[A_AXIS]);
  11324. delta_tower[B_AXIS][X_AXIS] = cos(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (delta_radius + trt[B_AXIS]); // front right tower
  11325. delta_tower[B_AXIS][Y_AXIS] = sin(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (delta_radius + trt[B_AXIS]);
  11326. delta_tower[C_AXIS][X_AXIS] = cos(RADIANS( 90 + delta_tower_angle_trim[C_AXIS])) * (delta_radius + trt[C_AXIS]); // back middle tower
  11327. delta_tower[C_AXIS][Y_AXIS] = sin(RADIANS( 90 + delta_tower_angle_trim[C_AXIS])) * (delta_radius + trt[C_AXIS]);
  11328. delta_diagonal_rod_2_tower[A_AXIS] = sq(delta_diagonal_rod + drt[A_AXIS]);
  11329. delta_diagonal_rod_2_tower[B_AXIS] = sq(delta_diagonal_rod + drt[B_AXIS]);
  11330. delta_diagonal_rod_2_tower[C_AXIS] = sq(delta_diagonal_rod + drt[C_AXIS]);
  11331. update_software_endstops(Z_AXIS);
  11332. axis_homed = 0;
  11333. }
  11334. /**
  11335. * Delta Inverse Kinematics
  11336. *
  11337. * Calculate the tower positions for a given machine
  11338. * position, storing the result in the delta[] array.
  11339. *
  11340. * This is an expensive calculation, requiring 3 square
  11341. * roots per segmented linear move, and strains the limits
  11342. * of a Mega2560 with a Graphical Display.
  11343. *
  11344. * Suggested optimizations include:
  11345. *
  11346. * - Disable the home_offset (M206) and/or position_shift (G92)
  11347. * features to remove up to 12 float additions.
  11348. */
  11349. #define DELTA_DEBUG(VAR) do { \
  11350. SERIAL_ECHOPAIR("cartesian X:", VAR[X_AXIS]); \
  11351. SERIAL_ECHOPAIR(" Y:", VAR[Y_AXIS]); \
  11352. SERIAL_ECHOLNPAIR(" Z:", VAR[Z_AXIS]); \
  11353. SERIAL_ECHOPAIR("delta A:", delta[A_AXIS]); \
  11354. SERIAL_ECHOPAIR(" B:", delta[B_AXIS]); \
  11355. SERIAL_ECHOLNPAIR(" C:", delta[C_AXIS]); \
  11356. }while(0)
  11357. void inverse_kinematics(const float raw[XYZ]) {
  11358. #if HOTENDS > 1
  11359. // Delta hotend offsets must be applied in Cartesian space with no "spoofing"
  11360. const float pos[XYZ] = {
  11361. raw[X_AXIS] - hotend_offset[X_AXIS][active_extruder],
  11362. raw[Y_AXIS] - hotend_offset[Y_AXIS][active_extruder],
  11363. raw[Z_AXIS]
  11364. };
  11365. DELTA_IK(pos);
  11366. //DELTA_DEBUG(pos);
  11367. #else
  11368. DELTA_IK(raw);
  11369. //DELTA_DEBUG(raw);
  11370. #endif
  11371. }
  11372. /**
  11373. * Calculate the highest Z position where the
  11374. * effector has the full range of XY motion.
  11375. */
  11376. float delta_safe_distance_from_top() {
  11377. float cartesian[XYZ] = { 0, 0, 0 };
  11378. inverse_kinematics(cartesian);
  11379. const float centered_extent = delta[A_AXIS];
  11380. cartesian[Y_AXIS] = DELTA_PRINTABLE_RADIUS;
  11381. inverse_kinematics(cartesian);
  11382. return ABS(centered_extent - delta[A_AXIS]);
  11383. }
  11384. /**
  11385. * Delta Forward Kinematics
  11386. *
  11387. * See the Wikipedia article "Trilateration"
  11388. * https://en.wikipedia.org/wiki/Trilateration
  11389. *
  11390. * Establish a new coordinate system in the plane of the
  11391. * three carriage points. This system has its origin at
  11392. * tower1, with tower2 on the X axis. Tower3 is in the X-Y
  11393. * plane with a Z component of zero.
  11394. * We will define unit vectors in this coordinate system
  11395. * in our original coordinate system. Then when we calculate
  11396. * the Xnew, Ynew and Znew values, we can translate back into
  11397. * the original system by moving along those unit vectors
  11398. * by the corresponding values.
  11399. *
  11400. * Variable names matched to Marlin, c-version, and avoid the
  11401. * use of any vector library.
  11402. *
  11403. * by Andreas Hardtung 2016-06-07
  11404. * based on a Java function from "Delta Robot Kinematics V3"
  11405. * by Steve Graves
  11406. *
  11407. * The result is stored in the cartes[] array.
  11408. */
  11409. void forward_kinematics_DELTA(const float &z1, const float &z2, const float &z3) {
  11410. // Create a vector in old coordinates along x axis of new coordinate
  11411. const float p12[] = {
  11412. delta_tower[B_AXIS][X_AXIS] - delta_tower[A_AXIS][X_AXIS],
  11413. delta_tower[B_AXIS][Y_AXIS] - delta_tower[A_AXIS][Y_AXIS],
  11414. z2 - z1
  11415. },
  11416. // Get the reciprocal of Magnitude of vector.
  11417. d2 = sq(p12[0]) + sq(p12[1]) + sq(p12[2]), inv_d = RSQRT(d2),
  11418. // Create unit vector by multiplying by the inverse of the magnitude.
  11419. ex[3] = { p12[0] * inv_d, p12[1] * inv_d, p12[2] * inv_d },
  11420. // Get the vector from the origin of the new system to the third point.
  11421. p13[3] = {
  11422. delta_tower[C_AXIS][X_AXIS] - delta_tower[A_AXIS][X_AXIS],
  11423. delta_tower[C_AXIS][Y_AXIS] - delta_tower[A_AXIS][Y_AXIS],
  11424. z3 - z1
  11425. },
  11426. // Use the dot product to find the component of this vector on the X axis.
  11427. i = ex[0] * p13[0] + ex[1] * p13[1] + ex[2] * p13[2],
  11428. // Create a vector along the x axis that represents the x component of p13.
  11429. iex[] = { ex[0] * i, ex[1] * i, ex[2] * i };
  11430. // Subtract the X component from the original vector leaving only Y. We use the
  11431. // variable that will be the unit vector after we scale it.
  11432. float ey[3] = { p13[0] - iex[0], p13[1] - iex[1], p13[2] - iex[2] };
  11433. // The magnitude and the inverse of the magnitude of Y component
  11434. const float j2 = sq(ey[0]) + sq(ey[1]) + sq(ey[2]), inv_j = RSQRT(j2);
  11435. // Convert to a unit vector
  11436. ey[0] *= inv_j; ey[1] *= inv_j; ey[2] *= inv_j;
  11437. // The cross product of the unit x and y is the unit z
  11438. // float[] ez = vectorCrossProd(ex, ey);
  11439. const float ez[3] = {
  11440. ex[1] * ey[2] - ex[2] * ey[1],
  11441. ex[2] * ey[0] - ex[0] * ey[2],
  11442. ex[0] * ey[1] - ex[1] * ey[0]
  11443. },
  11444. // We now have the d, i and j values defined in Wikipedia.
  11445. // Plug them into the equations defined in Wikipedia for Xnew, Ynew and Znew
  11446. Xnew = (delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[B_AXIS] + d2) * inv_d * 0.5,
  11447. Ynew = ((delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[C_AXIS] + sq(i) + j2) * 0.5 - i * Xnew) * inv_j,
  11448. Znew = SQRT(delta_diagonal_rod_2_tower[A_AXIS] - HYPOT2(Xnew, Ynew));
  11449. // Start from the origin of the old coordinates and add vectors in the
  11450. // old coords that represent the Xnew, Ynew and Znew to find the point
  11451. // in the old system.
  11452. cartes[X_AXIS] = delta_tower[A_AXIS][X_AXIS] + ex[0] * Xnew + ey[0] * Ynew - ez[0] * Znew;
  11453. cartes[Y_AXIS] = delta_tower[A_AXIS][Y_AXIS] + ex[1] * Xnew + ey[1] * Ynew - ez[1] * Znew;
  11454. cartes[Z_AXIS] = z1 + ex[2] * Xnew + ey[2] * Ynew - ez[2] * Znew;
  11455. }
  11456. void forward_kinematics_DELTA(const float (&point)[ABC]) {
  11457. forward_kinematics_DELTA(point[A_AXIS], point[B_AXIS], point[C_AXIS]);
  11458. }
  11459. #endif // DELTA
  11460. #if ENABLED(HANGPRINTER)
  11461. /**
  11462. * Recalculate factors used for hangprinter kinematics whenever
  11463. * settings have been changed (e.g., by M665).
  11464. */
  11465. void recalc_hangprinter_settings(){
  11466. HANGPRINTER_IK_ORIGIN(line_lengths_origin);
  11467. #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
  11468. const uint8_t mech_adv_tmp[MOV_AXIS] = MECHANICAL_ADVANTAGE,
  11469. actn_pts_tmp[MOV_AXIS] = ACTION_POINTS;
  11470. const uint16_t m_g_t_tmp[MOV_AXIS] = MOTOR_GEAR_TEETH,
  11471. s_g_t_tmp[MOV_AXIS] = SPOOL_GEAR_TEETH;
  11472. const float mnt_l_tmp[MOV_AXIS] = MOUNTED_LINE;
  11473. float s_r2_tmp[MOV_AXIS] = SPOOL_RADII,
  11474. steps_per_unit_times_r_tmp[MOV_AXIS];
  11475. uint8_t nr_lines_dir_tmp[MOV_AXIS];
  11476. LOOP_MOV_AXIS(i){
  11477. steps_per_unit_times_r_tmp[i] = (float(mech_adv_tmp[i])*STEPS_PER_MOTOR_REVOLUTION*s_g_t_tmp[i])/(2*M_PI*m_g_t_tmp[i]);
  11478. nr_lines_dir_tmp[i] = mech_adv_tmp[i]*actn_pts_tmp[i];
  11479. s_r2_tmp[i] *= s_r2_tmp[i];
  11480. planner.k2[i] = -(float)nr_lines_dir_tmp[i]*SPOOL_BUILDUP_FACTOR;
  11481. planner.k0[i] = 2.0*steps_per_unit_times_r_tmp[i]/planner.k2[i];
  11482. }
  11483. // Assumes spools are mounted near D-anchor in ceiling
  11484. #define HYP3D(x,y,z) SQRT(sq(x) + sq(y) + sq(z))
  11485. float line_on_spool_origin_tmp[MOV_AXIS];
  11486. line_on_spool_origin_tmp[A_AXIS] = actn_pts_tmp[A_AXIS] * mnt_l_tmp[A_AXIS]
  11487. - actn_pts_tmp[A_AXIS] * HYPOT(anchor_A_y, anchor_D_z - anchor_A_z)
  11488. - nr_lines_dir_tmp[A_AXIS] * line_lengths_origin[A_AXIS];
  11489. line_on_spool_origin_tmp[B_AXIS] = actn_pts_tmp[B_AXIS] * mnt_l_tmp[B_AXIS]
  11490. - actn_pts_tmp[B_AXIS] * HYP3D(anchor_B_x, anchor_B_y, anchor_D_z - anchor_B_z)
  11491. - nr_lines_dir_tmp[B_AXIS] * line_lengths_origin[B_AXIS];
  11492. line_on_spool_origin_tmp[C_AXIS] = actn_pts_tmp[C_AXIS] * mnt_l_tmp[C_AXIS]
  11493. - actn_pts_tmp[C_AXIS] * HYP3D(anchor_C_x, anchor_C_y, anchor_D_z - anchor_C_z)
  11494. - nr_lines_dir_tmp[C_AXIS] * line_lengths_origin[C_AXIS];
  11495. line_on_spool_origin_tmp[D_AXIS] = actn_pts_tmp[D_AXIS] * mnt_l_tmp[D_AXIS]
  11496. - nr_lines_dir_tmp[D_AXIS] * line_lengths_origin[D_AXIS];
  11497. LOOP_MOV_AXIS(i) {
  11498. planner.axis_steps_per_mm[i] = steps_per_unit_times_r_tmp[i] /
  11499. SQRT((SPOOL_BUILDUP_FACTOR) * line_on_spool_origin_tmp[i] + s_r2_tmp[i]);
  11500. planner.k1[i] = (SPOOL_BUILDUP_FACTOR) *
  11501. (line_on_spool_origin_tmp[i] + nr_lines_dir_tmp[i] * line_lengths_origin[i]) + s_r2_tmp[i];
  11502. planner.sqrtk1[i] = SQRT(planner.k1[i]);
  11503. }
  11504. planner.axis_steps_per_mm[E_AXIS] = DEFAULT_E_AXIS_STEPS_PER_UNIT;
  11505. #endif // LINE_BUILDUP_COMPENSATION_FEATURE
  11506. SYNC_PLAN_POSITION_KINEMATIC(); // recalcs line lengths in case anchor was moved
  11507. }
  11508. /**
  11509. * Hangprinter inverse kinematics
  11510. */
  11511. void inverse_kinematics(const float raw[XYZ]) {
  11512. HANGPRINTER_IK(raw);
  11513. }
  11514. /**
  11515. * Hangprinter forward kinematics
  11516. * Basic idea is to subtract squared line lengths to get linear equations.
  11517. * Subtracting d*d from a*a, b*b, and c*c gives the cleanest derivation:
  11518. *
  11519. * a*a - d*d = k1 + k2*y + k3*z <---- a line (I)
  11520. * b*b - d*d = k4 + k5*x + k6*y + k7*z <---- a plane (II)
  11521. * c*c - d*d = k8 + k9*x + k10*y + k11*z <---- a plane (III)
  11522. *
  11523. * Use (I) to reduce (II) and (III) into lines. Eliminate y, keep z.
  11524. *
  11525. * (II): b*b - d*d = k12 + k13*x + k14*z
  11526. * <=> x = k0b + k1b*z, <---- a line (IV)
  11527. *
  11528. * (III): c*c - d*d = k15 + k16*x + k17*z
  11529. * <=> x = k0c + k1c*z, <---- a line (V)
  11530. *
  11531. * where k1, k2, ..., k17, k0b, k0c, k1b, and k1c are known constants.
  11532. *
  11533. * These two straight lines are not parallel, so they will cross in exactly one point.
  11534. * Find z by setting (IV) = (V)
  11535. * Find x by inserting z into (V)
  11536. * Find y by inserting z into (I)
  11537. *
  11538. * Warning: truncation errors will typically be in the order of a few tens of microns.
  11539. */
  11540. void forward_kinematics_HANGPRINTER(float a, float b, float c, float d){
  11541. const float Asq = sq(anchor_A_y) + sq(anchor_A_z),
  11542. Bsq = sq(anchor_B_x) + sq(anchor_B_y) + sq(anchor_B_z),
  11543. Csq = sq(anchor_C_x) + sq(anchor_C_y) + sq(anchor_C_z),
  11544. Dsq = sq(anchor_D_z),
  11545. aa = sq(a),
  11546. dd = sq(d),
  11547. k0b = (-sq(b) + Bsq - Dsq + dd) / (2.0 * anchor_B_x) + (anchor_B_y / (2.0 * anchor_A_y * anchor_B_x)) * (Dsq - Asq + aa - dd),
  11548. k0c = (-sq(c) + Csq - Dsq + dd) / (2.0 * anchor_C_x) + (anchor_C_y / (2.0 * anchor_A_y * anchor_C_x)) * (Dsq - Asq + aa - dd),
  11549. k1b = (anchor_B_y * (anchor_A_z - anchor_D_z)) / (anchor_A_y * anchor_B_x) + (anchor_D_z - anchor_B_z) / anchor_B_x,
  11550. k1c = (anchor_C_y * (anchor_A_z - anchor_D_z)) / (anchor_A_y * anchor_C_x) + (anchor_D_z - anchor_C_z) / anchor_C_x;
  11551. cartes[Z_AXIS] = (k0b - k0c) / (k1c - k1b);
  11552. cartes[X_AXIS] = k0c + k1c * cartes[Z_AXIS];
  11553. cartes[Y_AXIS] = (Asq - Dsq - aa + dd) / (2.0 * anchor_A_y) + ((anchor_D_z - anchor_A_z) / anchor_A_y) * cartes[Z_AXIS];
  11554. }
  11555. #endif // HANGPRINTER
  11556. /**
  11557. * Get the stepper positions in the cartes[] array.
  11558. * Forward kinematics are applied for DELTA and SCARA.
  11559. *
  11560. * The result is in the current coordinate space with
  11561. * leveling applied. The coordinates need to be run through
  11562. * unapply_leveling to obtain machine coordinates suitable
  11563. * for current_position, etc.
  11564. */
  11565. void get_cartesian_from_steppers() {
  11566. #if ENABLED(DELTA)
  11567. forward_kinematics_DELTA(
  11568. planner.get_axis_position_mm(A_AXIS),
  11569. planner.get_axis_position_mm(B_AXIS),
  11570. planner.get_axis_position_mm(C_AXIS)
  11571. );
  11572. #elif ENABLED(HANGPRINTER)
  11573. forward_kinematics_HANGPRINTER(
  11574. planner.get_axis_position_mm(A_AXIS),
  11575. planner.get_axis_position_mm(B_AXIS),
  11576. planner.get_axis_position_mm(C_AXIS),
  11577. planner.get_axis_position_mm(D_AXIS)
  11578. );
  11579. #else
  11580. #if IS_SCARA
  11581. forward_kinematics_SCARA(
  11582. planner.get_axis_position_degrees(A_AXIS),
  11583. planner.get_axis_position_degrees(B_AXIS)
  11584. );
  11585. #else
  11586. cartes[X_AXIS] = planner.get_axis_position_mm(X_AXIS);
  11587. cartes[Y_AXIS] = planner.get_axis_position_mm(Y_AXIS);
  11588. #endif
  11589. cartes[Z_AXIS] = planner.get_axis_position_mm(Z_AXIS);
  11590. #endif
  11591. }
  11592. /**
  11593. * Set the current_position for an axis based on
  11594. * the stepper positions, removing any leveling that
  11595. * may have been applied.
  11596. *
  11597. * To prevent small shifts in axis position always call
  11598. * SYNC_PLAN_POSITION_KINEMATIC after updating axes with this.
  11599. *
  11600. * To keep hosts in sync, always call report_current_position
  11601. * after updating the current_position.
  11602. */
  11603. void set_current_from_steppers_for_axis(const AxisEnum axis) {
  11604. get_cartesian_from_steppers();
  11605. #if PLANNER_LEVELING
  11606. planner.unapply_leveling(cartes);
  11607. #endif
  11608. if (axis == ALL_AXES)
  11609. COPY(current_position, cartes);
  11610. else
  11611. current_position[axis] = cartes[axis];
  11612. }
  11613. #if IS_CARTESIAN
  11614. #if ENABLED(SEGMENT_LEVELED_MOVES)
  11615. /**
  11616. * Prepare a segmented move on a CARTESIAN setup.
  11617. *
  11618. * This calls planner.buffer_line several times, adding
  11619. * small incremental moves. This allows the planner to
  11620. * apply more detailed bed leveling to the full move.
  11621. */
  11622. inline void segmented_line_to_destination(const float &fr_mm_s, const float segment_size=LEVELED_SEGMENT_LENGTH) {
  11623. const float xdiff = destination[X_AXIS] - current_position[X_AXIS],
  11624. ydiff = destination[Y_AXIS] - current_position[Y_AXIS];
  11625. // If the move is only in Z/E don't split up the move
  11626. if (!xdiff && !ydiff) {
  11627. planner.buffer_line_kinematic(destination, fr_mm_s, active_extruder);
  11628. return;
  11629. }
  11630. // Remaining cartesian distances
  11631. const float zdiff = destination[Z_AXIS] - current_position[Z_AXIS],
  11632. ediff = destination[E_CART] - current_position[E_CART];
  11633. // Get the linear distance in XYZ
  11634. // If the move is very short, check the E move distance
  11635. // No E move either? Game over.
  11636. float cartesian_mm = SQRT(sq(xdiff) + sq(ydiff) + sq(zdiff));
  11637. if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = ABS(ediff);
  11638. if (UNEAR_ZERO(cartesian_mm)) return;
  11639. // The length divided by the segment size
  11640. // At least one segment is required
  11641. uint16_t segments = cartesian_mm / segment_size;
  11642. NOLESS(segments, 1);
  11643. // The approximate length of each segment
  11644. const float inv_segments = 1.0f / float(segments),
  11645. cartesian_segment_mm = cartesian_mm * inv_segments,
  11646. segment_distance[XYZE] = {
  11647. xdiff * inv_segments,
  11648. ydiff * inv_segments,
  11649. zdiff * inv_segments,
  11650. ediff * inv_segments
  11651. };
  11652. // SERIAL_ECHOPAIR("mm=", cartesian_mm);
  11653. // SERIAL_ECHOLNPAIR(" segments=", segments);
  11654. // SERIAL_ECHOLNPAIR(" segment_mm=", cartesian_segment_mm);
  11655. // Get the raw current position as starting point
  11656. float raw[XYZE];
  11657. COPY(raw, current_position);
  11658. // Calculate and execute the segments
  11659. while (--segments) {
  11660. static millis_t next_idle_ms = millis() + 200UL;
  11661. thermalManager.manage_heater(); // This returns immediately if not really needed.
  11662. if (ELAPSED(millis(), next_idle_ms)) {
  11663. next_idle_ms = millis() + 200UL;
  11664. idle();
  11665. }
  11666. LOOP_XYZE(i) raw[i] += segment_distance[i];
  11667. if (!planner.buffer_line_kinematic(raw, fr_mm_s, active_extruder, cartesian_segment_mm))
  11668. break;
  11669. }
  11670. // Since segment_distance is only approximate,
  11671. // the final move must be to the exact destination.
  11672. planner.buffer_line_kinematic(destination, fr_mm_s, active_extruder, cartesian_segment_mm);
  11673. }
  11674. #elif ENABLED(MESH_BED_LEVELING)
  11675. /**
  11676. * Prepare a mesh-leveled linear move in a Cartesian setup,
  11677. * splitting the move where it crosses mesh borders.
  11678. */
  11679. void mesh_line_to_destination(const float fr_mm_s, uint8_t x_splits=0xFF, uint8_t y_splits=0xFF) {
  11680. // Get current and destination cells for this line
  11681. int cx1 = mbl.cell_index_x(current_position[X_AXIS]),
  11682. cy1 = mbl.cell_index_y(current_position[Y_AXIS]),
  11683. cx2 = mbl.cell_index_x(destination[X_AXIS]),
  11684. cy2 = mbl.cell_index_y(destination[Y_AXIS]);
  11685. NOMORE(cx1, GRID_MAX_POINTS_X - 2);
  11686. NOMORE(cy1, GRID_MAX_POINTS_Y - 2);
  11687. NOMORE(cx2, GRID_MAX_POINTS_X - 2);
  11688. NOMORE(cy2, GRID_MAX_POINTS_Y - 2);
  11689. // Start and end in the same cell? No split needed.
  11690. if (cx1 == cx2 && cy1 == cy2) {
  11691. buffer_line_to_destination(fr_mm_s);
  11692. set_current_from_destination();
  11693. return;
  11694. }
  11695. #define MBL_SEGMENT_END(A) (current_position[_AXIS(A)] + (destination[_AXIS(A)] - current_position[_AXIS(A)]) * normalized_dist)
  11696. #define MBL_SEGMENT_END_E (current_position[E_CART] + (destination[E_CART] - current_position[E_CART]) * normalized_dist)
  11697. float normalized_dist, end[XYZE];
  11698. const int8_t gcx = MAX(cx1, cx2), gcy = MAX(cy1, cy2);
  11699. // Crosses on the X and not already split on this X?
  11700. // The x_splits flags are insurance against rounding errors.
  11701. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  11702. // Split on the X grid line
  11703. CBI(x_splits, gcx);
  11704. COPY(end, destination);
  11705. destination[X_AXIS] = mbl.index_to_xpos[gcx];
  11706. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  11707. destination[Y_AXIS] = MBL_SEGMENT_END(Y);
  11708. }
  11709. // Crosses on the Y and not already split on this Y?
  11710. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  11711. // Split on the Y grid line
  11712. CBI(y_splits, gcy);
  11713. COPY(end, destination);
  11714. destination[Y_AXIS] = mbl.index_to_ypos[gcy];
  11715. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  11716. destination[X_AXIS] = MBL_SEGMENT_END(X);
  11717. }
  11718. else {
  11719. // Must already have been split on these border(s)
  11720. buffer_line_to_destination(fr_mm_s);
  11721. set_current_from_destination();
  11722. return;
  11723. }
  11724. destination[Z_AXIS] = MBL_SEGMENT_END(Z);
  11725. destination[E_CART] = MBL_SEGMENT_END_E;
  11726. // Do the split and look for more borders
  11727. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  11728. // Restore destination from stack
  11729. COPY(destination, end);
  11730. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  11731. }
  11732. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  11733. #define CELL_INDEX(A,V) ((V - bilinear_start[_AXIS(A)]) * ABL_BG_FACTOR(_AXIS(A)))
  11734. /**
  11735. * Prepare a bilinear-leveled linear move on Cartesian,
  11736. * splitting the move where it crosses grid borders.
  11737. */
  11738. void bilinear_line_to_destination(const float fr_mm_s, uint16_t x_splits=0xFFFF, uint16_t y_splits=0xFFFF) {
  11739. // Get current and destination cells for this line
  11740. int cx1 = CELL_INDEX(X, current_position[X_AXIS]),
  11741. cy1 = CELL_INDEX(Y, current_position[Y_AXIS]),
  11742. cx2 = CELL_INDEX(X, destination[X_AXIS]),
  11743. cy2 = CELL_INDEX(Y, destination[Y_AXIS]);
  11744. cx1 = constrain(cx1, 0, ABL_BG_POINTS_X - 2);
  11745. cy1 = constrain(cy1, 0, ABL_BG_POINTS_Y - 2);
  11746. cx2 = constrain(cx2, 0, ABL_BG_POINTS_X - 2);
  11747. cy2 = constrain(cy2, 0, ABL_BG_POINTS_Y - 2);
  11748. // Start and end in the same cell? No split needed.
  11749. if (cx1 == cx2 && cy1 == cy2) {
  11750. buffer_line_to_destination(fr_mm_s);
  11751. set_current_from_destination();
  11752. return;
  11753. }
  11754. #define LINE_SEGMENT_END(A) (current_position[_AXIS(A)] + (destination[_AXIS(A)] - current_position[_AXIS(A)]) * normalized_dist)
  11755. #define LINE_SEGMENT_END_E (current_position[E_CART] + (destination[E_CART] - current_position[E_CART]) * normalized_dist)
  11756. float normalized_dist, end[XYZE];
  11757. const int8_t gcx = MAX(cx1, cx2), gcy = MAX(cy1, cy2);
  11758. // Crosses on the X and not already split on this X?
  11759. // The x_splits flags are insurance against rounding errors.
  11760. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  11761. // Split on the X grid line
  11762. CBI(x_splits, gcx);
  11763. COPY(end, destination);
  11764. destination[X_AXIS] = bilinear_start[X_AXIS] + ABL_BG_SPACING(X_AXIS) * gcx;
  11765. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  11766. destination[Y_AXIS] = LINE_SEGMENT_END(Y);
  11767. }
  11768. // Crosses on the Y and not already split on this Y?
  11769. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  11770. // Split on the Y grid line
  11771. CBI(y_splits, gcy);
  11772. COPY(end, destination);
  11773. destination[Y_AXIS] = bilinear_start[Y_AXIS] + ABL_BG_SPACING(Y_AXIS) * gcy;
  11774. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  11775. destination[X_AXIS] = LINE_SEGMENT_END(X);
  11776. }
  11777. else {
  11778. // Must already have been split on these border(s)
  11779. buffer_line_to_destination(fr_mm_s);
  11780. set_current_from_destination();
  11781. return;
  11782. }
  11783. destination[Z_AXIS] = LINE_SEGMENT_END(Z);
  11784. destination[E_CART] = LINE_SEGMENT_END_E;
  11785. // Do the split and look for more borders
  11786. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  11787. // Restore destination from stack
  11788. COPY(destination, end);
  11789. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  11790. }
  11791. #endif // AUTO_BED_LEVELING_BILINEAR
  11792. #endif // IS_CARTESIAN
  11793. #if !UBL_SEGMENTED
  11794. #if IS_KINEMATIC
  11795. #if IS_SCARA
  11796. /**
  11797. * Before raising this value, use M665 S[seg_per_sec] to decrease
  11798. * the number of segments-per-second. Default is 200. Some deltas
  11799. * do better with 160 or lower. It would be good to know how many
  11800. * segments-per-second are actually possible for SCARA on AVR.
  11801. *
  11802. * Longer segments result in less kinematic overhead
  11803. * but may produce jagged lines. Try 0.5mm, 1.0mm, and 2.0mm
  11804. * and compare the difference.
  11805. */
  11806. #define SCARA_MIN_SEGMENT_LENGTH 0.5f
  11807. #endif
  11808. /**
  11809. * Prepare a linear move in a DELTA, SCARA or HANGPRINTER setup.
  11810. *
  11811. * This calls planner.buffer_line several times, adding
  11812. * small incremental moves for DELTA, SCARA or HANGPRINTER.
  11813. *
  11814. * For Unified Bed Leveling (Delta or Segmented Cartesian)
  11815. * the ubl.prepare_segmented_line_to method replaces this.
  11816. */
  11817. inline bool prepare_kinematic_move_to(const float (&rtarget)[XYZE]) {
  11818. // Get the top feedrate of the move in the XY plane
  11819. const float _feedrate_mm_s = MMS_SCALED(feedrate_mm_s);
  11820. const float xdiff = rtarget[X_AXIS] - current_position[X_AXIS],
  11821. ydiff = rtarget[Y_AXIS] - current_position[Y_AXIS]
  11822. #if ENABLED(HANGPRINTER)
  11823. , zdiff = rtarget[Z_AXIS] - current_position[Z_AXIS]
  11824. #endif
  11825. ;
  11826. // If the move is only in Z/E (for Hangprinter only in E) don't split up the move
  11827. if (!xdiff && !ydiff
  11828. #if ENABLED(HANGPRINTER)
  11829. && !zdiff
  11830. #endif
  11831. ) {
  11832. planner.buffer_line_kinematic(rtarget, _feedrate_mm_s, active_extruder);
  11833. return false; // caller will update current_position
  11834. }
  11835. // Fail if attempting move outside printable radius
  11836. if (!position_is_reachable(rtarget[X_AXIS], rtarget[Y_AXIS])) return true;
  11837. // Remaining cartesian distances
  11838. const float
  11839. #if DISABLED(HANGPRINTER)
  11840. zdiff = rtarget[Z_AXIS] - current_position[Z_AXIS],
  11841. #endif
  11842. ediff = rtarget[E_CART] - current_position[E_CART];
  11843. // Get the linear distance in XYZ
  11844. // If the move is very short, check the E move distance
  11845. // No E move either? Game over.
  11846. float cartesian_mm = SQRT(sq(xdiff) + sq(ydiff) + sq(zdiff));
  11847. if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = ABS(ediff);
  11848. if (UNEAR_ZERO(cartesian_mm)) return true;
  11849. // Minimum number of seconds to move the given distance
  11850. const float seconds = cartesian_mm / _feedrate_mm_s;
  11851. // The number of segments-per-second times the duration
  11852. // gives the number of segments
  11853. uint16_t segments = delta_segments_per_second * seconds;
  11854. // For SCARA enforce a minimum segment size
  11855. #if IS_SCARA
  11856. NOMORE(segments, cartesian_mm * (1.0f / float(SCARA_MIN_SEGMENT_LENGTH)));
  11857. #endif
  11858. // At least one segment is required
  11859. NOLESS(segments, 1);
  11860. // The approximate length of each segment
  11861. const float inv_segments = 1.0f / float(segments),
  11862. segment_distance[XYZE] = {
  11863. xdiff * inv_segments,
  11864. ydiff * inv_segments,
  11865. zdiff * inv_segments,
  11866. ediff * inv_segments
  11867. };
  11868. #if !HAS_FEEDRATE_SCALING
  11869. const float cartesian_segment_mm = cartesian_mm * inv_segments;
  11870. #endif
  11871. /*
  11872. SERIAL_ECHOPAIR("mm=", cartesian_mm);
  11873. SERIAL_ECHOPAIR(" seconds=", seconds);
  11874. SERIAL_ECHOPAIR(" segments=", segments);
  11875. #if !HAS_FEEDRATE_SCALING
  11876. SERIAL_ECHOPAIR(" segment_mm=", cartesian_segment_mm);
  11877. #endif
  11878. SERIAL_EOL();
  11879. //*/
  11880. #if HAS_FEEDRATE_SCALING
  11881. // SCARA needs to scale the feed rate from mm/s to degrees/s
  11882. // i.e., Complete the angular vector in the given time.
  11883. const float segment_length = cartesian_mm * inv_segments,
  11884. inv_segment_length = 1.0f / segment_length, // 1/mm/segs
  11885. inverse_secs = inv_segment_length * _feedrate_mm_s;
  11886. float oldA = planner.position_float[A_AXIS],
  11887. oldB = planner.position_float[B_AXIS]
  11888. #if ENABLED(DELTA_FEEDRATE_SCALING)
  11889. , oldC = planner.position_float[C_AXIS]
  11890. #endif
  11891. ;
  11892. /*
  11893. SERIAL_ECHOPGM("Scaled kinematic move: ");
  11894. SERIAL_ECHOPAIR(" segment_length (inv)=", segment_length);
  11895. SERIAL_ECHOPAIR(" (", inv_segment_length);
  11896. SERIAL_ECHOPAIR(") _feedrate_mm_s=", _feedrate_mm_s);
  11897. SERIAL_ECHOPAIR(" inverse_secs=", inverse_secs);
  11898. SERIAL_ECHOPAIR(" oldA=", oldA);
  11899. SERIAL_ECHOPAIR(" oldB=", oldB);
  11900. #if ENABLED(DELTA_FEEDRATE_SCALING)
  11901. SERIAL_ECHOPAIR(" oldC=", oldC);
  11902. #endif
  11903. SERIAL_EOL();
  11904. safe_delay(5);
  11905. //*/
  11906. #endif
  11907. // Get the current position as starting point
  11908. float raw[XYZE];
  11909. COPY(raw, current_position);
  11910. // Calculate and execute the segments
  11911. while (--segments) {
  11912. static millis_t next_idle_ms = millis() + 200UL;
  11913. thermalManager.manage_heater(); // This returns immediately if not really needed.
  11914. if (ELAPSED(millis(), next_idle_ms)) {
  11915. next_idle_ms = millis() + 200UL;
  11916. idle();
  11917. }
  11918. LOOP_XYZE(i) raw[i] += segment_distance[i];
  11919. #if ENABLED(DELTA) && HOTENDS < 2
  11920. DELTA_IK(raw); // Delta can inline its kinematics
  11921. #elif ENABLED(HANGPRINTER)
  11922. HANGPRINTER_IK(raw); // Modifies line_lengths[ABCD]
  11923. #else
  11924. inverse_kinematics(raw);
  11925. #endif
  11926. ADJUST_DELTA(raw); // Adjust Z if bed leveling is enabled
  11927. #if ENABLED(SCARA_FEEDRATE_SCALING)
  11928. // For SCARA scale the feed rate from mm/s to degrees/s
  11929. // i.e., Complete the angular vector in the given time.
  11930. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], raw[Z_AXIS], raw[E_CART], HYPOT(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB) * inverse_secs, active_extruder, segment_length))
  11931. break;
  11932. /*
  11933. SERIAL_ECHO(segments);
  11934. SERIAL_ECHOPAIR(": X=", raw[X_AXIS]); SERIAL_ECHOPAIR(" Y=", raw[Y_AXIS]);
  11935. SERIAL_ECHOPAIR(" A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]);
  11936. SERIAL_ECHOLNPAIR(" F", HYPOT(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB) * inverse_secs * 60);
  11937. safe_delay(5);
  11938. //*/
  11939. oldA = delta[A_AXIS]; oldB = delta[B_AXIS];
  11940. #elif ENABLED(DELTA_FEEDRATE_SCALING)
  11941. // For DELTA scale the feed rate from Effector mm/s to Carriage mm/s
  11942. // i.e., Complete the linear vector in the given time.
  11943. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_AXIS], SQRT(sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC)) * inverse_secs, active_extruder, segment_length))
  11944. break;
  11945. /*
  11946. SERIAL_ECHO(segments);
  11947. SERIAL_ECHOPAIR(": X=", raw[X_AXIS]); SERIAL_ECHOPAIR(" Y=", raw[Y_AXIS]);
  11948. SERIAL_ECHOPAIR(" A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]); SERIAL_ECHOPAIR(" C=", delta[C_AXIS]);
  11949. SERIAL_ECHOLNPAIR(" F", SQRT(sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC)) * inverse_secs * 60);
  11950. safe_delay(5);
  11951. //*/
  11952. oldA = delta[A_AXIS]; oldB = delta[B_AXIS]; oldC = delta[C_AXIS];
  11953. #elif ENABLED(HANGPRINTER)
  11954. if (!planner.buffer_line(line_lengths[A_AXIS], line_lengths[B_AXIS], line_lengths[C_AXIS], line_lengths[D_AXIS], raw[E_CART], _feedrate_mm_s, active_extruder, cartesian_segment_mm))
  11955. break;
  11956. #else
  11957. if (!planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_CART], _feedrate_mm_s, active_extruder, cartesian_segment_mm))
  11958. break;
  11959. #endif
  11960. }
  11961. // Ensure last segment arrives at target location.
  11962. #if HAS_FEEDRATE_SCALING
  11963. inverse_kinematics(rtarget);
  11964. ADJUST_DELTA(rtarget);
  11965. #endif
  11966. #if ENABLED(SCARA_FEEDRATE_SCALING)
  11967. const float diff2 = HYPOT2(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB);
  11968. if (diff2) {
  11969. planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], rtarget[Z_AXIS], rtarget[E_CART], SQRT(diff2) * inverse_secs, active_extruder, segment_length);
  11970. /*
  11971. SERIAL_ECHOPAIR("final: A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]);
  11972. SERIAL_ECHOPAIR(" adiff=", delta[A_AXIS] - oldA); SERIAL_ECHOPAIR(" bdiff=", delta[B_AXIS] - oldB);
  11973. SERIAL_ECHOLNPAIR(" F", SQRT(diff2) * inverse_secs * 60);
  11974. SERIAL_EOL();
  11975. safe_delay(5);
  11976. //*/
  11977. }
  11978. #elif ENABLED(DELTA_FEEDRATE_SCALING)
  11979. const float diff2 = sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC);
  11980. if (diff2) {
  11981. planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], rtarget[E_AXIS], SQRT(diff2) * inverse_secs, active_extruder, segment_length);
  11982. /*
  11983. SERIAL_ECHOPAIR("final: A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]); SERIAL_ECHOPAIR(" C=", delta[C_AXIS]);
  11984. SERIAL_ECHOPAIR(" adiff=", delta[A_AXIS] - oldA); SERIAL_ECHOPAIR(" bdiff=", delta[B_AXIS] - oldB); SERIAL_ECHOPAIR(" cdiff=", delta[C_AXIS] - oldC);
  11985. SERIAL_ECHOLNPAIR(" F", SQRT(diff2) * inverse_secs * 60);
  11986. SERIAL_EOL();
  11987. safe_delay(5);
  11988. //*/
  11989. }
  11990. #else
  11991. planner.buffer_line_kinematic(rtarget, _feedrate_mm_s, active_extruder, cartesian_segment_mm);
  11992. #endif
  11993. return false; // caller will update current_position
  11994. }
  11995. #else // !IS_KINEMATIC
  11996. /**
  11997. * Prepare a linear move in a Cartesian setup.
  11998. *
  11999. * When a mesh-based leveling system is active, moves are segmented
  12000. * according to the configuration of the leveling system.
  12001. *
  12002. * Returns true if current_position[] was set to destination[]
  12003. */
  12004. inline bool prepare_move_to_destination_cartesian() {
  12005. #if HAS_MESH
  12006. if (planner.leveling_active && planner.leveling_active_at_z(destination[Z_AXIS])) {
  12007. #if ENABLED(AUTO_BED_LEVELING_UBL)
  12008. ubl.line_to_destination_cartesian(MMS_SCALED(feedrate_mm_s), active_extruder); // UBL's motion routine needs to know about
  12009. return true; // all moves, including Z-only moves.
  12010. #elif ENABLED(SEGMENT_LEVELED_MOVES)
  12011. segmented_line_to_destination(MMS_SCALED(feedrate_mm_s));
  12012. return false; // caller will update current_position
  12013. #else
  12014. /**
  12015. * For MBL and ABL-BILINEAR only segment moves when X or Y are involved.
  12016. * Otherwise fall through to do a direct single move.
  12017. */
  12018. if (current_position[X_AXIS] != destination[X_AXIS] || current_position[Y_AXIS] != destination[Y_AXIS]) {
  12019. #if ENABLED(MESH_BED_LEVELING)
  12020. mesh_line_to_destination(MMS_SCALED(feedrate_mm_s));
  12021. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  12022. bilinear_line_to_destination(MMS_SCALED(feedrate_mm_s));
  12023. #endif
  12024. return true;
  12025. }
  12026. #endif
  12027. }
  12028. #endif // HAS_MESH
  12029. buffer_line_to_destination(MMS_SCALED(feedrate_mm_s));
  12030. return false; // caller will update current_position
  12031. }
  12032. #endif // !IS_KINEMATIC
  12033. #endif // !UBL_SEGMENTED
  12034. #if ENABLED(DUAL_X_CARRIAGE)
  12035. /**
  12036. * Unpark the carriage, if needed
  12037. */
  12038. inline bool dual_x_carriage_unpark() {
  12039. if (active_extruder_parked)
  12040. switch (dual_x_carriage_mode) {
  12041. case DXC_FULL_CONTROL_MODE: break;
  12042. case DXC_AUTO_PARK_MODE:
  12043. if (current_position[E_CART] == destination[E_CART]) {
  12044. // This is a travel move (with no extrusion)
  12045. // Skip it, but keep track of the current position
  12046. // (so it can be used as the start of the next non-travel move)
  12047. if (delayed_move_time != 0xFFFFFFFFUL) {
  12048. set_current_from_destination();
  12049. NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]);
  12050. delayed_move_time = millis();
  12051. return true;
  12052. }
  12053. }
  12054. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  12055. for (uint8_t i = 0; i < 3; i++)
  12056. if (!planner.buffer_line(
  12057. i == 0 ? raised_parked_position[X_AXIS] : current_position[X_AXIS],
  12058. i == 0 ? raised_parked_position[Y_AXIS] : current_position[Y_AXIS],
  12059. i == 2 ? current_position[Z_AXIS] : raised_parked_position[Z_AXIS],
  12060. current_position[E_CART],
  12061. i == 1 ? PLANNER_XY_FEEDRATE() : planner.max_feedrate_mm_s[Z_AXIS],
  12062. active_extruder)
  12063. ) break;
  12064. delayed_move_time = 0;
  12065. active_extruder_parked = false;
  12066. #if ENABLED(DEBUG_LEVELING_FEATURE)
  12067. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Clear active_extruder_parked");
  12068. #endif
  12069. break;
  12070. case DXC_DUPLICATION_MODE:
  12071. if (active_extruder == 0) {
  12072. #if ENABLED(DEBUG_LEVELING_FEATURE)
  12073. if (DEBUGGING(LEVELING)) {
  12074. SERIAL_ECHOPAIR("Set planner X", inactive_extruder_x_pos);
  12075. SERIAL_ECHOLNPAIR(" ... Line to X", current_position[X_AXIS] + duplicate_extruder_x_offset);
  12076. }
  12077. #endif
  12078. // move duplicate extruder into correct duplication position.
  12079. planner.set_position_mm(inactive_extruder_x_pos, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART]);
  12080. if (!planner.buffer_line(
  12081. current_position[X_AXIS] + duplicate_extruder_x_offset,
  12082. current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART],
  12083. planner.max_feedrate_mm_s[X_AXIS], 1)
  12084. ) break;
  12085. planner.synchronize();
  12086. SYNC_PLAN_POSITION_KINEMATIC();
  12087. extruder_duplication_enabled = true;
  12088. active_extruder_parked = false;
  12089. #if ENABLED(DEBUG_LEVELING_FEATURE)
  12090. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Set extruder_duplication_enabled\nClear active_extruder_parked");
  12091. #endif
  12092. }
  12093. else {
  12094. #if ENABLED(DEBUG_LEVELING_FEATURE)
  12095. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Active extruder not 0");
  12096. #endif
  12097. }
  12098. break;
  12099. }
  12100. return false;
  12101. }
  12102. #endif // DUAL_X_CARRIAGE
  12103. /**
  12104. * Prepare a single move and get ready for the next one
  12105. *
  12106. * This may result in several calls to planner.buffer_line to
  12107. * do smaller moves for DELTA, SCARA, HANGPRINTER, mesh moves, etc.
  12108. *
  12109. * Make sure current_position[E] and destination[E] are good
  12110. * before calling or cold/lengthy extrusion may get missed.
  12111. */
  12112. void prepare_move_to_destination() {
  12113. clamp_to_software_endstops(destination);
  12114. #if ENABLED(PREVENT_COLD_EXTRUSION) || ENABLED(PREVENT_LENGTHY_EXTRUDE)
  12115. if (!DEBUGGING(DRYRUN)) {
  12116. if (destination[E_CART] != current_position[E_CART]) {
  12117. #if ENABLED(PREVENT_COLD_EXTRUSION)
  12118. if (thermalManager.tooColdToExtrude(active_extruder)) {
  12119. current_position[E_CART] = destination[E_CART]; // Behave as if the move really took place, but ignore E part
  12120. SERIAL_ECHO_START();
  12121. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  12122. }
  12123. #endif // PREVENT_COLD_EXTRUSION
  12124. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  12125. if (ABS(destination[E_CART] - current_position[E_CART]) * planner.e_factor[active_extruder] > (EXTRUDE_MAXLENGTH)) {
  12126. current_position[E_CART] = destination[E_CART]; // Behave as if the move really took place, but ignore E part
  12127. SERIAL_ECHO_START();
  12128. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  12129. }
  12130. #endif // PREVENT_LENGTHY_EXTRUDE
  12131. }
  12132. }
  12133. #endif
  12134. #if ENABLED(DUAL_X_CARRIAGE)
  12135. if (dual_x_carriage_unpark()) return;
  12136. #endif
  12137. if (
  12138. #if UBL_SEGMENTED
  12139. ubl.prepare_segmented_line_to(destination, MMS_SCALED(feedrate_mm_s))
  12140. #elif IS_KINEMATIC
  12141. prepare_kinematic_move_to(destination)
  12142. #else
  12143. prepare_move_to_destination_cartesian()
  12144. #endif
  12145. ) return;
  12146. set_current_from_destination();
  12147. }
  12148. #if ENABLED(ARC_SUPPORT)
  12149. #if N_ARC_CORRECTION < 1
  12150. #undef N_ARC_CORRECTION
  12151. #define N_ARC_CORRECTION 1
  12152. #endif
  12153. /**
  12154. * Plan an arc in 2 dimensions
  12155. *
  12156. * The arc is approximated by generating many small linear segments.
  12157. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm)
  12158. * Arcs should only be made relatively large (over 5mm), as larger arcs with
  12159. * larger segments will tend to be more efficient. Your slicer should have
  12160. * options for G2/G3 arc generation. In future these options may be GCode tunable.
  12161. */
  12162. void plan_arc(
  12163. const float (&cart)[XYZE], // Destination position
  12164. const float (&offset)[2], // Center of rotation relative to current_position
  12165. const bool clockwise // Clockwise?
  12166. ) {
  12167. #if ENABLED(CNC_WORKSPACE_PLANES)
  12168. AxisEnum p_axis, q_axis, l_axis;
  12169. switch (workspace_plane) {
  12170. default:
  12171. case PLANE_XY: p_axis = X_AXIS; q_axis = Y_AXIS; l_axis = Z_AXIS; break;
  12172. case PLANE_ZX: p_axis = Z_AXIS; q_axis = X_AXIS; l_axis = Y_AXIS; break;
  12173. case PLANE_YZ: p_axis = Y_AXIS; q_axis = Z_AXIS; l_axis = X_AXIS; break;
  12174. }
  12175. #else
  12176. constexpr AxisEnum p_axis = X_AXIS, q_axis = Y_AXIS, l_axis = Z_AXIS;
  12177. #endif
  12178. // Radius vector from center to current location
  12179. float r_P = -offset[0], r_Q = -offset[1];
  12180. const float radius = HYPOT(r_P, r_Q),
  12181. center_P = current_position[p_axis] - r_P,
  12182. center_Q = current_position[q_axis] - r_Q,
  12183. rt_X = cart[p_axis] - center_P,
  12184. rt_Y = cart[q_axis] - center_Q,
  12185. linear_travel = cart[l_axis] - current_position[l_axis],
  12186. extruder_travel = cart[E_CART] - current_position[E_CART];
  12187. // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required.
  12188. float angular_travel = ATAN2(r_P * rt_Y - r_Q * rt_X, r_P * rt_X + r_Q * rt_Y);
  12189. if (angular_travel < 0) angular_travel += RADIANS(360);
  12190. if (clockwise) angular_travel -= RADIANS(360);
  12191. // Make a circle if the angular rotation is 0 and the target is current position
  12192. if (angular_travel == 0 && current_position[p_axis] == cart[p_axis] && current_position[q_axis] == cart[q_axis])
  12193. angular_travel = RADIANS(360);
  12194. const float flat_mm = radius * angular_travel,
  12195. mm_of_travel = linear_travel ? HYPOT(flat_mm, linear_travel) : ABS(flat_mm);
  12196. if (mm_of_travel < 0.001f) return;
  12197. uint16_t segments = FLOOR(mm_of_travel / (MM_PER_ARC_SEGMENT));
  12198. NOLESS(segments, 1);
  12199. /**
  12200. * Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
  12201. * and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
  12202. * r_T = [cos(phi) -sin(phi);
  12203. * sin(phi) cos(phi)] * r ;
  12204. *
  12205. * For arc generation, the center of the circle is the axis of rotation and the radius vector is
  12206. * defined from the circle center to the initial position. Each line segment is formed by successive
  12207. * vector rotations. This requires only two cos() and sin() computations to form the rotation
  12208. * matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
  12209. * all double numbers are single precision on the Arduino. (True double precision will not have
  12210. * round off issues for CNC applications.) Single precision error can accumulate to be greater than
  12211. * tool precision in some cases. Therefore, arc path correction is implemented.
  12212. *
  12213. * Small angle approximation may be used to reduce computation overhead further. This approximation
  12214. * holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words,
  12215. * theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
  12216. * to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
  12217. * numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
  12218. * issue for CNC machines with the single precision Arduino calculations.
  12219. *
  12220. * This approximation also allows plan_arc to immediately insert a line segment into the planner
  12221. * without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
  12222. * a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead.
  12223. * This is important when there are successive arc motions.
  12224. */
  12225. // Vector rotation matrix values
  12226. float raw[XYZE];
  12227. const float theta_per_segment = angular_travel / segments,
  12228. linear_per_segment = linear_travel / segments,
  12229. extruder_per_segment = extruder_travel / segments,
  12230. sin_T = theta_per_segment,
  12231. cos_T = 1 - 0.5f * sq(theta_per_segment); // Small angle approximation
  12232. // Initialize the linear axis
  12233. raw[l_axis] = current_position[l_axis];
  12234. // Initialize the extruder axis
  12235. raw[E_CART] = current_position[E_CART];
  12236. const float fr_mm_s = MMS_SCALED(feedrate_mm_s);
  12237. millis_t next_idle_ms = millis() + 200UL;
  12238. #if HAS_FEEDRATE_SCALING
  12239. // SCARA needs to scale the feed rate from mm/s to degrees/s
  12240. const float inv_segment_length = 1.0f / (MM_PER_ARC_SEGMENT),
  12241. inverse_secs = inv_segment_length * fr_mm_s;
  12242. float oldA = planner.position_float[A_AXIS],
  12243. oldB = planner.position_float[B_AXIS]
  12244. #if ENABLED(DELTA_FEEDRATE_SCALING)
  12245. , oldC = planner.position_float[C_AXIS]
  12246. #endif
  12247. ;
  12248. #endif
  12249. #if N_ARC_CORRECTION > 1
  12250. int8_t arc_recalc_count = N_ARC_CORRECTION;
  12251. #endif
  12252. for (uint16_t i = 1; i < segments; i++) { // Iterate (segments-1) times
  12253. thermalManager.manage_heater();
  12254. if (ELAPSED(millis(), next_idle_ms)) {
  12255. next_idle_ms = millis() + 200UL;
  12256. idle();
  12257. }
  12258. #if N_ARC_CORRECTION > 1
  12259. if (--arc_recalc_count) {
  12260. // Apply vector rotation matrix to previous r_P / 1
  12261. const float r_new_Y = r_P * sin_T + r_Q * cos_T;
  12262. r_P = r_P * cos_T - r_Q * sin_T;
  12263. r_Q = r_new_Y;
  12264. }
  12265. else
  12266. #endif
  12267. {
  12268. #if N_ARC_CORRECTION > 1
  12269. arc_recalc_count = N_ARC_CORRECTION;
  12270. #endif
  12271. // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
  12272. // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
  12273. // To reduce stuttering, the sin and cos could be computed at different times.
  12274. // For now, compute both at the same time.
  12275. const float cos_Ti = cos(i * theta_per_segment), sin_Ti = sin(i * theta_per_segment);
  12276. r_P = -offset[0] * cos_Ti + offset[1] * sin_Ti;
  12277. r_Q = -offset[0] * sin_Ti - offset[1] * cos_Ti;
  12278. }
  12279. // Update raw location
  12280. raw[p_axis] = center_P + r_P;
  12281. raw[q_axis] = center_Q + r_Q;
  12282. raw[l_axis] += linear_per_segment;
  12283. raw[E_CART] += extruder_per_segment;
  12284. clamp_to_software_endstops(raw);
  12285. #if HAS_FEEDRATE_SCALING
  12286. inverse_kinematics(raw);
  12287. ADJUST_DELTA(raw);
  12288. #endif
  12289. #if ENABLED(SCARA_FEEDRATE_SCALING)
  12290. // For SCARA scale the feed rate from mm/s to degrees/s
  12291. // i.e., Complete the angular vector in the given time.
  12292. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], raw[Z_AXIS], raw[E_CART], HYPOT(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT))
  12293. break;
  12294. oldA = delta[A_AXIS]; oldB = delta[B_AXIS];
  12295. #elif ENABLED(DELTA_FEEDRATE_SCALING)
  12296. // For DELTA scale the feed rate from Effector mm/s to Carriage mm/s
  12297. // i.e., Complete the linear vector in the given time.
  12298. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_AXIS], SQRT(sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC)) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT))
  12299. break;
  12300. oldA = delta[A_AXIS]; oldB = delta[B_AXIS]; oldC = delta[C_AXIS];
  12301. #elif HAS_UBL_AND_CURVES
  12302. float pos[XYZ] = { raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS] };
  12303. planner.apply_leveling(pos);
  12304. if (!planner.buffer_segment(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS], raw[E_CART], fr_mm_s, active_extruder, MM_PER_ARC_SEGMENT))
  12305. break;
  12306. #else
  12307. if (!planner.buffer_line_kinematic(raw, fr_mm_s, active_extruder))
  12308. break;
  12309. #endif
  12310. }
  12311. // Ensure last segment arrives at target location.
  12312. #if HAS_FEEDRATE_SCALING
  12313. inverse_kinematics(cart);
  12314. ADJUST_DELTA(cart);
  12315. #endif
  12316. #if ENABLED(SCARA_FEEDRATE_SCALING)
  12317. const float diff2 = HYPOT2(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB);
  12318. if (diff2)
  12319. planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], cart[Z_AXIS], cart[E_CART], SQRT(diff2) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT);
  12320. #elif ENABLED(DELTA_FEEDRATE_SCALING)
  12321. const float diff2 = sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC);
  12322. if (diff2)
  12323. planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], cart[E_CART], SQRT(diff2) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT);
  12324. #elif HAS_UBL_AND_CURVES
  12325. float pos[XYZ] = { cart[X_AXIS], cart[Y_AXIS], cart[Z_AXIS] };
  12326. planner.apply_leveling(pos);
  12327. planner.buffer_segment(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS], cart[E_CART], fr_mm_s, active_extruder, MM_PER_ARC_SEGMENT);
  12328. #else
  12329. planner.buffer_line_kinematic(cart, fr_mm_s, active_extruder);
  12330. #endif
  12331. COPY(current_position, cart);
  12332. } // plan_arc
  12333. #endif // ARC_SUPPORT
  12334. #if ENABLED(BEZIER_CURVE_SUPPORT)
  12335. void plan_cubic_move(const float (&cart)[XYZE], const float (&offset)[4]) {
  12336. cubic_b_spline(current_position, cart, offset, MMS_SCALED(feedrate_mm_s), active_extruder);
  12337. COPY(current_position, cart);
  12338. }
  12339. #endif // BEZIER_CURVE_SUPPORT
  12340. #if ENABLED(USE_CONTROLLER_FAN)
  12341. void controllerFan() {
  12342. static millis_t lastMotorOn = 0, // Last time a motor was turned on
  12343. nextMotorCheck = 0; // Last time the state was checked
  12344. const millis_t ms = millis();
  12345. if (ELAPSED(ms, nextMotorCheck)) {
  12346. nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s
  12347. // If any of the drivers or the bed are enabled...
  12348. if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON
  12349. #if HAS_HEATED_BED
  12350. || thermalManager.soft_pwm_amount_bed > 0
  12351. #endif
  12352. #if HAS_X2_ENABLE
  12353. || X2_ENABLE_READ == X_ENABLE_ON
  12354. #endif
  12355. #if HAS_Y2_ENABLE
  12356. || Y2_ENABLE_READ == Y_ENABLE_ON
  12357. #endif
  12358. #if HAS_Z2_ENABLE
  12359. || Z2_ENABLE_READ == Z_ENABLE_ON
  12360. #endif
  12361. || E0_ENABLE_READ == E_ENABLE_ON
  12362. #if E_STEPPERS > 1
  12363. || E1_ENABLE_READ == E_ENABLE_ON
  12364. #if E_STEPPERS > 2
  12365. || E2_ENABLE_READ == E_ENABLE_ON
  12366. #if E_STEPPERS > 3
  12367. || E3_ENABLE_READ == E_ENABLE_ON
  12368. #if E_STEPPERS > 4
  12369. || E4_ENABLE_READ == E_ENABLE_ON
  12370. #endif
  12371. #endif
  12372. #endif
  12373. #endif
  12374. ) {
  12375. lastMotorOn = ms; //... set time to NOW so the fan will turn on
  12376. }
  12377. // Fan off if no steppers have been enabled for CONTROLLERFAN_SECS seconds
  12378. const uint8_t speed = (lastMotorOn && PENDING(ms, lastMotorOn + (CONTROLLERFAN_SECS) * 1000UL)) ? CONTROLLERFAN_SPEED : 0;
  12379. controllerFanSpeed = speed;
  12380. // allows digital or PWM fan output to be used (see M42 handling)
  12381. WRITE(CONTROLLER_FAN_PIN, speed);
  12382. analogWrite(CONTROLLER_FAN_PIN, speed);
  12383. }
  12384. }
  12385. #endif // USE_CONTROLLER_FAN
  12386. #if ENABLED(MORGAN_SCARA)
  12387. /**
  12388. * Morgan SCARA Forward Kinematics. Results in cartes[].
  12389. * Maths and first version by QHARLEY.
  12390. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  12391. */
  12392. void forward_kinematics_SCARA(const float &a, const float &b) {
  12393. float a_sin = sin(RADIANS(a)) * L1,
  12394. a_cos = cos(RADIANS(a)) * L1,
  12395. b_sin = sin(RADIANS(b)) * L2,
  12396. b_cos = cos(RADIANS(b)) * L2;
  12397. cartes[X_AXIS] = a_cos + b_cos + SCARA_OFFSET_X; //theta
  12398. cartes[Y_AXIS] = a_sin + b_sin + SCARA_OFFSET_Y; //theta+phi
  12399. /*
  12400. SERIAL_ECHOPAIR("SCARA FK Angle a=", a);
  12401. SERIAL_ECHOPAIR(" b=", b);
  12402. SERIAL_ECHOPAIR(" a_sin=", a_sin);
  12403. SERIAL_ECHOPAIR(" a_cos=", a_cos);
  12404. SERIAL_ECHOPAIR(" b_sin=", b_sin);
  12405. SERIAL_ECHOLNPAIR(" b_cos=", b_cos);
  12406. SERIAL_ECHOPAIR(" cartes[X_AXIS]=", cartes[X_AXIS]);
  12407. SERIAL_ECHOLNPAIR(" cartes[Y_AXIS]=", cartes[Y_AXIS]);
  12408. //*/
  12409. }
  12410. /**
  12411. * Morgan SCARA Inverse Kinematics. Results in delta[].
  12412. *
  12413. * See http://forums.reprap.org/read.php?185,283327
  12414. *
  12415. * Maths and first version by QHARLEY.
  12416. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  12417. */
  12418. void inverse_kinematics(const float raw[XYZ]) {
  12419. static float C2, S2, SK1, SK2, THETA, PSI;
  12420. float sx = raw[X_AXIS] - SCARA_OFFSET_X, // Translate SCARA to standard X Y
  12421. sy = raw[Y_AXIS] - SCARA_OFFSET_Y; // With scaling factor.
  12422. if (L1 == L2)
  12423. C2 = HYPOT2(sx, sy) / L1_2_2 - 1;
  12424. else
  12425. C2 = (HYPOT2(sx, sy) - (L1_2 + L2_2)) / (2.0 * L1 * L2);
  12426. S2 = SQRT(1 - sq(C2));
  12427. // Unrotated Arm1 plus rotated Arm2 gives the distance from Center to End
  12428. SK1 = L1 + L2 * C2;
  12429. // Rotated Arm2 gives the distance from Arm1 to Arm2
  12430. SK2 = L2 * S2;
  12431. // Angle of Arm1 is the difference between Center-to-End angle and the Center-to-Elbow
  12432. THETA = ATAN2(SK1, SK2) - ATAN2(sx, sy);
  12433. // Angle of Arm2
  12434. PSI = ATAN2(S2, C2);
  12435. delta[A_AXIS] = DEGREES(THETA); // theta is support arm angle
  12436. delta[B_AXIS] = DEGREES(THETA + PSI); // equal to sub arm angle (inverted motor)
  12437. delta[C_AXIS] = raw[Z_AXIS];
  12438. /*
  12439. DEBUG_POS("SCARA IK", raw);
  12440. DEBUG_POS("SCARA IK", delta);
  12441. SERIAL_ECHOPAIR(" SCARA (x,y) ", sx);
  12442. SERIAL_ECHOPAIR(",", sy);
  12443. SERIAL_ECHOPAIR(" C2=", C2);
  12444. SERIAL_ECHOPAIR(" S2=", S2);
  12445. SERIAL_ECHOPAIR(" Theta=", THETA);
  12446. SERIAL_ECHOLNPAIR(" Phi=", PHI);
  12447. //*/
  12448. }
  12449. #endif // MORGAN_SCARA
  12450. #if ENABLED(TEMP_STAT_LEDS)
  12451. static bool red_led = false;
  12452. static millis_t next_status_led_update_ms = 0;
  12453. void handle_status_leds(void) {
  12454. if (ELAPSED(millis(), next_status_led_update_ms)) {
  12455. next_status_led_update_ms += 500; // Update every 0.5s
  12456. float max_temp = 0.0;
  12457. #if HAS_HEATED_BED
  12458. max_temp = MAX3(max_temp, thermalManager.degTargetBed(), thermalManager.degBed());
  12459. #endif
  12460. HOTEND_LOOP()
  12461. max_temp = MAX3(max_temp, thermalManager.degHotend(e), thermalManager.degTargetHotend(e));
  12462. const bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led;
  12463. if (new_led != red_led) {
  12464. red_led = new_led;
  12465. #if PIN_EXISTS(STAT_LED_RED)
  12466. WRITE(STAT_LED_RED_PIN, new_led ? HIGH : LOW);
  12467. #if PIN_EXISTS(STAT_LED_BLUE)
  12468. WRITE(STAT_LED_BLUE_PIN, new_led ? LOW : HIGH);
  12469. #endif
  12470. #else
  12471. WRITE(STAT_LED_BLUE_PIN, new_led ? HIGH : LOW);
  12472. #endif
  12473. }
  12474. }
  12475. }
  12476. #endif
  12477. void enable_all_steppers() {
  12478. #if ENABLED(AUTO_POWER_CONTROL)
  12479. powerManager.power_on();
  12480. #endif
  12481. #if ENABLED(HANGPRINTER)
  12482. enable_A();
  12483. enable_B();
  12484. enable_C();
  12485. enable_D();
  12486. #else
  12487. enable_X();
  12488. enable_Y();
  12489. enable_Z();
  12490. enable_E4();
  12491. #endif
  12492. enable_E0();
  12493. enable_E1();
  12494. enable_E2();
  12495. enable_E3();
  12496. }
  12497. void disable_e_stepper(const uint8_t e) {
  12498. switch (e) {
  12499. case 0: disable_E0(); break;
  12500. case 1: disable_E1(); break;
  12501. case 2: disable_E2(); break;
  12502. case 3: disable_E3(); break;
  12503. case 4: disable_E4(); break;
  12504. }
  12505. }
  12506. void disable_e_steppers() {
  12507. disable_E0();
  12508. disable_E1();
  12509. disable_E2();
  12510. disable_E3();
  12511. disable_E4();
  12512. }
  12513. void disable_all_steppers() {
  12514. disable_X();
  12515. disable_Y();
  12516. disable_Z();
  12517. disable_e_steppers();
  12518. }
  12519. /**
  12520. * Manage several activities:
  12521. * - Check for Filament Runout
  12522. * - Keep the command buffer full
  12523. * - Check for maximum inactive time between commands
  12524. * - Check for maximum inactive time between stepper commands
  12525. * - Check if pin CHDK needs to go LOW
  12526. * - Check for KILL button held down
  12527. * - Check for HOME button held down
  12528. * - Check if cooling fan needs to be switched on
  12529. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  12530. */
  12531. void manage_inactivity(const bool ignore_stepper_queue/*=false*/) {
  12532. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  12533. runout.run();
  12534. #endif
  12535. if (commands_in_queue < BUFSIZE) get_available_commands();
  12536. const millis_t ms = millis();
  12537. if (max_inactive_time && ELAPSED(ms, previous_move_ms + max_inactive_time)) {
  12538. SERIAL_ERROR_START();
  12539. SERIAL_ECHOLNPAIR(MSG_KILL_INACTIVE_TIME, parser.command_ptr);
  12540. kill(PSTR(MSG_KILLED));
  12541. }
  12542. // Prevent steppers timing-out in the middle of M600
  12543. #if ENABLED(ADVANCED_PAUSE_FEATURE) && ENABLED(PAUSE_PARK_NO_STEPPER_TIMEOUT)
  12544. #define MOVE_AWAY_TEST !did_pause_print
  12545. #else
  12546. #define MOVE_AWAY_TEST true
  12547. #endif
  12548. if (stepper_inactive_time) {
  12549. if (planner.has_blocks_queued())
  12550. previous_move_ms = ms; // reset_stepper_timeout to keep steppers powered
  12551. else if (MOVE_AWAY_TEST && !ignore_stepper_queue && ELAPSED(ms, previous_move_ms + stepper_inactive_time)) {
  12552. #if ENABLED(DISABLE_INACTIVE_X)
  12553. disable_X();
  12554. #endif
  12555. #if ENABLED(DISABLE_INACTIVE_Y)
  12556. disable_Y();
  12557. #endif
  12558. #if ENABLED(DISABLE_INACTIVE_Z)
  12559. disable_Z();
  12560. #endif
  12561. #if ENABLED(DISABLE_INACTIVE_E)
  12562. disable_e_steppers();
  12563. #endif
  12564. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(ULTIPANEL) // Only needed with an LCD
  12565. if (ubl.lcd_map_control) ubl.lcd_map_control = defer_return_to_status = false;
  12566. #endif
  12567. }
  12568. }
  12569. #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH
  12570. if (chdkActive && ELAPSED(ms, chdkHigh + CHDK_DELAY)) {
  12571. chdkActive = false;
  12572. WRITE(CHDK, LOW);
  12573. }
  12574. #endif
  12575. #if HAS_KILL
  12576. // Check if the kill button was pressed and wait just in case it was an accidental
  12577. // key kill key press
  12578. // -------------------------------------------------------------------------------
  12579. static int killCount = 0; // make the inactivity button a bit less responsive
  12580. const int KILL_DELAY = 750;
  12581. if (!READ(KILL_PIN))
  12582. killCount++;
  12583. else if (killCount > 0)
  12584. killCount--;
  12585. // Exceeded threshold and we can confirm that it was not accidental
  12586. // KILL the machine
  12587. // ----------------------------------------------------------------
  12588. if (killCount >= KILL_DELAY) {
  12589. SERIAL_ERROR_START();
  12590. SERIAL_ERRORLNPGM(MSG_KILL_BUTTON);
  12591. kill(PSTR(MSG_KILLED));
  12592. }
  12593. #endif
  12594. #if HAS_HOME
  12595. // Check to see if we have to home, use poor man's debouncer
  12596. // ---------------------------------------------------------
  12597. static int homeDebounceCount = 0; // poor man's debouncing count
  12598. const int HOME_DEBOUNCE_DELAY = 2500;
  12599. if (!IS_SD_PRINTING() && !READ(HOME_PIN)) {
  12600. if (!homeDebounceCount) {
  12601. enqueue_and_echo_commands_P(PSTR("G28"));
  12602. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  12603. }
  12604. if (homeDebounceCount < HOME_DEBOUNCE_DELAY)
  12605. homeDebounceCount++;
  12606. else
  12607. homeDebounceCount = 0;
  12608. }
  12609. #endif
  12610. #if ENABLED(USE_CONTROLLER_FAN)
  12611. controllerFan(); // Check if fan should be turned on to cool stepper drivers down
  12612. #endif
  12613. #if ENABLED(AUTO_POWER_CONTROL)
  12614. powerManager.check();
  12615. #endif
  12616. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  12617. if (thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP
  12618. && ELAPSED(ms, previous_move_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000UL)
  12619. && !planner.has_blocks_queued()
  12620. ) {
  12621. #if ENABLED(SWITCHING_EXTRUDER)
  12622. bool oldstatus;
  12623. switch (active_extruder) {
  12624. default: oldstatus = E0_ENABLE_READ; enable_E0(); break;
  12625. #if E_STEPPERS > 1
  12626. case 2: case 3: oldstatus = E1_ENABLE_READ; enable_E1(); break;
  12627. #if E_STEPPERS > 2
  12628. case 4: oldstatus = E2_ENABLE_READ; enable_E2(); break;
  12629. #endif // E_STEPPERS > 2
  12630. #endif // E_STEPPERS > 1
  12631. }
  12632. #else // !SWITCHING_EXTRUDER
  12633. bool oldstatus;
  12634. switch (active_extruder) {
  12635. default: oldstatus = E0_ENABLE_READ; enable_E0(); break;
  12636. #if E_STEPPERS > 1
  12637. case 1: oldstatus = E1_ENABLE_READ; enable_E1(); break;
  12638. #if E_STEPPERS > 2
  12639. case 2: oldstatus = E2_ENABLE_READ; enable_E2(); break;
  12640. #if E_STEPPERS > 3
  12641. case 3: oldstatus = E3_ENABLE_READ; enable_E3(); break;
  12642. #if E_STEPPERS > 4
  12643. case 4: oldstatus = E4_ENABLE_READ; enable_E4(); break;
  12644. #endif // E_STEPPERS > 4
  12645. #endif // E_STEPPERS > 3
  12646. #endif // E_STEPPERS > 2
  12647. #endif // E_STEPPERS > 1
  12648. }
  12649. #endif // !SWITCHING_EXTRUDER
  12650. const float olde = current_position[E_CART];
  12651. current_position[E_CART] += EXTRUDER_RUNOUT_EXTRUDE;
  12652. planner.buffer_line_kinematic(current_position, MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED), active_extruder);
  12653. current_position[E_CART] = olde;
  12654. planner.set_e_position_mm(olde);
  12655. planner.synchronize();
  12656. #if ENABLED(SWITCHING_EXTRUDER)
  12657. switch (active_extruder) {
  12658. default: oldstatus = E0_ENABLE_WRITE(oldstatus); break;
  12659. #if E_STEPPERS > 1
  12660. case 2: case 3: oldstatus = E1_ENABLE_WRITE(oldstatus); break;
  12661. #if E_STEPPERS > 2
  12662. case 4: oldstatus = E2_ENABLE_WRITE(oldstatus); break;
  12663. #endif // E_STEPPERS > 2
  12664. #endif // E_STEPPERS > 1
  12665. }
  12666. #else // !SWITCHING_EXTRUDER
  12667. switch (active_extruder) {
  12668. case 0: E0_ENABLE_WRITE(oldstatus); break;
  12669. #if E_STEPPERS > 1
  12670. case 1: E1_ENABLE_WRITE(oldstatus); break;
  12671. #if E_STEPPERS > 2
  12672. case 2: E2_ENABLE_WRITE(oldstatus); break;
  12673. #if E_STEPPERS > 3
  12674. case 3: E3_ENABLE_WRITE(oldstatus); break;
  12675. #if E_STEPPERS > 4
  12676. case 4: E4_ENABLE_WRITE(oldstatus); break;
  12677. #endif // E_STEPPERS > 4
  12678. #endif // E_STEPPERS > 3
  12679. #endif // E_STEPPERS > 2
  12680. #endif // E_STEPPERS > 1
  12681. }
  12682. #endif // !SWITCHING_EXTRUDER
  12683. previous_move_ms = ms; // reset_stepper_timeout to keep steppers powered
  12684. }
  12685. #endif // EXTRUDER_RUNOUT_PREVENT
  12686. #if ENABLED(DUAL_X_CARRIAGE)
  12687. // handle delayed move timeout
  12688. if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) {
  12689. // travel moves have been received so enact them
  12690. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  12691. set_destination_from_current();
  12692. prepare_move_to_destination();
  12693. }
  12694. #endif
  12695. #if ENABLED(TEMP_STAT_LEDS)
  12696. handle_status_leds();
  12697. #endif
  12698. #if ENABLED(MONITOR_DRIVER_STATUS)
  12699. monitor_tmc_driver();
  12700. #endif
  12701. planner.check_axes_activity();
  12702. }
  12703. /**
  12704. * Standard idle routine keeps the machine alive
  12705. */
  12706. void idle(
  12707. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  12708. bool no_stepper_sleep/*=false*/
  12709. #endif
  12710. ) {
  12711. #if ENABLED(MAX7219_DEBUG)
  12712. max7219.idle_tasks();
  12713. #endif
  12714. lcd_update();
  12715. host_keepalive();
  12716. manage_inactivity(
  12717. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  12718. no_stepper_sleep
  12719. #endif
  12720. );
  12721. thermalManager.manage_heater();
  12722. #if ENABLED(PRINTCOUNTER)
  12723. print_job_timer.tick();
  12724. #endif
  12725. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  12726. buzzer.tick();
  12727. #endif
  12728. #if ENABLED(I2C_POSITION_ENCODERS)
  12729. static millis_t i2cpem_next_update_ms;
  12730. if (planner.has_blocks_queued() && ELAPSED(millis(), i2cpem_next_update_ms)) {
  12731. I2CPEM.update();
  12732. i2cpem_next_update_ms = millis() + I2CPE_MIN_UPD_TIME_MS;
  12733. }
  12734. #endif
  12735. #if HAS_AUTO_REPORTING
  12736. if (!suspend_auto_report) {
  12737. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  12738. thermalManager.auto_report_temperatures();
  12739. #endif
  12740. #if ENABLED(AUTO_REPORT_SD_STATUS)
  12741. card.auto_report_sd_status();
  12742. #endif
  12743. }
  12744. #endif
  12745. }
  12746. /**
  12747. * Kill all activity and lock the machine.
  12748. * After this the machine will need to be reset.
  12749. */
  12750. void kill(const char* lcd_msg) {
  12751. SERIAL_ERROR_START();
  12752. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  12753. thermalManager.disable_all_heaters();
  12754. disable_all_steppers();
  12755. #if ENABLED(ULTRA_LCD)
  12756. kill_screen(lcd_msg);
  12757. #else
  12758. UNUSED(lcd_msg);
  12759. #endif
  12760. _delay_ms(600); // Wait a short time (allows messages to get out before shutting down.
  12761. cli(); // Stop interrupts
  12762. _delay_ms(250); //Wait to ensure all interrupts routines stopped
  12763. thermalManager.disable_all_heaters(); //turn off heaters again
  12764. #ifdef ACTION_ON_KILL
  12765. SERIAL_ECHOLNPGM("//action:" ACTION_ON_KILL);
  12766. #endif
  12767. #if HAS_POWER_SWITCH
  12768. PSU_OFF();
  12769. #endif
  12770. suicide();
  12771. while (1) {
  12772. #if ENABLED(USE_WATCHDOG)
  12773. watchdog_reset();
  12774. #endif
  12775. } // Wait for reset
  12776. }
  12777. /**
  12778. * Turn off heaters and stop the print in progress
  12779. * After a stop the machine may be resumed with M999
  12780. */
  12781. void stop() {
  12782. thermalManager.disable_all_heaters(); // 'unpause' taken care of in here
  12783. #if ENABLED(PROBING_FANS_OFF)
  12784. if (fans_paused) fans_pause(false); // put things back the way they were
  12785. #endif
  12786. if (IsRunning()) {
  12787. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  12788. SERIAL_ERROR_START();
  12789. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  12790. LCD_MESSAGEPGM(MSG_STOPPED);
  12791. safe_delay(350); // allow enough time for messages to get out before stopping
  12792. Running = false;
  12793. }
  12794. }
  12795. /**
  12796. * Marlin entry-point: Set up before the program loop
  12797. * - Set up the kill pin, filament runout, power hold
  12798. * - Start the serial port
  12799. * - Print startup messages and diagnostics
  12800. * - Get EEPROM or default settings
  12801. * - Initialize managers for:
  12802. * • temperature
  12803. * • planner
  12804. * • watchdog
  12805. * • stepper
  12806. * • photo pin
  12807. * • servos
  12808. * • LCD controller
  12809. * • Digipot I2C
  12810. * • Z probe sled
  12811. * • status LEDs
  12812. */
  12813. void setup() {
  12814. #if ENABLED(MAX7219_DEBUG)
  12815. max7219.init();
  12816. #endif
  12817. #if ENABLED(DISABLE_JTAG)
  12818. // Disable JTAG on AT90USB chips to free up pins for IO
  12819. MCUCR = 0x80;
  12820. MCUCR = 0x80;
  12821. #endif
  12822. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  12823. runout.setup();
  12824. #endif
  12825. setup_killpin();
  12826. setup_powerhold();
  12827. #if HAS_STEPPER_RESET
  12828. disableStepperDrivers();
  12829. #endif
  12830. MYSERIAL0.begin(BAUDRATE);
  12831. SERIAL_PROTOCOLLNPGM("start");
  12832. SERIAL_ECHO_START();
  12833. // Prepare communication for TMC drivers
  12834. #if HAS_DRIVER(TMC2130)
  12835. tmc_init_cs_pins();
  12836. #endif
  12837. #if HAS_DRIVER(TMC2208)
  12838. tmc2208_serial_begin();
  12839. #endif
  12840. // Check startup - does nothing if bootloader sets MCUSR to 0
  12841. byte mcu = MCUSR;
  12842. if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  12843. if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  12844. if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  12845. if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  12846. if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  12847. MCUSR = 0;
  12848. SERIAL_ECHOPGM(MSG_MARLIN);
  12849. SERIAL_CHAR(' ');
  12850. SERIAL_ECHOLNPGM(SHORT_BUILD_VERSION);
  12851. SERIAL_EOL();
  12852. #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR)
  12853. SERIAL_ECHO_START();
  12854. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  12855. SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE);
  12856. SERIAL_ECHOLNPGM(MSG_AUTHOR STRING_CONFIG_H_AUTHOR);
  12857. SERIAL_ECHO_START();
  12858. SERIAL_ECHOLNPGM("Compiled: " __DATE__);
  12859. #endif
  12860. SERIAL_ECHO_START();
  12861. SERIAL_ECHOPAIR(MSG_FREE_MEMORY, freeMemory());
  12862. SERIAL_ECHOLNPAIR(MSG_PLANNER_BUFFER_BYTES, int(sizeof(block_t))*(BLOCK_BUFFER_SIZE));
  12863. // Send "ok" after commands by default
  12864. for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true;
  12865. // Load data from EEPROM if available (or use defaults)
  12866. // This also updates variables in the planner, elsewhere
  12867. (void)settings.load();
  12868. #if HAS_M206_COMMAND
  12869. // Initialize current position based on home_offset
  12870. COPY(current_position, home_offset);
  12871. #else
  12872. ZERO(current_position);
  12873. #endif
  12874. // Vital to init stepper/planner equivalent for current_position
  12875. SYNC_PLAN_POSITION_KINEMATIC();
  12876. thermalManager.init(); // Initialize temperature loop
  12877. print_job_timer.init(); // Initial setup of print job timer
  12878. endstops.init(); // Init endstops and pullups
  12879. stepper.init(); // Init stepper. This enables interrupts!
  12880. servo_init(); // Initialize all servos, stow servo probe
  12881. #if HAS_PHOTOGRAPH
  12882. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  12883. #endif
  12884. #if HAS_CASE_LIGHT
  12885. case_light_on = CASE_LIGHT_DEFAULT_ON;
  12886. case_light_brightness = CASE_LIGHT_DEFAULT_BRIGHTNESS;
  12887. update_case_light();
  12888. #endif
  12889. #if ENABLED(SPINDLE_LASER_ENABLE)
  12890. OUT_WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // init spindle to off
  12891. #if SPINDLE_DIR_CHANGE
  12892. OUT_WRITE(SPINDLE_DIR_PIN, SPINDLE_INVERT_DIR ? 255 : 0); // init rotation to clockwise (M3)
  12893. #endif
  12894. #if ENABLED(SPINDLE_LASER_PWM)
  12895. SET_OUTPUT(SPINDLE_LASER_PWM_PIN);
  12896. analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0); // set to lowest speed
  12897. #endif
  12898. #endif
  12899. #if HAS_BED_PROBE
  12900. endstops.enable_z_probe(false);
  12901. #endif
  12902. #if ENABLED(USE_CONTROLLER_FAN)
  12903. SET_OUTPUT(CONTROLLER_FAN_PIN); //Set pin used for driver cooling fan
  12904. #endif
  12905. #if HAS_STEPPER_RESET
  12906. enableStepperDrivers();
  12907. #endif
  12908. #if ENABLED(DIGIPOT_I2C)
  12909. digipot_i2c_init();
  12910. #endif
  12911. #if ENABLED(DAC_STEPPER_CURRENT)
  12912. dac_init();
  12913. #endif
  12914. #if (ENABLED(Z_PROBE_SLED) || ENABLED(SOLENOID_PROBE)) && HAS_SOLENOID_1
  12915. OUT_WRITE(SOL1_PIN, LOW); // turn it off
  12916. #endif
  12917. #if HAS_HOME
  12918. SET_INPUT_PULLUP(HOME_PIN);
  12919. #endif
  12920. #if PIN_EXISTS(STAT_LED_RED)
  12921. OUT_WRITE(STAT_LED_RED_PIN, LOW); // turn it off
  12922. #endif
  12923. #if PIN_EXISTS(STAT_LED_BLUE)
  12924. OUT_WRITE(STAT_LED_BLUE_PIN, LOW); // turn it off
  12925. #endif
  12926. #if HAS_COLOR_LEDS
  12927. leds.setup();
  12928. #endif
  12929. #if ENABLED(RGB_LED) || ENABLED(RGBW_LED)
  12930. SET_OUTPUT(RGB_LED_R_PIN);
  12931. SET_OUTPUT(RGB_LED_G_PIN);
  12932. SET_OUTPUT(RGB_LED_B_PIN);
  12933. #if ENABLED(RGBW_LED)
  12934. SET_OUTPUT(RGB_LED_W_PIN);
  12935. #endif
  12936. #endif
  12937. #if ENABLED(MK2_MULTIPLEXER)
  12938. SET_OUTPUT(E_MUX0_PIN);
  12939. SET_OUTPUT(E_MUX1_PIN);
  12940. SET_OUTPUT(E_MUX2_PIN);
  12941. #endif
  12942. #if HAS_FANMUX
  12943. fanmux_init();
  12944. #endif
  12945. lcd_init();
  12946. lcd_reset_status();
  12947. #if ENABLED(SHOW_BOOTSCREEN)
  12948. lcd_bootscreen();
  12949. #endif
  12950. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  12951. // Virtual Tools 0, 1, 2, 3 = Filament 1, 2, 3, 4, etc.
  12952. for (uint8_t t = 0; t < MIXING_VIRTUAL_TOOLS && t < MIXING_STEPPERS; t++)
  12953. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  12954. mixing_virtual_tool_mix[t][i] = (t == i) ? 1.0 : 0.0;
  12955. // Remaining virtual tools are 100% filament 1
  12956. #if MIXING_STEPPERS < MIXING_VIRTUAL_TOOLS
  12957. for (uint8_t t = MIXING_STEPPERS; t < MIXING_VIRTUAL_TOOLS; t++)
  12958. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  12959. mixing_virtual_tool_mix[t][i] = (i == 0) ? 1.0 : 0.0;
  12960. #endif
  12961. // Initialize mixing to tool 0 color
  12962. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  12963. mixing_factor[i] = mixing_virtual_tool_mix[0][i];
  12964. #endif
  12965. #if ENABLED(BLTOUCH)
  12966. // Make sure any BLTouch error condition is cleared
  12967. bltouch_command(BLTOUCH_RESET);
  12968. set_bltouch_deployed(false);
  12969. #endif
  12970. #if ENABLED(I2C_POSITION_ENCODERS)
  12971. I2CPEM.init();
  12972. #endif
  12973. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  12974. i2c.onReceive(i2c_on_receive);
  12975. i2c.onRequest(i2c_on_request);
  12976. #endif
  12977. #if DO_SWITCH_EXTRUDER
  12978. move_extruder_servo(0); // Initialize extruder servo
  12979. #endif
  12980. #if ENABLED(SWITCHING_NOZZLE)
  12981. move_nozzle_servo(0); // Initialize nozzle servo
  12982. #endif
  12983. #if ENABLED(PARKING_EXTRUDER)
  12984. #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT)
  12985. pe_activate_magnet(0);
  12986. pe_activate_magnet(1);
  12987. #else
  12988. pe_deactivate_magnet(0);
  12989. pe_deactivate_magnet(1);
  12990. #endif
  12991. #endif
  12992. #if ENABLED(POWER_LOSS_RECOVERY)
  12993. check_print_job_recovery();
  12994. #endif
  12995. #if ENABLED(USE_WATCHDOG)
  12996. watchdog_init();
  12997. #endif
  12998. #if ENABLED(HANGPRINTER)
  12999. enable_A();
  13000. enable_B();
  13001. enable_C();
  13002. enable_D();
  13003. #endif
  13004. #if ENABLED(SDSUPPORT) && DISABLED(ULTRA_LCD)
  13005. card.beginautostart();
  13006. #endif
  13007. }
  13008. /**
  13009. * The main Marlin program loop
  13010. *
  13011. * - Abort SD printing if flagged
  13012. * - Save or log commands to SD
  13013. * - Process available commands (if not saving)
  13014. * - Call heater manager
  13015. * - Call inactivity manager
  13016. * - Call endstop manager
  13017. * - Call LCD update
  13018. */
  13019. void loop() {
  13020. #if ENABLED(SDSUPPORT)
  13021. card.checkautostart();
  13022. if (card.abort_sd_printing) {
  13023. card.stopSDPrint(
  13024. #if SD_RESORT
  13025. true
  13026. #endif
  13027. );
  13028. clear_command_queue();
  13029. quickstop_stepper();
  13030. print_job_timer.stop();
  13031. thermalManager.disable_all_heaters();
  13032. #if FAN_COUNT > 0
  13033. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  13034. #endif
  13035. wait_for_heatup = false;
  13036. #if ENABLED(POWER_LOSS_RECOVERY)
  13037. card.removeJobRecoveryFile();
  13038. #endif
  13039. }
  13040. #endif // SDSUPPORT
  13041. if (commands_in_queue < BUFSIZE) get_available_commands();
  13042. if (commands_in_queue) {
  13043. #if ENABLED(SDSUPPORT)
  13044. if (card.saving) {
  13045. char* command = command_queue[cmd_queue_index_r];
  13046. if (strstr_P(command, PSTR("M29"))) {
  13047. // M29 closes the file
  13048. card.closefile();
  13049. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  13050. #if USE_MARLINSERIAL
  13051. #if ENABLED(SERIAL_STATS_DROPPED_RX)
  13052. SERIAL_ECHOLNPAIR("Dropped bytes: ", customizedSerial.dropped());
  13053. #endif
  13054. #if ENABLED(SERIAL_STATS_MAX_RX_QUEUED)
  13055. SERIAL_ECHOLNPAIR("Max RX Queue Size: ", customizedSerial.rxMaxEnqueued());
  13056. #endif
  13057. #endif
  13058. ok_to_send();
  13059. }
  13060. else {
  13061. // Write the string from the read buffer to SD
  13062. card.write_command(command);
  13063. if (card.logging)
  13064. process_next_command(); // The card is saving because it's logging
  13065. else
  13066. ok_to_send();
  13067. }
  13068. }
  13069. else {
  13070. process_next_command();
  13071. #if ENABLED(POWER_LOSS_RECOVERY)
  13072. if (card.cardOK && card.sdprinting) save_job_recovery_info();
  13073. #endif
  13074. }
  13075. #else
  13076. process_next_command();
  13077. #endif // SDSUPPORT
  13078. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  13079. if (commands_in_queue) {
  13080. --commands_in_queue;
  13081. if (++cmd_queue_index_r >= BUFSIZE) cmd_queue_index_r = 0;
  13082. }
  13083. }
  13084. endstops.event_handler();
  13085. idle();
  13086. }