Marlin_main.cpp 199 KB

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