Marlin_main.cpp 210 KB

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