Marlin_main.cpp 210 KB

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