My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Marlin_main.cpp 189KB

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