Marlin_main.cpp 172 KB

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