My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Marlin_main.cpp 233KB

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