Marlin_main.cpp 215 KB

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