Marlin_main.cpp 172 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029
  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. #ifdef MESH_BED_LEVELING
  31. #include "mesh_bed_leveling.h"
  32. #include "mesh_bed_calibration.h"
  33. #endif
  34. #include "ultralcd.h"
  35. #include "Configuration_prusa.h"
  36. #include "planner.h"
  37. #include "stepper.h"
  38. #include "temperature.h"
  39. #include "motion_control.h"
  40. #include "cardreader.h"
  41. #include "watchdog.h"
  42. #include "ConfigurationStore.h"
  43. #include "language.h"
  44. #include "pins_arduino.h"
  45. #include "math.h"
  46. #ifdef BLINKM
  47. #include "BlinkM.h"
  48. #include "Wire.h"
  49. #endif
  50. #ifdef ULTRALCD
  51. #include "ultralcd.h"
  52. #endif
  53. #if NUM_SERVOS > 0
  54. #include "Servo.h"
  55. #endif
  56. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  57. #include <SPI.h>
  58. #endif
  59. #define VERSION_STRING "1.0.2"
  60. #include "ultralcd.h"
  61. // Macros for bit masks
  62. #define BIT(b) (1<<(b))
  63. #define TEST(n,b) (((n)&BIT(b))!=0)
  64. #define SET_BIT(n,b,value) (n) ^= ((-value)^(n)) & (BIT(b))
  65. // look here for descriptions of G-codes: http://linuxcnc.org/handbook/gcode/g-code.html
  66. // http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  67. //Implemented Codes
  68. //-------------------
  69. // PRUSA CODES
  70. // P F - Returns FW versions
  71. // P R - Returns revision of printer
  72. // G0 -> G1
  73. // G1 - Coordinated Movement X Y Z E
  74. // G2 - CW ARC
  75. // G3 - CCW ARC
  76. // G4 - Dwell S<seconds> or P<milliseconds>
  77. // G10 - retract filament according to settings of M207
  78. // G11 - retract recover filament according to settings of M208
  79. // G28 - Home all Axis
  80. // G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  81. // G30 - Single Z Probe, probes bed at current XY location.
  82. // G31 - Dock sled (Z_PROBE_SLED only)
  83. // G32 - Undock sled (Z_PROBE_SLED only)
  84. // G80 - Automatic mesh bed leveling
  85. // G81 - Print bed profile
  86. // G90 - Use Absolute Coordinates
  87. // G91 - Use Relative Coordinates
  88. // G92 - Set current position to coordinates given
  89. // M Codes
  90. // M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  91. // M1 - Same as M0
  92. // M17 - Enable/Power all stepper motors
  93. // M18 - Disable all stepper motors; same as M84
  94. // M20 - List SD card
  95. // M21 - Init SD card
  96. // M22 - Release SD card
  97. // M23 - Select SD file (M23 filename.g)
  98. // M24 - Start/resume SD print
  99. // M25 - Pause SD print
  100. // M26 - Set SD position in bytes (M26 S12345)
  101. // M27 - Report SD print status
  102. // M28 - Start SD write (M28 filename.g)
  103. // M29 - Stop SD write
  104. // M30 - Delete file from SD (M30 filename.g)
  105. // M31 - Output time since last M109 or SD card start to serial
  106. // M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  107. // syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  108. // Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  109. // The '#' is necessary when calling from within sd files, as it stops buffer prereading
  110. // 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.
  111. // M80 - Turn on Power Supply
  112. // M81 - Turn off Power Supply
  113. // M82 - Set E codes absolute (default)
  114. // M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  115. // M84 - Disable steppers until next move,
  116. // or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  117. // M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  118. // M92 - Set axis_steps_per_unit - same syntax as G92
  119. // M104 - Set extruder target temp
  120. // M105 - Read current temp
  121. // M106 - Fan on
  122. // M107 - Fan off
  123. // M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  124. // Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  125. // IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  126. // M112 - Emergency stop
  127. // M114 - Output current position to serial port
  128. // M115 - Capabilities string
  129. // M117 - display message
  130. // M119 - Output Endstop status to serial port
  131. // M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  132. // M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  133. // M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  134. // M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  135. // M140 - Set bed target temp
  136. // 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.
  137. // M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  138. // Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  139. // M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  140. // M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  141. // M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  142. // M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  143. // M204 - Set default acceleration: S normal moves T filament only moves (M204 S3000 T7000) in mm/sec^2 also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  144. // 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
  145. // M206 - set additional homing offset
  146. // M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  147. // M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  148. // 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.
  149. // M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  150. // M220 S<factor in percent>- set speed factor override percentage
  151. // M221 S<factor in percent>- set extrude factor override percentage
  152. // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  153. // M240 - Trigger a camera to take a photograph
  154. // M250 - Set LCD contrast C<contrast value> (value 0..63)
  155. // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  156. // M300 - Play beep sound S<frequency Hz> P<duration ms>
  157. // M301 - Set PID parameters P I and D
  158. // M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  159. // M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  160. // M304 - Set bed PID parameters P I and D
  161. // M400 - Finish all moves
  162. // M401 - Lower z-probe if present
  163. // M402 - Raise z-probe if present
  164. // M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  165. // M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  166. // M406 - Turn off Filament Sensor extrusion control
  167. // M407 - Displays measured filament diameter
  168. // M500 - stores parameters in EEPROM
  169. // M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  170. // M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  171. // M503 - print the current settings (from memory not from EEPROM)
  172. // M509 - force language selection on next restart
  173. // M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  174. // M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  175. // M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  176. // M907 - Set digital trimpot motor current using axis codes.
  177. // M908 - Control digital trimpot directly.
  178. // M350 - Set microstepping mode.
  179. // M351 - Toggle MS1 MS2 pins directly.
  180. // M928 - Start SD logging (M928 filename.g) - ended by M29
  181. // M999 - Restart after being stopped by error
  182. //Stepper Movement Variables
  183. //===========================================================================
  184. //=============================imported variables============================
  185. //===========================================================================
  186. //===========================================================================
  187. //=============================public variables=============================
  188. //===========================================================================
  189. #ifdef SDSUPPORT
  190. CardReader card;
  191. #endif
  192. union Data
  193. {
  194. byte b[2];
  195. int value;
  196. };
  197. int babystepLoad[3];
  198. float homing_feedrate[] = HOMING_FEEDRATE;
  199. // Currently only the extruder axis may be switched to a relative mode.
  200. // Other axes are always absolute or relative based on the common relative_mode flag.
  201. bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
  202. int feedmultiply=100; //100->1 200->2
  203. int saved_feedmultiply;
  204. int extrudemultiply=100; //100->1 200->2
  205. int extruder_multiply[EXTRUDERS] = {100
  206. #if EXTRUDERS > 1
  207. , 100
  208. #if EXTRUDERS > 2
  209. , 100
  210. #endif
  211. #endif
  212. };
  213. bool is_usb_printing = false;
  214. bool _doMeshL = false;
  215. unsigned int usb_printing_counter;
  216. int lcd_change_fil_state = 0;
  217. int feedmultiplyBckp = 100;
  218. unsigned char lang_selected = 0;
  219. unsigned long total_filament_used;
  220. unsigned int heating_status;
  221. unsigned int heating_status_counter;
  222. bool custom_message;
  223. unsigned int custom_message_type;
  224. unsigned int custom_message_state;
  225. bool volumetric_enabled = false;
  226. float filament_size[EXTRUDERS] = { DEFAULT_NOMINAL_FILAMENT_DIA
  227. #if EXTRUDERS > 1
  228. , DEFAULT_NOMINAL_FILAMENT_DIA
  229. #if EXTRUDERS > 2
  230. , DEFAULT_NOMINAL_FILAMENT_DIA
  231. #endif
  232. #endif
  233. };
  234. float volumetric_multiplier[EXTRUDERS] = {1.0
  235. #if EXTRUDERS > 1
  236. , 1.0
  237. #if EXTRUDERS > 2
  238. , 1.0
  239. #endif
  240. #endif
  241. };
  242. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  243. float add_homing[3]={0,0,0};
  244. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  245. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  246. bool axis_known_position[3] = {false, false, false};
  247. float zprobe_zoffset;
  248. // Extruder offset
  249. #if EXTRUDERS > 1
  250. #ifndef DUAL_X_CARRIAGE
  251. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  252. #else
  253. #define NUM_EXTRUDER_OFFSETS 3 // supports offsets in XYZ plane
  254. #endif
  255. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  256. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  257. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  258. #endif
  259. };
  260. #endif
  261. uint8_t active_extruder = 0;
  262. int fanSpeed=0;
  263. #ifdef FWRETRACT
  264. bool autoretract_enabled=false;
  265. bool retracted[EXTRUDERS]={false
  266. #if EXTRUDERS > 1
  267. , false
  268. #if EXTRUDERS > 2
  269. , false
  270. #endif
  271. #endif
  272. };
  273. bool retracted_swap[EXTRUDERS]={false
  274. #if EXTRUDERS > 1
  275. , false
  276. #if EXTRUDERS > 2
  277. , false
  278. #endif
  279. #endif
  280. };
  281. float retract_length = RETRACT_LENGTH;
  282. float retract_length_swap = RETRACT_LENGTH_SWAP;
  283. float retract_feedrate = RETRACT_FEEDRATE;
  284. float retract_zlift = RETRACT_ZLIFT;
  285. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  286. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  287. float retract_recover_feedrate = RETRACT_RECOVER_FEEDRATE;
  288. #endif
  289. #ifdef ULTIPANEL
  290. #ifdef PS_DEFAULT_OFF
  291. bool powersupply = false;
  292. #else
  293. bool powersupply = true;
  294. #endif
  295. #endif
  296. bool cancel_heatup = false ;
  297. #ifdef FILAMENT_SENSOR
  298. //Variables for Filament Sensor input
  299. float filament_width_nominal=DEFAULT_NOMINAL_FILAMENT_DIA; //Set nominal filament width, can be changed with M404
  300. bool filament_sensor=false; //M405 turns on filament_sensor control, M406 turns it off
  301. float filament_width_meas=DEFAULT_MEASURED_FILAMENT_DIA; //Stores the measured filament diameter
  302. signed char measurement_delay[MAX_MEASUREMENT_DELAY+1]; //ring buffer to delay measurement store extruder factor after subtracting 100
  303. int delay_index1=0; //index into ring buffer
  304. int delay_index2=-1; //index into ring buffer - set to -1 on startup to indicate ring buffer needs to be initialized
  305. float delay_dist=0; //delay distance counter
  306. int meas_delay_cm = MEASUREMENT_DELAY_CM; //distance delay setting
  307. #endif
  308. const char errormagic[] PROGMEM = "Error:";
  309. const char echomagic[] PROGMEM = "echo:";
  310. //===========================================================================
  311. //=============================Private Variables=============================
  312. //===========================================================================
  313. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  314. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  315. static float delta[3] = {0.0, 0.0, 0.0};
  316. // For tracing an arc
  317. static float offset[3] = {0.0, 0.0, 0.0};
  318. static bool home_all_axis = true;
  319. static float feedrate = 1500.0, next_feedrate, saved_feedrate;
  320. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  321. // Determines Absolute or Relative Coordinates.
  322. // Also there is bool axis_relative_modes[] per axis flag.
  323. static bool relative_mode = false;
  324. // String circular buffer. Commands may be pushed to the buffer from both sides:
  325. // Chained commands will be pushed to the front, interactive (from LCD menu)
  326. // and printing commands (from serial line or from SD card) are pushed to the tail.
  327. // First character of each entry indicates the type of the entry:
  328. #define CMDBUFFER_CURRENT_TYPE_UNKNOWN 0
  329. // Command in cmdbuffer was sent over USB.
  330. #define CMDBUFFER_CURRENT_TYPE_USB 1
  331. // Command in cmdbuffer was read from SDCARD.
  332. #define CMDBUFFER_CURRENT_TYPE_SDCARD 2
  333. // Command in cmdbuffer was generated by the UI.
  334. #define CMDBUFFER_CURRENT_TYPE_UI 3
  335. // Command in cmdbuffer was generated by another G-code.
  336. #define CMDBUFFER_CURRENT_TYPE_CHAINED 4
  337. // How much space to reserve for the chained commands
  338. // of type CMDBUFFER_CURRENT_TYPE_CHAINED,
  339. // which are pushed to the front of the queue?
  340. // Maximum 5 commands of max length 20 + null terminator.
  341. #define CMDBUFFER_RESERVE_FRONT (5*21)
  342. // Reserve BUFSIZE lines of length MAX_CMD_SIZE plus CMDBUFFER_RESERVE_FRONT.
  343. static char cmdbuffer[BUFSIZE * (MAX_CMD_SIZE + 1) + CMDBUFFER_RESERVE_FRONT];
  344. // Head of the circular buffer, where to read.
  345. static int bufindr = 0;
  346. // Tail of the buffer, where to write.
  347. static int bufindw = 0;
  348. // Number of lines in cmdbuffer.
  349. static int buflen = 0;
  350. // Flag for processing the current command inside the main Arduino loop().
  351. // If a new command was pushed to the front of a command buffer while
  352. // processing another command, this replaces the command on the top.
  353. // Therefore don't remove the command from the queue in the loop() function.
  354. static bool cmdbuffer_front_already_processed = false;
  355. // Type of a command, which is to be executed right now.
  356. #define CMDBUFFER_CURRENT_TYPE (cmdbuffer[bufindr])
  357. // String of a command, which is to be executed right now.
  358. #define CMDBUFFER_CURRENT_STRING (cmdbuffer+bufindr+1)
  359. static int serial_count = 0;
  360. static boolean comment_mode = false;
  361. static char *strchr_pointer; // just a pointer to find chars in the command string like X, Y, Z, E, etc
  362. const int sensitive_pins[] = SENSITIVE_PINS; // Sensitive pin list for M42
  363. //static float tt = 0;
  364. //static float bt = 0;
  365. //Inactivity shutdown variables
  366. static unsigned long previous_millis_cmd = 0;
  367. static unsigned long max_inactive_time = 0;
  368. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  369. unsigned long starttime=0;
  370. unsigned long stoptime=0;
  371. unsigned long _usb_timer = 0;
  372. static uint8_t tmp_extruder;
  373. bool Stopped=false;
  374. #if NUM_SERVOS > 0
  375. Servo servos[NUM_SERVOS];
  376. #endif
  377. bool CooldownNoWait = true;
  378. bool target_direction;
  379. //Insert variables if CHDK is defined
  380. #ifdef CHDK
  381. unsigned long chdkHigh = 0;
  382. boolean chdkActive = false;
  383. #endif
  384. //===========================================================================
  385. //=============================Routines======================================
  386. //===========================================================================
  387. void get_arc_coordinates();
  388. bool setTargetedHotend(int code);
  389. void serial_echopair_P(const char *s_P, float v)
  390. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  391. void serial_echopair_P(const char *s_P, double v)
  392. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  393. void serial_echopair_P(const char *s_P, unsigned long v)
  394. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  395. #ifdef SDSUPPORT
  396. #include "SdFatUtil.h"
  397. int freeMemory() { return SdFatUtil::FreeRam(); }
  398. #else
  399. extern "C" {
  400. extern unsigned int __bss_end;
  401. extern unsigned int __heap_start;
  402. extern void *__brkval;
  403. int freeMemory() {
  404. int free_memory;
  405. if ((int)__brkval == 0)
  406. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  407. else
  408. free_memory = ((int)&free_memory) - ((int)__brkval);
  409. return free_memory;
  410. }
  411. }
  412. #endif //!SDSUPPORT
  413. // Pop the currently processed command from the queue.
  414. // It is expected, that there is at least one command in the queue.
  415. void cmdqueue_pop_front()
  416. {
  417. if (buflen > 0) {
  418. SERIAL_ECHOPGM("Dequeing ");
  419. SERIAL_ECHO(cmdbuffer+bufindr+1);
  420. SERIAL_ECHOLNPGM("");
  421. SERIAL_ECHOPGM("Old indices: buflen ");
  422. SERIAL_ECHO(buflen);
  423. SERIAL_ECHOPGM(", bufindr ");
  424. SERIAL_ECHO(bufindr);
  425. SERIAL_ECHOPGM(", bufindw ");
  426. SERIAL_ECHO(bufindw);
  427. SERIAL_ECHOPGM(", serial_count ");
  428. SERIAL_ECHO(serial_count);
  429. SERIAL_ECHOPGM(", bufsize ");
  430. SERIAL_ECHO(sizeof(cmdbuffer));
  431. SERIAL_ECHOLNPGM("");
  432. if (-- buflen == 0) {
  433. // Empty buffer.
  434. if (serial_count == 0)
  435. // No serial communication is pending. Reset both pointers to zero.
  436. bufindw = 0;
  437. bufindr = bufindw;
  438. } else {
  439. // There is at least one ready line in the buffer.
  440. // First skip the current command ID and iterate up to the end of the string.
  441. for (++ bufindr; cmdbuffer[bufindr] != 0; ++ bufindr) ;
  442. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  443. for (++ bufindr; bufindr < sizeof(cmdbuffer) && cmdbuffer[bufindr] == 0; ++ bufindr) ;
  444. // If the end of the buffer was empty,
  445. if (bufindr == sizeof(cmdbuffer)) {
  446. // skip to the start and find the nonzero command.
  447. for (bufindr = 0; cmdbuffer[bufindr] == 0; ++ bufindr) ;
  448. }
  449. SERIAL_ECHOPGM("New indices: buflen ");
  450. SERIAL_ECHO(buflen);
  451. SERIAL_ECHOPGM(", bufindr ");
  452. SERIAL_ECHO(bufindr);
  453. SERIAL_ECHOPGM(", bufindw ");
  454. SERIAL_ECHO(bufindw);
  455. SERIAL_ECHOPGM(", serial_count ");
  456. SERIAL_ECHO(serial_count);
  457. SERIAL_ECHOPGM(" new command on the top: ");
  458. SERIAL_ECHO(cmdbuffer+bufindr+1);
  459. SERIAL_ECHOLNPGM("");
  460. }
  461. }
  462. }
  463. // How long a string could be pushed to the front of the command queue?
  464. // If yes, adjust bufindr to the new position, where the new command could be enqued.
  465. // len_asked does not contain the zero terminator size.
  466. bool cmdqueue_could_enqueue_front(int len_asked)
  467. {
  468. // MAX_CMD_SIZE has to accommodate the zero terminator.
  469. if (len_asked >= MAX_CMD_SIZE)
  470. return false;
  471. // Remove the currently processed command from the queue.
  472. if (! cmdbuffer_front_already_processed) {
  473. cmdqueue_pop_front();
  474. cmdbuffer_front_already_processed = true;
  475. }
  476. if (bufindr == bufindw && buflen > 0)
  477. // Full buffer.
  478. return false;
  479. // Adjust the end of the write buffer based on whether a partial line is in the receive buffer.
  480. int endw = (serial_count > 0) ? (bufindw + MAX_CMD_SIZE + 1) : bufindw;
  481. if (bufindw < bufindr)
  482. // Simple case. There is a contiguous space between the write buffer and the read buffer.
  483. return endw + len_asked + 2 < bufindr;
  484. // Otherwise the free space is split between the start and end.
  485. if (len_asked + 2 <= bufindr) {
  486. // Could fit at the start.
  487. bufindr -= len_asked + 2;
  488. return true;
  489. }
  490. int bufindr_new = sizeof(cmdbuffer) - len_asked - 2;
  491. if (endw <= bufindr_new) {
  492. memset(cmdbuffer, 0, bufindr);
  493. bufindr = bufindr_new;
  494. return true;
  495. }
  496. return false;
  497. }
  498. // Could one enqueue a command of lenthg len_asked into the buffer,
  499. // while leaving CMDBUFFER_RESERVE_FRONT at the start?
  500. // If yes, adjust bufindw to the new position, where the new command could be enqued.
  501. // len_asked does not contain the zero terminator size.
  502. bool cmdqueue_could_enqueue_back(int len_asked)
  503. {
  504. // MAX_CMD_SIZE has to accommodate the zero terminator.
  505. if (len_asked >= MAX_CMD_SIZE)
  506. return false;
  507. if (bufindr == bufindw && buflen > 0)
  508. // Full buffer.
  509. return false;
  510. if (serial_count > 0) {
  511. // If there is some data stored starting at bufindw, len_asked is certainly smaller than
  512. // the allocated data buffer. Try to reserve a new buffer and to move the already received
  513. // serial data.
  514. // How much memory to reserve for the commands pushed to the front?
  515. // End of the queue, when pushing to the end.
  516. int endw = bufindw + len_asked + 2;
  517. if (bufindw < bufindr)
  518. // Simple case. There is a contiguous space between the write buffer and the read buffer.
  519. return endw + CMDBUFFER_RESERVE_FRONT <= bufindr;
  520. // Otherwise the free space is split between the start and end.
  521. if (// Could one fit to the end, including the reserve?
  522. endw + CMDBUFFER_RESERVE_FRONT <= sizeof(cmdbuffer) ||
  523. // Could one fit to the end, and the reserve to the start?
  524. (endw <= sizeof(cmdbuffer) && CMDBUFFER_RESERVE_FRONT <= bufindr))
  525. return true;
  526. // Could one fit both to the start?
  527. if (len_asked + 2 + CMDBUFFER_RESERVE_FRONT <= bufindr) {
  528. // Mark the rest of the buffer as used.
  529. memset(cmdbuffer+bufindw, 0, sizeof(cmdbuffer)-bufindw);
  530. // and point to the start.
  531. bufindw = 0;
  532. return true;
  533. }
  534. } else {
  535. // How much memory to reserve for the commands pushed to the front?
  536. // End of the queue, when pushing to the end.
  537. int endw = bufindw + len_asked + 2;
  538. if (bufindw < bufindr)
  539. // Simple case. There is a contiguous space between the write buffer and the read buffer.
  540. return endw + CMDBUFFER_RESERVE_FRONT <= bufindr;
  541. // Otherwise the free space is split between the start and end.
  542. if (// Could one fit to the end, including the reserve?
  543. endw + CMDBUFFER_RESERVE_FRONT <= sizeof(cmdbuffer) ||
  544. // Could one fit to the end, and the reserve to the start?
  545. (endw <= sizeof(cmdbuffer) && CMDBUFFER_RESERVE_FRONT <= bufindr))
  546. return true;
  547. // Could one fit both to the start?
  548. if (len_asked + 2 + CMDBUFFER_RESERVE_FRONT <= bufindr) {
  549. // Mark the rest of the buffer as used.
  550. memset(cmdbuffer+bufindw, 0, sizeof(cmdbuffer)-bufindw);
  551. // and point to the start.
  552. bufindw = 0;
  553. return true;
  554. }
  555. }
  556. return false;
  557. }
  558. void cmdqueue_dump_to_serial()
  559. {
  560. SERIAL_ECHOLNPGM("Content of the buffer: ");
  561. if (buflen == 0) {
  562. SERIAL_ECHOLNPGM("The command buffer is empty.");
  563. } else {
  564. SERIAL_ECHOPGM("Number of entries: ");
  565. SERIAL_ECHO(buflen);
  566. SERIAL_ECHOLNPGM("");
  567. }
  568. if (bufindr < bufindw) {
  569. } else {
  570. // for (uint8_t i = 0; i < BUFSIZE; ++ i)
  571. // SERIAL_ECHO(cmdbuffer[(i+bufindw)%BUFSIZE]);
  572. }
  573. SERIAL_ECHOLNPGM("End of the buffer.");
  574. }
  575. //adds an command to the main command buffer
  576. //thats really done in a non-safe way.
  577. //needs overworking someday
  578. // Currently the maximum length of a command piped through this function is around 20 characters
  579. void enquecommand(const char *cmd, bool from_progmem)
  580. {
  581. int len = from_progmem ? strlen_P(cmd) : strlen(cmd);
  582. // Does cmd fit the queue while leaving sufficient space at the front for the chained commands?
  583. // If it fits, it may move bufindw, so it points to a contiguous buffer, which fits cmd.
  584. if (cmdqueue_could_enqueue_back(len)) {
  585. // This is dangerous if a mixing of serial and this happens
  586. // This may easily be tested: If serial_count > 0, we have a problem.
  587. cmdbuffer[bufindw] = CMDBUFFER_CURRENT_TYPE_UI;
  588. if (from_progmem)
  589. strcpy_P(cmdbuffer + bufindw + 1, cmd);
  590. else
  591. strcpy(cmdbuffer + bufindw + 1, cmd);
  592. SERIAL_ECHO_START;
  593. SERIAL_ECHORPGM(MSG_Enqueing);
  594. SERIAL_ECHO(cmdbuffer + bufindw + 1);
  595. SERIAL_ECHOLNPGM("\"");
  596. bufindw += len + 2;
  597. if (bufindw == sizeof(cmdbuffer))
  598. bufindw = 0;
  599. ++ buflen;
  600. } else {
  601. SERIAL_ECHO_START;
  602. SERIAL_ECHORPGM(MSG_Enqueing);
  603. if (from_progmem)
  604. SERIAL_PROTOCOLRPGM(cmd);
  605. else
  606. SERIAL_ECHO(cmd);
  607. SERIAL_ECHOLNPGM("\" failed: Buffer full!");
  608. cmdqueue_dump_to_serial();
  609. }
  610. }
  611. void enquecommand_front(const char *cmd, bool from_progmem)
  612. {
  613. int len = from_progmem ? strlen_P(cmd) : strlen(cmd);
  614. // Does cmd fit the queue? This call shall move bufindr, so the command may be copied.
  615. if (cmdqueue_could_enqueue_front(len)) {
  616. cmdbuffer[bufindr] = CMDBUFFER_CURRENT_TYPE_UI;
  617. if (from_progmem)
  618. strcpy_P(cmdbuffer + bufindr + 1, cmd);
  619. else
  620. strcpy(cmdbuffer + bufindr + 1, cmd);
  621. SERIAL_ECHO_START;
  622. SERIAL_ECHOPGM("Enqueing to the front: \"");
  623. SERIAL_ECHO(cmdbuffer + bufindr + 1);
  624. SERIAL_ECHOLNPGM("\"");
  625. } else {
  626. SERIAL_ECHO_START;
  627. SERIAL_ECHOPGM("Enqueing to the front: \"");
  628. if (from_progmem)
  629. SERIAL_PROTOCOLRPGM(cmd);
  630. else
  631. SERIAL_ECHO(cmd);
  632. SERIAL_ECHOLNPGM("\" failed: Buffer full!");
  633. cmdqueue_dump_to_serial();
  634. }
  635. }
  636. void setup_killpin()
  637. {
  638. #if defined(KILL_PIN) && KILL_PIN > -1
  639. SET_INPUT(KILL_PIN);
  640. WRITE(KILL_PIN,HIGH);
  641. #endif
  642. }
  643. void setup_photpin()
  644. {
  645. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  646. SET_OUTPUT(PHOTOGRAPH_PIN);
  647. WRITE(PHOTOGRAPH_PIN, LOW);
  648. #endif
  649. }
  650. void setup_powerhold()
  651. {
  652. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  653. SET_OUTPUT(SUICIDE_PIN);
  654. WRITE(SUICIDE_PIN, HIGH);
  655. #endif
  656. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  657. SET_OUTPUT(PS_ON_PIN);
  658. #if defined(PS_DEFAULT_OFF)
  659. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  660. #else
  661. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  662. #endif
  663. #endif
  664. }
  665. void suicide()
  666. {
  667. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  668. SET_OUTPUT(SUICIDE_PIN);
  669. WRITE(SUICIDE_PIN, LOW);
  670. #endif
  671. }
  672. void servo_init()
  673. {
  674. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  675. servos[0].attach(SERVO0_PIN);
  676. #endif
  677. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  678. servos[1].attach(SERVO1_PIN);
  679. #endif
  680. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  681. servos[2].attach(SERVO2_PIN);
  682. #endif
  683. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  684. servos[3].attach(SERVO3_PIN);
  685. #endif
  686. #if (NUM_SERVOS >= 5)
  687. #error "TODO: enter initalisation code for more servos"
  688. #endif
  689. }
  690. static void lcd_language_menu();
  691. #ifdef MESH_BED_LEVELING
  692. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  693. #endif
  694. // "Setup" function is called by the Arduino framework on startup.
  695. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  696. // are initialized by the main() routine provided by the Arduino framework.
  697. void setup()
  698. {
  699. setup_killpin();
  700. setup_powerhold();
  701. MYSERIAL.begin(BAUDRATE);
  702. SERIAL_PROTOCOLLNPGM("start");
  703. SERIAL_ECHO_START;
  704. #if 0
  705. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  706. for (int i = 0; i < 4096; ++ i) {
  707. int b = eeprom_read_byte((unsigned char*)i);
  708. if (b != 255) {
  709. SERIAL_ECHO(i);
  710. SERIAL_ECHO(":");
  711. SERIAL_ECHO(b);
  712. SERIAL_ECHOLN("");
  713. }
  714. }
  715. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  716. #endif
  717. // Check startup - does nothing if bootloader sets MCUSR to 0
  718. byte mcu = MCUSR;
  719. if(mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  720. if(mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  721. if(mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  722. if(mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  723. if(mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);
  724. MCUSR=0;
  725. //SERIAL_ECHORPGM(MSG_MARLIN);
  726. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  727. #ifdef STRING_VERSION_CONFIG_H
  728. #ifdef STRING_CONFIG_H_AUTHOR
  729. SERIAL_ECHO_START;
  730. SERIAL_ECHORPGM(MSG_CONFIGURATION_VER);
  731. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  732. SERIAL_ECHORPGM(MSG_AUTHOR);
  733. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  734. SERIAL_ECHOPGM("Compiled: ");
  735. SERIAL_ECHOLNPGM(__DATE__);
  736. #endif
  737. #endif
  738. SERIAL_ECHO_START;
  739. SERIAL_ECHORPGM(MSG_FREE_MEMORY);
  740. SERIAL_ECHO(freeMemory());
  741. SERIAL_ECHORPGM(MSG_PLANNER_BUFFER_BYTES);
  742. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  743. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  744. Config_RetrieveSettings();
  745. tp_init(); // Initialize temperature loop
  746. plan_init(); // Initialize planner;
  747. watchdog_init();
  748. st_init(); // Initialize stepper, this enables interrupts!
  749. setup_photpin();
  750. servo_init();
  751. // Reset the machine correction matrix.
  752. // It does not make sense to load the correction matrix until the machine is homed.
  753. world2machine_reset();
  754. lcd_init();
  755. if(!READ(BTN_ENC) ){
  756. _delay_ms(1000);
  757. if(!READ(BTN_ENC) ){
  758. SET_OUTPUT(BEEPER);
  759. WRITE(BEEPER,HIGH);
  760. lcd_force_language_selection();
  761. while(!READ(BTN_ENC));
  762. WRITE(BEEPER,LOW);
  763. }
  764. }else{
  765. _delay_ms(1000); // wait 1sec to display the splash screen
  766. }
  767. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  768. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  769. #endif
  770. #ifdef DIGIPOT_I2C
  771. digipot_i2c_init();
  772. #endif
  773. setup_homepin();
  774. #if defined(Z_AXIS_ALWAYS_ON)
  775. enable_z();
  776. #endif
  777. }
  778. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  779. // Before loop(), the setup() function is called by the main() routine.
  780. void loop()
  781. {
  782. if (usb_printing_counter > 0 && millis()-_usb_timer > 1000)
  783. {
  784. is_usb_printing = true;
  785. usb_printing_counter--;
  786. _usb_timer = millis();
  787. }
  788. if (usb_printing_counter == 0)
  789. {
  790. is_usb_printing = false;
  791. }
  792. get_command();
  793. #ifdef SDSUPPORT
  794. card.checkautostart(false);
  795. #endif
  796. if(buflen)
  797. {
  798. #ifdef SDSUPPORT
  799. if(card.saving)
  800. {
  801. // Saving a G-code file onto an SD-card is in progress.
  802. // Saving starts with M28, saving until M29 is seen.
  803. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  804. card.write_command(CMDBUFFER_CURRENT_STRING);
  805. if(card.logging)
  806. process_commands();
  807. else
  808. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  809. } else {
  810. card.closefile();
  811. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  812. }
  813. } else {
  814. process_commands();
  815. }
  816. #else
  817. process_commands();
  818. #endif //SDSUPPORT
  819. if (! cmdbuffer_front_already_processed)
  820. cmdqueue_pop_front();
  821. cmdbuffer_front_already_processed = false;
  822. }
  823. //check heater every n milliseconds
  824. manage_heater();
  825. manage_inactivity();
  826. checkHitEndstops();
  827. lcd_update();
  828. }
  829. void get_command()
  830. {
  831. // Test and reserve space for the new command string.
  832. if (! cmdqueue_could_enqueue_back(MAX_CMD_SIZE-1))
  833. return;
  834. while (MYSERIAL.available() > 0) {
  835. char serial_char = MYSERIAL.read();
  836. if(serial_char == '\n' ||
  837. serial_char == '\r' ||
  838. (serial_char == ':' && comment_mode == false) ||
  839. serial_count >= (MAX_CMD_SIZE - 1) )
  840. {
  841. if(!serial_count) { //if empty line
  842. comment_mode = false; //for new command
  843. return;
  844. }
  845. cmdbuffer[bufindw+serial_count+1] = 0; //terminate string
  846. if(!comment_mode){
  847. comment_mode = false; //for new command
  848. if ((strchr_pointer = strchr(cmdbuffer+bufindw+1, 'N')) != NULL)
  849. {
  850. // Line number met. When sending a G-code over a serial line, each line may be stamped with its index,
  851. // and Marlin tests, whether the successive lines are stamped with an increasing line number ID.
  852. gcode_N = (strtol(strchr_pointer+1, NULL, 10));
  853. if(gcode_N != gcode_LastN+1 && (strstr_P(cmdbuffer+bufindw+1, PSTR("M110")) == NULL) ) {
  854. // M110 - set current line number.
  855. // Line numbers not sent in succession.
  856. SERIAL_ERROR_START;
  857. SERIAL_ERRORRPGM(MSG_ERR_LINE_NO);
  858. SERIAL_ERRORLN(gcode_LastN);
  859. //Serial.println(gcode_N);
  860. FlushSerialRequestResend();
  861. serial_count = 0;
  862. return;
  863. }
  864. if((strchr_pointer = strchr(cmdbuffer+bufindw+1, '*')) != NULL)
  865. {
  866. byte checksum = 0;
  867. char *p = cmdbuffer+bufindw+1;
  868. while (p != strchr_pointer)
  869. checksum = checksum^(*p++);
  870. if (int(strtol(strchr_pointer+1, NULL, 10)) != int(checksum)) {
  871. SERIAL_ERROR_START;
  872. SERIAL_ERRORRPGM(MSG_ERR_CHECKSUM_MISMATCH);
  873. SERIAL_ERRORLN(gcode_LastN);
  874. FlushSerialRequestResend();
  875. serial_count = 0;
  876. return;
  877. }
  878. // If no errors, remove the checksum and continue parsing.
  879. *strchr_pointer = 0;
  880. }
  881. else
  882. {
  883. SERIAL_ERROR_START;
  884. SERIAL_ERRORRPGM(MSG_ERR_NO_CHECKSUM);
  885. SERIAL_ERRORLN(gcode_LastN);
  886. FlushSerialRequestResend();
  887. serial_count = 0;
  888. return;
  889. }
  890. gcode_LastN = gcode_N;
  891. //if no errors, continue parsing
  892. } // end of 'N' command
  893. else // if we don't receive 'N' but still see '*'
  894. {
  895. if((strchr(cmdbuffer+bufindw+1, '*') != NULL))
  896. {
  897. SERIAL_ERROR_START;
  898. SERIAL_ERRORRPGM(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM);
  899. SERIAL_ERRORLN(gcode_LastN);
  900. serial_count = 0;
  901. return;
  902. }
  903. } // end of '*' command
  904. if ((strchr_pointer = strchr(cmdbuffer+bufindw+1, 'G')) != NULL) {
  905. if (! IS_SD_PRINTING) {
  906. usb_printing_counter = 10;
  907. is_usb_printing = true;
  908. }
  909. if (Stopped == true) {
  910. int gcode = strtol(strchr_pointer+1, NULL, 10);
  911. if (gcode >= 0 && gcode <= 3) {
  912. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  913. LCD_MESSAGERPGM(MSG_STOPPED);
  914. }
  915. }
  916. } // end of 'G' command
  917. //If command was e-stop process now
  918. if(strcmp(cmdbuffer+bufindw+1, "M112") == 0)
  919. kill();
  920. // Store the current line into buffer, move to the next line.
  921. cmdbuffer[bufindw] = CMDBUFFER_CURRENT_TYPE_USB;
  922. SERIAL_ECHO_START;
  923. SERIAL_ECHOPGM("Storing a command line to buffer: ");
  924. SERIAL_ECHO(cmdbuffer+bufindw+1);
  925. SERIAL_ECHOLNPGM("");
  926. bufindw += strlen(cmdbuffer+bufindw+1) + 2;
  927. if (bufindw == sizeof(cmdbuffer))
  928. bufindw = 0;
  929. ++ buflen;
  930. } // end of 'not comment mode'
  931. serial_count = 0; //clear buffer
  932. // Don't call cmdqueue_could_enqueue_back if there are no characters waiting
  933. // in the queue, as this function will reserve the memory.
  934. if (MYSERIAL.available() == 0 || ! cmdqueue_could_enqueue_back(MAX_CMD_SIZE-1))
  935. return;
  936. } // end of "end of line" processing
  937. else {
  938. // Not an "end of line" symbol. Store the new character into a buffer.
  939. if(serial_char == ';') comment_mode = true;
  940. if(!comment_mode) cmdbuffer[bufindw+1+serial_count++] = serial_char;
  941. }
  942. } // end of serial line processing loop
  943. #ifdef SDSUPPORT
  944. if(!card.sdprinting || serial_count!=0){
  945. // If there is a half filled buffer from serial line, wait until return before
  946. // continuing with the serial line.
  947. return;
  948. }
  949. //'#' stops reading from SD to the buffer prematurely, so procedural macro calls are possible
  950. // if it occurs, stop_buffering is triggered and the buffer is ran dry.
  951. // this character _can_ occur in serial com, due to checksums. however, no checksums are used in SD printing
  952. static bool stop_buffering=false;
  953. if(buflen==0) stop_buffering=false;
  954. // Reads whole lines from the SD card. Never leaves a half-filled line in the cmdbuffer.
  955. while( !card.eof() && !stop_buffering) {
  956. int16_t n=card.get();
  957. char serial_char = (char)n;
  958. if(serial_char == '\n' ||
  959. serial_char == '\r' ||
  960. (serial_char == '#' && comment_mode == false) ||
  961. (serial_char == ':' && comment_mode == false) ||
  962. serial_count >= (MAX_CMD_SIZE - 1)||n==-1)
  963. {
  964. if(card.eof()){
  965. SERIAL_PROTOCOLLNRPGM(MSG_FILE_PRINTED);
  966. stoptime=millis();
  967. char time[30];
  968. unsigned long t=(stoptime-starttime)/1000;
  969. int hours, minutes;
  970. minutes=(t/60)%60;
  971. hours=t/60/60;
  972. save_statistics(total_filament_used, t);
  973. sprintf_P(time, PSTR("%i hours %i minutes"),hours, minutes);
  974. SERIAL_ECHO_START;
  975. SERIAL_ECHOLN(time);
  976. lcd_setstatus(time);
  977. card.printingHasFinished();
  978. card.checkautostart(true);
  979. }
  980. if(serial_char=='#')
  981. stop_buffering=true;
  982. if(!serial_count)
  983. {
  984. comment_mode = false; //for new command
  985. return; //if empty line
  986. }
  987. cmdbuffer[bufindw+serial_count+1] = 0; //terminate string
  988. cmdbuffer[bufindw] = CMDBUFFER_CURRENT_TYPE_SDCARD;
  989. ++ buflen;
  990. bufindw += strlen(cmdbuffer+bufindw+1) + 2;
  991. if (bufindw == sizeof(cmdbuffer))
  992. bufindw = 0;
  993. comment_mode = false; //for new command
  994. serial_count = 0; //clear buffer
  995. // The following line will reserve buffer space if available.
  996. if (! cmdqueue_could_enqueue_back(MAX_CMD_SIZE-1))
  997. return;
  998. }
  999. else
  1000. {
  1001. if(serial_char == ';') comment_mode = true;
  1002. if(!comment_mode) cmdbuffer[bufindw+1+serial_count++] = serial_char;
  1003. }
  1004. }
  1005. #endif //SDSUPPORT
  1006. }
  1007. // Return True if a character was found
  1008. static inline bool code_seen(char code) { return (strchr_pointer = strchr(CMDBUFFER_CURRENT_STRING, code)) != NULL; }
  1009. static inline float code_value() { return strtod(strchr_pointer+1, NULL); }
  1010. static inline long code_value_long() { return strtol(strchr_pointer+1, NULL, 10); }
  1011. static inline int16_t code_value_short() { return int16_t(strtol(strchr_pointer+1, NULL, 10)); };
  1012. #define DEFINE_PGM_READ_ANY(type, reader) \
  1013. static inline type pgm_read_any(const type *p) \
  1014. { return pgm_read_##reader##_near(p); }
  1015. DEFINE_PGM_READ_ANY(float, float);
  1016. DEFINE_PGM_READ_ANY(signed char, byte);
  1017. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1018. static const PROGMEM type array##_P[3] = \
  1019. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1020. static inline type array(int axis) \
  1021. { return pgm_read_any(&array##_P[axis]); } \
  1022. type array##_ext(int axis) \
  1023. { return pgm_read_any(&array##_P[axis]); }
  1024. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1025. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1026. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1027. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1028. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1029. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1030. #ifdef DUAL_X_CARRIAGE
  1031. #if EXTRUDERS == 1 || defined(COREXY) \
  1032. || !defined(X2_ENABLE_PIN) || !defined(X2_STEP_PIN) || !defined(X2_DIR_PIN) \
  1033. || !defined(X2_HOME_POS) || !defined(X2_MIN_POS) || !defined(X2_MAX_POS) \
  1034. || !defined(X_MAX_PIN) || X_MAX_PIN < 0
  1035. #error "Missing or invalid definitions for DUAL_X_CARRIAGE mode."
  1036. #endif
  1037. #if X_HOME_DIR != -1 || X2_HOME_DIR != 1
  1038. #error "Please use canonical x-carriage assignment" // the x-carriages are defined by their homing directions
  1039. #endif
  1040. #define DXC_FULL_CONTROL_MODE 0
  1041. #define DXC_AUTO_PARK_MODE 1
  1042. #define DXC_DUPLICATION_MODE 2
  1043. static int dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  1044. static float x_home_pos(int extruder) {
  1045. if (extruder == 0)
  1046. return base_home_pos(X_AXIS) + add_homing[X_AXIS];
  1047. else
  1048. // In dual carriage mode the extruder offset provides an override of the
  1049. // second X-carriage offset when homed - otherwise X2_HOME_POS is used.
  1050. // This allow soft recalibration of the second extruder offset position without firmware reflash
  1051. // (through the M218 command).
  1052. return (extruder_offset[X_AXIS][1] > 0) ? extruder_offset[X_AXIS][1] : X2_HOME_POS;
  1053. }
  1054. static int x_home_dir(int extruder) {
  1055. return (extruder == 0) ? X_HOME_DIR : X2_HOME_DIR;
  1056. }
  1057. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  1058. static bool active_extruder_parked = false; // used in mode 1 & 2
  1059. static float raised_parked_position[NUM_AXIS]; // used in mode 1
  1060. static unsigned long delayed_move_time = 0; // used in mode 1
  1061. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  1062. static float duplicate_extruder_temp_offset = 0; // used in mode 2
  1063. bool extruder_duplication_enabled = false; // used in mode 2
  1064. #endif //DUAL_X_CARRIAGE
  1065. static void axis_is_at_home(int axis) {
  1066. #ifdef DUAL_X_CARRIAGE
  1067. if (axis == X_AXIS) {
  1068. if (active_extruder != 0) {
  1069. current_position[X_AXIS] = x_home_pos(active_extruder);
  1070. min_pos[X_AXIS] = X2_MIN_POS;
  1071. max_pos[X_AXIS] = max(extruder_offset[X_AXIS][1], X2_MAX_POS);
  1072. return;
  1073. }
  1074. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && active_extruder == 0) {
  1075. current_position[X_AXIS] = base_home_pos(X_AXIS) + add_homing[X_AXIS];
  1076. min_pos[X_AXIS] = base_min_pos(X_AXIS) + add_homing[X_AXIS];
  1077. max_pos[X_AXIS] = min(base_max_pos(X_AXIS) + add_homing[X_AXIS],
  1078. max(extruder_offset[X_AXIS][1], X2_MAX_POS) - duplicate_extruder_x_offset);
  1079. return;
  1080. }
  1081. }
  1082. #endif
  1083. current_position[axis] = base_home_pos(axis) + add_homing[axis];
  1084. min_pos[axis] = base_min_pos(axis) + add_homing[axis];
  1085. max_pos[axis] = base_max_pos(axis) + add_homing[axis];
  1086. }
  1087. inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); }
  1088. inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); }
  1089. static void setup_for_endstop_move() {
  1090. saved_feedrate = feedrate;
  1091. saved_feedmultiply = feedmultiply;
  1092. feedmultiply = 100;
  1093. previous_millis_cmd = millis();
  1094. enable_endstops(true);
  1095. }
  1096. static void clean_up_after_endstop_move() {
  1097. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1098. enable_endstops(false);
  1099. #endif
  1100. feedrate = saved_feedrate;
  1101. feedmultiply = saved_feedmultiply;
  1102. previous_millis_cmd = millis();
  1103. }
  1104. #ifdef ENABLE_AUTO_BED_LEVELING
  1105. #ifdef AUTO_BED_LEVELING_GRID
  1106. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1107. {
  1108. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1109. planeNormal.debug("planeNormal");
  1110. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1111. //bedLevel.debug("bedLevel");
  1112. //plan_bed_level_matrix.debug("bed level before");
  1113. //vector_3 uncorrected_position = plan_get_position_mm();
  1114. //uncorrected_position.debug("position before");
  1115. vector_3 corrected_position = plan_get_position();
  1116. // corrected_position.debug("position after");
  1117. current_position[X_AXIS] = corrected_position.x;
  1118. current_position[Y_AXIS] = corrected_position.y;
  1119. current_position[Z_AXIS] = corrected_position.z;
  1120. // put the bed at 0 so we don't go below it.
  1121. current_position[Z_AXIS] = zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1122. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1123. }
  1124. #else // not AUTO_BED_LEVELING_GRID
  1125. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1126. plan_bed_level_matrix.set_to_identity();
  1127. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1128. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1129. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1130. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1131. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1132. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1133. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1134. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1135. vector_3 corrected_position = plan_get_position();
  1136. current_position[X_AXIS] = corrected_position.x;
  1137. current_position[Y_AXIS] = corrected_position.y;
  1138. current_position[Z_AXIS] = corrected_position.z;
  1139. // put the bed at 0 so we don't go below it.
  1140. current_position[Z_AXIS] = zprobe_zoffset;
  1141. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1142. }
  1143. #endif // AUTO_BED_LEVELING_GRID
  1144. static void run_z_probe() {
  1145. plan_bed_level_matrix.set_to_identity();
  1146. feedrate = homing_feedrate[Z_AXIS];
  1147. // move down until you find the bed
  1148. float zPosition = -10;
  1149. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1150. st_synchronize();
  1151. // we have to let the planner know where we are right now as it is not where we said to go.
  1152. zPosition = st_get_position_mm(Z_AXIS);
  1153. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1154. // move up the retract distance
  1155. zPosition += home_retract_mm(Z_AXIS);
  1156. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1157. st_synchronize();
  1158. // move back down slowly to find bed
  1159. feedrate = homing_feedrate[Z_AXIS]/4;
  1160. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1161. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1162. st_synchronize();
  1163. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1164. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1165. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1166. }
  1167. static void do_blocking_move_to(float x, float y, float z) {
  1168. float oldFeedRate = feedrate;
  1169. feedrate = homing_feedrate[Z_AXIS];
  1170. current_position[Z_AXIS] = z;
  1171. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder);
  1172. st_synchronize();
  1173. feedrate = XY_TRAVEL_SPEED;
  1174. current_position[X_AXIS] = x;
  1175. current_position[Y_AXIS] = y;
  1176. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder);
  1177. st_synchronize();
  1178. feedrate = oldFeedRate;
  1179. }
  1180. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1181. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1182. }
  1183. /// Probe bed height at position (x,y), returns the measured z value
  1184. static float probe_pt(float x, float y, float z_before) {
  1185. // move to right place
  1186. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1187. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1188. run_z_probe();
  1189. float measured_z = current_position[Z_AXIS];
  1190. SERIAL_PROTOCOLRPGM(MSG_BED);
  1191. SERIAL_PROTOCOLPGM(" x: ");
  1192. SERIAL_PROTOCOL(x);
  1193. SERIAL_PROTOCOLPGM(" y: ");
  1194. SERIAL_PROTOCOL(y);
  1195. SERIAL_PROTOCOLPGM(" z: ");
  1196. SERIAL_PROTOCOL(measured_z);
  1197. SERIAL_PROTOCOLPGM("\n");
  1198. return measured_z;
  1199. }
  1200. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1201. static void homeaxis(int axis) {
  1202. #define HOMEAXIS_DO(LETTER) \
  1203. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1204. if (axis==X_AXIS ? HOMEAXIS_DO(X) :
  1205. axis==Y_AXIS ? HOMEAXIS_DO(Y) :
  1206. axis==Z_AXIS ? HOMEAXIS_DO(Z) :
  1207. 0) {
  1208. int axis_home_dir = home_dir(axis);
  1209. #ifdef DUAL_X_CARRIAGE
  1210. if (axis == X_AXIS)
  1211. axis_home_dir = x_home_dir(active_extruder);
  1212. #endif
  1213. current_position[axis] = 0;
  1214. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1215. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1216. feedrate = homing_feedrate[axis];
  1217. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1218. st_synchronize();
  1219. current_position[axis] = 0;
  1220. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1221. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1222. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1223. st_synchronize();
  1224. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1225. feedrate = homing_feedrate[axis]/2 ;
  1226. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1227. st_synchronize();
  1228. axis_is_at_home(axis);
  1229. destination[axis] = current_position[axis];
  1230. feedrate = 0.0;
  1231. endstops_hit_on_purpose();
  1232. axis_known_position[axis] = true;
  1233. }
  1234. }
  1235. void refresh_cmd_timeout(void)
  1236. {
  1237. previous_millis_cmd = millis();
  1238. }
  1239. #ifdef FWRETRACT
  1240. void retract(bool retracting, bool swapretract = false) {
  1241. if(retracting && !retracted[active_extruder]) {
  1242. destination[X_AXIS]=current_position[X_AXIS];
  1243. destination[Y_AXIS]=current_position[Y_AXIS];
  1244. destination[Z_AXIS]=current_position[Z_AXIS];
  1245. destination[E_AXIS]=current_position[E_AXIS];
  1246. if (swapretract) {
  1247. current_position[E_AXIS]+=retract_length_swap/volumetric_multiplier[active_extruder];
  1248. } else {
  1249. current_position[E_AXIS]+=retract_length/volumetric_multiplier[active_extruder];
  1250. }
  1251. plan_set_e_position(current_position[E_AXIS]);
  1252. float oldFeedrate = feedrate;
  1253. feedrate=retract_feedrate*60;
  1254. retracted[active_extruder]=true;
  1255. prepare_move();
  1256. current_position[Z_AXIS]-=retract_zlift;
  1257. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1258. prepare_move();
  1259. feedrate = oldFeedrate;
  1260. } else if(!retracting && retracted[active_extruder]) {
  1261. destination[X_AXIS]=current_position[X_AXIS];
  1262. destination[Y_AXIS]=current_position[Y_AXIS];
  1263. destination[Z_AXIS]=current_position[Z_AXIS];
  1264. destination[E_AXIS]=current_position[E_AXIS];
  1265. current_position[Z_AXIS]+=retract_zlift;
  1266. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1267. //prepare_move();
  1268. if (swapretract) {
  1269. current_position[E_AXIS]-=(retract_length_swap+retract_recover_length_swap)/volumetric_multiplier[active_extruder];
  1270. } else {
  1271. current_position[E_AXIS]-=(retract_length+retract_recover_length)/volumetric_multiplier[active_extruder];
  1272. }
  1273. plan_set_e_position(current_position[E_AXIS]);
  1274. float oldFeedrate = feedrate;
  1275. feedrate=retract_recover_feedrate*60;
  1276. retracted[active_extruder]=false;
  1277. prepare_move();
  1278. feedrate = oldFeedrate;
  1279. }
  1280. } //retract
  1281. #endif //FWRETRACT
  1282. void process_commands()
  1283. {
  1284. #ifdef FILAMENT_RUNOUT_SUPPORT
  1285. SET_INPUT(FR_SENS);
  1286. #endif
  1287. unsigned long codenum; //throw away variable
  1288. char *starpos = NULL;
  1289. #ifdef ENABLE_AUTO_BED_LEVELING
  1290. float x_tmp, y_tmp, z_tmp, real_z;
  1291. #endif
  1292. // PRUSA GCODES
  1293. /*
  1294. if(code_seen('PRUSA')){
  1295. if(code_seen('Fir')){
  1296. SERIAL_PROTOCOLLN(FW_version);
  1297. } else if(code_seen('Rev')){
  1298. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  1299. } else if(code_seen('Lang')) {
  1300. lcd_force_language_selection();
  1301. } else if(code_seen('Lz')) {
  1302. EEPROM_save_B(EEPROM_BABYSTEP_Z,0);
  1303. }
  1304. //else if (code_seen('Cal')) {
  1305. // lcd_calibration();
  1306. // }
  1307. }
  1308. else
  1309. */
  1310. if(code_seen('G'))
  1311. {
  1312. switch((int)code_value())
  1313. {
  1314. case 0: // G0 -> G1
  1315. case 1: // G1
  1316. if(Stopped == false) {
  1317. #ifdef FILAMENT_RUNOUT_SUPPORT
  1318. if(READ(FR_SENS)){
  1319. feedmultiplyBckp=feedmultiply;
  1320. float target[4];
  1321. float lastpos[4];
  1322. target[X_AXIS]=current_position[X_AXIS];
  1323. target[Y_AXIS]=current_position[Y_AXIS];
  1324. target[Z_AXIS]=current_position[Z_AXIS];
  1325. target[E_AXIS]=current_position[E_AXIS];
  1326. lastpos[X_AXIS]=current_position[X_AXIS];
  1327. lastpos[Y_AXIS]=current_position[Y_AXIS];
  1328. lastpos[Z_AXIS]=current_position[Z_AXIS];
  1329. lastpos[E_AXIS]=current_position[E_AXIS];
  1330. //retract by E
  1331. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT ;
  1332. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  1333. target[Z_AXIS]+= FILAMENTCHANGE_ZADD ;
  1334. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 300, active_extruder);
  1335. target[X_AXIS]= FILAMENTCHANGE_XPOS ;
  1336. target[Y_AXIS]= FILAMENTCHANGE_YPOS ;
  1337. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder);
  1338. target[E_AXIS]+= FILAMENTCHANGE_FINALRETRACT ;
  1339. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  1340. //finish moves
  1341. st_synchronize();
  1342. //disable extruder steppers so filament can be removed
  1343. disable_e0();
  1344. disable_e1();
  1345. disable_e2();
  1346. delay(100);
  1347. //LCD_ALERTMESSAGEPGM(MSG_FILAMENTCHANGE);
  1348. uint8_t cnt=0;
  1349. int counterBeep = 0;
  1350. lcd_wait_interact();
  1351. while(!lcd_clicked()){
  1352. cnt++;
  1353. manage_heater();
  1354. manage_inactivity(true);
  1355. //lcd_update();
  1356. if(cnt==0)
  1357. {
  1358. #if BEEPER > 0
  1359. if (counterBeep== 500){
  1360. counterBeep = 0;
  1361. }
  1362. SET_OUTPUT(BEEPER);
  1363. if (counterBeep== 0){
  1364. WRITE(BEEPER,HIGH);
  1365. }
  1366. if (counterBeep== 20){
  1367. WRITE(BEEPER,LOW);
  1368. }
  1369. counterBeep++;
  1370. #else
  1371. #if !defined(LCD_FEEDBACK_FREQUENCY_HZ) || !defined(LCD_FEEDBACK_FREQUENCY_DURATION_MS)
  1372. lcd_buzz(1000/6,100);
  1373. #else
  1374. lcd_buzz(LCD_FEEDBACK_FREQUENCY_DURATION_MS,LCD_FEEDBACK_FREQUENCY_HZ);
  1375. #endif
  1376. #endif
  1377. }
  1378. }
  1379. WRITE(BEEPER,LOW);
  1380. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  1381. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  1382. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  1383. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1384. lcd_change_fil_state = 0;
  1385. lcd_loading_filament();
  1386. while ((lcd_change_fil_state == 0)||(lcd_change_fil_state != 1)){
  1387. lcd_change_fil_state = 0;
  1388. lcd_alright();
  1389. switch(lcd_change_fil_state){
  1390. case 2:
  1391. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  1392. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  1393. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  1394. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1395. lcd_loading_filament();
  1396. break;
  1397. case 3:
  1398. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  1399. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1400. lcd_loading_color();
  1401. break;
  1402. default:
  1403. lcd_change_success();
  1404. break;
  1405. }
  1406. }
  1407. target[E_AXIS]+= 5;
  1408. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1409. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT;
  1410. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  1411. //current_position[E_AXIS]=target[E_AXIS]; //the long retract of L is compensated by manual filament feeding
  1412. //plan_set_e_position(current_position[E_AXIS]);
  1413. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //should do nothing
  1414. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //move xy back
  1415. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 200, active_extruder); //move z back
  1416. target[E_AXIS]= target[E_AXIS] - FILAMENTCHANGE_FIRSTRETRACT;
  1417. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 5, active_extruder); //final untretract
  1418. plan_set_e_position(lastpos[E_AXIS]);
  1419. feedmultiply=feedmultiplyBckp;
  1420. char cmd[9];
  1421. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  1422. enquecommand(cmd);
  1423. }
  1424. #endif
  1425. get_coordinates(); // For X Y Z E F
  1426. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS])*100);
  1427. #ifdef FWRETRACT
  1428. if(autoretract_enabled)
  1429. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  1430. float echange=destination[E_AXIS]-current_position[E_AXIS];
  1431. if((echange<-MIN_RETRACT && !retracted) || (echange>MIN_RETRACT && retracted)) { //move appears to be an attempt to retract or recover
  1432. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  1433. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  1434. retract(!retracted);
  1435. return;
  1436. }
  1437. }
  1438. #endif //FWRETRACT
  1439. prepare_move();
  1440. //ClearToSend();
  1441. }
  1442. break;
  1443. case 2: // G2 - CW ARC
  1444. if(Stopped == false) {
  1445. get_arc_coordinates();
  1446. prepare_arc_move(true);
  1447. }
  1448. break;
  1449. case 3: // G3 - CCW ARC
  1450. if(Stopped == false) {
  1451. get_arc_coordinates();
  1452. prepare_arc_move(false);
  1453. }
  1454. break;
  1455. case 4: // G4 dwell
  1456. LCD_MESSAGERPGM(MSG_DWELL);
  1457. codenum = 0;
  1458. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  1459. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  1460. st_synchronize();
  1461. codenum += millis(); // keep track of when we started waiting
  1462. previous_millis_cmd = millis();
  1463. while(millis() < codenum) {
  1464. manage_heater();
  1465. manage_inactivity();
  1466. lcd_update();
  1467. }
  1468. break;
  1469. #ifdef FWRETRACT
  1470. case 10: // G10 retract
  1471. #if EXTRUDERS > 1
  1472. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  1473. retract(true,retracted_swap[active_extruder]);
  1474. #else
  1475. retract(true);
  1476. #endif
  1477. break;
  1478. case 11: // G11 retract_recover
  1479. #if EXTRUDERS > 1
  1480. retract(false,retracted_swap[active_extruder]);
  1481. #else
  1482. retract(false);
  1483. #endif
  1484. break;
  1485. #endif //FWRETRACT
  1486. case 28: //G28 Home all Axis one at a time
  1487. #ifdef ENABLE_AUTO_BED_LEVELING
  1488. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  1489. #endif //ENABLE_AUTO_BED_LEVELING
  1490. _doMeshL = false;
  1491. // For mesh bed leveling deactivate the matrix temporarily
  1492. #ifdef MESH_BED_LEVELING
  1493. mbl.active = 0;
  1494. #endif
  1495. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  1496. // the planner will not perform any adjustments in the XY plane.
  1497. world2machine_reset();
  1498. saved_feedrate = feedrate;
  1499. saved_feedmultiply = feedmultiply;
  1500. feedmultiply = 100;
  1501. previous_millis_cmd = millis();
  1502. enable_endstops(true);
  1503. for(int8_t i=0; i < NUM_AXIS; i++) {
  1504. destination[i] = current_position[i];
  1505. }
  1506. feedrate = 0.0;
  1507. home_all_axis = !((code_seen(axis_codes[X_AXIS])) || (code_seen(axis_codes[Y_AXIS])) || (code_seen(axis_codes[Z_AXIS])));
  1508. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  1509. if((home_all_axis) || (code_seen(axis_codes[Z_AXIS]))) {
  1510. homeaxis(Z_AXIS);
  1511. }
  1512. #endif
  1513. #ifdef QUICK_HOME
  1514. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  1515. if((home_all_axis)||( code_seen(axis_codes[X_AXIS]) && code_seen(axis_codes[Y_AXIS])) ) //first diagonal move
  1516. {
  1517. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  1518. #ifndef DUAL_X_CARRIAGE
  1519. int x_axis_home_dir = home_dir(X_AXIS);
  1520. #else
  1521. int x_axis_home_dir = x_home_dir(active_extruder);
  1522. extruder_duplication_enabled = false;
  1523. #endif
  1524. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1525. destination[X_AXIS] = 1.5 * max_length(X_AXIS) * x_axis_home_dir;destination[Y_AXIS] = 1.5 * max_length(Y_AXIS) * home_dir(Y_AXIS);
  1526. feedrate = homing_feedrate[X_AXIS];
  1527. if(homing_feedrate[Y_AXIS]<feedrate)
  1528. feedrate = homing_feedrate[Y_AXIS];
  1529. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  1530. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  1531. } else {
  1532. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  1533. }
  1534. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1535. st_synchronize();
  1536. axis_is_at_home(X_AXIS);
  1537. axis_is_at_home(Y_AXIS);
  1538. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1539. destination[X_AXIS] = current_position[X_AXIS];
  1540. destination[Y_AXIS] = current_position[Y_AXIS];
  1541. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1542. feedrate = 0.0;
  1543. st_synchronize();
  1544. endstops_hit_on_purpose();
  1545. current_position[X_AXIS] = destination[X_AXIS];
  1546. current_position[Y_AXIS] = destination[Y_AXIS];
  1547. current_position[Z_AXIS] = destination[Z_AXIS];
  1548. }
  1549. #endif /* QUICK_HOME */
  1550. if (home_all_axis)
  1551. {
  1552. _doMeshL = true;
  1553. }
  1554. if((home_all_axis) || (code_seen(axis_codes[X_AXIS])))
  1555. {
  1556. #ifdef DUAL_X_CARRIAGE
  1557. int tmp_extruder = active_extruder;
  1558. extruder_duplication_enabled = false;
  1559. active_extruder = !active_extruder;
  1560. homeaxis(X_AXIS);
  1561. inactive_extruder_x_pos = current_position[X_AXIS];
  1562. active_extruder = tmp_extruder;
  1563. homeaxis(X_AXIS);
  1564. // reset state used by the different modes
  1565. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  1566. delayed_move_time = 0;
  1567. active_extruder_parked = true;
  1568. #else
  1569. homeaxis(X_AXIS);
  1570. #endif
  1571. }
  1572. if((home_all_axis) || (code_seen(axis_codes[Y_AXIS]))) {
  1573. homeaxis(Y_AXIS);
  1574. }
  1575. if(code_seen(axis_codes[X_AXIS]))
  1576. {
  1577. if(code_value_long() != 0) {
  1578. current_position[X_AXIS]=code_value()+add_homing[X_AXIS];
  1579. }
  1580. }
  1581. if(code_seen(axis_codes[Y_AXIS])) {
  1582. if(code_value_long() != 0) {
  1583. current_position[Y_AXIS]=code_value()+add_homing[Y_AXIS];
  1584. }
  1585. }
  1586. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  1587. #ifndef Z_SAFE_HOMING
  1588. if((home_all_axis) || (code_seen(axis_codes[Z_AXIS]))) {
  1589. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  1590. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  1591. feedrate = max_feedrate[Z_AXIS];
  1592. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  1593. st_synchronize();
  1594. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  1595. #ifdef MESH_BED_LEVELING // If Mesh bed leveling, moxve X&Y to safe position for home
  1596. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] ))
  1597. {
  1598. homeaxis(X_AXIS);
  1599. homeaxis(Y_AXIS);
  1600. }
  1601. // 1st mesh bed leveling measurement point, corrected.
  1602. world2machine_initialize();
  1603. current_position[X_AXIS] = world2machine_rotation_and_skew[0][0] * pgm_read_float(bed_ref_points) + world2machine_rotation_and_skew[0][1] * pgm_read_float(bed_ref_points+1) + world2machine_shift[0];
  1604. current_position[Y_AXIS] = world2machine_rotation_and_skew[1][0] * pgm_read_float(bed_ref_points) + world2machine_rotation_and_skew[1][1] * pgm_read_float(bed_ref_points+1) + world2machine_shift[1];
  1605. world2machine_reset();
  1606. // mbl.get_meas_xy(0, 0, destination[X_AXIS], destination[Y_AXIS], false);
  1607. // destination[X_AXIS] = MESH_MIN_X - X_PROBE_OFFSET_FROM_EXTRUDER;
  1608. // destination[Y_AXIS] = MESH_MIN_Y - Y_PROBE_OFFSET_FROM_EXTRUDER;
  1609. destination[Z_AXIS] = MESH_HOME_Z_SEARCH; // Set destination away from bed
  1610. feedrate = homing_feedrate[Z_AXIS]/10;
  1611. current_position[Z_AXIS] = 0;
  1612. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1613. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  1614. st_synchronize();
  1615. current_position[X_AXIS] = destination[X_AXIS];
  1616. current_position[Y_AXIS] = destination[Y_AXIS];
  1617. homeaxis(Z_AXIS);
  1618. _doMeshL = true;
  1619. #else // MESH_BED_LEVELING
  1620. homeaxis(Z_AXIS);
  1621. #endif // MESH_BED_LEVELING
  1622. }
  1623. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  1624. if(home_all_axis) {
  1625. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  1626. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  1627. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  1628. feedrate = XY_TRAVEL_SPEED/60;
  1629. current_position[Z_AXIS] = 0;
  1630. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1631. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  1632. st_synchronize();
  1633. current_position[X_AXIS] = destination[X_AXIS];
  1634. current_position[Y_AXIS] = destination[Y_AXIS];
  1635. homeaxis(Z_AXIS);
  1636. }
  1637. // Let's see if X and Y are homed and probe is inside bed area.
  1638. if(code_seen(axis_codes[Z_AXIS])) {
  1639. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  1640. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  1641. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  1642. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  1643. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  1644. current_position[Z_AXIS] = 0;
  1645. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1646. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  1647. feedrate = max_feedrate[Z_AXIS];
  1648. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  1649. st_synchronize();
  1650. homeaxis(Z_AXIS);
  1651. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  1652. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  1653. SERIAL_ECHO_START;
  1654. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  1655. } else {
  1656. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  1657. SERIAL_ECHO_START;
  1658. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  1659. }
  1660. }
  1661. #endif // Z_SAFE_HOMING
  1662. #endif // Z_HOME_DIR < 0
  1663. if(code_seen(axis_codes[Z_AXIS])) {
  1664. if(code_value_long() != 0) {
  1665. current_position[Z_AXIS]=code_value()+add_homing[Z_AXIS];
  1666. }
  1667. }
  1668. #ifdef ENABLE_AUTO_BED_LEVELING
  1669. if((home_all_axis) || (code_seen(axis_codes[Z_AXIS]))) {
  1670. current_position[Z_AXIS] += zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  1671. }
  1672. #endif
  1673. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1674. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1675. enable_endstops(false);
  1676. #endif
  1677. feedrate = saved_feedrate;
  1678. feedmultiply = saved_feedmultiply;
  1679. previous_millis_cmd = millis();
  1680. endstops_hit_on_purpose();
  1681. #ifndef MESH_BED_LEVELING
  1682. if(card.sdprinting) {
  1683. EEPROM_read_B(EEPROM_BABYSTEP_Z,&babystepLoad[2]);
  1684. if(babystepLoad[2] != 0){
  1685. lcd_adjust_z();
  1686. }
  1687. }
  1688. #endif
  1689. // Load the machine correction matrix
  1690. world2machine_initialize();
  1691. // and correct the current_position to match the transformed coordinate system.
  1692. world2machine_update_current();
  1693. #ifdef MESH_BED_LEVELING
  1694. if (code_seen('W'))
  1695. {
  1696. _doMeshL = false;
  1697. SERIAL_ECHOLN("G80 disabled");
  1698. }
  1699. if ( _doMeshL)
  1700. {
  1701. st_synchronize();
  1702. // Push the commands to the front of the message queue in the reverse order!
  1703. // There shall be always enough space reserved for these commands.
  1704. enquecommand_front_P((PSTR("G80")));
  1705. }
  1706. #endif
  1707. break;
  1708. #ifdef ENABLE_AUTO_BED_LEVELING
  1709. case 29: // G29 Detailed Z-Probe, probes the bed at 3 or more points.
  1710. {
  1711. #if Z_MIN_PIN == -1
  1712. #error "You must have a Z_MIN endstop in order to enable Auto Bed Leveling feature! Z_MIN_PIN must point to a valid hardware pin."
  1713. #endif
  1714. // Prevent user from running a G29 without first homing in X and Y
  1715. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  1716. {
  1717. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  1718. SERIAL_ECHO_START;
  1719. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  1720. break; // abort G29, since we don't know where we are
  1721. }
  1722. st_synchronize();
  1723. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  1724. //vector_3 corrected_position = plan_get_position_mm();
  1725. //corrected_position.debug("position before G29");
  1726. plan_bed_level_matrix.set_to_identity();
  1727. vector_3 uncorrected_position = plan_get_position();
  1728. //uncorrected_position.debug("position durring G29");
  1729. current_position[X_AXIS] = uncorrected_position.x;
  1730. current_position[Y_AXIS] = uncorrected_position.y;
  1731. current_position[Z_AXIS] = uncorrected_position.z;
  1732. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1733. setup_for_endstop_move();
  1734. feedrate = homing_feedrate[Z_AXIS];
  1735. #ifdef AUTO_BED_LEVELING_GRID
  1736. // probe at the points of a lattice grid
  1737. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  1738. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  1739. // solve the plane equation ax + by + d = z
  1740. // A is the matrix with rows [x y 1] for all the probed points
  1741. // B is the vector of the Z positions
  1742. // 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
  1743. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  1744. // "A" matrix of the linear system of equations
  1745. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  1746. // "B" vector of Z points
  1747. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  1748. int probePointCounter = 0;
  1749. bool zig = true;
  1750. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  1751. {
  1752. int xProbe, xInc;
  1753. if (zig)
  1754. {
  1755. xProbe = LEFT_PROBE_BED_POSITION;
  1756. //xEnd = RIGHT_PROBE_BED_POSITION;
  1757. xInc = xGridSpacing;
  1758. zig = false;
  1759. } else // zag
  1760. {
  1761. xProbe = RIGHT_PROBE_BED_POSITION;
  1762. //xEnd = LEFT_PROBE_BED_POSITION;
  1763. xInc = -xGridSpacing;
  1764. zig = true;
  1765. }
  1766. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  1767. {
  1768. float z_before;
  1769. if (probePointCounter == 0)
  1770. {
  1771. // raise before probing
  1772. z_before = Z_RAISE_BEFORE_PROBING;
  1773. } else
  1774. {
  1775. // raise extruder
  1776. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  1777. }
  1778. float measured_z = probe_pt(xProbe, yProbe, z_before);
  1779. eqnBVector[probePointCounter] = measured_z;
  1780. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  1781. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  1782. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  1783. probePointCounter++;
  1784. xProbe += xInc;
  1785. }
  1786. }
  1787. clean_up_after_endstop_move();
  1788. // solve lsq problem
  1789. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  1790. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  1791. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  1792. SERIAL_PROTOCOLPGM(" b: ");
  1793. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  1794. SERIAL_PROTOCOLPGM(" d: ");
  1795. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  1796. set_bed_level_equation_lsq(plane_equation_coefficients);
  1797. free(plane_equation_coefficients);
  1798. #else // AUTO_BED_LEVELING_GRID not defined
  1799. // Probe at 3 arbitrary points
  1800. // probe 1
  1801. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  1802. // probe 2
  1803. float z_at_pt_2 = probe_pt(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS);
  1804. // probe 3
  1805. float z_at_pt_3 = probe_pt(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS);
  1806. clean_up_after_endstop_move();
  1807. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  1808. #endif // AUTO_BED_LEVELING_GRID
  1809. st_synchronize();
  1810. // The following code correct the Z height difference from z-probe position and hotend tip position.
  1811. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  1812. // When the bed is uneven, this height must be corrected.
  1813. 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)
  1814. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  1815. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  1816. z_tmp = current_position[Z_AXIS];
  1817. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  1818. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  1819. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1820. }
  1821. break;
  1822. #ifndef Z_PROBE_SLED
  1823. case 30: // G30 Single Z Probe
  1824. {
  1825. st_synchronize();
  1826. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  1827. setup_for_endstop_move();
  1828. feedrate = homing_feedrate[Z_AXIS];
  1829. run_z_probe();
  1830. SERIAL_PROTOCOLPGM(MSG_BED);
  1831. SERIAL_PROTOCOLPGM(" X: ");
  1832. SERIAL_PROTOCOL(current_position[X_AXIS]);
  1833. SERIAL_PROTOCOLPGM(" Y: ");
  1834. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  1835. SERIAL_PROTOCOLPGM(" Z: ");
  1836. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  1837. SERIAL_PROTOCOLPGM("\n");
  1838. clean_up_after_endstop_move();
  1839. }
  1840. break;
  1841. #else
  1842. case 31: // dock the sled
  1843. dock_sled(true);
  1844. break;
  1845. case 32: // undock the sled
  1846. dock_sled(false);
  1847. break;
  1848. #endif // Z_PROBE_SLED
  1849. #endif // ENABLE_AUTO_BED_LEVELING
  1850. #ifdef MESH_BED_LEVELING
  1851. /**
  1852. * G80: Mesh-based Z probe, probes a grid and produces a
  1853. * mesh to compensate for variable bed height
  1854. *
  1855. * The S0 report the points as below
  1856. *
  1857. * +----> X-axis
  1858. * |
  1859. * |
  1860. * v Y-axis
  1861. *
  1862. */
  1863. case 80:
  1864. {
  1865. if (!IS_SD_PRINTING)
  1866. {
  1867. custom_message = true;
  1868. custom_message_type = 1;
  1869. custom_message_state = (MESH_MEAS_NUM_X_POINTS * MESH_MEAS_NUM_Y_POINTS) + 10;
  1870. }
  1871. // Firstly check if we know where we are
  1872. if ( !( axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS] ) ){
  1873. // We don't know where we are! HOME!
  1874. // Push the commands to the front of the message queue in the reverse order!
  1875. // There shall be always enough space reserved for these commands.
  1876. enquecommand_front_P((PSTR("G80")));
  1877. enquecommand_front_P((PSTR("G28 W0")));
  1878. break;
  1879. }
  1880. mbl.reset();
  1881. // Cycle through all points and probe them
  1882. // First move up.
  1883. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  1884. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  1885. // The move to the first calibration point.
  1886. current_position[X_AXIS] = pgm_read_float(bed_ref_points);
  1887. current_position[Y_AXIS] = pgm_read_float(bed_ref_points+1);
  1888. // mbl.get_meas_xy(0, 0, current_position[X_AXIS], current_position[Y_AXIS], false);
  1889. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[X_AXIS]/30, active_extruder);
  1890. // Wait until the move is finished.
  1891. st_synchronize();
  1892. int mesh_point = 0;
  1893. int ix = 0;
  1894. int iy = 0;
  1895. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS]/20;
  1896. int Z_PROBE_FEEDRATE = homing_feedrate[Z_AXIS]/60;
  1897. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS]/40;
  1898. setup_for_endstop_move();
  1899. while (mesh_point != MESH_MEAS_NUM_X_POINTS * MESH_MEAS_NUM_Y_POINTS) {
  1900. // Move Z to proper distance
  1901. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  1902. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  1903. st_synchronize();
  1904. // Get cords of measuring point
  1905. ix = mesh_point % MESH_MEAS_NUM_X_POINTS;
  1906. iy = mesh_point / MESH_MEAS_NUM_X_POINTS;
  1907. if (iy & 1) ix = (MESH_MEAS_NUM_X_POINTS - 1) - ix; // Zig zag
  1908. current_position[X_AXIS] = pgm_read_float(bed_ref_points+2*mesh_point);
  1909. current_position[Y_AXIS] = pgm_read_float(bed_ref_points+2*mesh_point+1);
  1910. // mbl.get_meas_xy(ix, iy, current_position[X_AXIS], current_position[Y_AXIS], false);
  1911. enable_endstops(false);
  1912. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], XY_AXIS_FEEDRATE, active_extruder);
  1913. st_synchronize();
  1914. // Go down until endstop is hit
  1915. find_bed_induction_sensor_point_z();
  1916. mbl.set_z(ix, iy, current_position[Z_AXIS]);
  1917. if (!IS_SD_PRINTING)
  1918. {
  1919. custom_message_state--;
  1920. }
  1921. mesh_point++;
  1922. }
  1923. clean_up_after_endstop_move();
  1924. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  1925. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS],current_position[Z_AXIS] , current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  1926. mbl.upsample_3x3();
  1927. mbl.active = 1;
  1928. current_position[X_AXIS] = X_MIN_POS+0.2;
  1929. current_position[Y_AXIS] = Y_MIN_POS+0.2;
  1930. current_position[Z_AXIS] = Z_MIN_POS;
  1931. plan_buffer_line(current_position[X_AXIS], current_position[X_AXIS], current_position[Z_AXIS], current_position[E_AXIS], XY_AXIS_FEEDRATE, active_extruder);
  1932. st_synchronize();
  1933. if(card.sdprinting || is_usb_printing )
  1934. {
  1935. if(eeprom_read_byte((unsigned char*)EEPROM_BABYSTEP_Z_SET) == 0x01)
  1936. {
  1937. EEPROM_read_B(EEPROM_BABYSTEP_Z,&babystepLoad[2]);
  1938. babystepsTodo[Z_AXIS] = babystepLoad[2];
  1939. }
  1940. }
  1941. }
  1942. break;
  1943. /**
  1944. * G81: Print mesh bed leveling status and bed profile if activated
  1945. */
  1946. case 81:
  1947. if (mbl.active) {
  1948. SERIAL_PROTOCOLPGM("Num X,Y: ");
  1949. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  1950. SERIAL_PROTOCOLPGM(",");
  1951. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  1952. SERIAL_PROTOCOLPGM("\nZ search height: ");
  1953. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  1954. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  1955. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  1956. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  1957. SERIAL_PROTOCOLPGM(" ");
  1958. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  1959. }
  1960. SERIAL_PROTOCOLPGM("\n");
  1961. }
  1962. }
  1963. else
  1964. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  1965. break;
  1966. /**
  1967. * G82: Single Z probe at current location
  1968. *
  1969. * WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  1970. *
  1971. */
  1972. case 82:
  1973. SERIAL_PROTOCOLLNPGM("Finding bed ");
  1974. setup_for_endstop_move();
  1975. find_bed_induction_sensor_point_z();
  1976. clean_up_after_endstop_move();
  1977. SERIAL_PROTOCOLPGM("Bed found at: ");
  1978. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  1979. SERIAL_PROTOCOLPGM("\n");
  1980. break;
  1981. /**
  1982. * G83: Babystep in Z and store to EEPROM
  1983. */
  1984. case 83:
  1985. {
  1986. int babystepz = code_seen('S') ? code_value() : 0;
  1987. int BabyPosition = code_seen('P') ? code_value() : 0;
  1988. if (babystepz != 0) {
  1989. if (BabyPosition > 4) {
  1990. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  1991. }else{
  1992. // Save it to the eeprom
  1993. babystepLoad[2] = babystepz;
  1994. EEPROM_save_B(EEPROM_BABYSTEP_Z0+(BabyPosition*2),&babystepLoad[2]);
  1995. // adjist the Z
  1996. babystepsTodo[Z_AXIS] = babystepLoad[2];
  1997. }
  1998. }
  1999. }
  2000. break;
  2001. /**
  2002. * G84: UNDO Babystep Z (move Z axis back)
  2003. */
  2004. case 84:
  2005. babystepsTodo[Z_AXIS] = -babystepLoad[2];
  2006. break;
  2007. /**
  2008. * G85: Pick best babystep
  2009. */
  2010. case 85:
  2011. lcd_pick_babystep();
  2012. break;
  2013. /**
  2014. * G86: Disable babystep correction after home
  2015. */
  2016. case 86:
  2017. eeprom_write_byte((unsigned char*)EEPROM_BABYSTEP_Z_SET, 0xFF);
  2018. break;
  2019. /**
  2020. * G87: Enable babystep correction after home
  2021. */
  2022. case 87:
  2023. eeprom_write_byte((unsigned char*)EEPROM_BABYSTEP_Z_SET, 0x01);
  2024. break;
  2025. case 88:
  2026. break;
  2027. #endif // ENABLE_MESH_BED_LEVELING
  2028. case 90: // G90
  2029. relative_mode = false;
  2030. break;
  2031. case 91: // G91
  2032. relative_mode = true;
  2033. break;
  2034. case 92: // G92
  2035. if(!code_seen(axis_codes[E_AXIS]))
  2036. st_synchronize();
  2037. for(int8_t i=0; i < NUM_AXIS; i++) {
  2038. if(code_seen(axis_codes[i])) {
  2039. if(i == E_AXIS) {
  2040. current_position[i] = code_value();
  2041. plan_set_e_position(current_position[E_AXIS]);
  2042. }
  2043. else {
  2044. current_position[i] = code_value()+add_homing[i];
  2045. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2046. }
  2047. }
  2048. }
  2049. break;
  2050. }
  2051. } // end if(code_seen('G'))
  2052. else if(code_seen('M'))
  2053. {
  2054. switch( (int)code_value() )
  2055. {
  2056. #ifdef ULTIPANEL
  2057. case 0: // M0 - Unconditional stop - Wait for user button press on LCD
  2058. case 1: // M1 - Conditional stop - Wait for user button press on LCD
  2059. {
  2060. char *src = strchr_pointer + 2;
  2061. codenum = 0;
  2062. bool hasP = false, hasS = false;
  2063. if (code_seen('P')) {
  2064. codenum = code_value(); // milliseconds to wait
  2065. hasP = codenum > 0;
  2066. }
  2067. if (code_seen('S')) {
  2068. codenum = code_value() * 1000; // seconds to wait
  2069. hasS = codenum > 0;
  2070. }
  2071. starpos = strchr(src, '*');
  2072. if (starpos != NULL) *(starpos) = '\0';
  2073. while (*src == ' ') ++src;
  2074. if (!hasP && !hasS && *src != '\0') {
  2075. lcd_setstatus(src);
  2076. } else {
  2077. LCD_MESSAGERPGM(MSG_USERWAIT);
  2078. }
  2079. lcd_ignore_click();
  2080. st_synchronize();
  2081. previous_millis_cmd = millis();
  2082. if (codenum > 0){
  2083. codenum += millis(); // keep track of when we started waiting
  2084. while(millis() < codenum && !lcd_clicked()){
  2085. manage_heater();
  2086. manage_inactivity();
  2087. lcd_update();
  2088. }
  2089. lcd_ignore_click(false);
  2090. }else{
  2091. if (!lcd_detected())
  2092. break;
  2093. while(!lcd_clicked()){
  2094. manage_heater();
  2095. manage_inactivity();
  2096. lcd_update();
  2097. }
  2098. }
  2099. if (IS_SD_PRINTING)
  2100. LCD_MESSAGERPGM(MSG_RESUMING);
  2101. else
  2102. LCD_MESSAGERPGM(WELCOME_MSG);
  2103. }
  2104. break;
  2105. #endif
  2106. case 17:
  2107. LCD_MESSAGERPGM(MSG_NO_MOVE);
  2108. enable_x();
  2109. enable_y();
  2110. enable_z();
  2111. enable_e0();
  2112. enable_e1();
  2113. enable_e2();
  2114. break;
  2115. #ifdef SDSUPPORT
  2116. case 20: // M20 - list SD card
  2117. SERIAL_PROTOCOLLNRPGM(MSG_BEGIN_FILE_LIST);
  2118. card.ls();
  2119. SERIAL_PROTOCOLLNRPGM(MSG_END_FILE_LIST);
  2120. break;
  2121. case 21: // M21 - init SD card
  2122. card.initsd();
  2123. break;
  2124. case 22: //M22 - release SD card
  2125. card.release();
  2126. break;
  2127. case 23: //M23 - Select file
  2128. starpos = (strchr(strchr_pointer + 4,'*'));
  2129. if(starpos!=NULL)
  2130. *(starpos)='\0';
  2131. card.openFile(strchr_pointer + 4,true);
  2132. break;
  2133. case 24: //M24 - Start SD print
  2134. card.startFileprint();
  2135. starttime=millis();
  2136. break;
  2137. case 25: //M25 - Pause SD print
  2138. card.pauseSDPrint();
  2139. break;
  2140. case 26: //M26 - Set SD index
  2141. if(card.cardOK && code_seen('S')) {
  2142. card.setIndex(code_value_long());
  2143. }
  2144. break;
  2145. case 27: //M27 - Get SD status
  2146. card.getStatus();
  2147. break;
  2148. case 28: //M28 - Start SD write
  2149. starpos = (strchr(strchr_pointer + 4,'*'));
  2150. if(starpos != NULL){
  2151. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  2152. strchr_pointer = strchr(npos,' ') + 1;
  2153. *(starpos) = '\0';
  2154. }
  2155. card.openFile(strchr_pointer+4,false);
  2156. break;
  2157. case 29: //M29 - Stop SD write
  2158. //processed in write to file routine above
  2159. //card,saving = false;
  2160. break;
  2161. case 30: //M30 <filename> Delete File
  2162. if (card.cardOK){
  2163. card.closefile();
  2164. starpos = (strchr(strchr_pointer + 4,'*'));
  2165. if(starpos != NULL){
  2166. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  2167. strchr_pointer = strchr(npos,' ') + 1;
  2168. *(starpos) = '\0';
  2169. }
  2170. card.removeFile(strchr_pointer + 4);
  2171. }
  2172. break;
  2173. case 32: //M32 - Select file and start SD print
  2174. {
  2175. if(card.sdprinting) {
  2176. st_synchronize();
  2177. }
  2178. starpos = (strchr(strchr_pointer + 4,'*'));
  2179. char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  2180. if(namestartpos==NULL)
  2181. {
  2182. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  2183. }
  2184. else
  2185. namestartpos++; //to skip the '!'
  2186. if(starpos!=NULL)
  2187. *(starpos)='\0';
  2188. bool call_procedure=(code_seen('P'));
  2189. if(strchr_pointer>namestartpos)
  2190. call_procedure=false; //false alert, 'P' found within filename
  2191. if( card.cardOK )
  2192. {
  2193. card.openFile(namestartpos,true,!call_procedure);
  2194. if(code_seen('S'))
  2195. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  2196. card.setIndex(code_value_long());
  2197. card.startFileprint();
  2198. if(!call_procedure)
  2199. starttime=millis(); //procedure calls count as normal print time.
  2200. }
  2201. } break;
  2202. case 928: //M928 - Start SD write
  2203. starpos = (strchr(strchr_pointer + 5,'*'));
  2204. if(starpos != NULL){
  2205. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  2206. strchr_pointer = strchr(npos,' ') + 1;
  2207. *(starpos) = '\0';
  2208. }
  2209. card.openLogFile(strchr_pointer+5);
  2210. break;
  2211. #endif //SDSUPPORT
  2212. case 31: //M31 take time since the start of the SD print or an M109 command
  2213. {
  2214. stoptime=millis();
  2215. char time[30];
  2216. unsigned long t=(stoptime-starttime)/1000;
  2217. int sec,min;
  2218. min=t/60;
  2219. sec=t%60;
  2220. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  2221. SERIAL_ECHO_START;
  2222. SERIAL_ECHOLN(time);
  2223. lcd_setstatus(time);
  2224. autotempShutdown();
  2225. }
  2226. break;
  2227. case 42: //M42 -Change pin status via gcode
  2228. if (code_seen('S'))
  2229. {
  2230. int pin_status = code_value();
  2231. int pin_number = LED_PIN;
  2232. if (code_seen('P') && pin_status >= 0 && pin_status <= 255)
  2233. pin_number = code_value();
  2234. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  2235. {
  2236. if (sensitive_pins[i] == pin_number)
  2237. {
  2238. pin_number = -1;
  2239. break;
  2240. }
  2241. }
  2242. #if defined(FAN_PIN) && FAN_PIN > -1
  2243. if (pin_number == FAN_PIN)
  2244. fanSpeed = pin_status;
  2245. #endif
  2246. if (pin_number > -1)
  2247. {
  2248. pinMode(pin_number, OUTPUT);
  2249. digitalWrite(pin_number, pin_status);
  2250. analogWrite(pin_number, pin_status);
  2251. }
  2252. }
  2253. break;
  2254. case 45:
  2255. reset_bed_offset_and_skew();
  2256. world2machine_reset();
  2257. break;
  2258. case 46: // M46: mesh_bed_calibration with manual Z up
  2259. {
  2260. // Firstly check if we know where we are
  2261. if ( !( axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) ){
  2262. // We don't know where we are! HOME!
  2263. // Push the commands to the front of the message queue in the reverse order!
  2264. // There shall be always enough space reserved for these commands.
  2265. enquecommand_front_P((PSTR("M46")));
  2266. enquecommand_front_P((PSTR("G28 X Y")));
  2267. break;
  2268. }
  2269. lcd_update_enable(false);
  2270. if (lcd_calibrate_z_end_stop_manual()) {
  2271. mbl.reset();
  2272. setup_for_endstop_move();
  2273. find_bed_offset_and_skew();
  2274. clean_up_after_endstop_move();
  2275. // Print head up.
  2276. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2277. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS],current_position[Z_AXIS] , current_position[E_AXIS], homing_feedrate[Z_AXIS]/40, active_extruder);
  2278. st_synchronize();
  2279. // Push the commands to the front of the message queue in the reverse order!
  2280. // There shall be always enough space reserved for these commands.
  2281. enquecommand_front_P((PSTR("M47")));
  2282. enquecommand_front_P((PSTR("G28 X Y")));
  2283. } else {
  2284. // User canceled the operation. Give up.
  2285. lcd_update_enable(true);
  2286. lcd_implementation_clear();
  2287. // lcd_return_to_status();
  2288. lcd_update();
  2289. }
  2290. }
  2291. break;
  2292. case 47:
  2293. {
  2294. // Firstly check if we know where we are
  2295. if ( !( axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) ) {
  2296. // We don't know where we are! HOME!
  2297. // Push the commands to the front of the message queue in the reverse order!
  2298. // There shall be always enough space reserved for these commands.
  2299. enquecommand_front_P((PSTR("M47")));
  2300. enquecommand_front_P((PSTR("G28 X Y")));
  2301. break;
  2302. }
  2303. lcd_update_enable(false);
  2304. mbl.reset();
  2305. setup_for_endstop_move();
  2306. bool success = improve_bed_offset_and_skew(1);
  2307. clean_up_after_endstop_move();
  2308. // Print head up.
  2309. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2310. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS],current_position[Z_AXIS] , current_position[E_AXIS], homing_feedrate[Z_AXIS]/40, active_extruder);
  2311. st_synchronize();
  2312. lcd_update_enable(true);
  2313. lcd_update();
  2314. if (success) {
  2315. // Mesh bed leveling.
  2316. // Push the commands to the front of the message queue in the reverse order!
  2317. // There shall be always enough space reserved for these commands.
  2318. enquecommand_front_P((PSTR("G80")));
  2319. }
  2320. break;
  2321. }
  2322. case 48:
  2323. lcd_diag_show_end_stops();
  2324. break;
  2325. // M48 Z-Probe repeatability measurement function.
  2326. //
  2327. // Usage: M48 <n #_samples> <X X_position_for_samples> <Y Y_position_for_samples> <V Verbose_Level> <L legs_of_movement_prior_to_doing_probe>
  2328. //
  2329. // This function assumes the bed has been homed. Specificaly, that a G28 command
  2330. // as been issued prior to invoking the M48 Z-Probe repeatability measurement function.
  2331. // Any information generated by a prior G29 Bed leveling command will be lost and need to be
  2332. // regenerated.
  2333. //
  2334. // The number of samples will default to 10 if not specified. You can use upper or lower case
  2335. // letters for any of the options EXCEPT n. n must be in lower case because Marlin uses a capital
  2336. // N for its communication protocol and will get horribly confused if you send it a capital N.
  2337. //
  2338. #ifdef ENABLE_AUTO_BED_LEVELING
  2339. #ifdef Z_PROBE_REPEATABILITY_TEST
  2340. case 48: // M48 Z-Probe repeatability
  2341. {
  2342. #if Z_MIN_PIN == -1
  2343. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  2344. #endif
  2345. double sum=0.0;
  2346. double mean=0.0;
  2347. double sigma=0.0;
  2348. double sample_set[50];
  2349. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  2350. double X_current, Y_current, Z_current;
  2351. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  2352. if (code_seen('V') || code_seen('v')) {
  2353. verbose_level = code_value();
  2354. if (verbose_level<0 || verbose_level>4 ) {
  2355. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  2356. goto Sigma_Exit;
  2357. }
  2358. }
  2359. if (verbose_level > 0) {
  2360. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  2361. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  2362. }
  2363. if (code_seen('n')) {
  2364. n_samples = code_value();
  2365. if (n_samples<4 || n_samples>50 ) {
  2366. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  2367. goto Sigma_Exit;
  2368. }
  2369. }
  2370. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  2371. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  2372. Z_current = st_get_position_mm(Z_AXIS);
  2373. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  2374. ext_position = st_get_position_mm(E_AXIS);
  2375. if (code_seen('X') || code_seen('x') ) {
  2376. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  2377. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  2378. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  2379. goto Sigma_Exit;
  2380. }
  2381. }
  2382. if (code_seen('Y') || code_seen('y') ) {
  2383. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  2384. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  2385. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  2386. goto Sigma_Exit;
  2387. }
  2388. }
  2389. if (code_seen('L') || code_seen('l') ) {
  2390. n_legs = code_value();
  2391. if ( n_legs==1 )
  2392. n_legs = 2;
  2393. if ( n_legs<0 || n_legs>15 ) {
  2394. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  2395. goto Sigma_Exit;
  2396. }
  2397. }
  2398. //
  2399. // Do all the preliminary setup work. First raise the probe.
  2400. //
  2401. st_synchronize();
  2402. plan_bed_level_matrix.set_to_identity();
  2403. plan_buffer_line( X_current, Y_current, Z_start_location,
  2404. ext_position,
  2405. homing_feedrate[Z_AXIS]/60,
  2406. active_extruder);
  2407. st_synchronize();
  2408. //
  2409. // Now get everything to the specified probe point So we can safely do a probe to
  2410. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  2411. // use that as a starting point for each probe.
  2412. //
  2413. if (verbose_level > 2)
  2414. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  2415. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  2416. ext_position,
  2417. homing_feedrate[X_AXIS]/60,
  2418. active_extruder);
  2419. st_synchronize();
  2420. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  2421. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  2422. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  2423. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  2424. //
  2425. // OK, do the inital probe to get us close to the bed.
  2426. // Then retrace the right amount and use that in subsequent probes
  2427. //
  2428. setup_for_endstop_move();
  2429. run_z_probe();
  2430. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  2431. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  2432. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  2433. ext_position,
  2434. homing_feedrate[X_AXIS]/60,
  2435. active_extruder);
  2436. st_synchronize();
  2437. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  2438. for( n=0; n<n_samples; n++) {
  2439. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  2440. if ( n_legs) {
  2441. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  2442. int rotational_direction, l;
  2443. rotational_direction = (unsigned long) millis() & 0x0001; // clockwise or counter clockwise
  2444. radius = (unsigned long) millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  2445. theta = (float) ((unsigned long) millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  2446. //SERIAL_ECHOPAIR("starting radius: ",radius);
  2447. //SERIAL_ECHOPAIR(" theta: ",theta);
  2448. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  2449. //SERIAL_PROTOCOLLNPGM("");
  2450. for( l=0; l<n_legs-1; l++) {
  2451. if (rotational_direction==1)
  2452. theta += (float) ((unsigned long) millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  2453. else
  2454. theta -= (float) ((unsigned long) millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  2455. radius += (float) ( ((long) ((unsigned long) millis() % (long) 10)) - 5);
  2456. if ( radius<0.0 )
  2457. radius = -radius;
  2458. X_current = X_probe_location + cos(theta) * radius;
  2459. Y_current = Y_probe_location + sin(theta) * radius;
  2460. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  2461. X_current = X_MIN_POS;
  2462. if ( X_current>X_MAX_POS)
  2463. X_current = X_MAX_POS;
  2464. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  2465. Y_current = Y_MIN_POS;
  2466. if ( Y_current>Y_MAX_POS)
  2467. Y_current = Y_MAX_POS;
  2468. if (verbose_level>3 ) {
  2469. SERIAL_ECHOPAIR("x: ", X_current);
  2470. SERIAL_ECHOPAIR("y: ", Y_current);
  2471. SERIAL_PROTOCOLLNPGM("");
  2472. }
  2473. do_blocking_move_to( X_current, Y_current, Z_current );
  2474. }
  2475. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  2476. }
  2477. setup_for_endstop_move();
  2478. run_z_probe();
  2479. sample_set[n] = current_position[Z_AXIS];
  2480. //
  2481. // Get the current mean for the data points we have so far
  2482. //
  2483. sum=0.0;
  2484. for( j=0; j<=n; j++) {
  2485. sum = sum + sample_set[j];
  2486. }
  2487. mean = sum / (double (n+1));
  2488. //
  2489. // Now, use that mean to calculate the standard deviation for the
  2490. // data points we have so far
  2491. //
  2492. sum=0.0;
  2493. for( j=0; j<=n; j++) {
  2494. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  2495. }
  2496. sigma = sqrt( sum / (double (n+1)) );
  2497. if (verbose_level > 1) {
  2498. SERIAL_PROTOCOL(n+1);
  2499. SERIAL_PROTOCOL(" of ");
  2500. SERIAL_PROTOCOL(n_samples);
  2501. SERIAL_PROTOCOLPGM(" z: ");
  2502. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  2503. }
  2504. if (verbose_level > 2) {
  2505. SERIAL_PROTOCOL(" mean: ");
  2506. SERIAL_PROTOCOL_F(mean,6);
  2507. SERIAL_PROTOCOL(" sigma: ");
  2508. SERIAL_PROTOCOL_F(sigma,6);
  2509. }
  2510. if (verbose_level > 0)
  2511. SERIAL_PROTOCOLPGM("\n");
  2512. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  2513. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  2514. st_synchronize();
  2515. }
  2516. delay(1000);
  2517. clean_up_after_endstop_move();
  2518. // enable_endstops(true);
  2519. if (verbose_level > 0) {
  2520. SERIAL_PROTOCOLPGM("Mean: ");
  2521. SERIAL_PROTOCOL_F(mean, 6);
  2522. SERIAL_PROTOCOLPGM("\n");
  2523. }
  2524. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  2525. SERIAL_PROTOCOL_F(sigma, 6);
  2526. SERIAL_PROTOCOLPGM("\n\n");
  2527. Sigma_Exit:
  2528. break;
  2529. }
  2530. #endif // Z_PROBE_REPEATABILITY_TEST
  2531. #endif // ENABLE_AUTO_BED_LEVELING
  2532. case 104: // M104
  2533. if(setTargetedHotend(104)){
  2534. break;
  2535. }
  2536. if (code_seen('S')) setTargetHotend(code_value(), tmp_extruder);
  2537. #ifdef DUAL_X_CARRIAGE
  2538. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && tmp_extruder == 0)
  2539. setTargetHotend1(code_value() == 0.0 ? 0.0 : code_value() + duplicate_extruder_temp_offset);
  2540. #endif
  2541. setWatch();
  2542. break;
  2543. case 112: // M112 -Emergency Stop
  2544. kill();
  2545. break;
  2546. case 140: // M140 set bed temp
  2547. if (code_seen('S')) setTargetBed(code_value());
  2548. break;
  2549. case 105 : // M105
  2550. if(setTargetedHotend(105)){
  2551. break;
  2552. }
  2553. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  2554. SERIAL_PROTOCOLPGM("ok T:");
  2555. SERIAL_PROTOCOL_F(degHotend(tmp_extruder),1);
  2556. SERIAL_PROTOCOLPGM(" /");
  2557. SERIAL_PROTOCOL_F(degTargetHotend(tmp_extruder),1);
  2558. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2559. SERIAL_PROTOCOLPGM(" B:");
  2560. SERIAL_PROTOCOL_F(degBed(),1);
  2561. SERIAL_PROTOCOLPGM(" /");
  2562. SERIAL_PROTOCOL_F(degTargetBed(),1);
  2563. #endif //TEMP_BED_PIN
  2564. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2565. SERIAL_PROTOCOLPGM(" T");
  2566. SERIAL_PROTOCOL(cur_extruder);
  2567. SERIAL_PROTOCOLPGM(":");
  2568. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2569. SERIAL_PROTOCOLPGM(" /");
  2570. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  2571. }
  2572. #else
  2573. SERIAL_ERROR_START;
  2574. SERIAL_ERRORLNRPGM(MSG_ERR_NO_THERMISTORS);
  2575. #endif
  2576. SERIAL_PROTOCOLPGM(" @:");
  2577. #ifdef EXTRUDER_WATTS
  2578. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  2579. SERIAL_PROTOCOLPGM("W");
  2580. #else
  2581. SERIAL_PROTOCOL(getHeaterPower(tmp_extruder));
  2582. #endif
  2583. SERIAL_PROTOCOLPGM(" B@:");
  2584. #ifdef BED_WATTS
  2585. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  2586. SERIAL_PROTOCOLPGM("W");
  2587. #else
  2588. SERIAL_PROTOCOL(getHeaterPower(-1));
  2589. #endif
  2590. #ifdef SHOW_TEMP_ADC_VALUES
  2591. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2592. SERIAL_PROTOCOLPGM(" ADC B:");
  2593. SERIAL_PROTOCOL_F(degBed(),1);
  2594. SERIAL_PROTOCOLPGM("C->");
  2595. SERIAL_PROTOCOL_F(rawBedTemp()/OVERSAMPLENR,0);
  2596. #endif
  2597. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2598. SERIAL_PROTOCOLPGM(" T");
  2599. SERIAL_PROTOCOL(cur_extruder);
  2600. SERIAL_PROTOCOLPGM(":");
  2601. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2602. SERIAL_PROTOCOLPGM("C->");
  2603. SERIAL_PROTOCOL_F(rawHotendTemp(cur_extruder)/OVERSAMPLENR,0);
  2604. }
  2605. #endif
  2606. SERIAL_PROTOCOLLN("");
  2607. return;
  2608. break;
  2609. case 109:
  2610. {// M109 - Wait for extruder heater to reach target.
  2611. if(setTargetedHotend(109)){
  2612. break;
  2613. }
  2614. LCD_MESSAGERPGM(MSG_HEATING);
  2615. heating_status = 1;
  2616. #ifdef AUTOTEMP
  2617. autotemp_enabled=false;
  2618. #endif
  2619. if (code_seen('S')) {
  2620. setTargetHotend(code_value(), tmp_extruder);
  2621. #ifdef DUAL_X_CARRIAGE
  2622. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && tmp_extruder == 0)
  2623. setTargetHotend1(code_value() == 0.0 ? 0.0 : code_value() + duplicate_extruder_temp_offset);
  2624. #endif
  2625. CooldownNoWait = true;
  2626. } else if (code_seen('R')) {
  2627. setTargetHotend(code_value(), tmp_extruder);
  2628. #ifdef DUAL_X_CARRIAGE
  2629. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && tmp_extruder == 0)
  2630. setTargetHotend1(code_value() == 0.0 ? 0.0 : code_value() + duplicate_extruder_temp_offset);
  2631. #endif
  2632. CooldownNoWait = false;
  2633. }
  2634. #ifdef AUTOTEMP
  2635. if (code_seen('S')) autotemp_min=code_value();
  2636. if (code_seen('B')) autotemp_max=code_value();
  2637. if (code_seen('F'))
  2638. {
  2639. autotemp_factor=code_value();
  2640. autotemp_enabled=true;
  2641. }
  2642. #endif
  2643. setWatch();
  2644. codenum = millis();
  2645. /* See if we are heating up or cooling down */
  2646. target_direction = isHeatingHotend(tmp_extruder); // true if heating, false if cooling
  2647. cancel_heatup = false;
  2648. #ifdef TEMP_RESIDENCY_TIME
  2649. long residencyStart;
  2650. residencyStart = -1;
  2651. /* continue to loop until we have reached the target temp
  2652. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  2653. while((!cancel_heatup)&&((residencyStart == -1) ||
  2654. (residencyStart >= 0 && (((unsigned int) (millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL)))) ) {
  2655. #else
  2656. while ( target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder)&&(CooldownNoWait==false)) ) {
  2657. #endif //TEMP_RESIDENCY_TIME
  2658. if( (millis() - codenum) > 1000UL )
  2659. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  2660. SERIAL_PROTOCOLPGM("T:");
  2661. SERIAL_PROTOCOL_F(degHotend(tmp_extruder),1);
  2662. SERIAL_PROTOCOLPGM(" E:");
  2663. SERIAL_PROTOCOL((int)tmp_extruder);
  2664. #ifdef TEMP_RESIDENCY_TIME
  2665. SERIAL_PROTOCOLPGM(" W:");
  2666. if(residencyStart > -1)
  2667. {
  2668. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (millis() - residencyStart)) / 1000UL;
  2669. SERIAL_PROTOCOLLN( codenum );
  2670. }
  2671. else
  2672. {
  2673. SERIAL_PROTOCOLLN( "?" );
  2674. }
  2675. #else
  2676. SERIAL_PROTOCOLLN("");
  2677. #endif
  2678. codenum = millis();
  2679. }
  2680. manage_heater();
  2681. manage_inactivity();
  2682. lcd_update();
  2683. #ifdef TEMP_RESIDENCY_TIME
  2684. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  2685. or when current temp falls outside the hysteresis after target temp was reached */
  2686. if ((residencyStart == -1 && target_direction && (degHotend(tmp_extruder) >= (degTargetHotend(tmp_extruder)-TEMP_WINDOW))) ||
  2687. (residencyStart == -1 && !target_direction && (degHotend(tmp_extruder) <= (degTargetHotend(tmp_extruder)+TEMP_WINDOW))) ||
  2688. (residencyStart > -1 && labs(degHotend(tmp_extruder) - degTargetHotend(tmp_extruder)) > TEMP_HYSTERESIS) )
  2689. {
  2690. residencyStart = millis();
  2691. }
  2692. #endif //TEMP_RESIDENCY_TIME
  2693. }
  2694. LCD_MESSAGERPGM(MSG_HEATING_COMPLETE);
  2695. heating_status = 2;
  2696. starttime=millis();
  2697. previous_millis_cmd = millis();
  2698. }
  2699. break;
  2700. case 190: // M190 - Wait for bed heater to reach target.
  2701. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2702. LCD_MESSAGERPGM(MSG_BED_HEATING);
  2703. heating_status = 3;
  2704. if (code_seen('S'))
  2705. {
  2706. setTargetBed(code_value());
  2707. CooldownNoWait = true;
  2708. }
  2709. else if (code_seen('R'))
  2710. {
  2711. setTargetBed(code_value());
  2712. CooldownNoWait = false;
  2713. }
  2714. codenum = millis();
  2715. cancel_heatup = false;
  2716. target_direction = isHeatingBed(); // true if heating, false if cooling
  2717. while ( (target_direction)&&(!cancel_heatup) ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false)) )
  2718. {
  2719. if(( millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  2720. {
  2721. float tt=degHotend(active_extruder);
  2722. SERIAL_PROTOCOLPGM("T:");
  2723. SERIAL_PROTOCOL(tt);
  2724. SERIAL_PROTOCOLPGM(" E:");
  2725. SERIAL_PROTOCOL((int)active_extruder);
  2726. SERIAL_PROTOCOLPGM(" B:");
  2727. SERIAL_PROTOCOL_F(degBed(),1);
  2728. SERIAL_PROTOCOLLN("");
  2729. codenum = millis();
  2730. }
  2731. manage_heater();
  2732. manage_inactivity();
  2733. lcd_update();
  2734. }
  2735. LCD_MESSAGERPGM(MSG_BED_DONE);
  2736. heating_status = 4;
  2737. previous_millis_cmd = millis();
  2738. #endif
  2739. break;
  2740. #if defined(FAN_PIN) && FAN_PIN > -1
  2741. case 106: //M106 Fan On
  2742. if (code_seen('S')){
  2743. fanSpeed=constrain(code_value(),0,255);
  2744. }
  2745. else {
  2746. fanSpeed=255;
  2747. }
  2748. break;
  2749. case 107: //M107 Fan Off
  2750. fanSpeed = 0;
  2751. break;
  2752. #endif //FAN_PIN
  2753. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  2754. case 80: // M80 - Turn on Power Supply
  2755. SET_OUTPUT(PS_ON_PIN); //GND
  2756. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  2757. // If you have a switch on suicide pin, this is useful
  2758. // if you want to start another print with suicide feature after
  2759. // a print without suicide...
  2760. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  2761. SET_OUTPUT(SUICIDE_PIN);
  2762. WRITE(SUICIDE_PIN, HIGH);
  2763. #endif
  2764. #ifdef ULTIPANEL
  2765. powersupply = true;
  2766. LCD_MESSAGERPGM(WELCOME_MSG);
  2767. lcd_update();
  2768. #endif
  2769. break;
  2770. #endif
  2771. case 81: // M81 - Turn off Power Supply
  2772. disable_heater();
  2773. st_synchronize();
  2774. disable_e0();
  2775. disable_e1();
  2776. disable_e2();
  2777. finishAndDisableSteppers();
  2778. fanSpeed = 0;
  2779. delay(1000); // Wait a little before to switch off
  2780. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  2781. st_synchronize();
  2782. suicide();
  2783. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  2784. SET_OUTPUT(PS_ON_PIN);
  2785. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  2786. #endif
  2787. #ifdef ULTIPANEL
  2788. powersupply = false;
  2789. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR("."))); //!!
  2790. /*
  2791. MACHNAME = "Prusa i3"
  2792. MSGOFF = "Vypnuto"
  2793. "Prusai3"" ""vypnuto""."
  2794. "Prusa i3"" "MSG_ALL[lang_selected][50]"."
  2795. */
  2796. lcd_update();
  2797. #endif
  2798. break;
  2799. case 82:
  2800. axis_relative_modes[3] = false;
  2801. break;
  2802. case 83:
  2803. axis_relative_modes[3] = true;
  2804. break;
  2805. case 18: //compatibility
  2806. case 84: // M84
  2807. if(code_seen('S')){
  2808. stepper_inactive_time = code_value() * 1000;
  2809. }
  2810. else
  2811. {
  2812. 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])));
  2813. if(all_axis)
  2814. {
  2815. st_synchronize();
  2816. disable_e0();
  2817. disable_e1();
  2818. disable_e2();
  2819. finishAndDisableSteppers();
  2820. }
  2821. else
  2822. {
  2823. st_synchronize();
  2824. if(code_seen('X')) disable_x();
  2825. if(code_seen('Y')) disable_y();
  2826. if(code_seen('Z')) disable_z();
  2827. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  2828. if(code_seen('E')) {
  2829. disable_e0();
  2830. disable_e1();
  2831. disable_e2();
  2832. }
  2833. #endif
  2834. }
  2835. }
  2836. break;
  2837. case 85: // M85
  2838. if(code_seen('S')) {
  2839. max_inactive_time = code_value() * 1000;
  2840. }
  2841. break;
  2842. case 92: // M92
  2843. for(int8_t i=0; i < NUM_AXIS; i++)
  2844. {
  2845. if(code_seen(axis_codes[i]))
  2846. {
  2847. if(i == 3) { // E
  2848. float value = code_value();
  2849. if(value < 20.0) {
  2850. float factor = axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  2851. max_e_jerk *= factor;
  2852. max_feedrate[i] *= factor;
  2853. axis_steps_per_sqr_second[i] *= factor;
  2854. }
  2855. axis_steps_per_unit[i] = value;
  2856. }
  2857. else {
  2858. axis_steps_per_unit[i] = code_value();
  2859. }
  2860. }
  2861. }
  2862. break;
  2863. case 115: // M115
  2864. SERIAL_PROTOCOLRPGM(MSG_M115_REPORT);
  2865. break;
  2866. case 117: // M117 display message
  2867. starpos = (strchr(strchr_pointer + 5,'*'));
  2868. if(starpos!=NULL)
  2869. *(starpos)='\0';
  2870. lcd_setstatus(strchr_pointer + 5);
  2871. break;
  2872. case 114: // M114
  2873. SERIAL_PROTOCOLPGM("X:");
  2874. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2875. SERIAL_PROTOCOLPGM(" Y:");
  2876. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2877. SERIAL_PROTOCOLPGM(" Z:");
  2878. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2879. SERIAL_PROTOCOLPGM(" E:");
  2880. SERIAL_PROTOCOL(current_position[E_AXIS]);
  2881. SERIAL_PROTOCOLRPGM(MSG_COUNT_X);
  2882. SERIAL_PROTOCOL(float(st_get_position(X_AXIS))/axis_steps_per_unit[X_AXIS]);
  2883. SERIAL_PROTOCOLPGM(" Y:");
  2884. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS))/axis_steps_per_unit[Y_AXIS]);
  2885. SERIAL_PROTOCOLPGM(" Z:");
  2886. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS))/axis_steps_per_unit[Z_AXIS]);
  2887. SERIAL_PROTOCOLLN("");
  2888. break;
  2889. case 120: // M120
  2890. enable_endstops(false) ;
  2891. break;
  2892. case 121: // M121
  2893. enable_endstops(true) ;
  2894. break;
  2895. case 119: // M119
  2896. SERIAL_PROTOCOLRPGM(MSG_M119_REPORT);
  2897. SERIAL_PROTOCOLLN("");
  2898. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  2899. SERIAL_PROTOCOLRPGM(MSG_X_MIN);
  2900. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  2901. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  2902. }else{
  2903. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  2904. }
  2905. SERIAL_PROTOCOLLN("");
  2906. #endif
  2907. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  2908. SERIAL_PROTOCOLRPGM(MSG_X_MAX);
  2909. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  2910. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  2911. }else{
  2912. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  2913. }
  2914. SERIAL_PROTOCOLLN("");
  2915. #endif
  2916. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  2917. SERIAL_PROTOCOLRPGM(MSG_Y_MIN);
  2918. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  2919. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  2920. }else{
  2921. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  2922. }
  2923. SERIAL_PROTOCOLLN("");
  2924. #endif
  2925. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  2926. SERIAL_PROTOCOLRPGM(MSG_Y_MAX);
  2927. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  2928. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  2929. }else{
  2930. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  2931. }
  2932. SERIAL_PROTOCOLLN("");
  2933. #endif
  2934. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  2935. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  2936. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  2937. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  2938. }else{
  2939. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  2940. }
  2941. SERIAL_PROTOCOLLN("");
  2942. #endif
  2943. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  2944. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  2945. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  2946. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  2947. }else{
  2948. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  2949. }
  2950. SERIAL_PROTOCOLLN("");
  2951. #endif
  2952. break;
  2953. //TODO: update for all axis, use for loop
  2954. #ifdef BLINKM
  2955. case 150: // M150
  2956. {
  2957. byte red;
  2958. byte grn;
  2959. byte blu;
  2960. if(code_seen('R')) red = code_value();
  2961. if(code_seen('U')) grn = code_value();
  2962. if(code_seen('B')) blu = code_value();
  2963. SendColors(red,grn,blu);
  2964. }
  2965. break;
  2966. #endif //BLINKM
  2967. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  2968. {
  2969. tmp_extruder = active_extruder;
  2970. if(code_seen('T')) {
  2971. tmp_extruder = code_value();
  2972. if(tmp_extruder >= EXTRUDERS) {
  2973. SERIAL_ECHO_START;
  2974. SERIAL_ECHO(MSG_M200_INVALID_EXTRUDER);
  2975. break;
  2976. }
  2977. }
  2978. float area = .0;
  2979. if(code_seen('D')) {
  2980. float diameter = (float)code_value();
  2981. if (diameter == 0.0) {
  2982. // setting any extruder filament size disables volumetric on the assumption that
  2983. // slicers either generate in extruder values as cubic mm or as as filament feeds
  2984. // for all extruders
  2985. volumetric_enabled = false;
  2986. } else {
  2987. filament_size[tmp_extruder] = (float)code_value();
  2988. // make sure all extruders have some sane value for the filament size
  2989. filament_size[0] = (filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : filament_size[0]);
  2990. #if EXTRUDERS > 1
  2991. filament_size[1] = (filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : filament_size[1]);
  2992. #if EXTRUDERS > 2
  2993. filament_size[2] = (filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : filament_size[2]);
  2994. #endif
  2995. #endif
  2996. volumetric_enabled = true;
  2997. }
  2998. } else {
  2999. //reserved for setting filament diameter via UFID or filament measuring device
  3000. break;
  3001. }
  3002. calculate_volumetric_multipliers();
  3003. }
  3004. break;
  3005. case 201: // M201
  3006. for(int8_t i=0; i < NUM_AXIS; i++)
  3007. {
  3008. if(code_seen(axis_codes[i]))
  3009. {
  3010. max_acceleration_units_per_sq_second[i] = code_value();
  3011. }
  3012. }
  3013. // 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)
  3014. reset_acceleration_rates();
  3015. break;
  3016. #if 0 // Not used for Sprinter/grbl gen6
  3017. case 202: // M202
  3018. for(int8_t i=0; i < NUM_AXIS; i++) {
  3019. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * axis_steps_per_unit[i];
  3020. }
  3021. break;
  3022. #endif
  3023. case 203: // M203 max feedrate mm/sec
  3024. for(int8_t i=0; i < NUM_AXIS; i++) {
  3025. if(code_seen(axis_codes[i])) max_feedrate[i] = code_value();
  3026. }
  3027. break;
  3028. case 204: // M204 acclereration S normal moves T filmanent only moves
  3029. {
  3030. if(code_seen('S')) acceleration = code_value() ;
  3031. if(code_seen('T')) retract_acceleration = code_value() ;
  3032. }
  3033. break;
  3034. 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
  3035. {
  3036. if(code_seen('S')) minimumfeedrate = code_value();
  3037. if(code_seen('T')) mintravelfeedrate = code_value();
  3038. if(code_seen('B')) minsegmenttime = code_value() ;
  3039. if(code_seen('X')) max_xy_jerk = code_value() ;
  3040. if(code_seen('Z')) max_z_jerk = code_value() ;
  3041. if(code_seen('E')) max_e_jerk = code_value() ;
  3042. }
  3043. break;
  3044. case 206: // M206 additional homing offset
  3045. for(int8_t i=0; i < 3; i++)
  3046. {
  3047. if(code_seen(axis_codes[i])) add_homing[i] = code_value();
  3048. }
  3049. break;
  3050. #ifdef FWRETRACT
  3051. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  3052. {
  3053. if(code_seen('S'))
  3054. {
  3055. retract_length = code_value() ;
  3056. }
  3057. if(code_seen('F'))
  3058. {
  3059. retract_feedrate = code_value()/60 ;
  3060. }
  3061. if(code_seen('Z'))
  3062. {
  3063. retract_zlift = code_value() ;
  3064. }
  3065. }break;
  3066. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  3067. {
  3068. if(code_seen('S'))
  3069. {
  3070. retract_recover_length = code_value() ;
  3071. }
  3072. if(code_seen('F'))
  3073. {
  3074. retract_recover_feedrate = code_value()/60 ;
  3075. }
  3076. }break;
  3077. 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.
  3078. {
  3079. if(code_seen('S'))
  3080. {
  3081. int t= code_value() ;
  3082. switch(t)
  3083. {
  3084. case 0:
  3085. {
  3086. autoretract_enabled=false;
  3087. retracted[0]=false;
  3088. #if EXTRUDERS > 1
  3089. retracted[1]=false;
  3090. #endif
  3091. #if EXTRUDERS > 2
  3092. retracted[2]=false;
  3093. #endif
  3094. }break;
  3095. case 1:
  3096. {
  3097. autoretract_enabled=true;
  3098. retracted[0]=false;
  3099. #if EXTRUDERS > 1
  3100. retracted[1]=false;
  3101. #endif
  3102. #if EXTRUDERS > 2
  3103. retracted[2]=false;
  3104. #endif
  3105. }break;
  3106. default:
  3107. SERIAL_ECHO_START;
  3108. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  3109. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  3110. SERIAL_ECHOLNPGM("\"");
  3111. }
  3112. }
  3113. }break;
  3114. #endif // FWRETRACT
  3115. #if EXTRUDERS > 1
  3116. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3117. {
  3118. if(setTargetedHotend(218)){
  3119. break;
  3120. }
  3121. if(code_seen('X'))
  3122. {
  3123. extruder_offset[X_AXIS][tmp_extruder] = code_value();
  3124. }
  3125. if(code_seen('Y'))
  3126. {
  3127. extruder_offset[Y_AXIS][tmp_extruder] = code_value();
  3128. }
  3129. #ifdef DUAL_X_CARRIAGE
  3130. if(code_seen('Z'))
  3131. {
  3132. extruder_offset[Z_AXIS][tmp_extruder] = code_value();
  3133. }
  3134. #endif
  3135. SERIAL_ECHO_START;
  3136. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  3137. for(tmp_extruder = 0; tmp_extruder < EXTRUDERS; tmp_extruder++)
  3138. {
  3139. SERIAL_ECHO(" ");
  3140. SERIAL_ECHO(extruder_offset[X_AXIS][tmp_extruder]);
  3141. SERIAL_ECHO(",");
  3142. SERIAL_ECHO(extruder_offset[Y_AXIS][tmp_extruder]);
  3143. #ifdef DUAL_X_CARRIAGE
  3144. SERIAL_ECHO(",");
  3145. SERIAL_ECHO(extruder_offset[Z_AXIS][tmp_extruder]);
  3146. #endif
  3147. }
  3148. SERIAL_ECHOLN("");
  3149. }break;
  3150. #endif
  3151. case 220: // M220 S<factor in percent>- set speed factor override percentage
  3152. {
  3153. if(code_seen('S'))
  3154. {
  3155. feedmultiply = code_value() ;
  3156. }
  3157. }
  3158. break;
  3159. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  3160. {
  3161. if(code_seen('S'))
  3162. {
  3163. int tmp_code = code_value();
  3164. if (code_seen('T'))
  3165. {
  3166. if(setTargetedHotend(221)){
  3167. break;
  3168. }
  3169. extruder_multiply[tmp_extruder] = tmp_code;
  3170. }
  3171. else
  3172. {
  3173. extrudemultiply = tmp_code ;
  3174. }
  3175. }
  3176. }
  3177. break;
  3178. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3179. {
  3180. if(code_seen('P')){
  3181. int pin_number = code_value(); // pin number
  3182. int pin_state = -1; // required pin state - default is inverted
  3183. if(code_seen('S')) pin_state = code_value(); // required pin state
  3184. if(pin_state >= -1 && pin_state <= 1){
  3185. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  3186. {
  3187. if (sensitive_pins[i] == pin_number)
  3188. {
  3189. pin_number = -1;
  3190. break;
  3191. }
  3192. }
  3193. if (pin_number > -1)
  3194. {
  3195. int target = LOW;
  3196. st_synchronize();
  3197. pinMode(pin_number, INPUT);
  3198. switch(pin_state){
  3199. case 1:
  3200. target = HIGH;
  3201. break;
  3202. case 0:
  3203. target = LOW;
  3204. break;
  3205. case -1:
  3206. target = !digitalRead(pin_number);
  3207. break;
  3208. }
  3209. while(digitalRead(pin_number) != target){
  3210. manage_heater();
  3211. manage_inactivity();
  3212. lcd_update();
  3213. }
  3214. }
  3215. }
  3216. }
  3217. }
  3218. break;
  3219. #if NUM_SERVOS > 0
  3220. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3221. {
  3222. int servo_index = -1;
  3223. int servo_position = 0;
  3224. if (code_seen('P'))
  3225. servo_index = code_value();
  3226. if (code_seen('S')) {
  3227. servo_position = code_value();
  3228. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  3229. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  3230. servos[servo_index].attach(0);
  3231. #endif
  3232. servos[servo_index].write(servo_position);
  3233. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  3234. delay(PROBE_SERVO_DEACTIVATION_DELAY);
  3235. servos[servo_index].detach();
  3236. #endif
  3237. }
  3238. else {
  3239. SERIAL_ECHO_START;
  3240. SERIAL_ECHO("Servo ");
  3241. SERIAL_ECHO(servo_index);
  3242. SERIAL_ECHOLN(" out of range");
  3243. }
  3244. }
  3245. else if (servo_index >= 0) {
  3246. SERIAL_PROTOCOL(MSG_OK);
  3247. SERIAL_PROTOCOL(" Servo ");
  3248. SERIAL_PROTOCOL(servo_index);
  3249. SERIAL_PROTOCOL(": ");
  3250. SERIAL_PROTOCOL(servos[servo_index].read());
  3251. SERIAL_PROTOCOLLN("");
  3252. }
  3253. }
  3254. break;
  3255. #endif // NUM_SERVOS > 0
  3256. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  3257. case 300: // M300
  3258. {
  3259. int beepS = code_seen('S') ? code_value() : 110;
  3260. int beepP = code_seen('P') ? code_value() : 1000;
  3261. if (beepS > 0)
  3262. {
  3263. #if BEEPER > 0
  3264. tone(BEEPER, beepS);
  3265. delay(beepP);
  3266. noTone(BEEPER);
  3267. #elif defined(ULTRALCD)
  3268. lcd_buzz(beepS, beepP);
  3269. #elif defined(LCD_USE_I2C_BUZZER)
  3270. lcd_buzz(beepP, beepS);
  3271. #endif
  3272. }
  3273. else
  3274. {
  3275. delay(beepP);
  3276. }
  3277. }
  3278. break;
  3279. #endif // M300
  3280. #ifdef PIDTEMP
  3281. case 301: // M301
  3282. {
  3283. if(code_seen('P')) Kp = code_value();
  3284. if(code_seen('I')) Ki = scalePID_i(code_value());
  3285. if(code_seen('D')) Kd = scalePID_d(code_value());
  3286. #ifdef PID_ADD_EXTRUSION_RATE
  3287. if(code_seen('C')) Kc = code_value();
  3288. #endif
  3289. updatePID();
  3290. SERIAL_PROTOCOL(MSG_OK);
  3291. SERIAL_PROTOCOL(" p:");
  3292. SERIAL_PROTOCOL(Kp);
  3293. SERIAL_PROTOCOL(" i:");
  3294. SERIAL_PROTOCOL(unscalePID_i(Ki));
  3295. SERIAL_PROTOCOL(" d:");
  3296. SERIAL_PROTOCOL(unscalePID_d(Kd));
  3297. #ifdef PID_ADD_EXTRUSION_RATE
  3298. SERIAL_PROTOCOL(" c:");
  3299. //Kc does not have scaling applied above, or in resetting defaults
  3300. SERIAL_PROTOCOL(Kc);
  3301. #endif
  3302. SERIAL_PROTOCOLLN("");
  3303. }
  3304. break;
  3305. #endif //PIDTEMP
  3306. #ifdef PIDTEMPBED
  3307. case 304: // M304
  3308. {
  3309. if(code_seen('P')) bedKp = code_value();
  3310. if(code_seen('I')) bedKi = scalePID_i(code_value());
  3311. if(code_seen('D')) bedKd = scalePID_d(code_value());
  3312. updatePID();
  3313. SERIAL_PROTOCOL(MSG_OK);
  3314. SERIAL_PROTOCOL(" p:");
  3315. SERIAL_PROTOCOL(bedKp);
  3316. SERIAL_PROTOCOL(" i:");
  3317. SERIAL_PROTOCOL(unscalePID_i(bedKi));
  3318. SERIAL_PROTOCOL(" d:");
  3319. SERIAL_PROTOCOL(unscalePID_d(bedKd));
  3320. SERIAL_PROTOCOLLN("");
  3321. }
  3322. break;
  3323. #endif //PIDTEMP
  3324. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  3325. {
  3326. #ifdef CHDK
  3327. SET_OUTPUT(CHDK);
  3328. WRITE(CHDK, HIGH);
  3329. chdkHigh = millis();
  3330. chdkActive = true;
  3331. #else
  3332. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  3333. const uint8_t NUM_PULSES=16;
  3334. const float PULSE_LENGTH=0.01524;
  3335. for(int i=0; i < NUM_PULSES; i++) {
  3336. WRITE(PHOTOGRAPH_PIN, HIGH);
  3337. _delay_ms(PULSE_LENGTH);
  3338. WRITE(PHOTOGRAPH_PIN, LOW);
  3339. _delay_ms(PULSE_LENGTH);
  3340. }
  3341. delay(7.33);
  3342. for(int i=0; i < NUM_PULSES; i++) {
  3343. WRITE(PHOTOGRAPH_PIN, HIGH);
  3344. _delay_ms(PULSE_LENGTH);
  3345. WRITE(PHOTOGRAPH_PIN, LOW);
  3346. _delay_ms(PULSE_LENGTH);
  3347. }
  3348. #endif
  3349. #endif //chdk end if
  3350. }
  3351. break;
  3352. #ifdef DOGLCD
  3353. case 250: // M250 Set LCD contrast value: C<value> (value 0..63)
  3354. {
  3355. if (code_seen('C')) {
  3356. lcd_setcontrast( ((int)code_value())&63 );
  3357. }
  3358. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  3359. SERIAL_PROTOCOL(lcd_contrast);
  3360. SERIAL_PROTOCOLLN("");
  3361. }
  3362. break;
  3363. #endif
  3364. #ifdef PREVENT_DANGEROUS_EXTRUDE
  3365. case 302: // allow cold extrudes, or set the minimum extrude temperature
  3366. {
  3367. float temp = .0;
  3368. if (code_seen('S')) temp=code_value();
  3369. set_extrude_min_temp(temp);
  3370. }
  3371. break;
  3372. #endif
  3373. case 303: // M303 PID autotune
  3374. {
  3375. float temp = 150.0;
  3376. int e=0;
  3377. int c=5;
  3378. if (code_seen('E')) e=code_value();
  3379. if (e<0)
  3380. temp=70;
  3381. if (code_seen('S')) temp=code_value();
  3382. if (code_seen('C')) c=code_value();
  3383. PID_autotune(temp, e, c);
  3384. }
  3385. break;
  3386. case 400: // M400 finish all moves
  3387. {
  3388. st_synchronize();
  3389. }
  3390. break;
  3391. #ifdef FILAMENT_SENSOR
  3392. case 404: //M404 Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  3393. {
  3394. #if (FILWIDTH_PIN > -1)
  3395. if(code_seen('N')) filament_width_nominal=code_value();
  3396. else{
  3397. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  3398. SERIAL_PROTOCOLLN(filament_width_nominal);
  3399. }
  3400. #endif
  3401. }
  3402. break;
  3403. case 405: //M405 Turn on filament sensor for control
  3404. {
  3405. if(code_seen('D')) meas_delay_cm=code_value();
  3406. if(meas_delay_cm> MAX_MEASUREMENT_DELAY)
  3407. meas_delay_cm = MAX_MEASUREMENT_DELAY;
  3408. if(delay_index2 == -1) //initialize the ring buffer if it has not been done since startup
  3409. {
  3410. int temp_ratio = widthFil_to_size_ratio();
  3411. for (delay_index1=0; delay_index1<(MAX_MEASUREMENT_DELAY+1); ++delay_index1 ){
  3412. measurement_delay[delay_index1]=temp_ratio-100; //subtract 100 to scale within a signed byte
  3413. }
  3414. delay_index1=0;
  3415. delay_index2=0;
  3416. }
  3417. filament_sensor = true ;
  3418. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  3419. //SERIAL_PROTOCOL(filament_width_meas);
  3420. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  3421. //SERIAL_PROTOCOL(extrudemultiply);
  3422. }
  3423. break;
  3424. case 406: //M406 Turn off filament sensor for control
  3425. {
  3426. filament_sensor = false ;
  3427. }
  3428. break;
  3429. case 407: //M407 Display measured filament diameter
  3430. {
  3431. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  3432. SERIAL_PROTOCOLLN(filament_width_meas);
  3433. }
  3434. break;
  3435. #endif
  3436. case 500: // M500 Store settings in EEPROM
  3437. {
  3438. Config_StoreSettings();
  3439. }
  3440. break;
  3441. case 501: // M501 Read settings from EEPROM
  3442. {
  3443. Config_RetrieveSettings();
  3444. }
  3445. break;
  3446. case 502: // M502 Revert to default settings
  3447. {
  3448. Config_ResetDefault();
  3449. }
  3450. break;
  3451. case 503: // M503 print settings currently in memory
  3452. {
  3453. Config_PrintSettings();
  3454. }
  3455. break;
  3456. case 509: //M509 Force language selection
  3457. {
  3458. lcd_force_language_selection();
  3459. SERIAL_ECHO_START;
  3460. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  3461. }
  3462. break;
  3463. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  3464. case 540:
  3465. {
  3466. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  3467. }
  3468. break;
  3469. #endif
  3470. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  3471. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  3472. {
  3473. float value;
  3474. if (code_seen('Z'))
  3475. {
  3476. value = code_value();
  3477. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  3478. {
  3479. zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  3480. SERIAL_ECHO_START;
  3481. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  3482. SERIAL_PROTOCOLLN("");
  3483. }
  3484. else
  3485. {
  3486. SERIAL_ECHO_START;
  3487. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  3488. SERIAL_ECHORPGM(MSG_Z_MIN);
  3489. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  3490. SERIAL_ECHORPGM(MSG_Z_MAX);
  3491. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  3492. SERIAL_PROTOCOLLN("");
  3493. }
  3494. }
  3495. else
  3496. {
  3497. SERIAL_ECHO_START;
  3498. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  3499. SERIAL_ECHO(-zprobe_zoffset);
  3500. SERIAL_PROTOCOLLN("");
  3501. }
  3502. break;
  3503. }
  3504. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  3505. #ifdef FILAMENTCHANGEENABLE
  3506. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3507. {
  3508. st_synchronize();
  3509. feedmultiplyBckp=feedmultiply;
  3510. int8_t TooLowZ = 0;
  3511. float target[4];
  3512. float lastpos[4];
  3513. target[X_AXIS]=current_position[X_AXIS];
  3514. target[Y_AXIS]=current_position[Y_AXIS];
  3515. target[Z_AXIS]=current_position[Z_AXIS];
  3516. target[E_AXIS]=current_position[E_AXIS];
  3517. lastpos[X_AXIS]=current_position[X_AXIS];
  3518. lastpos[Y_AXIS]=current_position[Y_AXIS];
  3519. lastpos[Z_AXIS]=current_position[Z_AXIS];
  3520. lastpos[E_AXIS]=current_position[E_AXIS];
  3521. //Restract extruder
  3522. if(code_seen('E'))
  3523. {
  3524. target[E_AXIS]+= code_value();
  3525. }
  3526. else
  3527. {
  3528. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  3529. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT ;
  3530. #endif
  3531. }
  3532. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  3533. //Lift Z
  3534. if(code_seen('Z'))
  3535. {
  3536. target[Z_AXIS]+= code_value();
  3537. }
  3538. else
  3539. {
  3540. #ifdef FILAMENTCHANGE_ZADD
  3541. target[Z_AXIS]+= FILAMENTCHANGE_ZADD ;
  3542. if(target[Z_AXIS] < 10){
  3543. target[Z_AXIS]+= 10 ;
  3544. TooLowZ = 1;
  3545. }else{
  3546. TooLowZ = 0;
  3547. }
  3548. #endif
  3549. }
  3550. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  3551. //Move XY to side
  3552. if(code_seen('X'))
  3553. {
  3554. target[X_AXIS]+= code_value();
  3555. }
  3556. else
  3557. {
  3558. #ifdef FILAMENTCHANGE_XPOS
  3559. target[X_AXIS]= FILAMENTCHANGE_XPOS ;
  3560. #endif
  3561. }
  3562. if(code_seen('Y'))
  3563. {
  3564. target[Y_AXIS]= code_value();
  3565. }
  3566. else
  3567. {
  3568. #ifdef FILAMENTCHANGE_YPOS
  3569. target[Y_AXIS]= FILAMENTCHANGE_YPOS ;
  3570. #endif
  3571. }
  3572. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  3573. // Unload filament
  3574. if(code_seen('L'))
  3575. {
  3576. target[E_AXIS]+= code_value();
  3577. }
  3578. else
  3579. {
  3580. #ifdef FILAMENTCHANGE_FINALRETRACT
  3581. target[E_AXIS]+= FILAMENTCHANGE_FINALRETRACT ;
  3582. #endif
  3583. }
  3584. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  3585. //finish moves
  3586. st_synchronize();
  3587. //disable extruder steppers so filament can be removed
  3588. disable_e0();
  3589. disable_e1();
  3590. disable_e2();
  3591. delay(100);
  3592. //Wait for user to insert filament
  3593. uint8_t cnt=0;
  3594. int counterBeep = 0;
  3595. lcd_wait_interact();
  3596. while(!lcd_clicked()){
  3597. cnt++;
  3598. manage_heater();
  3599. manage_inactivity(true);
  3600. if(cnt==0)
  3601. {
  3602. #if BEEPER > 0
  3603. if (counterBeep== 500){
  3604. counterBeep = 0;
  3605. }
  3606. SET_OUTPUT(BEEPER);
  3607. if (counterBeep== 0){
  3608. WRITE(BEEPER,HIGH);
  3609. }
  3610. if (counterBeep== 20){
  3611. WRITE(BEEPER,LOW);
  3612. }
  3613. counterBeep++;
  3614. #else
  3615. #if !defined(LCD_FEEDBACK_FREQUENCY_HZ) || !defined(LCD_FEEDBACK_FREQUENCY_DURATION_MS)
  3616. lcd_buzz(1000/6,100);
  3617. #else
  3618. lcd_buzz(LCD_FEEDBACK_FREQUENCY_DURATION_MS,LCD_FEEDBACK_FREQUENCY_HZ);
  3619. #endif
  3620. #endif
  3621. }
  3622. }
  3623. //Filament inserted
  3624. WRITE(BEEPER,LOW);
  3625. //Feed the filament to the end of nozzle quickly
  3626. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3627. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EFEED, active_extruder);
  3628. //Extrude some filament
  3629. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3630. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EXFEED, active_extruder);
  3631. //Wait for user to check the state
  3632. lcd_change_fil_state = 0;
  3633. lcd_loading_filament();
  3634. while ((lcd_change_fil_state == 0)||(lcd_change_fil_state != 1)){
  3635. lcd_change_fil_state = 0;
  3636. lcd_alright();
  3637. switch(lcd_change_fil_state){
  3638. // Filament failed to load so load it again
  3639. case 2:
  3640. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3641. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EFEED, active_extruder);
  3642. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3643. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EXFEED, active_extruder);
  3644. lcd_loading_filament();
  3645. break;
  3646. // Filament loaded properly but color is not clear
  3647. case 3:
  3648. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3649. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3650. lcd_loading_color();
  3651. break;
  3652. // Everything good
  3653. default:
  3654. lcd_change_success();
  3655. break;
  3656. }
  3657. }
  3658. //Not let's go back to print
  3659. //Feed a little of filament to stabilize pressure
  3660. target[E_AXIS]+= FILAMENTCHANGE_RECFEED;
  3661. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EXFEED, active_extruder);
  3662. //Retract
  3663. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT;
  3664. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  3665. //plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //should do nothing
  3666. //Move XY back
  3667. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  3668. //Move Z back
  3669. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  3670. target[E_AXIS]= target[E_AXIS] - FILAMENTCHANGE_FIRSTRETRACT;
  3671. //Unretract
  3672. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  3673. //Set E position to original
  3674. plan_set_e_position(lastpos[E_AXIS]);
  3675. //Recover feed rate
  3676. feedmultiply=feedmultiplyBckp;
  3677. char cmd[9];
  3678. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3679. enquecommand(cmd);
  3680. }
  3681. break;
  3682. #endif //FILAMENTCHANGEENABLE
  3683. #ifdef DUAL_X_CARRIAGE
  3684. case 605: // Set dual x-carriage movement mode:
  3685. // M605 S0: Full control mode. The slicer has full control over x-carriage movement
  3686. // M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  3687. // M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  3688. // millimeters x-offset and an optional differential hotend temperature of
  3689. // mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  3690. // the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  3691. //
  3692. // Note: the X axis should be homed after changing dual x-carriage mode.
  3693. {
  3694. st_synchronize();
  3695. if (code_seen('S'))
  3696. dual_x_carriage_mode = code_value();
  3697. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE)
  3698. {
  3699. if (code_seen('X'))
  3700. duplicate_extruder_x_offset = max(code_value(),X2_MIN_POS - x_home_pos(0));
  3701. if (code_seen('R'))
  3702. duplicate_extruder_temp_offset = code_value();
  3703. SERIAL_ECHO_START;
  3704. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  3705. SERIAL_ECHO(" ");
  3706. SERIAL_ECHO(extruder_offset[X_AXIS][0]);
  3707. SERIAL_ECHO(",");
  3708. SERIAL_ECHO(extruder_offset[Y_AXIS][0]);
  3709. SERIAL_ECHO(" ");
  3710. SERIAL_ECHO(duplicate_extruder_x_offset);
  3711. SERIAL_ECHO(",");
  3712. SERIAL_ECHOLN(extruder_offset[Y_AXIS][1]);
  3713. }
  3714. else if (dual_x_carriage_mode != DXC_FULL_CONTROL_MODE && dual_x_carriage_mode != DXC_AUTO_PARK_MODE)
  3715. {
  3716. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  3717. }
  3718. active_extruder_parked = false;
  3719. extruder_duplication_enabled = false;
  3720. delayed_move_time = 0;
  3721. }
  3722. break;
  3723. #endif //DUAL_X_CARRIAGE
  3724. case 907: // M907 Set digital trimpot motor current using axis codes.
  3725. {
  3726. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  3727. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) digipot_current(i,code_value());
  3728. if(code_seen('B')) digipot_current(4,code_value());
  3729. if(code_seen('S')) for(int i=0;i<=4;i++) digipot_current(i,code_value());
  3730. #endif
  3731. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  3732. if(code_seen('X')) digipot_current(0, code_value());
  3733. #endif
  3734. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  3735. if(code_seen('Z')) digipot_current(1, code_value());
  3736. #endif
  3737. #ifdef MOTOR_CURRENT_PWM_E_PIN
  3738. if(code_seen('E')) digipot_current(2, code_value());
  3739. #endif
  3740. #ifdef DIGIPOT_I2C
  3741. // this one uses actual amps in floating point
  3742. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) digipot_i2c_set_current(i, code_value());
  3743. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  3744. 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());
  3745. #endif
  3746. }
  3747. break;
  3748. case 908: // M908 Control digital trimpot directly.
  3749. {
  3750. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  3751. uint8_t channel,current;
  3752. if(code_seen('P')) channel=code_value();
  3753. if(code_seen('S')) current=code_value();
  3754. digitalPotWrite(channel, current);
  3755. #endif
  3756. }
  3757. break;
  3758. case 350: // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  3759. {
  3760. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  3761. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  3762. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  3763. if(code_seen('B')) microstep_mode(4,code_value());
  3764. microstep_readings();
  3765. #endif
  3766. }
  3767. break;
  3768. case 351: // M351 Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  3769. {
  3770. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  3771. if(code_seen('S')) switch((int)code_value())
  3772. {
  3773. case 1:
  3774. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  3775. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  3776. break;
  3777. case 2:
  3778. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  3779. if(code_seen('B')) microstep_ms(4,-1,code_value());
  3780. break;
  3781. }
  3782. microstep_readings();
  3783. #endif
  3784. }
  3785. break;
  3786. case 999: // M999: Restart after being stopped
  3787. Stopped = false;
  3788. lcd_reset_alert_level();
  3789. gcode_LastN = Stopped_gcode_LastN;
  3790. FlushSerialRequestResend();
  3791. break;
  3792. }
  3793. } // end if(code_seen('M')) (end of M codes)
  3794. else if(code_seen('T'))
  3795. {
  3796. tmp_extruder = code_value();
  3797. if(tmp_extruder >= EXTRUDERS) {
  3798. SERIAL_ECHO_START;
  3799. SERIAL_ECHO("T");
  3800. SERIAL_ECHO(tmp_extruder);
  3801. SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
  3802. }
  3803. else {
  3804. boolean make_move = false;
  3805. if(code_seen('F')) {
  3806. make_move = true;
  3807. next_feedrate = code_value();
  3808. if(next_feedrate > 0.0) {
  3809. feedrate = next_feedrate;
  3810. }
  3811. }
  3812. #if EXTRUDERS > 1
  3813. if(tmp_extruder != active_extruder) {
  3814. // Save current position to return to after applying extruder offset
  3815. memcpy(destination, current_position, sizeof(destination));
  3816. #ifdef DUAL_X_CARRIAGE
  3817. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE && Stopped == false &&
  3818. (delayed_move_time != 0 || current_position[X_AXIS] != x_home_pos(active_extruder)))
  3819. {
  3820. // Park old head: 1) raise 2) move to park position 3) lower
  3821. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT,
  3822. current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  3823. plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT,
  3824. current_position[E_AXIS], max_feedrate[X_AXIS], active_extruder);
  3825. plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS],
  3826. current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  3827. st_synchronize();
  3828. }
  3829. // apply Y & Z extruder offset (x offset is already used in determining home pos)
  3830. current_position[Y_AXIS] = current_position[Y_AXIS] -
  3831. extruder_offset[Y_AXIS][active_extruder] +
  3832. extruder_offset[Y_AXIS][tmp_extruder];
  3833. current_position[Z_AXIS] = current_position[Z_AXIS] -
  3834. extruder_offset[Z_AXIS][active_extruder] +
  3835. extruder_offset[Z_AXIS][tmp_extruder];
  3836. active_extruder = tmp_extruder;
  3837. // This function resets the max/min values - the current position may be overwritten below.
  3838. axis_is_at_home(X_AXIS);
  3839. if (dual_x_carriage_mode == DXC_FULL_CONTROL_MODE)
  3840. {
  3841. current_position[X_AXIS] = inactive_extruder_x_pos;
  3842. inactive_extruder_x_pos = destination[X_AXIS];
  3843. }
  3844. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE)
  3845. {
  3846. active_extruder_parked = (active_extruder == 0); // this triggers the second extruder to move into the duplication position
  3847. if (active_extruder == 0 || active_extruder_parked)
  3848. current_position[X_AXIS] = inactive_extruder_x_pos;
  3849. else
  3850. current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset;
  3851. inactive_extruder_x_pos = destination[X_AXIS];
  3852. extruder_duplication_enabled = false;
  3853. }
  3854. else
  3855. {
  3856. // record raised toolhead position for use by unpark
  3857. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  3858. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  3859. active_extruder_parked = true;
  3860. delayed_move_time = 0;
  3861. }
  3862. #else
  3863. // Offset extruder (only by XY)
  3864. int i;
  3865. for(i = 0; i < 2; i++) {
  3866. current_position[i] = current_position[i] -
  3867. extruder_offset[i][active_extruder] +
  3868. extruder_offset[i][tmp_extruder];
  3869. }
  3870. // Set the new active extruder and position
  3871. active_extruder = tmp_extruder;
  3872. #endif //else DUAL_X_CARRIAGE
  3873. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  3874. // Move to the old position if 'F' was in the parameters
  3875. if(make_move && Stopped == false) {
  3876. prepare_move();
  3877. }
  3878. }
  3879. #endif
  3880. SERIAL_ECHO_START;
  3881. SERIAL_ECHO(MSG_ACTIVE_EXTRUDER);
  3882. SERIAL_PROTOCOLLN((int)active_extruder);
  3883. }
  3884. } // end if(code_seen('T')) (end of T codes)
  3885. else
  3886. {
  3887. SERIAL_ECHO_START;
  3888. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  3889. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  3890. SERIAL_ECHOLNPGM("\"");
  3891. }
  3892. ClearToSend();
  3893. }
  3894. void FlushSerialRequestResend()
  3895. {
  3896. //char cmdbuffer[bufindr][100]="Resend:";
  3897. MYSERIAL.flush();
  3898. SERIAL_PROTOCOLRPGM(MSG_RESEND);
  3899. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  3900. ClearToSend();
  3901. }
  3902. // Confirm the execution of a command, if sent from a serial line.
  3903. // Execution of a command from a SD card will not be confirmed.
  3904. void ClearToSend()
  3905. {
  3906. previous_millis_cmd = millis();
  3907. if (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB)
  3908. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  3909. }
  3910. void get_coordinates()
  3911. {
  3912. bool seen[4]={false,false,false,false};
  3913. for(int8_t i=0; i < NUM_AXIS; i++) {
  3914. if(code_seen(axis_codes[i]))
  3915. {
  3916. destination[i] = (float)code_value() + (axis_relative_modes[i] || relative_mode)*current_position[i];
  3917. seen[i]=true;
  3918. }
  3919. else destination[i] = current_position[i]; //Are these else lines really needed?
  3920. }
  3921. if(code_seen('F')) {
  3922. next_feedrate = code_value();
  3923. if(next_feedrate > 0.0) feedrate = next_feedrate;
  3924. }
  3925. }
  3926. void get_arc_coordinates()
  3927. {
  3928. #ifdef SF_ARC_FIX
  3929. bool relative_mode_backup = relative_mode;
  3930. relative_mode = true;
  3931. #endif
  3932. get_coordinates();
  3933. #ifdef SF_ARC_FIX
  3934. relative_mode=relative_mode_backup;
  3935. #endif
  3936. if(code_seen('I')) {
  3937. offset[0] = code_value();
  3938. }
  3939. else {
  3940. offset[0] = 0.0;
  3941. }
  3942. if(code_seen('J')) {
  3943. offset[1] = code_value();
  3944. }
  3945. else {
  3946. offset[1] = 0.0;
  3947. }
  3948. }
  3949. void clamp_to_software_endstops(float target[3])
  3950. {
  3951. if (min_software_endstops) {
  3952. if (target[X_AXIS] < min_pos[X_AXIS]) target[X_AXIS] = min_pos[X_AXIS];
  3953. if (target[Y_AXIS] < min_pos[Y_AXIS]) target[Y_AXIS] = min_pos[Y_AXIS];
  3954. float negative_z_offset = 0;
  3955. #ifdef ENABLE_AUTO_BED_LEVELING
  3956. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  3957. if (add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + add_homing[Z_AXIS];
  3958. #endif
  3959. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  3960. }
  3961. if (max_software_endstops) {
  3962. if (target[X_AXIS] > max_pos[X_AXIS]) target[X_AXIS] = max_pos[X_AXIS];
  3963. if (target[Y_AXIS] > max_pos[Y_AXIS]) target[Y_AXIS] = max_pos[Y_AXIS];
  3964. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  3965. }
  3966. }
  3967. #ifdef MESH_BED_LEVELING
  3968. void mesh_plan_buffer_line(const float &x, const float &y, const float &z, const float &e, const float &feed_rate, const uint8_t extruder) {
  3969. float dx = x - current_position[X_AXIS];
  3970. float dy = y - current_position[Y_AXIS];
  3971. float dz = z - current_position[Z_AXIS];
  3972. int n_segments = 0;
  3973. if (mbl.active) {
  3974. float len = abs(dx) + abs(dy) + abs(dz);
  3975. if (len > 0)
  3976. n_segments = int(floor(len / 30.f));
  3977. }
  3978. if (n_segments > 1) {
  3979. float de = e - current_position[E_AXIS];
  3980. for (int i = 1; i < n_segments; ++ i) {
  3981. float t = float(i) / float(n_segments);
  3982. plan_buffer_line(
  3983. current_position[X_AXIS] + t * dx,
  3984. current_position[Y_AXIS] + t * dy,
  3985. current_position[Z_AXIS] + t * dz,
  3986. current_position[E_AXIS] + t * de,
  3987. feed_rate, extruder);
  3988. }
  3989. }
  3990. // The rest of the path.
  3991. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  3992. set_current_to_destination();
  3993. }
  3994. #endif // MESH_BED_LEVELING
  3995. void prepare_move()
  3996. {
  3997. clamp_to_software_endstops(destination);
  3998. previous_millis_cmd = millis();
  3999. #ifdef DUAL_X_CARRIAGE
  4000. if (active_extruder_parked)
  4001. {
  4002. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && active_extruder == 0)
  4003. {
  4004. // move duplicate extruder into correct duplication position.
  4005. plan_set_position(inactive_extruder_x_pos, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  4006. plan_buffer_line(current_position[X_AXIS] + duplicate_extruder_x_offset, current_position[Y_AXIS], current_position[Z_AXIS],
  4007. current_position[E_AXIS], max_feedrate[X_AXIS], 1);
  4008. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  4009. st_synchronize();
  4010. extruder_duplication_enabled = true;
  4011. active_extruder_parked = false;
  4012. }
  4013. else if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) // handle unparking of head
  4014. {
  4015. if (current_position[E_AXIS] == destination[E_AXIS])
  4016. {
  4017. // this is a travel move - skit it but keep track of current position (so that it can later
  4018. // be used as start of first non-travel move)
  4019. if (delayed_move_time != 0xFFFFFFFFUL)
  4020. {
  4021. memcpy(current_position, destination, sizeof(current_position));
  4022. if (destination[Z_AXIS] > raised_parked_position[Z_AXIS])
  4023. raised_parked_position[Z_AXIS] = destination[Z_AXIS];
  4024. delayed_move_time = millis();
  4025. return;
  4026. }
  4027. }
  4028. delayed_move_time = 0;
  4029. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  4030. 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);
  4031. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], raised_parked_position[Z_AXIS],
  4032. current_position[E_AXIS], min(max_feedrate[X_AXIS],max_feedrate[Y_AXIS]), active_extruder);
  4033. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  4034. current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  4035. active_extruder_parked = false;
  4036. }
  4037. }
  4038. #endif //DUAL_X_CARRIAGE
  4039. // Do not use feedmultiply for E or Z only moves
  4040. if( (current_position[X_AXIS] == destination [X_AXIS]) && (current_position[Y_AXIS] == destination [Y_AXIS])) {
  4041. #ifdef MESH_BED_LEVELING
  4042. mesh_plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  4043. #else
  4044. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  4045. #endif
  4046. }
  4047. else {
  4048. #ifdef MESH_BED_LEVELING
  4049. mesh_plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate*feedmultiply/60/100.0, active_extruder);
  4050. #else
  4051. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate*feedmultiply/60/100.0, active_extruder);
  4052. #endif
  4053. }
  4054. for(int8_t i=0; i < NUM_AXIS; i++) {
  4055. current_position[i] = destination[i];
  4056. }
  4057. }
  4058. void prepare_arc_move(char isclockwise) {
  4059. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  4060. // Trace the arc
  4061. mc_arc(current_position, destination, offset, X_AXIS, Y_AXIS, Z_AXIS, feedrate*feedmultiply/60/100.0, r, isclockwise, active_extruder);
  4062. // As far as the parser is concerned, the position is now == target. In reality the
  4063. // motion control system might still be processing the action and the real tool position
  4064. // in any intermediate location.
  4065. for(int8_t i=0; i < NUM_AXIS; i++) {
  4066. current_position[i] = destination[i];
  4067. }
  4068. previous_millis_cmd = millis();
  4069. }
  4070. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  4071. #if defined(FAN_PIN)
  4072. #if CONTROLLERFAN_PIN == FAN_PIN
  4073. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  4074. #endif
  4075. #endif
  4076. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  4077. unsigned long lastMotorCheck = 0;
  4078. void controllerFan()
  4079. {
  4080. if ((millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  4081. {
  4082. lastMotorCheck = millis();
  4083. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  4084. #if EXTRUDERS > 2
  4085. || !READ(E2_ENABLE_PIN)
  4086. #endif
  4087. #if EXTRUDER > 1
  4088. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  4089. || !READ(X2_ENABLE_PIN)
  4090. #endif
  4091. || !READ(E1_ENABLE_PIN)
  4092. #endif
  4093. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  4094. {
  4095. lastMotor = millis(); //... set time to NOW so the fan will turn on
  4096. }
  4097. if ((millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  4098. {
  4099. digitalWrite(CONTROLLERFAN_PIN, 0);
  4100. analogWrite(CONTROLLERFAN_PIN, 0);
  4101. }
  4102. else
  4103. {
  4104. // allows digital or PWM fan output to be used (see M42 handling)
  4105. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  4106. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  4107. }
  4108. }
  4109. }
  4110. #endif
  4111. #ifdef TEMP_STAT_LEDS
  4112. static bool blue_led = false;
  4113. static bool red_led = false;
  4114. static uint32_t stat_update = 0;
  4115. void handle_status_leds(void) {
  4116. float max_temp = 0.0;
  4117. if(millis() > stat_update) {
  4118. stat_update += 500; // Update every 0.5s
  4119. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  4120. max_temp = max(max_temp, degHotend(cur_extruder));
  4121. max_temp = max(max_temp, degTargetHotend(cur_extruder));
  4122. }
  4123. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  4124. max_temp = max(max_temp, degTargetBed());
  4125. max_temp = max(max_temp, degBed());
  4126. #endif
  4127. if((max_temp > 55.0) && (red_led == false)) {
  4128. digitalWrite(STAT_LED_RED, 1);
  4129. digitalWrite(STAT_LED_BLUE, 0);
  4130. red_led = true;
  4131. blue_led = false;
  4132. }
  4133. if((max_temp < 54.0) && (blue_led == false)) {
  4134. digitalWrite(STAT_LED_RED, 0);
  4135. digitalWrite(STAT_LED_BLUE, 1);
  4136. red_led = false;
  4137. blue_led = true;
  4138. }
  4139. }
  4140. }
  4141. #endif
  4142. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  4143. {
  4144. #if defined(KILL_PIN) && KILL_PIN > -1
  4145. static int killCount = 0; // make the inactivity button a bit less responsive
  4146. const int KILL_DELAY = 10000;
  4147. #endif
  4148. if(buflen < (BUFSIZE-1))
  4149. get_command();
  4150. if( (millis() - previous_millis_cmd) > max_inactive_time )
  4151. if(max_inactive_time)
  4152. kill();
  4153. if(stepper_inactive_time) {
  4154. if( (millis() - previous_millis_cmd) > stepper_inactive_time )
  4155. {
  4156. if(blocks_queued() == false && ignore_stepper_queue == false) {
  4157. disable_x();
  4158. disable_y();
  4159. disable_z();
  4160. disable_e0();
  4161. disable_e1();
  4162. disable_e2();
  4163. }
  4164. }
  4165. }
  4166. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  4167. if (chdkActive && (millis() - chdkHigh > CHDK_DELAY))
  4168. {
  4169. chdkActive = false;
  4170. WRITE(CHDK, LOW);
  4171. }
  4172. #endif
  4173. #if defined(KILL_PIN) && KILL_PIN > -1
  4174. // Check if the kill button was pressed and wait just in case it was an accidental
  4175. // key kill key press
  4176. // -------------------------------------------------------------------------------
  4177. if( 0 == READ(KILL_PIN) )
  4178. {
  4179. killCount++;
  4180. }
  4181. else if (killCount > 0)
  4182. {
  4183. killCount--;
  4184. }
  4185. // Exceeded threshold and we can confirm that it was not accidental
  4186. // KILL the machine
  4187. // ----------------------------------------------------------------
  4188. if ( killCount >= KILL_DELAY)
  4189. {
  4190. kill();
  4191. }
  4192. #endif
  4193. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  4194. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  4195. #endif
  4196. #ifdef EXTRUDER_RUNOUT_PREVENT
  4197. if( (millis() - previous_millis_cmd) > EXTRUDER_RUNOUT_SECONDS*1000 )
  4198. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  4199. {
  4200. bool oldstatus=READ(E0_ENABLE_PIN);
  4201. enable_e0();
  4202. float oldepos=current_position[E_AXIS];
  4203. float oldedes=destination[E_AXIS];
  4204. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  4205. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/axis_steps_per_unit[E_AXIS],
  4206. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/axis_steps_per_unit[E_AXIS], active_extruder);
  4207. current_position[E_AXIS]=oldepos;
  4208. destination[E_AXIS]=oldedes;
  4209. plan_set_e_position(oldepos);
  4210. previous_millis_cmd=millis();
  4211. st_synchronize();
  4212. WRITE(E0_ENABLE_PIN,oldstatus);
  4213. }
  4214. #endif
  4215. #if defined(DUAL_X_CARRIAGE)
  4216. // handle delayed move timeout
  4217. if (delayed_move_time != 0 && (millis() - delayed_move_time) > 1000 && Stopped == false)
  4218. {
  4219. // travel moves have been received so enact them
  4220. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  4221. memcpy(destination,current_position,sizeof(destination));
  4222. prepare_move();
  4223. }
  4224. #endif
  4225. #ifdef TEMP_STAT_LEDS
  4226. handle_status_leds();
  4227. #endif
  4228. check_axes_activity();
  4229. }
  4230. void kill()
  4231. {
  4232. cli(); // Stop interrupts
  4233. disable_heater();
  4234. disable_x();
  4235. disable_y();
  4236. disable_z();
  4237. disable_e0();
  4238. disable_e1();
  4239. disable_e2();
  4240. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  4241. pinMode(PS_ON_PIN,INPUT);
  4242. #endif
  4243. SERIAL_ERROR_START;
  4244. SERIAL_ERRORLNRPGM(MSG_ERR_KILLED);
  4245. LCD_ALERTMESSAGERPGM(MSG_KILLED);
  4246. // FMC small patch to update the LCD before ending
  4247. sei(); // enable interrupts
  4248. for ( int i=5; i--; lcd_update())
  4249. {
  4250. delay(200);
  4251. }
  4252. cli(); // disable interrupts
  4253. suicide();
  4254. while(1) { /* Intentionally left empty */ } // Wait for reset
  4255. }
  4256. void Stop()
  4257. {
  4258. disable_heater();
  4259. if(Stopped == false) {
  4260. Stopped = true;
  4261. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  4262. SERIAL_ERROR_START;
  4263. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  4264. LCD_MESSAGERPGM(MSG_STOPPED);
  4265. }
  4266. }
  4267. bool IsStopped() { return Stopped; };
  4268. #ifdef FAST_PWM_FAN
  4269. void setPwmFrequency(uint8_t pin, int val)
  4270. {
  4271. val &= 0x07;
  4272. switch(digitalPinToTimer(pin))
  4273. {
  4274. #if defined(TCCR0A)
  4275. case TIMER0A:
  4276. case TIMER0B:
  4277. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  4278. // TCCR0B |= val;
  4279. break;
  4280. #endif
  4281. #if defined(TCCR1A)
  4282. case TIMER1A:
  4283. case TIMER1B:
  4284. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  4285. // TCCR1B |= val;
  4286. break;
  4287. #endif
  4288. #if defined(TCCR2)
  4289. case TIMER2:
  4290. case TIMER2:
  4291. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  4292. TCCR2 |= val;
  4293. break;
  4294. #endif
  4295. #if defined(TCCR2A)
  4296. case TIMER2A:
  4297. case TIMER2B:
  4298. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  4299. TCCR2B |= val;
  4300. break;
  4301. #endif
  4302. #if defined(TCCR3A)
  4303. case TIMER3A:
  4304. case TIMER3B:
  4305. case TIMER3C:
  4306. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  4307. TCCR3B |= val;
  4308. break;
  4309. #endif
  4310. #if defined(TCCR4A)
  4311. case TIMER4A:
  4312. case TIMER4B:
  4313. case TIMER4C:
  4314. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  4315. TCCR4B |= val;
  4316. break;
  4317. #endif
  4318. #if defined(TCCR5A)
  4319. case TIMER5A:
  4320. case TIMER5B:
  4321. case TIMER5C:
  4322. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  4323. TCCR5B |= val;
  4324. break;
  4325. #endif
  4326. }
  4327. }
  4328. #endif //FAST_PWM_FAN
  4329. bool setTargetedHotend(int code){
  4330. tmp_extruder = active_extruder;
  4331. if(code_seen('T')) {
  4332. tmp_extruder = code_value();
  4333. if(tmp_extruder >= EXTRUDERS) {
  4334. SERIAL_ECHO_START;
  4335. switch(code){
  4336. case 104:
  4337. SERIAL_ECHO(MSG_M104_INVALID_EXTRUDER);
  4338. break;
  4339. case 105:
  4340. SERIAL_ECHO(MSG_M105_INVALID_EXTRUDER);
  4341. break;
  4342. case 109:
  4343. SERIAL_ECHO(MSG_M109_INVALID_EXTRUDER);
  4344. break;
  4345. case 218:
  4346. SERIAL_ECHO(MSG_M218_INVALID_EXTRUDER);
  4347. break;
  4348. case 221:
  4349. SERIAL_ECHO(MSG_M221_INVALID_EXTRUDER);
  4350. break;
  4351. }
  4352. SERIAL_ECHOLN(tmp_extruder);
  4353. return true;
  4354. }
  4355. }
  4356. return false;
  4357. }
  4358. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time)
  4359. {
  4360. if (eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME) == 255 && eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME + 1) == 255 && eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME + 2) == 255 && eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME + 3) == 255)
  4361. {
  4362. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  4363. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  4364. }
  4365. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED);
  4366. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME);
  4367. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60));
  4368. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  4369. total_filament_used = 0;
  4370. }
  4371. float calculate_volumetric_multiplier(float diameter) {
  4372. float area = .0;
  4373. float radius = .0;
  4374. radius = diameter * .5;
  4375. if (! volumetric_enabled || radius == 0) {
  4376. area = 1;
  4377. }
  4378. else {
  4379. area = M_PI * pow(radius, 2);
  4380. }
  4381. return 1.0 / area;
  4382. }
  4383. void calculate_volumetric_multipliers() {
  4384. volumetric_multiplier[0] = calculate_volumetric_multiplier(filament_size[0]);
  4385. #if EXTRUDERS > 1
  4386. volumetric_multiplier[1] = calculate_volumetric_multiplier(filament_size[1]);
  4387. #if EXTRUDERS > 2
  4388. volumetric_multiplier[2] = calculate_volumetric_multiplier(filament_size[2]);
  4389. #endif
  4390. #endif
  4391. }
  4392. void delay_keep_alive(int ms)
  4393. {
  4394. for (;;) {
  4395. manage_heater();
  4396. manage_inactivity();
  4397. lcd_update();
  4398. if (ms == 0)
  4399. break;
  4400. else if (ms >= 50) {
  4401. delay(50);
  4402. ms -= 50;
  4403. } else {
  4404. delay(ms);
  4405. ms = 0;
  4406. }
  4407. }
  4408. }