My Marlin configs for Fabrikator Mini and CTC i3 Pro B
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Marlin_main.cpp 202KB

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