Marlin_main.cpp 354 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583
  1. /* -*- c++ -*- */
  2. /**
  3. * @file
  4. */
  5. /**
  6. * @mainpage Reprap 3D printer firmware based on Sprinter and grbl.
  7. *
  8. * @section intro_sec Introduction
  9. *
  10. * This firmware is a mashup between Sprinter and grbl.
  11. * https://github.com/kliment/Sprinter
  12. * https://github.com/simen/grbl/tree
  13. *
  14. * It has preliminary support for Matthew Roberts advance algorithm
  15. * http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
  16. *
  17. * Prusa Research s.r.o. https://www.prusa3d.cz
  18. *
  19. * @section copyright_sec Copyright
  20. *
  21. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  22. *
  23. * This program is free software: you can redistribute it and/or modify
  24. * it under the terms of the GNU General Public License as published by
  25. * the Free Software Foundation, either version 3 of the License, or
  26. * (at your option) any later version.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU General Public License
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  35. *
  36. * @section notes_sec Notes
  37. *
  38. * * Do not create static objects in global functions.
  39. * Otherwise constructor guard against concurrent calls is generated costing
  40. * about 8B RAM and 14B flash.
  41. *
  42. *
  43. */
  44. //-//
  45. #include "Configuration.h"
  46. #include "Marlin.h"
  47. #ifdef ENABLE_AUTO_BED_LEVELING
  48. #include "vector_3.h"
  49. #ifdef AUTO_BED_LEVELING_GRID
  50. #include "qr_solve.h"
  51. #endif
  52. #endif // ENABLE_AUTO_BED_LEVELING
  53. #ifdef MESH_BED_LEVELING
  54. #include "mesh_bed_leveling.h"
  55. #include "mesh_bed_calibration.h"
  56. #endif
  57. #include "printers.h"
  58. #include "menu.h"
  59. #include "ultralcd.h"
  60. #include "planner.h"
  61. #include "stepper.h"
  62. #include "temperature.h"
  63. #include "motion_control.h"
  64. #include "cardreader.h"
  65. #include "ConfigurationStore.h"
  66. #include "language.h"
  67. #include "pins_arduino.h"
  68. #include "math.h"
  69. #include "util.h"
  70. #include "Timer.h"
  71. #include <avr/wdt.h>
  72. #include <avr/pgmspace.h>
  73. #include "Dcodes.h"
  74. #include "AutoDeplete.h"
  75. #ifdef SWSPI
  76. #include "swspi.h"
  77. #endif //SWSPI
  78. #include "spi.h"
  79. #ifdef SWI2C
  80. #include "swi2c.h"
  81. #endif //SWI2C
  82. #ifdef FILAMENT_SENSOR
  83. #include "fsensor.h"
  84. #endif //FILAMENT_SENSOR
  85. #ifdef TMC2130
  86. #include "tmc2130.h"
  87. #endif //TMC2130
  88. #ifdef W25X20CL
  89. #include "w25x20cl.h"
  90. #include "optiboot_w25x20cl.h"
  91. #endif //W25X20CL
  92. #ifdef BLINKM
  93. #include "BlinkM.h"
  94. #include "Wire.h"
  95. #endif
  96. #ifdef ULTRALCD
  97. #include "ultralcd.h"
  98. #endif
  99. #if NUM_SERVOS > 0
  100. #include "Servo.h"
  101. #endif
  102. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  103. #include <SPI.h>
  104. #endif
  105. #include "mmu.h"
  106. #define VERSION_STRING "1.0.2"
  107. #include "ultralcd.h"
  108. #include "sound.h"
  109. #include "cmdqueue.h"
  110. #include "io_atmega2560.h"
  111. // Macros for bit masks
  112. #define BIT(b) (1<<(b))
  113. #define TEST(n,b) (((n)&BIT(b))!=0)
  114. #define SET_BIT(n,b,value) (n) ^= ((-value)^(n)) & (BIT(b))
  115. //Macro for print fan speed
  116. #define FAN_PULSE_WIDTH_LIMIT ((fanSpeed > 100) ? 3 : 4) //time in ms
  117. #define PRINTING_TYPE_SD 0
  118. #define PRINTING_TYPE_USB 1
  119. #define PRINTING_TYPE_NONE 2
  120. //filament types
  121. #define FILAMENT_DEFAULT 0
  122. #define FILAMENT_FLEX 1
  123. #define FILAMENT_PVA 2
  124. #define FILAMENT_UNDEFINED 255
  125. //Stepper Movement Variables
  126. //===========================================================================
  127. //=============================imported variables============================
  128. //===========================================================================
  129. //===========================================================================
  130. //=============================public variables=============================
  131. //===========================================================================
  132. #ifdef SDSUPPORT
  133. CardReader card;
  134. #endif
  135. unsigned long PingTime = _millis();
  136. unsigned long NcTime;
  137. uint8_t mbl_z_probe_nr = 3; //numer of Z measurements for each point in mesh bed leveling calibration
  138. //used for PINDA temp calibration and pause print
  139. #define DEFAULT_RETRACTION 1
  140. #define DEFAULT_RETRACTION_MM 4 //MM
  141. float default_retraction = DEFAULT_RETRACTION;
  142. float homing_feedrate[] = HOMING_FEEDRATE;
  143. // Currently only the extruder axis may be switched to a relative mode.
  144. // Other axes are always absolute or relative based on the common relative_mode flag.
  145. bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
  146. int feedmultiply=100; //100->1 200->2
  147. int extrudemultiply=100; //100->1 200->2
  148. int extruder_multiply[EXTRUDERS] = {100
  149. #if EXTRUDERS > 1
  150. , 100
  151. #if EXTRUDERS > 2
  152. , 100
  153. #endif
  154. #endif
  155. };
  156. int bowden_length[4] = {385, 385, 385, 385};
  157. bool is_usb_printing = false;
  158. bool homing_flag = false;
  159. bool temp_cal_active = false;
  160. unsigned long kicktime = _millis()+100000;
  161. unsigned int usb_printing_counter;
  162. int8_t lcd_change_fil_state = 0;
  163. unsigned long pause_time = 0;
  164. unsigned long start_pause_print = _millis();
  165. unsigned long t_fan_rising_edge = _millis();
  166. LongTimer safetyTimer;
  167. static LongTimer crashDetTimer;
  168. //unsigned long load_filament_time;
  169. bool mesh_bed_leveling_flag = false;
  170. bool mesh_bed_run_from_menu = false;
  171. bool prusa_sd_card_upload = false;
  172. unsigned int status_number = 0;
  173. unsigned long total_filament_used;
  174. unsigned int heating_status;
  175. unsigned int heating_status_counter;
  176. bool loading_flag = false;
  177. char snmm_filaments_used = 0;
  178. bool fan_state[2];
  179. int fan_edge_counter[2];
  180. int fan_speed[2];
  181. char dir_names[3][9];
  182. bool sortAlpha = false;
  183. float extruder_multiplier[EXTRUDERS] = {1.0
  184. #if EXTRUDERS > 1
  185. , 1.0
  186. #if EXTRUDERS > 2
  187. , 1.0
  188. #endif
  189. #endif
  190. };
  191. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  192. //shortcuts for more readable code
  193. #define _x current_position[X_AXIS]
  194. #define _y current_position[Y_AXIS]
  195. #define _z current_position[Z_AXIS]
  196. #define _e current_position[E_AXIS]
  197. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  198. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  199. bool axis_known_position[3] = {false, false, false};
  200. // Extruder offset
  201. #if EXTRUDERS > 1
  202. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  203. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  204. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  205. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  206. #endif
  207. };
  208. #endif
  209. uint8_t active_extruder = 0;
  210. int fanSpeed=0;
  211. #ifdef FWRETRACT
  212. bool retracted[EXTRUDERS]={false
  213. #if EXTRUDERS > 1
  214. , false
  215. #if EXTRUDERS > 2
  216. , false
  217. #endif
  218. #endif
  219. };
  220. bool retracted_swap[EXTRUDERS]={false
  221. #if EXTRUDERS > 1
  222. , false
  223. #if EXTRUDERS > 2
  224. , false
  225. #endif
  226. #endif
  227. };
  228. float retract_length_swap = RETRACT_LENGTH_SWAP;
  229. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  230. #endif
  231. #ifdef PS_DEFAULT_OFF
  232. bool powersupply = false;
  233. #else
  234. bool powersupply = true;
  235. #endif
  236. bool cancel_heatup = false ;
  237. int8_t busy_state = NOT_BUSY;
  238. static long prev_busy_signal_ms = -1;
  239. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  240. const char errormagic[] PROGMEM = "Error:";
  241. const char echomagic[] PROGMEM = "echo:";
  242. bool no_response = false;
  243. uint8_t important_status;
  244. uint8_t saved_filament_type;
  245. // save/restore printing in case that mmu was not responding
  246. bool mmu_print_saved = false;
  247. // storing estimated time to end of print counted by slicer
  248. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  249. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  250. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  251. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  252. bool wizard_active = false; //autoload temporarily disabled during wizard
  253. //===========================================================================
  254. //=============================Private Variables=============================
  255. //===========================================================================
  256. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  257. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  258. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  259. // For tracing an arc
  260. static float offset[3] = {0.0, 0.0, 0.0};
  261. static float feedrate = 1500.0, next_feedrate, saved_feedrate;
  262. // Determines Absolute or Relative Coordinates.
  263. // Also there is bool axis_relative_modes[] per axis flag.
  264. static bool relative_mode = false;
  265. const int sensitive_pins[] = SENSITIVE_PINS; // Sensitive pin list for M42
  266. //static float tt = 0;
  267. //static float bt = 0;
  268. //Inactivity shutdown variables
  269. static unsigned long previous_millis_cmd = 0;
  270. unsigned long max_inactive_time = 0;
  271. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  272. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  273. unsigned long starttime=0;
  274. unsigned long stoptime=0;
  275. unsigned long _usb_timer = 0;
  276. bool extruder_under_pressure = true;
  277. bool Stopped=false;
  278. #if NUM_SERVOS > 0
  279. Servo servos[NUM_SERVOS];
  280. #endif
  281. bool CooldownNoWait = true;
  282. bool target_direction;
  283. //Insert variables if CHDK is defined
  284. #ifdef CHDK
  285. unsigned long chdkHigh = 0;
  286. boolean chdkActive = false;
  287. #endif
  288. //! @name RAM save/restore printing
  289. //! @{
  290. bool saved_printing = false; //!< Print is paused and saved in RAM
  291. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  292. static uint8_t saved_printing_type = PRINTING_TYPE_SD;
  293. static float saved_pos[4] = { 0, 0, 0, 0 };
  294. //! Feedrate hopefully derived from an active block of the planner at the time the print has been canceled, in mm/min.
  295. static float saved_feedrate2 = 0;
  296. static uint8_t saved_active_extruder = 0;
  297. static float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  298. static bool saved_extruder_under_pressure = false;
  299. static bool saved_extruder_relative_mode = false;
  300. static int saved_fanSpeed = 0; //!< Print fan speed
  301. //! @}
  302. static int saved_feedmultiply_mm = 100;
  303. //===========================================================================
  304. //=============================Routines======================================
  305. //===========================================================================
  306. static void get_arc_coordinates();
  307. static bool setTargetedHotend(int code, uint8_t &extruder);
  308. static void print_time_remaining_init();
  309. static void wait_for_heater(long codenum, uint8_t extruder);
  310. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
  311. uint16_t gcode_in_progress = 0;
  312. uint16_t mcode_in_progress = 0;
  313. void serial_echopair_P(const char *s_P, float v)
  314. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  315. void serial_echopair_P(const char *s_P, double v)
  316. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  317. void serial_echopair_P(const char *s_P, unsigned long v)
  318. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  319. /*FORCE_INLINE*/ void serialprintPGM(const char *str)
  320. {
  321. #if 0
  322. char ch=pgm_read_byte(str);
  323. while(ch)
  324. {
  325. MYSERIAL.write(ch);
  326. ch=pgm_read_byte(++str);
  327. }
  328. #else
  329. // hmm, same size as the above version, the compiler did a good job optimizing the above
  330. while( uint8_t ch = pgm_read_byte(str) ){
  331. MYSERIAL.write((char)ch);
  332. ++str;
  333. }
  334. #endif
  335. }
  336. #ifdef SDSUPPORT
  337. #include "SdFatUtil.h"
  338. int freeMemory() { return SdFatUtil::FreeRam(); }
  339. #else
  340. extern "C" {
  341. extern unsigned int __bss_end;
  342. extern unsigned int __heap_start;
  343. extern void *__brkval;
  344. int freeMemory() {
  345. int free_memory;
  346. if ((int)__brkval == 0)
  347. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  348. else
  349. free_memory = ((int)&free_memory) - ((int)__brkval);
  350. return free_memory;
  351. }
  352. }
  353. #endif //!SDSUPPORT
  354. void setup_killpin()
  355. {
  356. #if defined(KILL_PIN) && KILL_PIN > -1
  357. SET_INPUT(KILL_PIN);
  358. WRITE(KILL_PIN,HIGH);
  359. #endif
  360. }
  361. // Set home pin
  362. void setup_homepin(void)
  363. {
  364. #if defined(HOME_PIN) && HOME_PIN > -1
  365. SET_INPUT(HOME_PIN);
  366. WRITE(HOME_PIN,HIGH);
  367. #endif
  368. }
  369. void setup_photpin()
  370. {
  371. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  372. SET_OUTPUT(PHOTOGRAPH_PIN);
  373. WRITE(PHOTOGRAPH_PIN, LOW);
  374. #endif
  375. }
  376. void setup_powerhold()
  377. {
  378. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  379. SET_OUTPUT(SUICIDE_PIN);
  380. WRITE(SUICIDE_PIN, HIGH);
  381. #endif
  382. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  383. SET_OUTPUT(PS_ON_PIN);
  384. #if defined(PS_DEFAULT_OFF)
  385. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  386. #else
  387. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  388. #endif
  389. #endif
  390. }
  391. void suicide()
  392. {
  393. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  394. SET_OUTPUT(SUICIDE_PIN);
  395. WRITE(SUICIDE_PIN, LOW);
  396. #endif
  397. }
  398. void servo_init()
  399. {
  400. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  401. servos[0].attach(SERVO0_PIN);
  402. #endif
  403. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  404. servos[1].attach(SERVO1_PIN);
  405. #endif
  406. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  407. servos[2].attach(SERVO2_PIN);
  408. #endif
  409. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  410. servos[3].attach(SERVO3_PIN);
  411. #endif
  412. #if (NUM_SERVOS >= 5)
  413. #error "TODO: enter initalisation code for more servos"
  414. #endif
  415. }
  416. bool fans_check_enabled = true;
  417. #ifdef TMC2130
  418. extern int8_t CrashDetectMenu;
  419. void crashdet_enable()
  420. {
  421. tmc2130_sg_stop_on_crash = true;
  422. eeprom_update_byte((uint8_t*)EEPROM_CRASH_DET, 0xFF);
  423. CrashDetectMenu = 1;
  424. }
  425. void crashdet_disable()
  426. {
  427. tmc2130_sg_stop_on_crash = false;
  428. tmc2130_sg_crash = 0;
  429. eeprom_update_byte((uint8_t*)EEPROM_CRASH_DET, 0x00);
  430. CrashDetectMenu = 0;
  431. }
  432. void crashdet_stop_and_save_print()
  433. {
  434. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  435. }
  436. void crashdet_restore_print_and_continue()
  437. {
  438. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  439. // babystep_apply();
  440. }
  441. void crashdet_stop_and_save_print2()
  442. {
  443. cli();
  444. planner_abort_hard(); //abort printing
  445. cmdqueue_reset(); //empty cmdqueue
  446. card.sdprinting = false;
  447. card.closefile();
  448. // Reset and re-enable the stepper timer just before the global interrupts are enabled.
  449. st_reset_timer();
  450. sei();
  451. }
  452. void crashdet_detected(uint8_t mask)
  453. {
  454. st_synchronize();
  455. static uint8_t crashDet_counter = 0;
  456. bool automatic_recovery_after_crash = true;
  457. if (crashDet_counter++ == 0) {
  458. crashDetTimer.start();
  459. }
  460. else if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)){
  461. crashDetTimer.stop();
  462. crashDet_counter = 0;
  463. }
  464. else if(crashDet_counter == CRASHDET_COUNTER_MAX){
  465. automatic_recovery_after_crash = false;
  466. crashDetTimer.stop();
  467. crashDet_counter = 0;
  468. }
  469. else {
  470. crashDetTimer.start();
  471. }
  472. lcd_update_enable(true);
  473. lcd_clear();
  474. lcd_update(2);
  475. if (mask & X_AXIS_MASK)
  476. {
  477. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_X, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_X) + 1);
  478. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT) + 1);
  479. }
  480. if (mask & Y_AXIS_MASK)
  481. {
  482. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_Y, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_Y) + 1);
  483. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT) + 1);
  484. }
  485. lcd_update_enable(true);
  486. lcd_update(2);
  487. lcd_setstatuspgm(_T(MSG_CRASH_DETECTED));
  488. gcode_G28(true, true, false); //home X and Y
  489. st_synchronize();
  490. if (automatic_recovery_after_crash) {
  491. enquecommand_P(PSTR("CRASH_RECOVER"));
  492. }else{
  493. setTargetHotend(0, active_extruder);
  494. bool yesno = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Crash detected. Resume print?"), false);
  495. lcd_update_enable(true);
  496. if (yesno)
  497. {
  498. enquecommand_P(PSTR("CRASH_RECOVER"));
  499. }
  500. else
  501. {
  502. enquecommand_P(PSTR("CRASH_CANCEL"));
  503. }
  504. }
  505. }
  506. void crashdet_recover()
  507. {
  508. crashdet_restore_print_and_continue();
  509. tmc2130_sg_stop_on_crash = true;
  510. }
  511. void crashdet_cancel()
  512. {
  513. saved_printing = false;
  514. tmc2130_sg_stop_on_crash = true;
  515. if (saved_printing_type == PRINTING_TYPE_SD) {
  516. lcd_print_stop();
  517. }else if(saved_printing_type == PRINTING_TYPE_USB){
  518. SERIAL_ECHOLNPGM("// action:cancel"); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  519. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  520. }
  521. }
  522. #endif //TMC2130
  523. void failstats_reset_print()
  524. {
  525. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  526. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  527. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  528. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  529. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  530. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  531. }
  532. #ifdef MESH_BED_LEVELING
  533. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  534. #endif
  535. // Factory reset function
  536. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  537. // Level input parameter sets depth of reset
  538. int er_progress = 0;
  539. static void factory_reset(char level)
  540. {
  541. lcd_clear();
  542. switch (level) {
  543. // Level 0: Language reset
  544. case 0:
  545. Sound_MakeCustom(100,0,false);
  546. lang_reset();
  547. break;
  548. //Level 1: Reset statistics
  549. case 1:
  550. Sound_MakeCustom(100,0,false);
  551. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  552. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  553. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  554. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  555. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  556. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  557. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  558. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  559. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  560. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  561. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  562. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  563. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  564. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  565. lcd_menu_statistics();
  566. break;
  567. // Level 2: Prepare for shipping
  568. case 2:
  569. //lcd_puts_P(PSTR("Factory RESET"));
  570. //lcd_puts_at_P(1,2,PSTR("Shipping prep"));
  571. // Force language selection at the next boot up.
  572. lang_reset();
  573. // Force the "Follow calibration flow" message at the next boot up.
  574. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  575. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  576. farm_no = 0;
  577. farm_mode = false;
  578. eeprom_update_byte((uint8_t*)EEPROM_FARM_MODE, farm_mode);
  579. EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
  580. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  581. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  582. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  583. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  584. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  585. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  586. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  587. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  588. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  589. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  590. #ifdef FILAMENT_SENSOR
  591. fsensor_enable();
  592. fsensor_autoload_set(true);
  593. #endif //FILAMENT_SENSOR
  594. Sound_MakeCustom(100,0,false);
  595. //_delay_ms(2000);
  596. break;
  597. // Level 3: erase everything, whole EEPROM will be set to 0xFF
  598. case 3:
  599. lcd_puts_P(PSTR("Factory RESET"));
  600. lcd_puts_at_P(1, 2, PSTR("ERASING all data"));
  601. Sound_MakeCustom(100,0,false);
  602. er_progress = 0;
  603. lcd_puts_at_P(3, 3, PSTR(" "));
  604. lcd_set_cursor(3, 3);
  605. lcd_print(er_progress);
  606. // Erase EEPROM
  607. for (int i = 0; i < 4096; i++) {
  608. eeprom_update_byte((uint8_t*)i, 0xFF);
  609. if (i % 41 == 0) {
  610. er_progress++;
  611. lcd_puts_at_P(3, 3, PSTR(" "));
  612. lcd_set_cursor(3, 3);
  613. lcd_print(er_progress);
  614. lcd_puts_P(PSTR("%"));
  615. }
  616. }
  617. break;
  618. case 4:
  619. bowden_menu();
  620. break;
  621. default:
  622. break;
  623. }
  624. }
  625. extern "C" {
  626. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  627. }
  628. int uart_putchar(char c, FILE *)
  629. {
  630. MYSERIAL.write(c);
  631. return 0;
  632. }
  633. void lcd_splash()
  634. {
  635. lcd_clear(); // clears display and homes screen
  636. lcd_puts_P(PSTR("\n Original Prusa i3\n Prusa Research"));
  637. }
  638. void factory_reset()
  639. {
  640. KEEPALIVE_STATE(PAUSED_FOR_USER);
  641. if (!READ(BTN_ENC))
  642. {
  643. _delay_ms(1000);
  644. if (!READ(BTN_ENC))
  645. {
  646. lcd_clear();
  647. lcd_puts_P(PSTR("Factory RESET"));
  648. SET_OUTPUT(BEEPER);
  649. if(eSoundMode!=e_SOUND_MODE_SILENT)
  650. WRITE(BEEPER, HIGH);
  651. while (!READ(BTN_ENC));
  652. WRITE(BEEPER, LOW);
  653. _delay_ms(2000);
  654. char level = reset_menu();
  655. factory_reset(level);
  656. switch (level) {
  657. case 0: _delay_ms(0); break;
  658. case 1: _delay_ms(0); break;
  659. case 2: _delay_ms(0); break;
  660. case 3: _delay_ms(0); break;
  661. }
  662. }
  663. }
  664. KEEPALIVE_STATE(IN_HANDLER);
  665. }
  666. void show_fw_version_warnings() {
  667. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  668. switch (FW_DEV_VERSION) {
  669. case(FW_VERSION_ALPHA): lcd_show_fullscreen_message_and_wait_P(_i("You are using firmware alpha version. This is development version. Using this version is not recommended and may cause printer damage.")); break;////MSG_FW_VERSION_ALPHA c=20 r=8
  670. case(FW_VERSION_BETA): lcd_show_fullscreen_message_and_wait_P(_i("You are using firmware beta version. This is development version. Using this version is not recommended and may cause printer damage.")); break;////MSG_FW_VERSION_BETA c=20 r=8
  671. case(FW_VERSION_DEVEL):
  672. case(FW_VERSION_DEBUG):
  673. lcd_update_enable(false);
  674. lcd_clear();
  675. #if FW_DEV_VERSION == FW_VERSION_DEVEL
  676. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  677. #else
  678. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  679. #endif
  680. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  681. lcd_puts_at_P(0, 2, PSTR("ver ")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  682. lcd_puts_at_P(0, 3, PSTR(FW_REPOSITORY));
  683. lcd_wait_for_click();
  684. break;
  685. // default: lcd_show_fullscreen_message_and_wait_P(_i("WARNING: This is an unofficial, unsupported build. Use at your own risk!")); break;////MSG_FW_VERSION_UNKNOWN c=20 r=8
  686. }
  687. lcd_update_enable(true);
  688. }
  689. //! @brief try to check if firmware is on right type of printer
  690. static void check_if_fw_is_on_right_printer(){
  691. #ifdef FILAMENT_SENSOR
  692. if((PRINTER_TYPE == PRINTER_MK3) || (PRINTER_TYPE == PRINTER_MK3S)){
  693. #ifdef IR_SENSOR
  694. swi2c_init();
  695. const uint8_t pat9125_detected = swi2c_readByte_A8(PAT9125_I2C_ADDR,0x00,NULL);
  696. if (pat9125_detected){
  697. lcd_show_fullscreen_message_and_wait_P(_i("MK3S firmware detected on MK3 printer"));}
  698. #endif //IR_SENSOR
  699. #ifdef PAT9125
  700. //will return 1 only if IR can detect filament in bondtech extruder so this may fail even when we have IR sensor
  701. const uint8_t ir_detected = !(PIN_GET(IR_SENSOR_PIN));
  702. if (ir_detected){
  703. lcd_show_fullscreen_message_and_wait_P(_i("MK3 firmware detected on MK3S printer"));}
  704. #endif //PAT9125
  705. }
  706. #endif //FILAMENT_SENSOR
  707. }
  708. uint8_t check_printer_version()
  709. {
  710. uint8_t version_changed = 0;
  711. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  712. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  713. if (printer_type != PRINTER_TYPE) {
  714. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  715. else version_changed |= 0b10;
  716. }
  717. if (motherboard != MOTHERBOARD) {
  718. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  719. else version_changed |= 0b01;
  720. }
  721. return version_changed;
  722. }
  723. #ifdef BOOTAPP
  724. #include "bootapp.h" //bootloader support
  725. #endif //BOOTAPP
  726. #if (LANG_MODE != 0) //secondary language support
  727. #ifdef W25X20CL
  728. // language update from external flash
  729. #define LANGBOOT_BLOCKSIZE 0x1000u
  730. #define LANGBOOT_RAMBUFFER 0x0800
  731. void update_sec_lang_from_external_flash()
  732. {
  733. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  734. {
  735. uint8_t lang = boot_reserved >> 4;
  736. uint8_t state = boot_reserved & 0xf;
  737. lang_table_header_t header;
  738. uint32_t src_addr;
  739. if (lang_get_header(lang, &header, &src_addr))
  740. {
  741. lcd_puts_at_P(1,3,PSTR("Language update."));
  742. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  743. _delay(100);
  744. boot_reserved = (state + 1) | (lang << 4);
  745. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  746. {
  747. cli();
  748. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  749. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  750. w25x20cl_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  751. if (state == 0)
  752. {
  753. //TODO - check header integrity
  754. }
  755. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  756. }
  757. else
  758. {
  759. //TODO - check sec lang data integrity
  760. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  761. }
  762. }
  763. }
  764. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  765. }
  766. #ifdef DEBUG_W25X20CL
  767. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  768. {
  769. lang_table_header_t header;
  770. uint8_t count = 0;
  771. uint32_t addr = 0x00000;
  772. while (1)
  773. {
  774. printf_P(_n("LANGTABLE%d:"), count);
  775. w25x20cl_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  776. if (header.magic != LANG_MAGIC)
  777. {
  778. printf_P(_n("NG!\n"));
  779. break;
  780. }
  781. printf_P(_n("OK\n"));
  782. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  783. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  784. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  785. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  786. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  787. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  788. addr += header.size;
  789. codes[count] = header.code;
  790. count ++;
  791. }
  792. return count;
  793. }
  794. void list_sec_lang_from_external_flash()
  795. {
  796. uint16_t codes[8];
  797. uint8_t count = lang_xflash_enum_codes(codes);
  798. printf_P(_n("XFlash lang count = %hhd\n"), count);
  799. }
  800. #endif //DEBUG_W25X20CL
  801. #endif //W25X20CL
  802. #endif //(LANG_MODE != 0)
  803. static void w25x20cl_err_msg()
  804. {
  805. lcd_clear();
  806. lcd_puts_P(_n("External SPI flash\nW25X20CL is not res-\nponding. Language\nswitch unavailable."));
  807. }
  808. // "Setup" function is called by the Arduino framework on startup.
  809. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  810. // are initialized by the main() routine provided by the Arduino framework.
  811. void setup()
  812. {
  813. mmu_init();
  814. ultralcd_init();
  815. #if (LCD_BL_PIN != -1) && defined (LCD_BL_PIN)
  816. analogWrite(LCD_BL_PIN, 255); //set full brightnes
  817. #endif //(LCD_BL_PIN != -1) && defined (LCD_BL_PIN)
  818. spi_init();
  819. lcd_splash();
  820. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  821. #ifdef W25X20CL
  822. bool w25x20cl_success = w25x20cl_init();
  823. if (w25x20cl_success)
  824. {
  825. optiboot_w25x20cl_enter();
  826. #if (LANG_MODE != 0) //secondary language support
  827. update_sec_lang_from_external_flash();
  828. #endif //(LANG_MODE != 0)
  829. }
  830. else
  831. {
  832. w25x20cl_err_msg();
  833. }
  834. #else
  835. const bool w25x20cl_success = true;
  836. #endif //W25X20CL
  837. setup_killpin();
  838. setup_powerhold();
  839. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  840. EEPROM_read_B(EEPROM_FARM_NUMBER, &farm_no);
  841. if ((farm_mode == 0xFF && farm_no == 0) || ((uint16_t)farm_no == 0xFFFF))
  842. farm_mode = false; //if farm_mode has not been stored to eeprom yet and farm number is set to zero or EEPROM is fresh, deactivate farm mode
  843. if ((uint16_t)farm_no == 0xFFFF) farm_no = 0;
  844. selectedSerialPort = eeprom_read_byte((uint8_t*)EEPROM_SECOND_SERIAL_ACTIVE);
  845. if (selectedSerialPort == 0xFF) selectedSerialPort = 0;
  846. if (farm_mode)
  847. {
  848. no_response = true; //we need confirmation by recieving PRUSA thx
  849. important_status = 8;
  850. prusa_statistics(8);
  851. selectedSerialPort = 1;
  852. #ifdef TMC2130
  853. //increased extruder current (PFW363)
  854. tmc2130_current_h[E_AXIS] = 36;
  855. tmc2130_current_r[E_AXIS] = 36;
  856. #endif //TMC2130
  857. #ifdef FILAMENT_SENSOR
  858. //disabled filament autoload (PFW360)
  859. fsensor_autoload_set(false);
  860. #endif //FILAMENT_SENSOR
  861. // ~ FanCheck -> on
  862. if(!(eeprom_read_byte((uint8_t*)EEPROM_FAN_CHECK_ENABLED)))
  863. eeprom_update_byte((unsigned char *)EEPROM_FAN_CHECK_ENABLED,true);
  864. }
  865. MYSERIAL.begin(BAUDRATE);
  866. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  867. #ifndef W25X20CL
  868. SERIAL_PROTOCOLLNPGM("start");
  869. #endif //W25X20CL
  870. stdout = uartout;
  871. SERIAL_ECHO_START;
  872. printf_P(PSTR(" " FW_VERSION_FULL "\n"));
  873. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  874. #ifdef DEBUG_SEC_LANG
  875. lang_table_header_t header;
  876. uint32_t src_addr = 0x00000;
  877. if (lang_get_header(1, &header, &src_addr))
  878. {
  879. //this is comparsion of some printing-methods regarding to flash space usage and code size/readability
  880. #define LT_PRINT_TEST 2
  881. // flash usage
  882. // total p.test
  883. //0 252718 t+c text code
  884. //1 253142 424 170 254
  885. //2 253040 322 164 158
  886. //3 253248 530 135 395
  887. #if (LT_PRINT_TEST==1) //not optimized printf
  888. printf_P(_n(" _src_addr = 0x%08lx\n"), src_addr);
  889. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  890. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  891. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  892. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  893. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  894. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  895. #elif (LT_PRINT_TEST==2) //optimized printf
  896. printf_P(
  897. _n(
  898. " _src_addr = 0x%08lx\n"
  899. " _lt_magic = 0x%08lx %S\n"
  900. " _lt_size = 0x%04x (%d)\n"
  901. " _lt_count = 0x%04x (%d)\n"
  902. " _lt_chsum = 0x%04x\n"
  903. " _lt_code = 0x%04x (%c%c)\n"
  904. " _lt_resv1 = 0x%08lx\n"
  905. ),
  906. src_addr,
  907. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  908. header.size, header.size,
  909. header.count, header.count,
  910. header.checksum,
  911. header.code, header.code >> 8, header.code & 0xff,
  912. header.signature
  913. );
  914. #elif (LT_PRINT_TEST==3) //arduino print/println (leading zeros not solved)
  915. MYSERIAL.print(" _src_addr = 0x");
  916. MYSERIAL.println(src_addr, 16);
  917. MYSERIAL.print(" _lt_magic = 0x");
  918. MYSERIAL.print(header.magic, 16);
  919. MYSERIAL.println((header.magic==LANG_MAGIC)?" OK":" NA");
  920. MYSERIAL.print(" _lt_size = 0x");
  921. MYSERIAL.print(header.size, 16);
  922. MYSERIAL.print(" (");
  923. MYSERIAL.print(header.size, 10);
  924. MYSERIAL.println(")");
  925. MYSERIAL.print(" _lt_count = 0x");
  926. MYSERIAL.print(header.count, 16);
  927. MYSERIAL.print(" (");
  928. MYSERIAL.print(header.count, 10);
  929. MYSERIAL.println(")");
  930. MYSERIAL.print(" _lt_chsum = 0x");
  931. MYSERIAL.println(header.checksum, 16);
  932. MYSERIAL.print(" _lt_code = 0x");
  933. MYSERIAL.print(header.code, 16);
  934. MYSERIAL.print(" (");
  935. MYSERIAL.print((char)(header.code >> 8), 0);
  936. MYSERIAL.print((char)(header.code & 0xff), 0);
  937. MYSERIAL.println(")");
  938. MYSERIAL.print(" _lt_resv1 = 0x");
  939. MYSERIAL.println(header.signature, 16);
  940. #endif //(LT_PRINT_TEST==)
  941. #undef LT_PRINT_TEST
  942. #if 0
  943. w25x20cl_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  944. for (uint16_t i = 0; i < 1024; i++)
  945. {
  946. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  947. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  948. if ((i % 16) == 15) putchar('\n');
  949. }
  950. #endif
  951. uint16_t sum = 0;
  952. for (uint16_t i = 0; i < header.size; i++)
  953. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  954. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  955. sum -= header.checksum; //subtract checksum
  956. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  957. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  958. if (sum == header.checksum)
  959. printf_P(_n("Checksum OK\n"), sum);
  960. else
  961. printf_P(_n("Checksum NG\n"), sum);
  962. }
  963. else
  964. printf_P(_n("lang_get_header failed!\n"));
  965. #if 0
  966. for (uint16_t i = 0; i < 1024*10; i++)
  967. {
  968. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  969. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  970. if ((i % 16) == 15) putchar('\n');
  971. }
  972. #endif
  973. #if 0
  974. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  975. for (int i = 0; i < 4096; ++i) {
  976. int b = eeprom_read_byte((unsigned char*)i);
  977. if (b != 255) {
  978. SERIAL_ECHO(i);
  979. SERIAL_ECHO(":");
  980. SERIAL_ECHO(b);
  981. SERIAL_ECHOLN("");
  982. }
  983. }
  984. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  985. #endif
  986. #endif //DEBUG_SEC_LANG
  987. // Check startup - does nothing if bootloader sets MCUSR to 0
  988. byte mcu = MCUSR;
  989. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  990. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  991. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  992. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  993. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  994. if (mcu & 1) puts_P(MSG_POWERUP);
  995. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  996. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  997. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  998. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  999. MCUSR = 0;
  1000. //SERIAL_ECHORPGM(MSG_MARLIN);
  1001. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  1002. #ifdef STRING_VERSION_CONFIG_H
  1003. #ifdef STRING_CONFIG_H_AUTHOR
  1004. SERIAL_ECHO_START;
  1005. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  1006. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  1007. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  1008. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  1009. SERIAL_ECHOPGM("Compiled: ");
  1010. SERIAL_ECHOLNPGM(__DATE__);
  1011. #endif
  1012. #endif
  1013. SERIAL_ECHO_START;
  1014. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1015. SERIAL_ECHO(freeMemory());
  1016. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1017. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1018. //lcd_update_enable(false); // why do we need this?? - andre
  1019. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1020. bool previous_settings_retrieved = false;
  1021. uint8_t hw_changed = check_printer_version();
  1022. if (!(hw_changed & 0b10)) { //if printer version wasn't changed, check for eeprom version and retrieve settings from eeprom in case that version wasn't changed
  1023. previous_settings_retrieved = Config_RetrieveSettings();
  1024. }
  1025. else { //printer version was changed so use default settings
  1026. Config_ResetDefault();
  1027. }
  1028. SdFatUtil::set_stack_guard(); //writes magic number at the end of static variables to protect against overwriting static memory by stack
  1029. tp_init(); // Initialize temperature loop
  1030. if (w25x20cl_success) lcd_splash(); // we need to do this again, because tp_init() kills lcd
  1031. else
  1032. {
  1033. w25x20cl_err_msg();
  1034. printf_P(_n("W25X20CL not responding.\n"));
  1035. }
  1036. plan_init(); // Initialize planner;
  1037. factory_reset();
  1038. lcd_encoder_diff=0;
  1039. #ifdef TMC2130
  1040. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1041. if (silentMode == 0xff) silentMode = 0;
  1042. tmc2130_mode = TMC2130_MODE_NORMAL;
  1043. uint8_t crashdet = eeprom_read_byte((uint8_t*)EEPROM_CRASH_DET);
  1044. if (crashdet && !farm_mode)
  1045. {
  1046. crashdet_enable();
  1047. puts_P(_N("CrashDetect ENABLED!"));
  1048. }
  1049. else
  1050. {
  1051. crashdet_disable();
  1052. puts_P(_N("CrashDetect DISABLED"));
  1053. }
  1054. #ifdef TMC2130_LINEARITY_CORRECTION
  1055. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1056. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1057. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1058. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1059. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1060. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1061. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1062. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1063. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1064. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1065. #endif //TMC2130_LINEARITY_CORRECTION
  1066. #ifdef TMC2130_VARIABLE_RESOLUTION
  1067. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1068. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1069. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1070. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1071. #else //TMC2130_VARIABLE_RESOLUTION
  1072. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1073. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1074. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1075. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1076. #endif //TMC2130_VARIABLE_RESOLUTION
  1077. #endif //TMC2130
  1078. st_init(); // Initialize stepper, this enables interrupts!
  1079. #ifdef UVLO_SUPPORT
  1080. setup_uvlo_interrupt();
  1081. #endif //UVLO_SUPPORT
  1082. #ifdef TMC2130
  1083. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1084. update_mode_profile();
  1085. tmc2130_init();
  1086. #endif //TMC2130
  1087. #ifdef PSU_Delta
  1088. init_force_z(); // ! important for correct Z-axis initialization
  1089. #endif // PSU_Delta
  1090. setup_photpin();
  1091. servo_init();
  1092. // Reset the machine correction matrix.
  1093. // It does not make sense to load the correction matrix until the machine is homed.
  1094. world2machine_reset();
  1095. #ifdef FILAMENT_SENSOR
  1096. fsensor_init();
  1097. #endif //FILAMENT_SENSOR
  1098. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1099. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1100. #endif
  1101. setup_homepin();
  1102. #ifdef TMC2130
  1103. if (1) {
  1104. // try to run to zero phase before powering the Z motor.
  1105. // Move in negative direction
  1106. WRITE(Z_DIR_PIN,INVERT_Z_DIR);
  1107. // Round the current micro-micro steps to micro steps.
  1108. for (uint16_t phase = (tmc2130_rd_MSCNT(Z_AXIS) + 8) >> 4; phase > 0; -- phase) {
  1109. // Until the phase counter is reset to zero.
  1110. WRITE(Z_STEP_PIN, !INVERT_Z_STEP_PIN);
  1111. _delay(2);
  1112. WRITE(Z_STEP_PIN, INVERT_Z_STEP_PIN);
  1113. _delay(2);
  1114. }
  1115. }
  1116. #endif //TMC2130
  1117. #if defined(Z_AXIS_ALWAYS_ON) && !defined(PSU_Delta)
  1118. enable_z();
  1119. #endif
  1120. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  1121. EEPROM_read_B(EEPROM_FARM_NUMBER, &farm_no);
  1122. if ((farm_mode == 0xFF && farm_no == 0) || (farm_no == static_cast<int>(0xFFFF))) farm_mode = false; //if farm_mode has not been stored to eeprom yet and farm number is set to zero or EEPROM is fresh, deactivate farm mode
  1123. if (farm_no == static_cast<int>(0xFFFF)) farm_no = 0;
  1124. if (farm_mode)
  1125. {
  1126. prusa_statistics(8);
  1127. }
  1128. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1129. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1130. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  1131. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff) {
  1132. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  1133. // where all the EEPROM entries are set to 0x0ff.
  1134. // Once a firmware boots up, it forces at least a language selection, which changes
  1135. // EEPROM_LANG to number lower than 0x0ff.
  1136. // 1) Set a high power mode.
  1137. #ifdef TMC2130
  1138. eeprom_write_byte((uint8_t*)EEPROM_SILENT, 0);
  1139. tmc2130_mode = TMC2130_MODE_NORMAL;
  1140. #endif //TMC2130
  1141. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  1142. }
  1143. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1144. // but this times out if a blocking dialog is shown in setup().
  1145. card.initsd();
  1146. #ifdef DEBUG_SD_SPEED_TEST
  1147. if (card.cardOK)
  1148. {
  1149. uint8_t* buff = (uint8_t*)block_buffer;
  1150. uint32_t block = 0;
  1151. uint32_t sumr = 0;
  1152. uint32_t sumw = 0;
  1153. for (int i = 0; i < 1024; i++)
  1154. {
  1155. uint32_t u = _micros();
  1156. bool res = card.card.readBlock(i, buff);
  1157. u = _micros() - u;
  1158. if (res)
  1159. {
  1160. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1161. sumr += u;
  1162. u = _micros();
  1163. res = card.card.writeBlock(i, buff);
  1164. u = _micros() - u;
  1165. if (res)
  1166. {
  1167. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1168. sumw += u;
  1169. }
  1170. else
  1171. {
  1172. printf_P(PSTR("writeBlock %4d error\n"), i);
  1173. break;
  1174. }
  1175. }
  1176. else
  1177. {
  1178. printf_P(PSTR("readBlock %4d error\n"), i);
  1179. break;
  1180. }
  1181. }
  1182. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1183. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1184. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1185. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1186. }
  1187. else
  1188. printf_P(PSTR("Card NG!\n"));
  1189. #endif //DEBUG_SD_SPEED_TEST
  1190. eeprom_init();
  1191. #ifdef SNMM
  1192. if (eeprom_read_dword((uint32_t*)EEPROM_BOWDEN_LENGTH) == 0x0ffffffff) { //bowden length used for SNMM
  1193. int _z = BOWDEN_LENGTH;
  1194. for(int i = 0; i<4; i++) EEPROM_save_B(EEPROM_BOWDEN_LENGTH + i * 2, &_z);
  1195. }
  1196. #endif
  1197. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1198. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1199. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1200. #if (LANG_MODE != 0) //secondary language support
  1201. #ifdef DEBUG_W25X20CL
  1202. W25X20CL_SPI_ENTER();
  1203. uint8_t uid[8]; // 64bit unique id
  1204. w25x20cl_rd_uid(uid);
  1205. puts_P(_n("W25X20CL UID="));
  1206. for (uint8_t i = 0; i < 8; i ++)
  1207. printf_P(PSTR("%02hhx"), uid[i]);
  1208. putchar('\n');
  1209. list_sec_lang_from_external_flash();
  1210. #endif //DEBUG_W25X20CL
  1211. // lang_reset();
  1212. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1213. lcd_language();
  1214. #ifdef DEBUG_SEC_LANG
  1215. uint16_t sec_lang_code = lang_get_code(1);
  1216. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1217. printf_P(_n("lang_selected=%d\nlang_table=0x%04x\nSEC_LANG_CODE=0x%04x (%c%c)\n"), lang_selected, ui, sec_lang_code, sec_lang_code >> 8, sec_lang_code & 0xff);
  1218. lang_print_sec_lang(uartout);
  1219. #endif //DEBUG_SEC_LANG
  1220. #endif //(LANG_MODE != 0)
  1221. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  1222. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1223. temp_cal_active = false;
  1224. } else temp_cal_active = eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE);
  1225. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1226. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1227. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1228. int16_t z_shift = 0;
  1229. for (uint8_t i = 0; i < 5; i++) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  1230. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1231. temp_cal_active = false;
  1232. }
  1233. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 255) {
  1234. eeprom_write_byte((uint8_t*)EEPROM_UVLO, 0);
  1235. }
  1236. if (eeprom_read_byte((uint8_t*)EEPROM_SD_SORT) == 255) {
  1237. eeprom_write_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1238. }
  1239. //mbl_mode_init();
  1240. mbl_settings_init();
  1241. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1242. if (SilentModeMenu_MMU == 255) {
  1243. SilentModeMenu_MMU = 1;
  1244. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1245. }
  1246. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1247. setup_fan_interrupt();
  1248. #endif //DEBUG_DISABLE_FANCHECK
  1249. #ifdef PAT9125
  1250. fsensor_setup_interrupt();
  1251. #endif //PAT9125
  1252. for (int i = 0; i<4; i++) EEPROM_read_B(EEPROM_BOWDEN_LENGTH + i * 2, &bowden_length[i]);
  1253. #ifndef DEBUG_DISABLE_STARTMSGS
  1254. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1255. if (!farm_mode) {
  1256. check_if_fw_is_on_right_printer();
  1257. show_fw_version_warnings();
  1258. }
  1259. switch (hw_changed) {
  1260. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1261. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1262. case(0b01):
  1263. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1264. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1265. break;
  1266. case(0b10):
  1267. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1268. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1269. break;
  1270. case(0b11):
  1271. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1272. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1273. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1274. break;
  1275. default: break; //no change, show no message
  1276. }
  1277. if (!previous_settings_retrieved) {
  1278. lcd_show_fullscreen_message_and_wait_P(_i("Old settings found. Default PID, Esteps etc. will be set.")); //if EEPROM version or printer type was changed, inform user that default setting were loaded////MSG_DEFAULT_SETTINGS_LOADED c=20 r=4
  1279. Config_StoreSettings();
  1280. }
  1281. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 1) {
  1282. lcd_wizard(WizState::Run);
  1283. }
  1284. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1285. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1286. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1287. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1288. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1289. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z, 0);
  1290. // Show the message.
  1291. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1292. }
  1293. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1294. // Show the message.
  1295. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1296. lcd_update_enable(true);
  1297. }
  1298. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && temp_cal_active == true && calibration_status_pinda() == false) {
  1299. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1300. lcd_update_enable(true);
  1301. }
  1302. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1303. // Show the message.
  1304. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1305. }
  1306. }
  1307. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1308. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1309. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1310. update_current_firmware_version_to_eeprom();
  1311. lcd_selftest();
  1312. }
  1313. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1314. KEEPALIVE_STATE(IN_PROCESS);
  1315. #endif //DEBUG_DISABLE_STARTMSGS
  1316. lcd_update_enable(true);
  1317. lcd_clear();
  1318. lcd_update(2);
  1319. // Store the currently running firmware into an eeprom,
  1320. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1321. update_current_firmware_version_to_eeprom();
  1322. #ifdef TMC2130
  1323. tmc2130_home_origin[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN);
  1324. tmc2130_home_bsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS);
  1325. tmc2130_home_fsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS);
  1326. if (tmc2130_home_origin[X_AXIS] == 0xff) tmc2130_home_origin[X_AXIS] = 0;
  1327. if (tmc2130_home_bsteps[X_AXIS] == 0xff) tmc2130_home_bsteps[X_AXIS] = 48;
  1328. if (tmc2130_home_fsteps[X_AXIS] == 0xff) tmc2130_home_fsteps[X_AXIS] = 48;
  1329. tmc2130_home_origin[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN);
  1330. tmc2130_home_bsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS);
  1331. tmc2130_home_fsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS);
  1332. if (tmc2130_home_origin[Y_AXIS] == 0xff) tmc2130_home_origin[Y_AXIS] = 0;
  1333. if (tmc2130_home_bsteps[Y_AXIS] == 0xff) tmc2130_home_bsteps[Y_AXIS] = 48;
  1334. if (tmc2130_home_fsteps[Y_AXIS] == 0xff) tmc2130_home_fsteps[Y_AXIS] = 48;
  1335. tmc2130_home_enabled = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED);
  1336. if (tmc2130_home_enabled == 0xff) tmc2130_home_enabled = 0;
  1337. #endif //TMC2130
  1338. #ifdef UVLO_SUPPORT
  1339. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1340. /*
  1341. if (lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1342. else {
  1343. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1344. lcd_update_enable(true);
  1345. lcd_update(2);
  1346. lcd_setstatuspgm(_T(WELCOME_MSG));
  1347. }
  1348. */
  1349. manage_heater(); // Update temperatures
  1350. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1351. printf_P(_N("Power panic detected!\nCurrent bed temp:%d\nSaved bed temp:%d\n"), (int)degBed(), eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED));
  1352. #endif
  1353. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1354. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1355. puts_P(_N("Automatic recovery!"));
  1356. #endif
  1357. recover_print(1);
  1358. }
  1359. else{
  1360. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1361. puts_P(_N("Normal recovery!"));
  1362. #endif
  1363. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) ) recover_print(0);
  1364. else {
  1365. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1366. lcd_update_enable(true);
  1367. lcd_update(2);
  1368. lcd_setstatuspgm(_T(WELCOME_MSG));
  1369. }
  1370. }
  1371. }
  1372. #endif //UVLO_SUPPORT
  1373. fCheckModeInit();
  1374. fSetMmuMode(mmu_enabled);
  1375. KEEPALIVE_STATE(NOT_BUSY);
  1376. #ifdef WATCHDOG
  1377. wdt_enable(WDTO_4S);
  1378. #endif //WATCHDOG
  1379. }
  1380. void trace();
  1381. #define CHUNK_SIZE 64 // bytes
  1382. #define SAFETY_MARGIN 1
  1383. char chunk[CHUNK_SIZE+SAFETY_MARGIN];
  1384. int chunkHead = 0;
  1385. void serial_read_stream() {
  1386. setAllTargetHotends(0);
  1387. setTargetBed(0);
  1388. lcd_clear();
  1389. lcd_puts_P(PSTR(" Upload in progress"));
  1390. // first wait for how many bytes we will receive
  1391. uint32_t bytesToReceive;
  1392. // receive the four bytes
  1393. char bytesToReceiveBuffer[4];
  1394. for (int i=0; i<4; i++) {
  1395. int data;
  1396. while ((data = MYSERIAL.read()) == -1) {};
  1397. bytesToReceiveBuffer[i] = data;
  1398. }
  1399. // make it a uint32
  1400. memcpy(&bytesToReceive, &bytesToReceiveBuffer, 4);
  1401. // we're ready, notify the sender
  1402. MYSERIAL.write('+');
  1403. // lock in the routine
  1404. uint32_t receivedBytes = 0;
  1405. while (prusa_sd_card_upload) {
  1406. int i;
  1407. for (i=0; i<CHUNK_SIZE; i++) {
  1408. int data;
  1409. // check if we're not done
  1410. if (receivedBytes == bytesToReceive) {
  1411. break;
  1412. }
  1413. // read the next byte
  1414. while ((data = MYSERIAL.read()) == -1) {};
  1415. receivedBytes++;
  1416. // save it to the chunk
  1417. chunk[i] = data;
  1418. }
  1419. // write the chunk to SD
  1420. card.write_command_no_newline(&chunk[0]);
  1421. // notify the sender we're ready for more data
  1422. MYSERIAL.write('+');
  1423. // for safety
  1424. manage_heater();
  1425. // check if we're done
  1426. if(receivedBytes == bytesToReceive) {
  1427. trace(); // beep
  1428. card.closefile();
  1429. prusa_sd_card_upload = false;
  1430. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1431. }
  1432. }
  1433. }
  1434. /**
  1435. * Output a "busy" message at regular intervals
  1436. * while the machine is not accepting commands.
  1437. */
  1438. void host_keepalive() {
  1439. #ifndef HOST_KEEPALIVE_FEATURE
  1440. return;
  1441. #endif //HOST_KEEPALIVE_FEATURE
  1442. if (farm_mode) return;
  1443. long ms = _millis();
  1444. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1445. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1446. switch (busy_state) {
  1447. case IN_HANDLER:
  1448. case IN_PROCESS:
  1449. SERIAL_ECHO_START;
  1450. SERIAL_ECHOLNPGM("busy: processing");
  1451. break;
  1452. case PAUSED_FOR_USER:
  1453. SERIAL_ECHO_START;
  1454. SERIAL_ECHOLNPGM("busy: paused for user");
  1455. break;
  1456. case PAUSED_FOR_INPUT:
  1457. SERIAL_ECHO_START;
  1458. SERIAL_ECHOLNPGM("busy: paused for input");
  1459. break;
  1460. default:
  1461. break;
  1462. }
  1463. }
  1464. prev_busy_signal_ms = ms;
  1465. }
  1466. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1467. // Before loop(), the setup() function is called by the main() routine.
  1468. void loop()
  1469. {
  1470. KEEPALIVE_STATE(NOT_BUSY);
  1471. if ((usb_printing_counter > 0) && ((_millis()-_usb_timer) > 1000))
  1472. {
  1473. is_usb_printing = true;
  1474. usb_printing_counter--;
  1475. _usb_timer = _millis();
  1476. }
  1477. if (usb_printing_counter == 0)
  1478. {
  1479. is_usb_printing = false;
  1480. }
  1481. if (prusa_sd_card_upload)
  1482. {
  1483. //we read byte-by byte
  1484. serial_read_stream();
  1485. } else
  1486. {
  1487. get_command();
  1488. #ifdef SDSUPPORT
  1489. card.checkautostart(false);
  1490. #endif
  1491. if(buflen)
  1492. {
  1493. cmdbuffer_front_already_processed = false;
  1494. #ifdef SDSUPPORT
  1495. if(card.saving)
  1496. {
  1497. // Saving a G-code file onto an SD-card is in progress.
  1498. // Saving starts with M28, saving until M29 is seen.
  1499. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1500. card.write_command(CMDBUFFER_CURRENT_STRING);
  1501. if(card.logging)
  1502. process_commands();
  1503. else
  1504. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1505. } else {
  1506. card.closefile();
  1507. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1508. }
  1509. } else {
  1510. process_commands();
  1511. }
  1512. #else
  1513. process_commands();
  1514. #endif //SDSUPPORT
  1515. if (! cmdbuffer_front_already_processed && buflen)
  1516. {
  1517. // ptr points to the start of the block currently being processed.
  1518. // The first character in the block is the block type.
  1519. char *ptr = cmdbuffer + bufindr;
  1520. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1521. // To support power panic, move the lenght of the command on the SD card to a planner buffer.
  1522. union {
  1523. struct {
  1524. char lo;
  1525. char hi;
  1526. } lohi;
  1527. uint16_t value;
  1528. } sdlen;
  1529. sdlen.value = 0;
  1530. {
  1531. // This block locks the interrupts globally for 3.25 us,
  1532. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1533. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1534. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1535. cli();
  1536. // Reset the command to something, which will be ignored by the power panic routine,
  1537. // so this buffer length will not be counted twice.
  1538. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1539. // Extract the current buffer length.
  1540. sdlen.lohi.lo = *ptr ++;
  1541. sdlen.lohi.hi = *ptr;
  1542. // and pass it to the planner queue.
  1543. planner_add_sd_length(sdlen.value);
  1544. sei();
  1545. }
  1546. }
  1547. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1548. cli();
  1549. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1550. // and one for each command to previous block in the planner queue.
  1551. planner_add_sd_length(1);
  1552. sei();
  1553. }
  1554. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1555. // this block's SD card length will not be counted twice as its command type has been replaced
  1556. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1557. cmdqueue_pop_front();
  1558. }
  1559. host_keepalive();
  1560. }
  1561. }
  1562. //check heater every n milliseconds
  1563. manage_heater();
  1564. isPrintPaused ? manage_inactivity(true) : manage_inactivity(false);
  1565. checkHitEndstops();
  1566. lcd_update(0);
  1567. #ifdef TMC2130
  1568. tmc2130_check_overtemp();
  1569. if (tmc2130_sg_crash)
  1570. {
  1571. uint8_t crash = tmc2130_sg_crash;
  1572. tmc2130_sg_crash = 0;
  1573. // crashdet_stop_and_save_print();
  1574. switch (crash)
  1575. {
  1576. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1577. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1578. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1579. }
  1580. }
  1581. #endif //TMC2130
  1582. mmu_loop();
  1583. }
  1584. #define DEFINE_PGM_READ_ANY(type, reader) \
  1585. static inline type pgm_read_any(const type *p) \
  1586. { return pgm_read_##reader##_near(p); }
  1587. DEFINE_PGM_READ_ANY(float, float);
  1588. DEFINE_PGM_READ_ANY(signed char, byte);
  1589. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1590. static const PROGMEM type array##_P[3] = \
  1591. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1592. static inline type array(int axis) \
  1593. { return pgm_read_any(&array##_P[axis]); } \
  1594. type array##_ext(int axis) \
  1595. { return pgm_read_any(&array##_P[axis]); }
  1596. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1597. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1598. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1599. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1600. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1601. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1602. static void axis_is_at_home(int axis) {
  1603. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1604. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1605. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1606. }
  1607. inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); }
  1608. inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); }
  1609. //! @return original feedmultiply
  1610. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1611. saved_feedrate = feedrate;
  1612. int l_feedmultiply = feedmultiply;
  1613. feedmultiply = 100;
  1614. previous_millis_cmd = _millis();
  1615. enable_endstops(enable_endstops_now);
  1616. return l_feedmultiply;
  1617. }
  1618. //! @param original_feedmultiply feedmultiply to restore
  1619. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1620. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1621. enable_endstops(false);
  1622. #endif
  1623. feedrate = saved_feedrate;
  1624. feedmultiply = original_feedmultiply;
  1625. previous_millis_cmd = _millis();
  1626. }
  1627. #ifdef ENABLE_AUTO_BED_LEVELING
  1628. #ifdef AUTO_BED_LEVELING_GRID
  1629. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1630. {
  1631. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1632. planeNormal.debug("planeNormal");
  1633. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1634. //bedLevel.debug("bedLevel");
  1635. //plan_bed_level_matrix.debug("bed level before");
  1636. //vector_3 uncorrected_position = plan_get_position_mm();
  1637. //uncorrected_position.debug("position before");
  1638. vector_3 corrected_position = plan_get_position();
  1639. // corrected_position.debug("position after");
  1640. current_position[X_AXIS] = corrected_position.x;
  1641. current_position[Y_AXIS] = corrected_position.y;
  1642. current_position[Z_AXIS] = corrected_position.z;
  1643. // put the bed at 0 so we don't go below it.
  1644. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1645. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1646. }
  1647. #else // not AUTO_BED_LEVELING_GRID
  1648. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1649. plan_bed_level_matrix.set_to_identity();
  1650. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1651. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1652. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1653. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1654. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1655. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1656. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1657. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1658. vector_3 corrected_position = plan_get_position();
  1659. current_position[X_AXIS] = corrected_position.x;
  1660. current_position[Y_AXIS] = corrected_position.y;
  1661. current_position[Z_AXIS] = corrected_position.z;
  1662. // put the bed at 0 so we don't go below it.
  1663. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1664. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1665. }
  1666. #endif // AUTO_BED_LEVELING_GRID
  1667. static void run_z_probe() {
  1668. plan_bed_level_matrix.set_to_identity();
  1669. feedrate = homing_feedrate[Z_AXIS];
  1670. // move down until you find the bed
  1671. float zPosition = -10;
  1672. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1673. st_synchronize();
  1674. // we have to let the planner know where we are right now as it is not where we said to go.
  1675. zPosition = st_get_position_mm(Z_AXIS);
  1676. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1677. // move up the retract distance
  1678. zPosition += home_retract_mm(Z_AXIS);
  1679. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1680. st_synchronize();
  1681. // move back down slowly to find bed
  1682. feedrate = homing_feedrate[Z_AXIS]/4;
  1683. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1684. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1685. st_synchronize();
  1686. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1687. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1688. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1689. }
  1690. static void do_blocking_move_to(float x, float y, float z) {
  1691. float oldFeedRate = feedrate;
  1692. feedrate = homing_feedrate[Z_AXIS];
  1693. current_position[Z_AXIS] = z;
  1694. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder);
  1695. st_synchronize();
  1696. feedrate = XY_TRAVEL_SPEED;
  1697. current_position[X_AXIS] = x;
  1698. current_position[Y_AXIS] = y;
  1699. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder);
  1700. st_synchronize();
  1701. feedrate = oldFeedRate;
  1702. }
  1703. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1704. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1705. }
  1706. /// Probe bed height at position (x,y), returns the measured z value
  1707. static float probe_pt(float x, float y, float z_before) {
  1708. // move to right place
  1709. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1710. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1711. run_z_probe();
  1712. float measured_z = current_position[Z_AXIS];
  1713. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1714. SERIAL_PROTOCOLPGM(" x: ");
  1715. SERIAL_PROTOCOL(x);
  1716. SERIAL_PROTOCOLPGM(" y: ");
  1717. SERIAL_PROTOCOL(y);
  1718. SERIAL_PROTOCOLPGM(" z: ");
  1719. SERIAL_PROTOCOL(measured_z);
  1720. SERIAL_PROTOCOLPGM("\n");
  1721. return measured_z;
  1722. }
  1723. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1724. #ifdef LIN_ADVANCE
  1725. /**
  1726. * M900: Set and/or Get advance K factor and WH/D ratio
  1727. *
  1728. * K<factor> Set advance K factor
  1729. * R<ratio> Set ratio directly (overrides WH/D)
  1730. * W<width> H<height> D<diam> Set ratio from WH/D
  1731. */
  1732. inline void gcode_M900() {
  1733. st_synchronize();
  1734. const float newK = code_seen('K') ? code_value_float() : -1;
  1735. if (newK >= 0) extruder_advance_k = newK;
  1736. float newR = code_seen('R') ? code_value_float() : -1;
  1737. if (newR < 0) {
  1738. const float newD = code_seen('D') ? code_value_float() : -1,
  1739. newW = code_seen('W') ? code_value_float() : -1,
  1740. newH = code_seen('H') ? code_value_float() : -1;
  1741. if (newD >= 0 && newW >= 0 && newH >= 0)
  1742. newR = newD ? (newW * newH) / (sq(newD * 0.5) * M_PI) : 0;
  1743. }
  1744. if (newR >= 0) advance_ed_ratio = newR;
  1745. SERIAL_ECHO_START;
  1746. SERIAL_ECHOPGM("Advance K=");
  1747. SERIAL_ECHOLN(extruder_advance_k);
  1748. SERIAL_ECHOPGM(" E/D=");
  1749. const float ratio = advance_ed_ratio;
  1750. if (ratio) SERIAL_ECHOLN(ratio); else SERIAL_ECHOLNPGM("Auto");
  1751. }
  1752. #endif // LIN_ADVANCE
  1753. bool check_commands() {
  1754. bool end_command_found = false;
  1755. while (buflen)
  1756. {
  1757. if ((code_seen("M84")) || (code_seen("M 84"))) end_command_found = true;
  1758. if (!cmdbuffer_front_already_processed)
  1759. cmdqueue_pop_front();
  1760. cmdbuffer_front_already_processed = false;
  1761. }
  1762. return end_command_found;
  1763. }
  1764. #ifdef TMC2130
  1765. bool calibrate_z_auto()
  1766. {
  1767. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1768. lcd_clear();
  1769. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1770. bool endstops_enabled = enable_endstops(true);
  1771. int axis_up_dir = -home_dir(Z_AXIS);
  1772. tmc2130_home_enter(Z_AXIS_MASK);
  1773. current_position[Z_AXIS] = 0;
  1774. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1775. set_destination_to_current();
  1776. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1777. feedrate = homing_feedrate[Z_AXIS];
  1778. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / 60, active_extruder);
  1779. st_synchronize();
  1780. // current_position[axis] = 0;
  1781. // plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1782. tmc2130_home_exit();
  1783. enable_endstops(false);
  1784. current_position[Z_AXIS] = 0;
  1785. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1786. set_destination_to_current();
  1787. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1788. feedrate = homing_feedrate[Z_AXIS] / 2;
  1789. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / 60, active_extruder);
  1790. st_synchronize();
  1791. enable_endstops(endstops_enabled);
  1792. if (PRINTER_TYPE == PRINTER_MK3) {
  1793. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1794. }
  1795. else {
  1796. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1797. }
  1798. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1799. return true;
  1800. }
  1801. #endif //TMC2130
  1802. #ifdef TMC2130
  1803. void homeaxis(int axis, uint8_t cnt, uint8_t* pstep)
  1804. #else
  1805. void homeaxis(int axis, uint8_t cnt)
  1806. #endif //TMC2130
  1807. {
  1808. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1809. #define HOMEAXIS_DO(LETTER) \
  1810. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1811. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1812. {
  1813. int axis_home_dir = home_dir(axis);
  1814. feedrate = homing_feedrate[axis];
  1815. #ifdef TMC2130
  1816. tmc2130_home_enter(X_AXIS_MASK << axis);
  1817. #endif //TMC2130
  1818. // Move away a bit, so that the print head does not touch the end position,
  1819. // and the following movement to endstop has a chance to achieve the required velocity
  1820. // for the stall guard to work.
  1821. current_position[axis] = 0;
  1822. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1823. set_destination_to_current();
  1824. // destination[axis] = 11.f;
  1825. destination[axis] = -3.f * axis_home_dir;
  1826. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1827. st_synchronize();
  1828. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1829. endstops_hit_on_purpose();
  1830. enable_endstops(false);
  1831. current_position[axis] = 0;
  1832. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1833. destination[axis] = 1. * axis_home_dir;
  1834. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1835. st_synchronize();
  1836. // Now continue to move up to the left end stop with the collision detection enabled.
  1837. enable_endstops(true);
  1838. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1839. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1840. st_synchronize();
  1841. for (uint8_t i = 0; i < cnt; i++)
  1842. {
  1843. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1844. endstops_hit_on_purpose();
  1845. enable_endstops(false);
  1846. current_position[axis] = 0;
  1847. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1848. destination[axis] = -10.f * axis_home_dir;
  1849. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1850. st_synchronize();
  1851. endstops_hit_on_purpose();
  1852. // Now move left up to the collision, this time with a repeatable velocity.
  1853. enable_endstops(true);
  1854. destination[axis] = 11.f * axis_home_dir;
  1855. #ifdef TMC2130
  1856. feedrate = homing_feedrate[axis];
  1857. #else //TMC2130
  1858. feedrate = homing_feedrate[axis] / 2;
  1859. #endif //TMC2130
  1860. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1861. st_synchronize();
  1862. #ifdef TMC2130
  1863. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1864. if (pstep) pstep[i] = mscnt >> 4;
  1865. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1866. #endif //TMC2130
  1867. }
  1868. endstops_hit_on_purpose();
  1869. enable_endstops(false);
  1870. #ifdef TMC2130
  1871. uint8_t orig = tmc2130_home_origin[axis];
  1872. uint8_t back = tmc2130_home_bsteps[axis];
  1873. if (tmc2130_home_enabled && (orig <= 63))
  1874. {
  1875. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1876. if (back > 0)
  1877. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1878. }
  1879. else
  1880. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1881. tmc2130_home_exit();
  1882. #endif //TMC2130
  1883. axis_is_at_home(axis);
  1884. axis_known_position[axis] = true;
  1885. // Move from minimum
  1886. #ifdef TMC2130
  1887. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1888. #else //TMC2130
  1889. float dist = - axis_home_dir * 0.01f * 64;
  1890. #endif //TMC2130
  1891. current_position[axis] -= dist;
  1892. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1893. current_position[axis] += dist;
  1894. destination[axis] = current_position[axis];
  1895. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], 0.5f*feedrate/60, active_extruder);
  1896. st_synchronize();
  1897. feedrate = 0.0;
  1898. }
  1899. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1900. {
  1901. #ifdef TMC2130
  1902. FORCE_HIGH_POWER_START;
  1903. #endif
  1904. int axis_home_dir = home_dir(axis);
  1905. current_position[axis] = 0;
  1906. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1907. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1908. feedrate = homing_feedrate[axis];
  1909. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1910. st_synchronize();
  1911. #ifdef TMC2130
  1912. if (READ(Z_TMC2130_DIAG) != 0) { //Z crash
  1913. FORCE_HIGH_POWER_END;
  1914. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1915. return;
  1916. }
  1917. #endif //TMC2130
  1918. current_position[axis] = 0;
  1919. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1920. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1921. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1922. st_synchronize();
  1923. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1924. feedrate = homing_feedrate[axis]/2 ;
  1925. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1926. st_synchronize();
  1927. #ifdef TMC2130
  1928. if (READ(Z_TMC2130_DIAG) != 0) { //Z crash
  1929. FORCE_HIGH_POWER_END;
  1930. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1931. return;
  1932. }
  1933. #endif //TMC2130
  1934. axis_is_at_home(axis);
  1935. destination[axis] = current_position[axis];
  1936. feedrate = 0.0;
  1937. endstops_hit_on_purpose();
  1938. axis_known_position[axis] = true;
  1939. #ifdef TMC2130
  1940. FORCE_HIGH_POWER_END;
  1941. #endif
  1942. }
  1943. enable_endstops(endstops_enabled);
  1944. }
  1945. /**/
  1946. void home_xy()
  1947. {
  1948. set_destination_to_current();
  1949. homeaxis(X_AXIS);
  1950. homeaxis(Y_AXIS);
  1951. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1952. endstops_hit_on_purpose();
  1953. }
  1954. void refresh_cmd_timeout(void)
  1955. {
  1956. previous_millis_cmd = _millis();
  1957. }
  1958. #ifdef FWRETRACT
  1959. void retract(bool retracting, bool swapretract = false) {
  1960. if(retracting && !retracted[active_extruder]) {
  1961. destination[X_AXIS]=current_position[X_AXIS];
  1962. destination[Y_AXIS]=current_position[Y_AXIS];
  1963. destination[Z_AXIS]=current_position[Z_AXIS];
  1964. destination[E_AXIS]=current_position[E_AXIS];
  1965. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  1966. plan_set_e_position(current_position[E_AXIS]);
  1967. float oldFeedrate = feedrate;
  1968. feedrate=cs.retract_feedrate*60;
  1969. retracted[active_extruder]=true;
  1970. prepare_move();
  1971. current_position[Z_AXIS]-=cs.retract_zlift;
  1972. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1973. prepare_move();
  1974. feedrate = oldFeedrate;
  1975. } else if(!retracting && retracted[active_extruder]) {
  1976. destination[X_AXIS]=current_position[X_AXIS];
  1977. destination[Y_AXIS]=current_position[Y_AXIS];
  1978. destination[Z_AXIS]=current_position[Z_AXIS];
  1979. destination[E_AXIS]=current_position[E_AXIS];
  1980. current_position[Z_AXIS]+=cs.retract_zlift;
  1981. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1982. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  1983. plan_set_e_position(current_position[E_AXIS]);
  1984. float oldFeedrate = feedrate;
  1985. feedrate=cs.retract_recover_feedrate*60;
  1986. retracted[active_extruder]=false;
  1987. prepare_move();
  1988. feedrate = oldFeedrate;
  1989. }
  1990. } //retract
  1991. #endif //FWRETRACT
  1992. void trace() {
  1993. Sound_MakeCustom(25,440,true);
  1994. }
  1995. /*
  1996. void ramming() {
  1997. // float tmp[4] = DEFAULT_MAX_FEEDRATE;
  1998. if (current_temperature[0] < 230) {
  1999. //PLA
  2000. max_feedrate[E_AXIS] = 50;
  2001. //current_position[E_AXIS] -= 8;
  2002. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  2003. //current_position[E_AXIS] += 8;
  2004. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  2005. current_position[E_AXIS] += 5.4;
  2006. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2800 / 60, active_extruder);
  2007. current_position[E_AXIS] += 3.2;
  2008. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2009. current_position[E_AXIS] += 3;
  2010. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3400 / 60, active_extruder);
  2011. st_synchronize();
  2012. max_feedrate[E_AXIS] = 80;
  2013. current_position[E_AXIS] -= 82;
  2014. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 9500 / 60, active_extruder);
  2015. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  2016. current_position[E_AXIS] -= 20;
  2017. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 1200 / 60, active_extruder);
  2018. current_position[E_AXIS] += 5;
  2019. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400 / 60, active_extruder);
  2020. current_position[E_AXIS] += 5;
  2021. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2022. current_position[E_AXIS] -= 10;
  2023. st_synchronize();
  2024. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2025. current_position[E_AXIS] += 10;
  2026. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2027. current_position[E_AXIS] -= 10;
  2028. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  2029. current_position[E_AXIS] += 10;
  2030. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  2031. current_position[E_AXIS] -= 10;
  2032. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  2033. st_synchronize();
  2034. }
  2035. else {
  2036. //ABS
  2037. max_feedrate[E_AXIS] = 50;
  2038. //current_position[E_AXIS] -= 8;
  2039. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  2040. //current_position[E_AXIS] += 8;
  2041. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  2042. current_position[E_AXIS] += 3.1;
  2043. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2000 / 60, active_extruder);
  2044. current_position[E_AXIS] += 3.1;
  2045. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2500 / 60, active_extruder);
  2046. current_position[E_AXIS] += 4;
  2047. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2048. st_synchronize();
  2049. //current_position[X_AXIS] += 23; //delay
  2050. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600/60, active_extruder); //delay
  2051. //current_position[X_AXIS] -= 23; //delay
  2052. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600/60, active_extruder); //delay
  2053. _delay(4700);
  2054. max_feedrate[E_AXIS] = 80;
  2055. current_position[E_AXIS] -= 92;
  2056. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 9900 / 60, active_extruder);
  2057. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  2058. current_position[E_AXIS] -= 5;
  2059. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  2060. current_position[E_AXIS] += 5;
  2061. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400 / 60, active_extruder);
  2062. current_position[E_AXIS] -= 5;
  2063. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2064. st_synchronize();
  2065. current_position[E_AXIS] += 5;
  2066. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2067. current_position[E_AXIS] -= 5;
  2068. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2069. current_position[E_AXIS] += 5;
  2070. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2071. current_position[E_AXIS] -= 5;
  2072. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2073. st_synchronize();
  2074. }
  2075. }
  2076. */
  2077. #ifdef TMC2130
  2078. void force_high_power_mode(bool start_high_power_section) {
  2079. uint8_t silent;
  2080. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2081. if (silent == 1) {
  2082. //we are in silent mode, set to normal mode to enable crash detection
  2083. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2084. st_synchronize();
  2085. cli();
  2086. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2087. update_mode_profile();
  2088. tmc2130_init();
  2089. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2090. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2091. st_reset_timer();
  2092. sei();
  2093. }
  2094. }
  2095. #endif //TMC2130
  2096. #ifdef TMC2130
  2097. static void gcode_G28(bool home_x_axis, long home_x_value, bool home_y_axis, long home_y_value, bool home_z_axis, long home_z_value, bool calib, bool without_mbl)
  2098. #else
  2099. static void gcode_G28(bool home_x_axis, long home_x_value, bool home_y_axis, long home_y_value, bool home_z_axis, long home_z_value, bool without_mbl)
  2100. #endif //TMC2130
  2101. {
  2102. st_synchronize();
  2103. #if 0
  2104. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2105. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2106. #endif
  2107. // Flag for the display update routine and to disable the print cancelation during homing.
  2108. homing_flag = true;
  2109. // Which axes should be homed?
  2110. bool home_x = home_x_axis;
  2111. bool home_y = home_y_axis;
  2112. bool home_z = home_z_axis;
  2113. // Either all X,Y,Z codes are present, or none of them.
  2114. bool home_all_axes = home_x == home_y && home_x == home_z;
  2115. if (home_all_axes)
  2116. // No X/Y/Z code provided means to home all axes.
  2117. home_x = home_y = home_z = true;
  2118. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2119. if (home_all_axes) {
  2120. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  2121. feedrate = homing_feedrate[Z_AXIS];
  2122. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate / 60, active_extruder);
  2123. st_synchronize();
  2124. }
  2125. #ifdef ENABLE_AUTO_BED_LEVELING
  2126. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2127. #endif //ENABLE_AUTO_BED_LEVELING
  2128. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2129. // the planner will not perform any adjustments in the XY plane.
  2130. // Wait for the motors to stop and update the current position with the absolute values.
  2131. world2machine_revert_to_uncorrected();
  2132. // For mesh bed leveling deactivate the matrix temporarily.
  2133. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2134. // in a single axis only.
  2135. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2136. #ifdef MESH_BED_LEVELING
  2137. uint8_t mbl_was_active = mbl.active;
  2138. mbl.active = 0;
  2139. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2140. #endif
  2141. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  2142. // consumed during the first movements following this statement.
  2143. if (home_z)
  2144. babystep_undo();
  2145. saved_feedrate = feedrate;
  2146. int l_feedmultiply = feedmultiply;
  2147. feedmultiply = 100;
  2148. previous_millis_cmd = _millis();
  2149. enable_endstops(true);
  2150. memcpy(destination, current_position, sizeof(destination));
  2151. feedrate = 0.0;
  2152. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2153. if(home_z)
  2154. homeaxis(Z_AXIS);
  2155. #endif
  2156. #ifdef QUICK_HOME
  2157. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2158. if(home_x && home_y) //first diagonal move
  2159. {
  2160. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2161. int x_axis_home_dir = home_dir(X_AXIS);
  2162. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2163. 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);
  2164. feedrate = homing_feedrate[X_AXIS];
  2165. if(homing_feedrate[Y_AXIS]<feedrate)
  2166. feedrate = homing_feedrate[Y_AXIS];
  2167. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2168. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2169. } else {
  2170. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2171. }
  2172. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  2173. st_synchronize();
  2174. axis_is_at_home(X_AXIS);
  2175. axis_is_at_home(Y_AXIS);
  2176. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2177. destination[X_AXIS] = current_position[X_AXIS];
  2178. destination[Y_AXIS] = current_position[Y_AXIS];
  2179. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  2180. feedrate = 0.0;
  2181. st_synchronize();
  2182. endstops_hit_on_purpose();
  2183. current_position[X_AXIS] = destination[X_AXIS];
  2184. current_position[Y_AXIS] = destination[Y_AXIS];
  2185. current_position[Z_AXIS] = destination[Z_AXIS];
  2186. }
  2187. #endif /* QUICK_HOME */
  2188. #ifdef TMC2130
  2189. if(home_x)
  2190. {
  2191. if (!calib)
  2192. homeaxis(X_AXIS);
  2193. else
  2194. tmc2130_home_calibrate(X_AXIS);
  2195. }
  2196. if(home_y)
  2197. {
  2198. if (!calib)
  2199. homeaxis(Y_AXIS);
  2200. else
  2201. tmc2130_home_calibrate(Y_AXIS);
  2202. }
  2203. #else //TMC2130
  2204. if(home_x) homeaxis(X_AXIS);
  2205. if(home_y) homeaxis(Y_AXIS);
  2206. #endif //TMC2130
  2207. if(home_x_axis && home_x_value != 0)
  2208. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2209. if(home_y_axis && home_y_value != 0)
  2210. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2211. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2212. #ifndef Z_SAFE_HOMING
  2213. if(home_z) {
  2214. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2215. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2216. feedrate = max_feedrate[Z_AXIS];
  2217. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2218. st_synchronize();
  2219. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2220. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP)) // If Mesh bed leveling, move X&Y to safe position for home
  2221. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] ))
  2222. {
  2223. homeaxis(X_AXIS);
  2224. homeaxis(Y_AXIS);
  2225. }
  2226. // 1st mesh bed leveling measurement point, corrected.
  2227. world2machine_initialize();
  2228. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2229. world2machine_reset();
  2230. if (destination[Y_AXIS] < Y_MIN_POS)
  2231. destination[Y_AXIS] = Y_MIN_POS;
  2232. destination[Z_AXIS] = MESH_HOME_Z_SEARCH; // Set destination away from bed
  2233. feedrate = homing_feedrate[Z_AXIS]/10;
  2234. current_position[Z_AXIS] = 0;
  2235. enable_endstops(false);
  2236. #ifdef DEBUG_BUILD
  2237. SERIAL_ECHOLNPGM("plan_set_position()");
  2238. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2239. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2240. #endif
  2241. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2242. #ifdef DEBUG_BUILD
  2243. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2244. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2245. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2246. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2247. #endif
  2248. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2249. st_synchronize();
  2250. current_position[X_AXIS] = destination[X_AXIS];
  2251. current_position[Y_AXIS] = destination[Y_AXIS];
  2252. enable_endstops(true);
  2253. endstops_hit_on_purpose();
  2254. homeaxis(Z_AXIS);
  2255. #else // MESH_BED_LEVELING
  2256. homeaxis(Z_AXIS);
  2257. #endif // MESH_BED_LEVELING
  2258. }
  2259. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2260. if(home_all_axes) {
  2261. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2262. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2263. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2264. feedrate = XY_TRAVEL_SPEED/60;
  2265. current_position[Z_AXIS] = 0;
  2266. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2267. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2268. st_synchronize();
  2269. current_position[X_AXIS] = destination[X_AXIS];
  2270. current_position[Y_AXIS] = destination[Y_AXIS];
  2271. homeaxis(Z_AXIS);
  2272. }
  2273. // Let's see if X and Y are homed and probe is inside bed area.
  2274. if(home_z) {
  2275. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2276. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2277. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2278. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2279. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2280. current_position[Z_AXIS] = 0;
  2281. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2282. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2283. feedrate = max_feedrate[Z_AXIS];
  2284. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2285. st_synchronize();
  2286. homeaxis(Z_AXIS);
  2287. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2288. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2289. SERIAL_ECHO_START;
  2290. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2291. } else {
  2292. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2293. SERIAL_ECHO_START;
  2294. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2295. }
  2296. }
  2297. #endif // Z_SAFE_HOMING
  2298. #endif // Z_HOME_DIR < 0
  2299. if(home_z_axis && home_z_value != 0)
  2300. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2301. #ifdef ENABLE_AUTO_BED_LEVELING
  2302. if(home_z)
  2303. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2304. #endif
  2305. // Set the planner and stepper routine positions.
  2306. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2307. // contains the machine coordinates.
  2308. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2309. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  2310. enable_endstops(false);
  2311. #endif
  2312. feedrate = saved_feedrate;
  2313. feedmultiply = l_feedmultiply;
  2314. previous_millis_cmd = _millis();
  2315. endstops_hit_on_purpose();
  2316. #ifndef MESH_BED_LEVELING
  2317. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  2318. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  2319. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  2320. lcd_adjust_z();
  2321. #endif
  2322. // Load the machine correction matrix
  2323. world2machine_initialize();
  2324. // and correct the current_position XY axes to match the transformed coordinate system.
  2325. world2machine_update_current();
  2326. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP))
  2327. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2328. {
  2329. if (! home_z && mbl_was_active) {
  2330. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2331. mbl.active = true;
  2332. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2333. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2334. }
  2335. }
  2336. else
  2337. {
  2338. st_synchronize();
  2339. homing_flag = false;
  2340. }
  2341. #endif
  2342. if (farm_mode) { prusa_statistics(20); };
  2343. homing_flag = false;
  2344. #if 0
  2345. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2346. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2347. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2348. #endif
  2349. }
  2350. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2351. {
  2352. #ifdef TMC2130
  2353. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2354. #else
  2355. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2356. #endif //TMC2130
  2357. }
  2358. void adjust_bed_reset()
  2359. {
  2360. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2361. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2362. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2363. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2364. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2365. }
  2366. //! @brief Calibrate XYZ
  2367. //! @param onlyZ if true, calibrate only Z axis
  2368. //! @param verbosity_level
  2369. //! @retval true Succeeded
  2370. //! @retval false Failed
  2371. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2372. {
  2373. bool final_result = false;
  2374. #ifdef TMC2130
  2375. FORCE_HIGH_POWER_START;
  2376. #endif // TMC2130
  2377. // Only Z calibration?
  2378. if (!onlyZ)
  2379. {
  2380. setTargetBed(0);
  2381. setAllTargetHotends(0);
  2382. adjust_bed_reset(); //reset bed level correction
  2383. }
  2384. // Disable the default update procedure of the display. We will do a modal dialog.
  2385. lcd_update_enable(false);
  2386. // Let the planner use the uncorrected coordinates.
  2387. mbl.reset();
  2388. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2389. // the planner will not perform any adjustments in the XY plane.
  2390. // Wait for the motors to stop and update the current position with the absolute values.
  2391. world2machine_revert_to_uncorrected();
  2392. // Reset the baby step value applied without moving the axes.
  2393. babystep_reset();
  2394. // Mark all axes as in a need for homing.
  2395. memset(axis_known_position, 0, sizeof(axis_known_position));
  2396. // Home in the XY plane.
  2397. //set_destination_to_current();
  2398. int l_feedmultiply = setup_for_endstop_move();
  2399. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2400. home_xy();
  2401. enable_endstops(false);
  2402. current_position[X_AXIS] += 5;
  2403. current_position[Y_AXIS] += 5;
  2404. 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);
  2405. st_synchronize();
  2406. // Let the user move the Z axes up to the end stoppers.
  2407. #ifdef TMC2130
  2408. if (calibrate_z_auto())
  2409. {
  2410. #else //TMC2130
  2411. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2412. {
  2413. #endif //TMC2130
  2414. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2415. if(onlyZ){
  2416. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2417. lcd_set_cursor(0, 3);
  2418. lcd_print(1);
  2419. lcd_puts_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE2));
  2420. }else{
  2421. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2422. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2423. lcd_set_cursor(0, 2);
  2424. lcd_print(1);
  2425. lcd_puts_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE2));
  2426. }
  2427. refresh_cmd_timeout();
  2428. #ifndef STEEL_SHEET
  2429. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2430. {
  2431. lcd_wait_for_cool_down();
  2432. }
  2433. #endif //STEEL_SHEET
  2434. if(!onlyZ)
  2435. {
  2436. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2437. #ifdef STEEL_SHEET
  2438. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  2439. if(result) lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2440. #endif //STEEL_SHEET
  2441. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2442. KEEPALIVE_STATE(IN_HANDLER);
  2443. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2444. lcd_set_cursor(0, 2);
  2445. lcd_print(1);
  2446. lcd_puts_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE2));
  2447. }
  2448. bool endstops_enabled = enable_endstops(false);
  2449. current_position[Z_AXIS] -= 1; //move 1mm down with disabled endstop
  2450. 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);
  2451. st_synchronize();
  2452. // Move the print head close to the bed.
  2453. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2454. enable_endstops(true);
  2455. #ifdef TMC2130
  2456. tmc2130_home_enter(Z_AXIS_MASK);
  2457. #endif //TMC2130
  2458. 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);
  2459. st_synchronize();
  2460. #ifdef TMC2130
  2461. tmc2130_home_exit();
  2462. #endif //TMC2130
  2463. enable_endstops(endstops_enabled);
  2464. if (st_get_position_mm(Z_AXIS) == MESH_HOME_Z_SEARCH)
  2465. {
  2466. if (onlyZ)
  2467. {
  2468. clean_up_after_endstop_move(l_feedmultiply);
  2469. // Z only calibration.
  2470. // Load the machine correction matrix
  2471. world2machine_initialize();
  2472. // and correct the current_position to match the transformed coordinate system.
  2473. world2machine_update_current();
  2474. //FIXME
  2475. bool result = sample_mesh_and_store_reference();
  2476. if (result)
  2477. {
  2478. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2479. // Shipped, the nozzle height has been set already. The user can start printing now.
  2480. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2481. final_result = true;
  2482. // babystep_apply();
  2483. }
  2484. }
  2485. else
  2486. {
  2487. // Reset the baby step value and the baby step applied flag.
  2488. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2489. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z, 0);
  2490. // Complete XYZ calibration.
  2491. uint8_t point_too_far_mask = 0;
  2492. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2493. clean_up_after_endstop_move(l_feedmultiply);
  2494. // Print head up.
  2495. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2496. 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);
  2497. st_synchronize();
  2498. //#ifndef NEW_XYZCAL
  2499. if (result >= 0)
  2500. {
  2501. #ifdef HEATBED_V2
  2502. sample_z();
  2503. #else //HEATBED_V2
  2504. point_too_far_mask = 0;
  2505. // Second half: The fine adjustment.
  2506. // Let the planner use the uncorrected coordinates.
  2507. mbl.reset();
  2508. world2machine_reset();
  2509. // Home in the XY plane.
  2510. int l_feedmultiply = setup_for_endstop_move();
  2511. home_xy();
  2512. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2513. clean_up_after_endstop_move(l_feedmultiply);
  2514. // Print head up.
  2515. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2516. 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);
  2517. st_synchronize();
  2518. // if (result >= 0) babystep_apply();
  2519. #endif //HEATBED_V2
  2520. }
  2521. //#endif //NEW_XYZCAL
  2522. lcd_update_enable(true);
  2523. lcd_update(2);
  2524. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2525. if (result >= 0)
  2526. {
  2527. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2528. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2529. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2530. final_result = true;
  2531. }
  2532. }
  2533. #ifdef TMC2130
  2534. tmc2130_home_exit();
  2535. #endif
  2536. }
  2537. else
  2538. {
  2539. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2540. final_result = false;
  2541. }
  2542. }
  2543. else
  2544. {
  2545. // Timeouted.
  2546. }
  2547. lcd_update_enable(true);
  2548. #ifdef TMC2130
  2549. FORCE_HIGH_POWER_END;
  2550. #endif // TMC2130
  2551. return final_result;
  2552. }
  2553. void gcode_M114()
  2554. {
  2555. SERIAL_PROTOCOLPGM("X:");
  2556. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2557. SERIAL_PROTOCOLPGM(" Y:");
  2558. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2559. SERIAL_PROTOCOLPGM(" Z:");
  2560. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2561. SERIAL_PROTOCOLPGM(" E:");
  2562. SERIAL_PROTOCOL(current_position[E_AXIS]);
  2563. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  2564. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  2565. SERIAL_PROTOCOLPGM(" Y:");
  2566. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  2567. SERIAL_PROTOCOLPGM(" Z:");
  2568. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  2569. SERIAL_PROTOCOLPGM(" E:");
  2570. SERIAL_PROTOCOL(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  2571. SERIAL_PROTOCOLLN("");
  2572. }
  2573. //! extracted code to compute z_shift for M600 in case of filament change operation
  2574. //! requested from fsensors.
  2575. //! The function ensures, that the printhead lifts to at least 25mm above the heat bed
  2576. //! unlike the previous implementation, which was adding 25mm even when the head was
  2577. //! printing at e.g. 24mm height.
  2578. //! A safety margin of FILAMENTCHANGE_ZADD is added in all cases to avoid touching
  2579. //! the printout.
  2580. //! This function is templated to enable fast change of computation data type.
  2581. //! @return new z_shift value
  2582. template<typename T>
  2583. static T gcode_M600_filament_change_z_shift()
  2584. {
  2585. #ifdef FILAMENTCHANGE_ZADD
  2586. static_assert(Z_MAX_POS < (255 - FILAMENTCHANGE_ZADD), "Z-range too high, change the T type from uint8_t to uint16_t");
  2587. // avoid floating point arithmetics when not necessary - results in shorter code
  2588. T ztmp = T( current_position[Z_AXIS] );
  2589. T z_shift = 0;
  2590. if(ztmp < T(25)){
  2591. z_shift = T(25) - ztmp; // make sure to be at least 25mm above the heat bed
  2592. }
  2593. return z_shift + T(FILAMENTCHANGE_ZADD); // always move above printout
  2594. #else
  2595. return T(0);
  2596. #endif
  2597. }
  2598. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/)
  2599. {
  2600. st_synchronize();
  2601. float lastpos[4];
  2602. if (farm_mode)
  2603. {
  2604. prusa_statistics(22);
  2605. }
  2606. //First backup current position and settings
  2607. int feedmultiplyBckp = feedmultiply;
  2608. float HotendTempBckp = degTargetHotend(active_extruder);
  2609. int fanSpeedBckp = fanSpeed;
  2610. lastpos[X_AXIS] = current_position[X_AXIS];
  2611. lastpos[Y_AXIS] = current_position[Y_AXIS];
  2612. lastpos[Z_AXIS] = current_position[Z_AXIS];
  2613. lastpos[E_AXIS] = current_position[E_AXIS];
  2614. //Retract E
  2615. current_position[E_AXIS] += e_shift;
  2616. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  2617. current_position[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  2618. st_synchronize();
  2619. //Lift Z
  2620. current_position[Z_AXIS] += z_shift;
  2621. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  2622. current_position[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  2623. st_synchronize();
  2624. //Move XY to side
  2625. current_position[X_AXIS] = x_position;
  2626. current_position[Y_AXIS] = y_position;
  2627. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  2628. current_position[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  2629. st_synchronize();
  2630. //Beep, manage nozzle heater and wait for user to start unload filament
  2631. if(!mmu_enabled) M600_wait_for_user(HotendTempBckp);
  2632. lcd_change_fil_state = 0;
  2633. // Unload filament
  2634. if (mmu_enabled) extr_unload(); //unload just current filament for multimaterial printers (used also in M702)
  2635. else unload_filament(); //unload filament for single material (used also in M702)
  2636. //finish moves
  2637. st_synchronize();
  2638. if (!mmu_enabled)
  2639. {
  2640. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2641. lcd_change_fil_state = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Was filament unload successful?"),
  2642. false, true); ////MSG_UNLOAD_SUCCESSFUL c=20 r=2
  2643. if (lcd_change_fil_state == 0)
  2644. {
  2645. lcd_clear();
  2646. lcd_set_cursor(0, 2);
  2647. lcd_puts_P(_T(MSG_PLEASE_WAIT));
  2648. current_position[X_AXIS] -= 100;
  2649. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  2650. current_position[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  2651. st_synchronize();
  2652. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually."));////MSG_CHECK_IDLER c=20 r=4
  2653. }
  2654. }
  2655. if (mmu_enabled)
  2656. {
  2657. if (!automatic) {
  2658. if (saved_printing) mmu_eject_filament(mmu_extruder, false); //if M600 was invoked by filament senzor (FINDA) eject filament so user can easily remove it
  2659. mmu_M600_wait_and_beep();
  2660. if (saved_printing) {
  2661. lcd_clear();
  2662. lcd_set_cursor(0, 2);
  2663. lcd_puts_P(_T(MSG_PLEASE_WAIT));
  2664. mmu_command(MmuCmd::R0);
  2665. manage_response(false, false);
  2666. }
  2667. }
  2668. mmu_M600_load_filament(automatic, HotendTempBckp);
  2669. }
  2670. else
  2671. M600_load_filament();
  2672. if (!automatic) M600_check_state(HotendTempBckp);
  2673. lcd_update_enable(true);
  2674. //Not let's go back to print
  2675. fanSpeed = fanSpeedBckp;
  2676. //Feed a little of filament to stabilize pressure
  2677. if (!automatic)
  2678. {
  2679. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  2680. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  2681. current_position[E_AXIS], FILAMENTCHANGE_EXFEED, active_extruder);
  2682. }
  2683. //Move XY back
  2684. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  2685. FILAMENTCHANGE_XYFEED, active_extruder);
  2686. st_synchronize();
  2687. //Move Z back
  2688. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS],
  2689. FILAMENTCHANGE_ZFEED, active_extruder);
  2690. st_synchronize();
  2691. //Set E position to original
  2692. plan_set_e_position(lastpos[E_AXIS]);
  2693. memcpy(current_position, lastpos, sizeof(lastpos));
  2694. memcpy(destination, current_position, sizeof(current_position));
  2695. //Recover feed rate
  2696. feedmultiply = feedmultiplyBckp;
  2697. char cmd[9];
  2698. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  2699. enquecommand(cmd);
  2700. #ifdef IR_SENSOR
  2701. //this will set fsensor_watch_autoload to correct value and prevent possible M701 gcode enqueuing when M600 is finished
  2702. fsensor_check_autoload();
  2703. #endif //IR_SENSOR
  2704. lcd_setstatuspgm(_T(WELCOME_MSG));
  2705. custom_message_type = CustomMsg::Status;
  2706. }
  2707. //! @brief Rise Z if too low to avoid blob/jam before filament loading
  2708. //!
  2709. //! It doesn't plan_buffer_line(), as it expects plan_buffer_line() to be called after
  2710. //! during extruding (loading) filament.
  2711. void marlin_rise_z(void)
  2712. {
  2713. if (current_position[Z_AXIS] < 20) current_position[Z_AXIS] += 30;
  2714. }
  2715. void gcode_M701()
  2716. {
  2717. printf_P(PSTR("gcode_M701 begin\n"));
  2718. if (farm_mode)
  2719. {
  2720. prusa_statistics(22);
  2721. }
  2722. if (mmu_enabled)
  2723. {
  2724. extr_adj(tmp_extruder);//loads current extruder
  2725. mmu_extruder = tmp_extruder;
  2726. }
  2727. else
  2728. {
  2729. enable_z();
  2730. custom_message_type = CustomMsg::FilamentLoading;
  2731. #ifdef FSENSOR_QUALITY
  2732. fsensor_oq_meassure_start(40);
  2733. #endif //FSENSOR_QUALITY
  2734. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  2735. current_position[E_AXIS] += 40;
  2736. 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
  2737. st_synchronize();
  2738. marlin_rise_z();
  2739. current_position[E_AXIS] += 30;
  2740. 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
  2741. load_filament_final_feed(); //slow sequence
  2742. st_synchronize();
  2743. Sound_MakeCustom(50,500,false);
  2744. if (!farm_mode && loading_flag) {
  2745. lcd_load_filament_color_check();
  2746. }
  2747. lcd_update_enable(true);
  2748. lcd_update(2);
  2749. lcd_setstatuspgm(_T(WELCOME_MSG));
  2750. disable_z();
  2751. loading_flag = false;
  2752. custom_message_type = CustomMsg::Status;
  2753. #ifdef FSENSOR_QUALITY
  2754. fsensor_oq_meassure_stop();
  2755. if (!fsensor_oq_result())
  2756. {
  2757. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Fil. sensor response is poor, disable it?"), false, true);
  2758. lcd_update_enable(true);
  2759. lcd_update(2);
  2760. if (disable)
  2761. fsensor_disable();
  2762. }
  2763. #endif //FSENSOR_QUALITY
  2764. }
  2765. }
  2766. /**
  2767. * @brief Get serial number from 32U2 processor
  2768. *
  2769. * Typical format of S/N is:CZPX0917X003XC13518
  2770. *
  2771. * Command operates only in farm mode, if not in farm mode, "Not in farm mode." is written to MYSERIAL.
  2772. *
  2773. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  2774. * reply is transmitted to serial port 1 character by character.
  2775. * Operation takes typically 23 ms. If the retransmit is not finished until 100 ms,
  2776. * it is interrupted, so less, or no characters are retransmitted, only newline character is send
  2777. * in any case.
  2778. */
  2779. static void gcode_PRUSA_SN()
  2780. {
  2781. if (farm_mode) {
  2782. selectedSerialPort = 0;
  2783. putchar(';');
  2784. putchar('S');
  2785. int numbersRead = 0;
  2786. ShortTimer timeout;
  2787. timeout.start();
  2788. while (numbersRead < 19) {
  2789. while (MSerial.available() > 0) {
  2790. uint8_t serial_char = MSerial.read();
  2791. selectedSerialPort = 1;
  2792. putchar(serial_char);
  2793. numbersRead++;
  2794. selectedSerialPort = 0;
  2795. }
  2796. if (timeout.expired(100u)) break;
  2797. }
  2798. selectedSerialPort = 1;
  2799. putchar('\n');
  2800. #if 0
  2801. for (int b = 0; b < 3; b++) {
  2802. _tone(BEEPER, 110);
  2803. _delay(50);
  2804. _noTone(BEEPER);
  2805. _delay(50);
  2806. }
  2807. #endif
  2808. } else {
  2809. puts_P(_N("Not in farm mode."));
  2810. }
  2811. }
  2812. //! Detection of faulty RAMBo 1.1b boards equipped with bigger capacitors
  2813. //! at the TACH_1 pin, which causes bad detection of print fan speed.
  2814. //! Warning: This function is not to be used by ordinary users, it is here only for automated testing purposes,
  2815. //! it may even interfere with other functions of the printer! You have been warned!
  2816. //! The test idea is to measure the time necessary to charge the capacitor.
  2817. //! So the algorithm is as follows:
  2818. //! 1. Set TACH_1 pin to INPUT mode and LOW
  2819. //! 2. Wait a few ms
  2820. //! 3. disable interrupts and measure the time until the TACH_1 pin reaches HIGH
  2821. //! Repeat 1.-3. several times
  2822. //! Good RAMBo's times are in the range of approx. 260-320 us
  2823. //! Bad RAMBo's times are approx. 260-1200 us
  2824. //! So basically we are interested in maximum time, the minima are mostly the same.
  2825. //! May be that's why the bad RAMBo's still produce some fan RPM reading, but not corresponding to reality
  2826. static void gcode_PRUSA_BadRAMBoFanTest(){
  2827. //printf_P(PSTR("Enter fan pin test\n"));
  2828. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1 && defined(IR_SENSOR)
  2829. fan_measuring = false; // prevent EXTINT7 breaking into the measurement
  2830. unsigned long tach1max = 0;
  2831. uint8_t tach1cntr = 0;
  2832. for( /* nothing */; tach1cntr < 100; ++tach1cntr){
  2833. //printf_P(PSTR("TACH_1: %d\n"), tach1cntr);
  2834. SET_OUTPUT(TACH_1);
  2835. WRITE(TACH_1, LOW);
  2836. _delay(20); // the delay may be lower
  2837. unsigned long tachMeasure = _micros();
  2838. cli();
  2839. SET_INPUT(TACH_1);
  2840. // just wait brutally in an endless cycle until we reach HIGH
  2841. // if this becomes a problem it may be improved to non-endless cycle
  2842. while( READ(TACH_1) == 0 ) ;
  2843. sei();
  2844. tachMeasure = _micros() - tachMeasure;
  2845. if( tach1max < tachMeasure )
  2846. tach1max = tachMeasure;
  2847. //printf_P(PSTR("TACH_1: %d: capacitor check time=%lu us\n"), (int)tach1cntr, tachMeasure);
  2848. }
  2849. //printf_P(PSTR("TACH_1: max=%lu us\n"), tach1max);
  2850. SERIAL_PROTOCOLPGM("RAMBo FAN ");
  2851. if( tach1max > 500 ){
  2852. // bad RAMBo
  2853. SERIAL_PROTOCOLLNPGM("BAD");
  2854. } else {
  2855. SERIAL_PROTOCOLLNPGM("OK");
  2856. }
  2857. // cleanup after the test function
  2858. SET_INPUT(TACH_1);
  2859. WRITE(TACH_1, HIGH);
  2860. #endif
  2861. }
  2862. #ifdef BACKLASH_X
  2863. extern uint8_t st_backlash_x;
  2864. #endif //BACKLASH_X
  2865. #ifdef BACKLASH_Y
  2866. extern uint8_t st_backlash_y;
  2867. #endif //BACKLASH_Y
  2868. //! \ingroup marlin_main
  2869. //! @brief Parse and process commands
  2870. //!
  2871. //! look here for descriptions of G-codes: http://linuxcnc.org/handbook/gcode/g-code.html
  2872. //! http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  2873. //!
  2874. //!
  2875. //! Implemented Codes
  2876. //! -------------------
  2877. //!
  2878. //! * _This list is not updated. Current documentation is maintained inside the process_cmd function._
  2879. //!
  2880. //!@n PRUSA CODES
  2881. //!@n P F - Returns FW versions
  2882. //!@n P R - Returns revision of printer
  2883. //!
  2884. //!@n G0 -> G1
  2885. //!@n G1 - Coordinated Movement X Y Z E
  2886. //!@n G2 - CW ARC
  2887. //!@n G3 - CCW ARC
  2888. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  2889. //!@n G10 - retract filament according to settings of M207
  2890. //!@n G11 - retract recover filament according to settings of M208
  2891. //!@n G28 - Home all Axis
  2892. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  2893. //!@n G30 - Single Z Probe, probes bed at current XY location.
  2894. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  2895. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  2896. //!@n G80 - Automatic mesh bed leveling
  2897. //!@n G81 - Print bed profile
  2898. //!@n G90 - Use Absolute Coordinates
  2899. //!@n G91 - Use Relative Coordinates
  2900. //!@n G92 - Set current position to coordinates given
  2901. //!
  2902. //!@n M Codes
  2903. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  2904. //!@n M1 - Same as M0
  2905. //!@n M17 - Enable/Power all stepper motors
  2906. //!@n M18 - Disable all stepper motors; same as M84
  2907. //!@n M20 - List SD card
  2908. //!@n M21 - Init SD card
  2909. //!@n M22 - Release SD card
  2910. //!@n M23 - Select SD file (M23 filename.g)
  2911. //!@n M24 - Start/resume SD print
  2912. //!@n M25 - Pause SD print
  2913. //!@n M26 - Set SD position in bytes (M26 S12345)
  2914. //!@n M27 - Report SD print status
  2915. //!@n M28 - Start SD write (M28 filename.g)
  2916. //!@n M29 - Stop SD write
  2917. //!@n M30 - Delete file from SD (M30 filename.g)
  2918. //!@n M31 - Output time since last M109 or SD card start to serial
  2919. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  2920. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  2921. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  2922. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  2923. //!@n 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.
  2924. //!@n M73 - Show percent done and print time remaining
  2925. //!@n M80 - Turn on Power Supply
  2926. //!@n M81 - Turn off Power Supply
  2927. //!@n M82 - Set E codes absolute (default)
  2928. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  2929. //!@n M84 - Disable steppers until next move,
  2930. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  2931. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  2932. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  2933. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  2934. //!@n M104 - Set extruder target temp
  2935. //!@n M105 - Read current temp
  2936. //!@n M106 - Fan on
  2937. //!@n M107 - Fan off
  2938. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  2939. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  2940. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  2941. //!@n M112 - Emergency stop
  2942. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  2943. //!@n M114 - Output current position to serial port
  2944. //!@n M115 - Capabilities string
  2945. //!@n M117 - display message
  2946. //!@n M119 - Output Endstop status to serial port
  2947. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  2948. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  2949. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  2950. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  2951. //!@n M140 - Set bed target temp
  2952. //!@n 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.
  2953. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  2954. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  2955. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  2956. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  2957. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  2958. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  2959. //!@n 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
  2960. //!@n 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
  2961. //!@n M206 - set additional homing offset
  2962. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  2963. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  2964. //!@n 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.
  2965. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  2966. //!@n M220 S<factor in percent>- set speed factor override percentage
  2967. //!@n M221 S<factor in percent>- set extrude factor override percentage
  2968. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  2969. //!@n M240 - Trigger a camera to take a photograph
  2970. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  2971. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  2972. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  2973. //!@n M301 - Set PID parameters P I and D
  2974. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  2975. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  2976. //!@n M304 - Set bed PID parameters P I and D
  2977. //!@n M400 - Finish all moves
  2978. //!@n M401 - Lower z-probe if present
  2979. //!@n M402 - Raise z-probe if present
  2980. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  2981. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  2982. //!@n M406 - Turn off Filament Sensor extrusion control
  2983. //!@n M407 - Displays measured filament diameter
  2984. //!@n M500 - stores parameters in EEPROM
  2985. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  2986. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  2987. //!@n M503 - print the current settings (from memory not from EEPROM)
  2988. //!@n M509 - force language selection on next restart
  2989. //!@n M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  2990. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  2991. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  2992. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  2993. //!@n M861 - Set / Read PINDA temperature compensation offsets
  2994. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  2995. //!@n M907 - Set digital trimpot motor current using axis codes.
  2996. //!@n M908 - Control digital trimpot directly.
  2997. //!@n M350 - Set microstepping mode.
  2998. //!@n M351 - Toggle MS1 MS2 pins directly.
  2999. //!
  3000. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  3001. //!@n M999 - Restart after being stopped by error
  3002. //! <br><br>
  3003. /** @defgroup marlin_main Marlin main */
  3004. /** \ingroup GCodes */
  3005. //! _This is a list of currently implemented G Codes in Prusa firmware (dynamically generated from doxygen)_
  3006. void process_commands()
  3007. {
  3008. #ifdef FANCHECK
  3009. if (fan_check_error){
  3010. if( fan_check_error == EFCE_DETECTED ){
  3011. fan_check_error = EFCE_REPORTED;
  3012. if(is_usb_printing){
  3013. SERIAL_PROTOCOLLNRPGM(MSG_OCTOPRINT_PAUSE);
  3014. }
  3015. else{
  3016. lcd_pause_print();
  3017. }
  3018. } // otherwise it has already been reported, so just ignore further processing
  3019. return;
  3020. }
  3021. #endif
  3022. if (!buflen) return; //empty command
  3023. #ifdef FILAMENT_RUNOUT_SUPPORT
  3024. SET_INPUT(FR_SENS);
  3025. #endif
  3026. #ifdef CMDBUFFER_DEBUG
  3027. SERIAL_ECHOPGM("Processing a GCODE command: ");
  3028. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  3029. SERIAL_ECHOLNPGM("");
  3030. SERIAL_ECHOPGM("In cmdqueue: ");
  3031. SERIAL_ECHO(buflen);
  3032. SERIAL_ECHOLNPGM("");
  3033. #endif /* CMDBUFFER_DEBUG */
  3034. unsigned long codenum; //throw away variable
  3035. char *starpos = NULL;
  3036. #ifdef ENABLE_AUTO_BED_LEVELING
  3037. float x_tmp, y_tmp, z_tmp, real_z;
  3038. #endif
  3039. // PRUSA GCODES
  3040. KEEPALIVE_STATE(IN_HANDLER);
  3041. #ifdef SNMM
  3042. float tmp_motor[3] = DEFAULT_PWM_MOTOR_CURRENT;
  3043. float tmp_motor_loud[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  3044. int8_t SilentMode;
  3045. #endif
  3046. if (code_seen("M117")) { //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  3047. starpos = (strchr(strchr_pointer + 5, '*'));
  3048. if (starpos != NULL)
  3049. *(starpos) = '\0';
  3050. lcd_setstatus(strchr_pointer + 5);
  3051. }
  3052. #ifdef TMC2130
  3053. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  3054. {
  3055. //! ### CRASH_DETECTED - TMC2130
  3056. // ---------------------------------
  3057. if(code_seen("CRASH_DETECTED"))
  3058. {
  3059. uint8_t mask = 0;
  3060. if (code_seen('X')) mask |= X_AXIS_MASK;
  3061. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  3062. crashdet_detected(mask);
  3063. }
  3064. //! ### CRASH_RECOVER - TMC2130
  3065. // ----------------------------------
  3066. else if(code_seen("CRASH_RECOVER"))
  3067. crashdet_recover();
  3068. //! ### CRASH_CANCEL - TMC2130
  3069. // ----------------------------------
  3070. else if(code_seen("CRASH_CANCEL"))
  3071. crashdet_cancel();
  3072. }
  3073. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3074. {
  3075. //! ### TMC_SET_WAVE_
  3076. // --------------------
  3077. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0)
  3078. {
  3079. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3080. axis = (axis == 'E')?3:(axis - 'X');
  3081. if (axis < 4)
  3082. {
  3083. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3084. tmc2130_set_wave(axis, 247, fac);
  3085. }
  3086. }
  3087. //! ### TMC_SET_STEP_
  3088. // ------------------
  3089. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0)
  3090. {
  3091. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3092. axis = (axis == 'E')?3:(axis - 'X');
  3093. if (axis < 4)
  3094. {
  3095. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3096. uint16_t res = tmc2130_get_res(axis);
  3097. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3098. }
  3099. }
  3100. //! ### TMC_SET_CHOP_
  3101. // -------------------
  3102. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0)
  3103. {
  3104. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3105. axis = (axis == 'E')?3:(axis - 'X');
  3106. if (axis < 4)
  3107. {
  3108. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  3109. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3110. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3111. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3112. char* str_end = 0;
  3113. if (CMDBUFFER_CURRENT_STRING[14])
  3114. {
  3115. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3116. if (str_end && *str_end)
  3117. {
  3118. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3119. if (str_end && *str_end)
  3120. {
  3121. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3122. if (str_end && *str_end)
  3123. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3124. }
  3125. }
  3126. }
  3127. tmc2130_chopper_config[axis].toff = chop0;
  3128. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3129. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3130. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3131. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3132. //printf_P(_N("TMC_SET_CHOP_%c %hhd %hhd %hhd %hhd\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3133. }
  3134. }
  3135. }
  3136. #ifdef BACKLASH_X
  3137. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3138. {
  3139. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3140. st_backlash_x = bl;
  3141. printf_P(_N("st_backlash_x = %hhd\n"), st_backlash_x);
  3142. }
  3143. #endif //BACKLASH_X
  3144. #ifdef BACKLASH_Y
  3145. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3146. {
  3147. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3148. st_backlash_y = bl;
  3149. printf_P(_N("st_backlash_y = %hhd\n"), st_backlash_y);
  3150. }
  3151. #endif //BACKLASH_Y
  3152. #endif //TMC2130
  3153. else if(code_seen("PRUSA")){
  3154. /*!
  3155. *
  3156. ### PRUSA - Internal command set
  3157. Set of internal PRUSA commands
  3158. PRUSA [ Ping | PRN | FAN | fn | thx | uvlo | fsensor_recover | MMURES | RESET | fv | M28 | SN | Fir | Rev | Lang | Lz | Beat | FR ]
  3159. - `Ping`
  3160. - `PRN` - Prints revision of the printer
  3161. - `FAN` - Prints fan details
  3162. - `fn` - Prints farm no.
  3163. - `thx`
  3164. - `uvlo`
  3165. - `fsensor_recover` - Filament sensor recover - restore print and continue
  3166. - `MMURES` - Reset MMU
  3167. - `RESET` - (Careful!)
  3168. - `fv` - ?
  3169. - `M28`
  3170. - `SN`
  3171. - `Fir` - Prints firmware version
  3172. - `Rev`- Prints filament size, elelectronics, nozzle type
  3173. - `Lang` - Reset the language
  3174. - `Lz`
  3175. - `Beat` - Kick farm link timer
  3176. - `FR` - Full factory reset
  3177. - `nozzle set <diameter>` - set nozzle diameter (farm mode only), e.g. `PRUSA nozzle set 0.4`
  3178. - `nozzle D<diameter>` - check the nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle D0.4`
  3179. - `nozzle` - prints nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle`
  3180. *
  3181. */
  3182. if (code_seen("Ping")) { // PRUSA Ping
  3183. if (farm_mode) {
  3184. PingTime = _millis();
  3185. //MYSERIAL.print(farm_no); MYSERIAL.println(": OK");
  3186. }
  3187. }
  3188. else if (code_seen("PRN")) { // PRUSA PRN
  3189. printf_P(_N("%d"), status_number);
  3190. } else if( code_seen("FANPINTST") ){
  3191. gcode_PRUSA_BadRAMBoFanTest();
  3192. }else if (code_seen("FAN")) { //! PRUSA FAN
  3193. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3194. }else if (code_seen("fn")) { // PRUSA fn
  3195. if (farm_mode) {
  3196. printf_P(_N("%d"), farm_no);
  3197. }
  3198. else {
  3199. puts_P(_N("Not in farm mode."));
  3200. }
  3201. }
  3202. else if (code_seen("thx")) // PRUSA thx
  3203. {
  3204. no_response = false;
  3205. }
  3206. else if (code_seen("uvlo")) // PRUSA uvlo
  3207. {
  3208. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3209. enquecommand_P(PSTR("M24"));
  3210. }
  3211. #ifdef FILAMENT_SENSOR
  3212. else if (code_seen("fsensor_recover")) // PRUSA fsensor_recover
  3213. {
  3214. fsensor_restore_print_and_continue();
  3215. }
  3216. #endif //FILAMENT_SENSOR
  3217. else if (code_seen("MMURES")) // PRUSA MMURES
  3218. {
  3219. mmu_reset();
  3220. }
  3221. else if (code_seen("RESET")) { // PRUSA RESET
  3222. // careful!
  3223. if (farm_mode) {
  3224. #if (defined(WATCHDOG) && (MOTHERBOARD == BOARD_EINSY_1_0a))
  3225. boot_app_magic = BOOT_APP_MAGIC;
  3226. boot_app_flags = BOOT_APP_FLG_RUN;
  3227. wdt_enable(WDTO_15MS);
  3228. cli();
  3229. while(1);
  3230. #else //WATCHDOG
  3231. asm volatile("jmp 0x3E000");
  3232. #endif //WATCHDOG
  3233. }
  3234. else {
  3235. MYSERIAL.println("Not in farm mode.");
  3236. }
  3237. }else if (code_seen("fv")) { // PRUSA fv
  3238. // get file version
  3239. #ifdef SDSUPPORT
  3240. card.openFile(strchr_pointer + 3,true);
  3241. while (true) {
  3242. uint16_t readByte = card.get();
  3243. MYSERIAL.write(readByte);
  3244. if (readByte=='\n') {
  3245. break;
  3246. }
  3247. }
  3248. card.closefile();
  3249. #endif // SDSUPPORT
  3250. } else if (code_seen("M28")) { // PRUSA M28
  3251. trace();
  3252. prusa_sd_card_upload = true;
  3253. card.openFile(strchr_pointer+4,false);
  3254. } else if (code_seen("SN")) { // PRUSA SN
  3255. gcode_PRUSA_SN();
  3256. } else if(code_seen("Fir")){ // PRUSA Fir
  3257. SERIAL_PROTOCOLLN(FW_VERSION_FULL);
  3258. } else if(code_seen("Rev")){ // PRUSA Rev
  3259. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3260. } else if(code_seen("Lang")) { // PRUSA Lang
  3261. lang_reset();
  3262. } else if(code_seen("Lz")) { // PRUSA Lz
  3263. EEPROM_save_B(EEPROM_BABYSTEP_Z,0);
  3264. } else if(code_seen("Beat")) { // PRUSA Beat
  3265. // Kick farm link timer
  3266. kicktime = _millis();
  3267. } else if(code_seen("FR")) { // PRUSA FR
  3268. // Factory full reset
  3269. factory_reset(0);
  3270. //-//
  3271. /*
  3272. } else if(code_seen("rrr")) {
  3273. MYSERIAL.println("=== checking ===");
  3274. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_CHECK_MODE),DEC);
  3275. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER),DEC);
  3276. MYSERIAL.println(eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM),DEC);
  3277. MYSERIAL.println(farm_mode,DEC);
  3278. MYSERIAL.println(eCheckMode,DEC);
  3279. } else if(code_seen("www")) {
  3280. MYSERIAL.println("=== @ FF ===");
  3281. eeprom_update_byte((uint8_t*)EEPROM_CHECK_MODE,0xFF);
  3282. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,0xFF);
  3283. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,0xFFFF);
  3284. */
  3285. } else if (code_seen("nozzle")) { // PRUSA nozzle
  3286. uint16_t nDiameter;
  3287. if(code_seen('D'))
  3288. {
  3289. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3290. nozzle_diameter_check(nDiameter);
  3291. }
  3292. else if(code_seen("set") && farm_mode)
  3293. {
  3294. strchr_pointer++; // skip 1st char (~ 's')
  3295. strchr_pointer++; // skip 2nd char (~ 'e')
  3296. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3297. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  3298. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  3299. }
  3300. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  3301. //-// !!! SupportMenu
  3302. /*
  3303. // musi byt PRED "PRUSA model"
  3304. } else if (code_seen("smodel")) { //! PRUSA smodel
  3305. size_t nOffset;
  3306. // ! -> "l"
  3307. strchr_pointer+=5*sizeof(*strchr_pointer); // skip 1st - 5th char (~ 'smode')
  3308. nOffset=strspn(strchr_pointer+1," \t\n\r\v\f");
  3309. if(*(strchr_pointer+1+nOffset))
  3310. printer_smodel_check(strchr_pointer);
  3311. else SERIAL_PROTOCOLLN(PRINTER_NAME);
  3312. } else if (code_seen("model")) { //! PRUSA model
  3313. uint16_t nPrinterModel;
  3314. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'mode')
  3315. nPrinterModel=(uint16_t)code_value_long();
  3316. if(nPrinterModel!=0)
  3317. printer_model_check(nPrinterModel);
  3318. else SERIAL_PROTOCOLLN(PRINTER_TYPE);
  3319. } else if (code_seen("version")) { //! PRUSA version
  3320. strchr_pointer+=7*sizeof(*strchr_pointer); // skip 1st - 7th char (~ 'version')
  3321. while(*strchr_pointer==' ') // skip leading spaces
  3322. strchr_pointer++;
  3323. if(*strchr_pointer!=0)
  3324. fw_version_check(strchr_pointer);
  3325. else SERIAL_PROTOCOLLN(FW_VERSION);
  3326. } else if (code_seen("gcode")) { //! PRUSA gcode
  3327. uint16_t nGcodeLevel;
  3328. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'gcod')
  3329. nGcodeLevel=(uint16_t)code_value_long();
  3330. if(nGcodeLevel!=0)
  3331. gcode_level_check(nGcodeLevel);
  3332. else SERIAL_PROTOCOLLN(GCODE_LEVEL);
  3333. */
  3334. }
  3335. //else if (code_seen('Cal')) {
  3336. // lcd_calibration();
  3337. // }
  3338. }
  3339. else if (code_seen('^')) {
  3340. // nothing, this is a version line
  3341. } else if(code_seen('G'))
  3342. {
  3343. gcode_in_progress = (int)code_value();
  3344. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3345. switch (gcode_in_progress)
  3346. {
  3347. //! ### G0, G1 - Coordinated movement X Y Z E
  3348. // --------------------------------------
  3349. case 0: // G0 -> G1
  3350. case 1: // G1
  3351. if(Stopped == false) {
  3352. #ifdef FILAMENT_RUNOUT_SUPPORT
  3353. if(READ(FR_SENS)){
  3354. int feedmultiplyBckp=feedmultiply;
  3355. float target[4];
  3356. float lastpos[4];
  3357. target[X_AXIS]=current_position[X_AXIS];
  3358. target[Y_AXIS]=current_position[Y_AXIS];
  3359. target[Z_AXIS]=current_position[Z_AXIS];
  3360. target[E_AXIS]=current_position[E_AXIS];
  3361. lastpos[X_AXIS]=current_position[X_AXIS];
  3362. lastpos[Y_AXIS]=current_position[Y_AXIS];
  3363. lastpos[Z_AXIS]=current_position[Z_AXIS];
  3364. lastpos[E_AXIS]=current_position[E_AXIS];
  3365. //retract by E
  3366. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT ;
  3367. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  3368. target[Z_AXIS]+= FILAMENTCHANGE_ZADD ;
  3369. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 300, active_extruder);
  3370. target[X_AXIS]= FILAMENTCHANGE_XPOS ;
  3371. target[Y_AXIS]= FILAMENTCHANGE_YPOS ;
  3372. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder);
  3373. target[E_AXIS]+= FILAMENTCHANGE_FINALRETRACT ;
  3374. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3375. //finish moves
  3376. st_synchronize();
  3377. //disable extruder steppers so filament can be removed
  3378. disable_e0();
  3379. disable_e1();
  3380. disable_e2();
  3381. _delay(100);
  3382. //LCD_ALERTMESSAGEPGM(_T(MSG_FILAMENTCHANGE));
  3383. uint8_t cnt=0;
  3384. int counterBeep = 0;
  3385. lcd_wait_interact();
  3386. while(!lcd_clicked()){
  3387. cnt++;
  3388. manage_heater();
  3389. manage_inactivity(true);
  3390. //lcd_update(0);
  3391. if(cnt==0)
  3392. {
  3393. #if BEEPER > 0
  3394. if (counterBeep== 500){
  3395. counterBeep = 0;
  3396. }
  3397. SET_OUTPUT(BEEPER);
  3398. if (counterBeep== 0){
  3399. if(eSoundMode!=e_SOUND_MODE_SILENT)
  3400. WRITE(BEEPER,HIGH);
  3401. }
  3402. if (counterBeep== 20){
  3403. WRITE(BEEPER,LOW);
  3404. }
  3405. counterBeep++;
  3406. #else
  3407. #endif
  3408. }
  3409. }
  3410. WRITE(BEEPER,LOW);
  3411. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3412. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3413. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3414. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3415. lcd_change_fil_state = 0;
  3416. lcd_loading_filament();
  3417. while ((lcd_change_fil_state == 0)||(lcd_change_fil_state != 1)){
  3418. lcd_change_fil_state = 0;
  3419. lcd_alright();
  3420. switch(lcd_change_fil_state){
  3421. case 2:
  3422. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3423. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3424. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3425. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3426. lcd_loading_filament();
  3427. break;
  3428. case 3:
  3429. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3430. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3431. lcd_loading_color();
  3432. break;
  3433. default:
  3434. lcd_change_success();
  3435. break;
  3436. }
  3437. }
  3438. target[E_AXIS]+= 5;
  3439. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3440. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT;
  3441. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  3442. //current_position[E_AXIS]=target[E_AXIS]; //the long retract of L is compensated by manual filament feeding
  3443. //plan_set_e_position(current_position[E_AXIS]);
  3444. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //should do nothing
  3445. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //move xy back
  3446. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 200, active_extruder); //move z back
  3447. target[E_AXIS]= target[E_AXIS] - FILAMENTCHANGE_FIRSTRETRACT;
  3448. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 5, active_extruder); //final untretract
  3449. plan_set_e_position(lastpos[E_AXIS]);
  3450. feedmultiply=feedmultiplyBckp;
  3451. char cmd[9];
  3452. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3453. enquecommand(cmd);
  3454. }
  3455. #endif
  3456. get_coordinates(); // For X Y Z E F
  3457. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3458. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3459. }
  3460. #ifdef FWRETRACT
  3461. if(cs.autoretract_enabled)
  3462. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3463. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3464. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3465. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3466. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3467. retract(!retracted[active_extruder]);
  3468. return;
  3469. }
  3470. }
  3471. #endif //FWRETRACT
  3472. prepare_move();
  3473. //ClearToSend();
  3474. }
  3475. break;
  3476. //! ### G2 - CW ARC
  3477. // ------------------------------
  3478. case 2:
  3479. if(Stopped == false) {
  3480. get_arc_coordinates();
  3481. prepare_arc_move(true);
  3482. }
  3483. break;
  3484. //! ### G3 - CCW ARC
  3485. // -------------------------------
  3486. case 3:
  3487. if(Stopped == false) {
  3488. get_arc_coordinates();
  3489. prepare_arc_move(false);
  3490. }
  3491. break;
  3492. //! ### G4 - Dwell
  3493. // -------------------------------
  3494. case 4:
  3495. codenum = 0;
  3496. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3497. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3498. if(codenum != 0) LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  3499. st_synchronize();
  3500. codenum += _millis(); // keep track of when we started waiting
  3501. previous_millis_cmd = _millis();
  3502. while(_millis() < codenum) {
  3503. manage_heater();
  3504. manage_inactivity();
  3505. lcd_update(0);
  3506. }
  3507. break;
  3508. #ifdef FWRETRACT
  3509. //! ### G10 Retract
  3510. // ------------------------------
  3511. case 10:
  3512. #if EXTRUDERS > 1
  3513. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  3514. retract(true,retracted_swap[active_extruder]);
  3515. #else
  3516. retract(true);
  3517. #endif
  3518. break;
  3519. //! ### G11 - Retract recover
  3520. // -----------------------------
  3521. case 11:
  3522. #if EXTRUDERS > 1
  3523. retract(false,retracted_swap[active_extruder]);
  3524. #else
  3525. retract(false);
  3526. #endif
  3527. break;
  3528. #endif //FWRETRACT
  3529. //! ### G28 - Home all Axis one at a time
  3530. // --------------------------------------------
  3531. case 28:
  3532. {
  3533. long home_x_value = 0;
  3534. long home_y_value = 0;
  3535. long home_z_value = 0;
  3536. // Which axes should be homed?
  3537. bool home_x = code_seen(axis_codes[X_AXIS]);
  3538. home_x_value = code_value_long();
  3539. bool home_y = code_seen(axis_codes[Y_AXIS]);
  3540. home_y_value = code_value_long();
  3541. bool home_z = code_seen(axis_codes[Z_AXIS]);
  3542. home_z_value = code_value_long();
  3543. bool without_mbl = code_seen('W');
  3544. // calibrate?
  3545. #ifdef TMC2130
  3546. bool calib = code_seen('C');
  3547. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  3548. #else
  3549. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  3550. #endif //TMC2130
  3551. if ((home_x || home_y || without_mbl || home_z) == false) {
  3552. // Push the commands to the front of the message queue in the reverse order!
  3553. // There shall be always enough space reserved for these commands.
  3554. goto case_G80;
  3555. }
  3556. break;
  3557. }
  3558. #ifdef ENABLE_AUTO_BED_LEVELING
  3559. //! ### G29 - Detailed Z-Probe
  3560. // --------------------------------
  3561. case 29:
  3562. {
  3563. #if Z_MIN_PIN == -1
  3564. #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."
  3565. #endif
  3566. // Prevent user from running a G29 without first homing in X and Y
  3567. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  3568. {
  3569. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  3570. SERIAL_ECHO_START;
  3571. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  3572. break; // abort G29, since we don't know where we are
  3573. }
  3574. st_synchronize();
  3575. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  3576. //vector_3 corrected_position = plan_get_position_mm();
  3577. //corrected_position.debug("position before G29");
  3578. plan_bed_level_matrix.set_to_identity();
  3579. vector_3 uncorrected_position = plan_get_position();
  3580. //uncorrected_position.debug("position durring G29");
  3581. current_position[X_AXIS] = uncorrected_position.x;
  3582. current_position[Y_AXIS] = uncorrected_position.y;
  3583. current_position[Z_AXIS] = uncorrected_position.z;
  3584. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  3585. int l_feedmultiply = setup_for_endstop_move();
  3586. feedrate = homing_feedrate[Z_AXIS];
  3587. #ifdef AUTO_BED_LEVELING_GRID
  3588. // probe at the points of a lattice grid
  3589. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  3590. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  3591. // solve the plane equation ax + by + d = z
  3592. // A is the matrix with rows [x y 1] for all the probed points
  3593. // B is the vector of the Z positions
  3594. // 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
  3595. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  3596. // "A" matrix of the linear system of equations
  3597. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  3598. // "B" vector of Z points
  3599. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  3600. int probePointCounter = 0;
  3601. bool zig = true;
  3602. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  3603. {
  3604. int xProbe, xInc;
  3605. if (zig)
  3606. {
  3607. xProbe = LEFT_PROBE_BED_POSITION;
  3608. //xEnd = RIGHT_PROBE_BED_POSITION;
  3609. xInc = xGridSpacing;
  3610. zig = false;
  3611. } else // zag
  3612. {
  3613. xProbe = RIGHT_PROBE_BED_POSITION;
  3614. //xEnd = LEFT_PROBE_BED_POSITION;
  3615. xInc = -xGridSpacing;
  3616. zig = true;
  3617. }
  3618. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  3619. {
  3620. float z_before;
  3621. if (probePointCounter == 0)
  3622. {
  3623. // raise before probing
  3624. z_before = Z_RAISE_BEFORE_PROBING;
  3625. } else
  3626. {
  3627. // raise extruder
  3628. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  3629. }
  3630. float measured_z = probe_pt(xProbe, yProbe, z_before);
  3631. eqnBVector[probePointCounter] = measured_z;
  3632. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  3633. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  3634. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  3635. probePointCounter++;
  3636. xProbe += xInc;
  3637. }
  3638. }
  3639. clean_up_after_endstop_move(l_feedmultiply);
  3640. // solve lsq problem
  3641. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  3642. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  3643. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  3644. SERIAL_PROTOCOLPGM(" b: ");
  3645. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  3646. SERIAL_PROTOCOLPGM(" d: ");
  3647. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  3648. set_bed_level_equation_lsq(plane_equation_coefficients);
  3649. free(plane_equation_coefficients);
  3650. #else // AUTO_BED_LEVELING_GRID not defined
  3651. // Probe at 3 arbitrary points
  3652. // probe 1
  3653. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  3654. // probe 2
  3655. 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);
  3656. // probe 3
  3657. 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);
  3658. clean_up_after_endstop_move(l_feedmultiply);
  3659. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  3660. #endif // AUTO_BED_LEVELING_GRID
  3661. st_synchronize();
  3662. // The following code correct the Z height difference from z-probe position and hotend tip position.
  3663. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  3664. // When the bed is uneven, this height must be corrected.
  3665. real_z = float(st_get_position(Z_AXIS))/cs.axis_steps_per_unit[Z_AXIS]; //get the real Z (since the auto bed leveling is already correcting the plane)
  3666. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  3667. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  3668. z_tmp = current_position[Z_AXIS];
  3669. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  3670. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  3671. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  3672. }
  3673. break;
  3674. #ifndef Z_PROBE_SLED
  3675. //! ### G30 - Single Z Probe
  3676. // ------------------------------------
  3677. case 30:
  3678. {
  3679. st_synchronize();
  3680. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  3681. int l_feedmultiply = setup_for_endstop_move();
  3682. feedrate = homing_feedrate[Z_AXIS];
  3683. run_z_probe();
  3684. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  3685. SERIAL_PROTOCOLPGM(" X: ");
  3686. SERIAL_PROTOCOL(current_position[X_AXIS]);
  3687. SERIAL_PROTOCOLPGM(" Y: ");
  3688. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3689. SERIAL_PROTOCOLPGM(" Z: ");
  3690. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3691. SERIAL_PROTOCOLPGM("\n");
  3692. clean_up_after_endstop_move(l_feedmultiply);
  3693. }
  3694. break;
  3695. #else
  3696. //! ### G31 - Dock the sled
  3697. // ---------------------------
  3698. case 31:
  3699. dock_sled(true);
  3700. break;
  3701. //! ### G32 - Undock the sled
  3702. // ----------------------------
  3703. case 32:
  3704. dock_sled(false);
  3705. break;
  3706. #endif // Z_PROBE_SLED
  3707. #endif // ENABLE_AUTO_BED_LEVELING
  3708. #ifdef MESH_BED_LEVELING
  3709. //! ### G30 - Single Z Probe
  3710. // ----------------------------
  3711. case 30:
  3712. {
  3713. st_synchronize();
  3714. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  3715. int l_feedmultiply = setup_for_endstop_move();
  3716. feedrate = homing_feedrate[Z_AXIS];
  3717. find_bed_induction_sensor_point_z(-10.f, 3);
  3718. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  3719. clean_up_after_endstop_move(l_feedmultiply);
  3720. }
  3721. break;
  3722. //! ### G75 - Print temperature interpolation
  3723. // ---------------------------------------------
  3724. case 75:
  3725. {
  3726. for (int i = 40; i <= 110; i++)
  3727. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  3728. }
  3729. break;
  3730. //! ### G76 - PINDA probe temperature calibration
  3731. // ------------------------------------------------
  3732. case 76:
  3733. {
  3734. #ifdef PINDA_THERMISTOR
  3735. if (true)
  3736. {
  3737. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  3738. //we need to know accurate position of first calibration point
  3739. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  3740. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first."));
  3741. break;
  3742. }
  3743. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  3744. {
  3745. // We don't know where we are! HOME!
  3746. // Push the commands to the front of the message queue in the reverse order!
  3747. // There shall be always enough space reserved for these commands.
  3748. repeatcommand_front(); // repeat G76 with all its parameters
  3749. enquecommand_front_P((PSTR("G28 W0")));
  3750. break;
  3751. }
  3752. lcd_show_fullscreen_message_and_wait_P(_i("Stable ambient temperature 21-26C is needed a rigid stand is required."));////MSG_TEMP_CAL_WARNING c=20 r=4
  3753. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  3754. if (result)
  3755. {
  3756. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3757. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3758. current_position[Z_AXIS] = 50;
  3759. current_position[Y_AXIS] = 180;
  3760. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3761. st_synchronize();
  3762. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  3763. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  3764. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  3765. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3766. st_synchronize();
  3767. gcode_G28(false, false, true);
  3768. }
  3769. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  3770. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  3771. current_position[Z_AXIS] = 100;
  3772. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3773. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  3774. lcd_temp_cal_show_result(false);
  3775. break;
  3776. }
  3777. }
  3778. lcd_update_enable(true);
  3779. KEEPALIVE_STATE(NOT_BUSY); //no need to print busy messages as we print current temperatures periodicaly
  3780. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  3781. float zero_z;
  3782. int z_shift = 0; //unit: steps
  3783. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  3784. if (start_temp < 35) start_temp = 35;
  3785. if (start_temp < current_temperature_pinda) start_temp += 5;
  3786. printf_P(_N("start temperature: %.1f\n"), start_temp);
  3787. // setTargetHotend(200, 0);
  3788. setTargetBed(70 + (start_temp - 30));
  3789. custom_message_type = CustomMsg::TempCal;
  3790. custom_message_state = 1;
  3791. lcd_setstatuspgm(_T(MSG_TEMP_CALIBRATION));
  3792. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3793. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3794. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3795. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3796. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3797. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3798. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3799. st_synchronize();
  3800. while (current_temperature_pinda < start_temp)
  3801. {
  3802. delay_keep_alive(1000);
  3803. serialecho_temperatures();
  3804. }
  3805. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  3806. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3807. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3808. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  3809. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  3810. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3811. st_synchronize();
  3812. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  3813. if (find_z_result == false) {
  3814. lcd_temp_cal_show_result(find_z_result);
  3815. break;
  3816. }
  3817. zero_z = current_position[Z_AXIS];
  3818. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  3819. int i = -1; for (; i < 5; i++)
  3820. {
  3821. float temp = (40 + i * 5);
  3822. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  3823. if (i >= 0) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  3824. if (start_temp <= temp) break;
  3825. }
  3826. for (i++; i < 5; i++)
  3827. {
  3828. float temp = (40 + i * 5);
  3829. printf_P(_N("\nStep: %d/6\n"), i + 2);
  3830. custom_message_state = i + 2;
  3831. setTargetBed(50 + 10 * (temp - 30) / 5);
  3832. // setTargetHotend(255, 0);
  3833. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3834. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3835. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3836. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3837. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3838. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3839. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3840. st_synchronize();
  3841. while (current_temperature_pinda < temp)
  3842. {
  3843. delay_keep_alive(1000);
  3844. serialecho_temperatures();
  3845. }
  3846. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3847. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3848. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  3849. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  3850. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3851. st_synchronize();
  3852. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  3853. if (find_z_result == false) {
  3854. lcd_temp_cal_show_result(find_z_result);
  3855. break;
  3856. }
  3857. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  3858. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  3859. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  3860. }
  3861. lcd_temp_cal_show_result(true);
  3862. break;
  3863. }
  3864. #endif //PINDA_THERMISTOR
  3865. setTargetBed(PINDA_MIN_T);
  3866. float zero_z;
  3867. int z_shift = 0; //unit: steps
  3868. int t_c; // temperature
  3869. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  3870. // We don't know where we are! HOME!
  3871. // Push the commands to the front of the message queue in the reverse order!
  3872. // There shall be always enough space reserved for these commands.
  3873. repeatcommand_front(); // repeat G76 with all its parameters
  3874. enquecommand_front_P((PSTR("G28 W0")));
  3875. break;
  3876. }
  3877. puts_P(_N("PINDA probe calibration start"));
  3878. custom_message_type = CustomMsg::TempCal;
  3879. custom_message_state = 1;
  3880. lcd_setstatuspgm(_T(MSG_TEMP_CALIBRATION));
  3881. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3882. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3883. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3884. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3885. st_synchronize();
  3886. while (abs(degBed() - PINDA_MIN_T) > 1) {
  3887. delay_keep_alive(1000);
  3888. serialecho_temperatures();
  3889. }
  3890. //enquecommand_P(PSTR("M190 S50"));
  3891. for (int i = 0; i < PINDA_HEAT_T; i++) {
  3892. delay_keep_alive(1000);
  3893. serialecho_temperatures();
  3894. }
  3895. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  3896. current_position[Z_AXIS] = 5;
  3897. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3898. current_position[X_AXIS] = BED_X0;
  3899. current_position[Y_AXIS] = BED_Y0;
  3900. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3901. st_synchronize();
  3902. find_bed_induction_sensor_point_z(-1.f);
  3903. zero_z = current_position[Z_AXIS];
  3904. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  3905. for (int i = 0; i<5; i++) {
  3906. printf_P(_N("\nStep: %d/6\n"), i + 2);
  3907. custom_message_state = i + 2;
  3908. t_c = 60 + i * 10;
  3909. setTargetBed(t_c);
  3910. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3911. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3912. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3913. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3914. st_synchronize();
  3915. while (degBed() < t_c) {
  3916. delay_keep_alive(1000);
  3917. serialecho_temperatures();
  3918. }
  3919. for (int i = 0; i < PINDA_HEAT_T; i++) {
  3920. delay_keep_alive(1000);
  3921. serialecho_temperatures();
  3922. }
  3923. current_position[Z_AXIS] = 5;
  3924. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3925. current_position[X_AXIS] = BED_X0;
  3926. current_position[Y_AXIS] = BED_Y0;
  3927. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3928. st_synchronize();
  3929. find_bed_induction_sensor_point_z(-1.f);
  3930. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  3931. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  3932. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i*2, &z_shift);
  3933. }
  3934. custom_message_type = CustomMsg::Status;
  3935. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  3936. puts_P(_N("Temperature calibration done."));
  3937. disable_x();
  3938. disable_y();
  3939. disable_z();
  3940. disable_e0();
  3941. disable_e1();
  3942. disable_e2();
  3943. setTargetBed(0); //set bed target temperature back to 0
  3944. lcd_show_fullscreen_message_and_wait_P(_T(MSG_TEMP_CALIBRATION_DONE));
  3945. temp_cal_active = true;
  3946. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  3947. lcd_update_enable(true);
  3948. lcd_update(2);
  3949. }
  3950. break;
  3951. //! ### G80 - Mesh-based Z probe
  3952. // -----------------------------------
  3953. /*
  3954. * Probes a grid and produces a mesh to compensate for variable bed height
  3955. * The S0 report the points as below
  3956. * +----> X-axis
  3957. * |
  3958. * |
  3959. * v Y-axis
  3960. */
  3961. case 80:
  3962. #ifdef MK1BP
  3963. break;
  3964. #endif //MK1BP
  3965. case_G80:
  3966. {
  3967. mesh_bed_leveling_flag = true;
  3968. static bool run = false;
  3969. #ifdef SUPPORT_VERBOSITY
  3970. int8_t verbosity_level = 0;
  3971. if (code_seen('V')) {
  3972. // Just 'V' without a number counts as V1.
  3973. char c = strchr_pointer[1];
  3974. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  3975. }
  3976. #endif //SUPPORT_VERBOSITY
  3977. // Firstly check if we know where we are
  3978. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  3979. // We don't know where we are! HOME!
  3980. // Push the commands to the front of the message queue in the reverse order!
  3981. // There shall be always enough space reserved for these commands.
  3982. if (lcd_commands_type != LcdCommands::StopPrint) {
  3983. repeatcommand_front(); // repeat G80 with all its parameters
  3984. enquecommand_front_P((PSTR("G28 W0")));
  3985. }
  3986. else {
  3987. mesh_bed_leveling_flag = false;
  3988. }
  3989. break;
  3990. }
  3991. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  3992. if (code_seen('N')) {
  3993. nMeasPoints = code_value_uint8();
  3994. if (nMeasPoints != 7) {
  3995. nMeasPoints = 3;
  3996. }
  3997. }
  3998. else {
  3999. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  4000. }
  4001. uint8_t nProbeRetry = 3;
  4002. if (code_seen('R')) {
  4003. nProbeRetry = code_value_uint8();
  4004. if (nProbeRetry > 10) {
  4005. nProbeRetry = 10;
  4006. }
  4007. }
  4008. else {
  4009. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  4010. }
  4011. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  4012. bool temp_comp_start = true;
  4013. #ifdef PINDA_THERMISTOR
  4014. temp_comp_start = false;
  4015. #endif //PINDA_THERMISTOR
  4016. if (temp_comp_start)
  4017. if (run == false && temp_cal_active == true && calibration_status_pinda() == true && target_temperature_bed >= 50) {
  4018. if (lcd_commands_type != LcdCommands::StopPrint) {
  4019. temp_compensation_start();
  4020. run = true;
  4021. repeatcommand_front(); // repeat G80 with all its parameters
  4022. enquecommand_front_P((PSTR("G28 W0")));
  4023. }
  4024. else {
  4025. mesh_bed_leveling_flag = false;
  4026. }
  4027. break;
  4028. }
  4029. run = false;
  4030. if (lcd_commands_type == LcdCommands::StopPrint) {
  4031. mesh_bed_leveling_flag = false;
  4032. break;
  4033. }
  4034. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  4035. CustomMsg custom_message_type_old = custom_message_type;
  4036. unsigned int custom_message_state_old = custom_message_state;
  4037. custom_message_type = CustomMsg::MeshBedLeveling;
  4038. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  4039. lcd_update(1);
  4040. mbl.reset(); //reset mesh bed leveling
  4041. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  4042. // consumed during the first movements following this statement.
  4043. babystep_undo();
  4044. // Cycle through all points and probe them
  4045. // First move up. During this first movement, the babystepping will be reverted.
  4046. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4047. 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);
  4048. // The move to the first calibration point.
  4049. current_position[X_AXIS] = BED_X0;
  4050. current_position[Y_AXIS] = BED_Y0;
  4051. #ifdef SUPPORT_VERBOSITY
  4052. if (verbosity_level >= 1)
  4053. {
  4054. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4055. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  4056. }
  4057. #else //SUPPORT_VERBOSITY
  4058. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4059. #endif //SUPPORT_VERBOSITY
  4060. 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);
  4061. // Wait until the move is finished.
  4062. st_synchronize();
  4063. uint8_t mesh_point = 0; //index number of calibration point
  4064. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  4065. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  4066. 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)
  4067. #ifdef SUPPORT_VERBOSITY
  4068. if (verbosity_level >= 1) {
  4069. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  4070. }
  4071. #endif // SUPPORT_VERBOSITY
  4072. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  4073. const char *kill_message = NULL;
  4074. while (mesh_point != nMeasPoints * nMeasPoints) {
  4075. // Get coords of a measuring point.
  4076. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  4077. uint8_t iy = mesh_point / nMeasPoints;
  4078. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  4079. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  4080. custom_message_state--;
  4081. mesh_point++;
  4082. continue; //skip
  4083. }*/
  4084. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  4085. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  4086. {
  4087. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  4088. }
  4089. float z0 = 0.f;
  4090. if (has_z && (mesh_point > 0)) {
  4091. uint16_t z_offset_u = 0;
  4092. if (nMeasPoints == 7) {
  4093. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  4094. }
  4095. else {
  4096. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  4097. }
  4098. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  4099. #ifdef SUPPORT_VERBOSITY
  4100. if (verbosity_level >= 1) {
  4101. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  4102. }
  4103. #endif // SUPPORT_VERBOSITY
  4104. }
  4105. // Move Z up to MESH_HOME_Z_SEARCH.
  4106. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4107. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  4108. float init_z_bckp = current_position[Z_AXIS];
  4109. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  4110. st_synchronize();
  4111. // Move to XY position of the sensor point.
  4112. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  4113. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  4114. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  4115. #ifdef SUPPORT_VERBOSITY
  4116. if (verbosity_level >= 1) {
  4117. clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4118. SERIAL_PROTOCOL(mesh_point);
  4119. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  4120. }
  4121. #else //SUPPORT_VERBOSITY
  4122. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4123. #endif // SUPPORT_VERBOSITY
  4124. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  4125. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], XY_AXIS_FEEDRATE, active_extruder);
  4126. st_synchronize();
  4127. // Go down until endstop is hit
  4128. const float Z_CALIBRATION_THRESHOLD = 1.f;
  4129. if (!find_bed_induction_sensor_point_z((has_z && mesh_point > 0) ? z0 - Z_CALIBRATION_THRESHOLD : -10.f, nProbeRetry)) { //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
  4130. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  4131. break;
  4132. }
  4133. if (init_z_bckp - current_position[Z_AXIS] < 0.1f) { //broken cable or initial Z coordinate too low. Go to MESH_HOME_Z_SEARCH and repeat last step (z-probe) again to distinguish between these two cases.
  4134. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  4135. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4136. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  4137. st_synchronize();
  4138. if (!find_bed_induction_sensor_point_z((has_z && mesh_point > 0) ? z0 - Z_CALIBRATION_THRESHOLD : -10.f, nProbeRetry)) { //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
  4139. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  4140. break;
  4141. }
  4142. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  4143. printf_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken.\n"));
  4144. break;
  4145. }
  4146. }
  4147. 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
  4148. printf_P(PSTR("Bed leveling failed. Sensor triggered too high.\n"));
  4149. break;
  4150. }
  4151. #ifdef SUPPORT_VERBOSITY
  4152. if (verbosity_level >= 10) {
  4153. SERIAL_ECHOPGM("X: ");
  4154. MYSERIAL.print(current_position[X_AXIS], 5);
  4155. SERIAL_ECHOLNPGM("");
  4156. SERIAL_ECHOPGM("Y: ");
  4157. MYSERIAL.print(current_position[Y_AXIS], 5);
  4158. SERIAL_PROTOCOLPGM("\n");
  4159. }
  4160. #endif // SUPPORT_VERBOSITY
  4161. float offset_z = 0;
  4162. #ifdef PINDA_THERMISTOR
  4163. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  4164. #endif //PINDA_THERMISTOR
  4165. // #ifdef SUPPORT_VERBOSITY
  4166. /* if (verbosity_level >= 1)
  4167. {
  4168. SERIAL_ECHOPGM("mesh bed leveling: ");
  4169. MYSERIAL.print(current_position[Z_AXIS], 5);
  4170. SERIAL_ECHOPGM(" offset: ");
  4171. MYSERIAL.print(offset_z, 5);
  4172. SERIAL_ECHOLNPGM("");
  4173. }*/
  4174. // #endif // SUPPORT_VERBOSITY
  4175. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  4176. custom_message_state--;
  4177. mesh_point++;
  4178. lcd_update(1);
  4179. }
  4180. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4181. #ifdef SUPPORT_VERBOSITY
  4182. if (verbosity_level >= 20) {
  4183. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  4184. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  4185. MYSERIAL.print(current_position[Z_AXIS], 5);
  4186. }
  4187. #endif // SUPPORT_VERBOSITY
  4188. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  4189. st_synchronize();
  4190. if (mesh_point != nMeasPoints * nMeasPoints) {
  4191. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  4192. bool bState;
  4193. do { // repeat until Z-leveling o.k.
  4194. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ..."));
  4195. #ifdef TMC2130
  4196. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  4197. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  4198. #else // TMC2130
  4199. lcd_wait_for_click_delay(0); // ~ no timeout
  4200. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  4201. #endif // TMC2130
  4202. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  4203. bState=enable_z_endstop(false);
  4204. current_position[Z_AXIS] -= 1;
  4205. 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);
  4206. st_synchronize();
  4207. enable_z_endstop(true);
  4208. #ifdef TMC2130
  4209. tmc2130_home_enter(Z_AXIS_MASK);
  4210. #endif // TMC2130
  4211. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4212. 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);
  4213. st_synchronize();
  4214. #ifdef TMC2130
  4215. tmc2130_home_exit();
  4216. #endif // TMC2130
  4217. enable_z_endstop(bState);
  4218. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  4219. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  4220. custom_message_type=CustomMsg::Status; // display / status-line recovery
  4221. lcd_update_enable(true); // display / status-line recovery
  4222. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  4223. repeatcommand_front(); // re-run (i.e. of "G80")
  4224. break;
  4225. }
  4226. clean_up_after_endstop_move(l_feedmultiply);
  4227. // SERIAL_ECHOLNPGM("clean up finished ");
  4228. bool apply_temp_comp = true;
  4229. #ifdef PINDA_THERMISTOR
  4230. apply_temp_comp = false;
  4231. #endif
  4232. if (apply_temp_comp)
  4233. if(temp_cal_active == true && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  4234. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  4235. // SERIAL_ECHOLNPGM("babystep applied");
  4236. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  4237. #ifdef SUPPORT_VERBOSITY
  4238. if (verbosity_level >= 1) {
  4239. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  4240. }
  4241. #endif // SUPPORT_VERBOSITY
  4242. for (uint8_t i = 0; i < 4; ++i) {
  4243. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  4244. long correction = 0;
  4245. if (code_seen(codes[i]))
  4246. correction = code_value_long();
  4247. else if (eeprom_bed_correction_valid) {
  4248. unsigned char *addr = (i < 2) ?
  4249. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  4250. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  4251. correction = eeprom_read_int8(addr);
  4252. }
  4253. if (correction == 0)
  4254. continue;
  4255. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  4256. SERIAL_ERROR_START;
  4257. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  4258. SERIAL_ECHO(correction);
  4259. SERIAL_ECHOLNPGM(" microns");
  4260. }
  4261. else {
  4262. float offset = float(correction) * 0.001f;
  4263. switch (i) {
  4264. case 0:
  4265. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  4266. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  4267. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  4268. }
  4269. }
  4270. break;
  4271. case 1:
  4272. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  4273. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  4274. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  4275. }
  4276. }
  4277. break;
  4278. case 2:
  4279. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  4280. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  4281. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  4282. }
  4283. }
  4284. break;
  4285. case 3:
  4286. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  4287. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  4288. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  4289. }
  4290. }
  4291. break;
  4292. }
  4293. }
  4294. }
  4295. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  4296. if (nMeasPoints == 3) {
  4297. mbl.upsample_3x3(); //interpolation from 3x3 to 7x7 points using largrangian polynomials while using the same array z_values[iy][ix] for storing (just coppying measured data to new destination and interpolating between them)
  4298. }
  4299. /*
  4300. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4301. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4302. SERIAL_PROTOCOLPGM(",");
  4303. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4304. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4305. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4306. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4307. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4308. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4309. SERIAL_PROTOCOLPGM(" ");
  4310. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4311. }
  4312. SERIAL_PROTOCOLPGM("\n");
  4313. }
  4314. */
  4315. if (nMeasPoints == 7 && magnet_elimination) {
  4316. mbl_interpolation(nMeasPoints);
  4317. }
  4318. /*
  4319. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4320. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4321. SERIAL_PROTOCOLPGM(",");
  4322. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4323. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4324. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4325. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4326. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4327. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4328. SERIAL_PROTOCOLPGM(" ");
  4329. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4330. }
  4331. SERIAL_PROTOCOLPGM("\n");
  4332. }
  4333. */
  4334. // SERIAL_ECHOLNPGM("Upsample finished");
  4335. mbl.active = 1; //activate mesh bed leveling
  4336. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  4337. go_home_with_z_lift();
  4338. // SERIAL_ECHOLNPGM("Go home finished");
  4339. //unretract (after PINDA preheat retraction)
  4340. if (degHotend(active_extruder) > EXTRUDE_MINTEMP && temp_cal_active == true && calibration_status_pinda() == true && target_temperature_bed >= 50) {
  4341. current_position[E_AXIS] += default_retraction;
  4342. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  4343. }
  4344. KEEPALIVE_STATE(NOT_BUSY);
  4345. // Restore custom message state
  4346. lcd_setstatuspgm(_T(WELCOME_MSG));
  4347. custom_message_type = custom_message_type_old;
  4348. custom_message_state = custom_message_state_old;
  4349. mesh_bed_leveling_flag = false;
  4350. mesh_bed_run_from_menu = false;
  4351. lcd_update(2);
  4352. }
  4353. break;
  4354. //! ### G81 - Mesh bed leveling status
  4355. // -----------------------------------------
  4356. /*
  4357. * Prints mesh bed leveling status and bed profile if activated
  4358. */
  4359. case 81:
  4360. if (mbl.active) {
  4361. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4362. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4363. SERIAL_PROTOCOLPGM(",");
  4364. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4365. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4366. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4367. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4368. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4369. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4370. SERIAL_PROTOCOLPGM(" ");
  4371. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4372. }
  4373. SERIAL_PROTOCOLPGM("\n");
  4374. }
  4375. }
  4376. else
  4377. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4378. break;
  4379. #if 0
  4380. /*
  4381. * G82: Single Z probe at current location
  4382. *
  4383. * WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4384. *
  4385. */
  4386. case 82:
  4387. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4388. int l_feedmultiply = setup_for_endstop_move();
  4389. find_bed_induction_sensor_point_z();
  4390. clean_up_after_endstop_move(l_feedmultiply);
  4391. SERIAL_PROTOCOLPGM("Bed found at: ");
  4392. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4393. SERIAL_PROTOCOLPGM("\n");
  4394. break;
  4395. /*
  4396. * G83: Prusa3D specific: Babystep in Z and store to EEPROM
  4397. */
  4398. case 83:
  4399. {
  4400. int babystepz = code_seen('S') ? code_value() : 0;
  4401. int BabyPosition = code_seen('P') ? code_value() : 0;
  4402. if (babystepz != 0) {
  4403. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4404. // Is the axis indexed starting with zero or one?
  4405. if (BabyPosition > 4) {
  4406. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4407. }else{
  4408. // Save it to the eeprom
  4409. babystepLoadZ = babystepz;
  4410. EEPROM_save_B(EEPROM_BABYSTEP_Z0+(BabyPosition*2),&babystepLoadZ);
  4411. // adjust the Z
  4412. babystepsTodoZadd(babystepLoadZ);
  4413. }
  4414. }
  4415. }
  4416. break;
  4417. /*
  4418. * G84: Prusa3D specific: UNDO Babystep Z (move Z axis back)
  4419. */
  4420. case 84:
  4421. babystepsTodoZsubtract(babystepLoadZ);
  4422. // babystepLoadZ = 0;
  4423. break;
  4424. /*
  4425. * G85: Prusa3D specific: Pick best babystep
  4426. */
  4427. case 85:
  4428. lcd_pick_babystep();
  4429. break;
  4430. #endif
  4431. /**
  4432. * ### G86 - Disable babystep correction after home
  4433. *
  4434. * This G-code will be performed at the start of a calibration script.
  4435. * (Prusa3D specific)
  4436. */
  4437. case 86:
  4438. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4439. break;
  4440. /**
  4441. * ### G87 - Enable babystep correction after home
  4442. *
  4443. *
  4444. * This G-code will be performed at the end of a calibration script.
  4445. * (Prusa3D specific)
  4446. */
  4447. case 87:
  4448. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4449. break;
  4450. /**
  4451. * ### G88 - Reserved
  4452. *
  4453. * Currently has no effect.
  4454. */
  4455. // Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4456. case 88:
  4457. break;
  4458. #endif // ENABLE_MESH_BED_LEVELING
  4459. //! ### G90 - Switch off relative mode
  4460. // -------------------------------
  4461. case 90:
  4462. relative_mode = false;
  4463. break;
  4464. //! ### G91 - Switch on relative mode
  4465. // -------------------------------
  4466. case 91:
  4467. relative_mode = true;
  4468. break;
  4469. //! ### G92 - Set position
  4470. // -----------------------------
  4471. case 92:
  4472. if(!code_seen(axis_codes[E_AXIS]))
  4473. st_synchronize();
  4474. for(int8_t i=0; i < NUM_AXIS; i++) {
  4475. if(code_seen(axis_codes[i])) {
  4476. if(i == E_AXIS) {
  4477. current_position[i] = code_value();
  4478. plan_set_e_position(current_position[E_AXIS]);
  4479. }
  4480. else {
  4481. current_position[i] = code_value()+cs.add_homing[i];
  4482. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  4483. }
  4484. }
  4485. }
  4486. break;
  4487. //! ### G98 - Activate farm mode
  4488. // -----------------------------------
  4489. case 98:
  4490. farm_mode = 1;
  4491. PingTime = _millis();
  4492. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  4493. EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
  4494. SilentModeMenu = SILENT_MODE_OFF;
  4495. eeprom_update_byte((unsigned char *)EEPROM_SILENT, SilentModeMenu);
  4496. fCheckModeInit(); // alternatively invoke printer reset
  4497. break;
  4498. //! ### G99 - Deactivate farm mode
  4499. // -------------------------------------
  4500. case 99:
  4501. farm_mode = 0;
  4502. lcd_printer_connected();
  4503. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  4504. lcd_update(2);
  4505. fCheckModeInit(); // alternatively invoke printer reset
  4506. break;
  4507. default:
  4508. printf_P(PSTR("Unknown G code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4509. }
  4510. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4511. gcode_in_progress = 0;
  4512. } // end if(code_seen('G'))
  4513. //! ---------------------------------------------------------------------------------
  4514. else if(code_seen('M'))
  4515. {
  4516. int index;
  4517. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4518. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4519. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4520. printf_P(PSTR("Invalid M code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4521. } else
  4522. {
  4523. mcode_in_progress = (int)code_value();
  4524. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4525. switch(mcode_in_progress)
  4526. {
  4527. //! ### M0, M1 - Stop the printer
  4528. // ---------------------------------------------------------------
  4529. case 0: // M0 - Unconditional stop - Wait for user button press on LCD
  4530. case 1: // M1 - Conditional stop - Wait for user button press on LCD
  4531. {
  4532. char *src = strchr_pointer + 2;
  4533. codenum = 0;
  4534. bool hasP = false, hasS = false;
  4535. if (code_seen('P')) {
  4536. codenum = code_value(); // milliseconds to wait
  4537. hasP = codenum > 0;
  4538. }
  4539. if (code_seen('S')) {
  4540. codenum = code_value() * 1000; // seconds to wait
  4541. hasS = codenum > 0;
  4542. }
  4543. starpos = strchr(src, '*');
  4544. if (starpos != NULL) *(starpos) = '\0';
  4545. while (*src == ' ') ++src;
  4546. if (!hasP && !hasS && *src != '\0') {
  4547. lcd_setstatus(src);
  4548. } else {
  4549. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT
  4550. }
  4551. lcd_ignore_click(); //call lcd_ignore_click aslo for else ???
  4552. st_synchronize();
  4553. previous_millis_cmd = _millis();
  4554. if (codenum > 0){
  4555. codenum += _millis(); // keep track of when we started waiting
  4556. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4557. while(_millis() < codenum && !lcd_clicked()){
  4558. manage_heater();
  4559. manage_inactivity(true);
  4560. lcd_update(0);
  4561. }
  4562. KEEPALIVE_STATE(IN_HANDLER);
  4563. lcd_ignore_click(false);
  4564. }else{
  4565. marlin_wait_for_click();
  4566. }
  4567. if (IS_SD_PRINTING)
  4568. LCD_MESSAGERPGM(_T(MSG_RESUMING_PRINT));
  4569. else
  4570. LCD_MESSAGERPGM(_T(WELCOME_MSG));
  4571. }
  4572. break;
  4573. //! ### M17 - Enable axes
  4574. // ---------------------------------
  4575. case 17:
  4576. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE
  4577. enable_x();
  4578. enable_y();
  4579. enable_z();
  4580. enable_e0();
  4581. enable_e1();
  4582. enable_e2();
  4583. break;
  4584. #ifdef SDSUPPORT
  4585. //! ### M20 - SD Card file list
  4586. // -----------------------------------
  4587. case 20:
  4588. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4589. card.ls();
  4590. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4591. break;
  4592. //! ### M21 - Init SD card
  4593. // ------------------------------------
  4594. case 21:
  4595. card.initsd();
  4596. break;
  4597. //! ### M22 - Release SD card
  4598. // -----------------------------------
  4599. case 22:
  4600. card.release();
  4601. break;
  4602. //! ### M23 - Select file
  4603. // -----------------------------------
  4604. case 23:
  4605. starpos = (strchr(strchr_pointer + 4,'*'));
  4606. if(starpos!=NULL)
  4607. *(starpos)='\0';
  4608. card.openFile(strchr_pointer + 4,true);
  4609. break;
  4610. //! ### M24 - Start SD print
  4611. // ----------------------------------
  4612. case 24:
  4613. if (!card.paused)
  4614. failstats_reset_print();
  4615. card.startFileprint();
  4616. starttime=_millis();
  4617. break;
  4618. //! ### M25 - Pause SD print
  4619. // ----------------------------------
  4620. case 25:
  4621. card.pauseSDPrint();
  4622. break;
  4623. //! ### M26 - Set SD index
  4624. // ----------------------------------
  4625. case 26:
  4626. if(card.cardOK && code_seen('S')) {
  4627. card.setIndex(code_value_long());
  4628. }
  4629. break;
  4630. //! ### M27 - Get SD status
  4631. // ----------------------------------
  4632. case 27:
  4633. card.getStatus();
  4634. break;
  4635. //! ### M28 - Start SD write
  4636. // ---------------------------------
  4637. case 28:
  4638. starpos = (strchr(strchr_pointer + 4,'*'));
  4639. if(starpos != NULL){
  4640. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4641. strchr_pointer = strchr(npos,' ') + 1;
  4642. *(starpos) = '\0';
  4643. }
  4644. card.openFile(strchr_pointer+4,false);
  4645. break;
  4646. //! ### M29 - Stop SD write
  4647. // -------------------------------------
  4648. //! Currently has no effect.
  4649. case 29:
  4650. //processed in write to file routine above
  4651. //card,saving = false;
  4652. break;
  4653. //! ### M30 - Delete file <filename>
  4654. // ----------------------------------
  4655. case 30:
  4656. if (card.cardOK){
  4657. card.closefile();
  4658. starpos = (strchr(strchr_pointer + 4,'*'));
  4659. if(starpos != NULL){
  4660. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4661. strchr_pointer = strchr(npos,' ') + 1;
  4662. *(starpos) = '\0';
  4663. }
  4664. card.removeFile(strchr_pointer + 4);
  4665. }
  4666. break;
  4667. //! ### M32 - Select file and start SD print
  4668. // ------------------------------------
  4669. case 32:
  4670. {
  4671. if(card.sdprinting) {
  4672. st_synchronize();
  4673. }
  4674. starpos = (strchr(strchr_pointer + 4,'*'));
  4675. char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4676. if(namestartpos==NULL)
  4677. {
  4678. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4679. }
  4680. else
  4681. namestartpos++; //to skip the '!'
  4682. if(starpos!=NULL)
  4683. *(starpos)='\0';
  4684. bool call_procedure=(code_seen('P'));
  4685. if(strchr_pointer>namestartpos)
  4686. call_procedure=false; //false alert, 'P' found within filename
  4687. if( card.cardOK )
  4688. {
  4689. card.openFile(namestartpos,true,!call_procedure);
  4690. if(code_seen('S'))
  4691. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4692. card.setIndex(code_value_long());
  4693. card.startFileprint();
  4694. if(!call_procedure)
  4695. starttime=_millis(); //procedure calls count as normal print time.
  4696. }
  4697. } break;
  4698. //! ### M982 - Start SD write
  4699. // ---------------------------------
  4700. case 928:
  4701. starpos = (strchr(strchr_pointer + 5,'*'));
  4702. if(starpos != NULL){
  4703. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4704. strchr_pointer = strchr(npos,' ') + 1;
  4705. *(starpos) = '\0';
  4706. }
  4707. card.openLogFile(strchr_pointer+5);
  4708. break;
  4709. #endif //SDSUPPORT
  4710. //! ### M31 - Report current print time
  4711. // --------------------------------------------------
  4712. case 31: //M31 take time since the start of the SD print or an M109 command
  4713. {
  4714. stoptime=_millis();
  4715. char time[30];
  4716. unsigned long t=(stoptime-starttime)/1000;
  4717. int sec,min;
  4718. min=t/60;
  4719. sec=t%60;
  4720. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4721. SERIAL_ECHO_START;
  4722. SERIAL_ECHOLN(time);
  4723. lcd_setstatus(time);
  4724. autotempShutdown();
  4725. }
  4726. break;
  4727. //! ### M42 - Set pin state
  4728. // -----------------------------
  4729. case 42:
  4730. if (code_seen('S'))
  4731. {
  4732. int pin_status = code_value();
  4733. int pin_number = LED_PIN;
  4734. if (code_seen('P') && pin_status >= 0 && pin_status <= 255)
  4735. pin_number = code_value();
  4736. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  4737. {
  4738. if (sensitive_pins[i] == pin_number)
  4739. {
  4740. pin_number = -1;
  4741. break;
  4742. }
  4743. }
  4744. #if defined(FAN_PIN) && FAN_PIN > -1
  4745. if (pin_number == FAN_PIN)
  4746. fanSpeed = pin_status;
  4747. #endif
  4748. if (pin_number > -1)
  4749. {
  4750. pinMode(pin_number, OUTPUT);
  4751. digitalWrite(pin_number, pin_status);
  4752. analogWrite(pin_number, pin_status);
  4753. }
  4754. }
  4755. break;
  4756. //! ### M44 - Reset the bed skew and offset calibration (Prusa specific)
  4757. // --------------------------------------------------------------------
  4758. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  4759. // Reset the baby step value and the baby step applied flag.
  4760. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4761. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z, 0);
  4762. // Reset the skew and offset in both RAM and EEPROM.
  4763. reset_bed_offset_and_skew();
  4764. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4765. // the planner will not perform any adjustments in the XY plane.
  4766. // Wait for the motors to stop and update the current position with the absolute values.
  4767. world2machine_revert_to_uncorrected();
  4768. break;
  4769. //! ### M45 - Bed skew and offset with manual Z up (Prusa specific)
  4770. // ------------------------------------------------------
  4771. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  4772. {
  4773. int8_t verbosity_level = 0;
  4774. bool only_Z = code_seen('Z');
  4775. #ifdef SUPPORT_VERBOSITY
  4776. if (code_seen('V'))
  4777. {
  4778. // Just 'V' without a number counts as V1.
  4779. char c = strchr_pointer[1];
  4780. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4781. }
  4782. #endif //SUPPORT_VERBOSITY
  4783. gcode_M45(only_Z, verbosity_level);
  4784. }
  4785. break;
  4786. /*
  4787. case 46:
  4788. {
  4789. // M46: Prusa3D: Show the assigned IP address.
  4790. uint8_t ip[4];
  4791. bool hasIP = card.ToshibaFlashAir_GetIP(ip);
  4792. if (hasIP) {
  4793. SERIAL_ECHOPGM("Toshiba FlashAir current IP: ");
  4794. SERIAL_ECHO(int(ip[0]));
  4795. SERIAL_ECHOPGM(".");
  4796. SERIAL_ECHO(int(ip[1]));
  4797. SERIAL_ECHOPGM(".");
  4798. SERIAL_ECHO(int(ip[2]));
  4799. SERIAL_ECHOPGM(".");
  4800. SERIAL_ECHO(int(ip[3]));
  4801. SERIAL_ECHOLNPGM("");
  4802. } else {
  4803. SERIAL_ECHOLNPGM("Toshiba FlashAir GetIP failed");
  4804. }
  4805. break;
  4806. }
  4807. */
  4808. //! ### M47 - Show end stops dialog on the display (Prusa specific)
  4809. // ----------------------------------------------------
  4810. case 47:
  4811. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4812. lcd_diag_show_end_stops();
  4813. KEEPALIVE_STATE(IN_HANDLER);
  4814. break;
  4815. #if 0
  4816. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  4817. {
  4818. // Disable the default update procedure of the display. We will do a modal dialog.
  4819. lcd_update_enable(false);
  4820. // Let the planner use the uncorrected coordinates.
  4821. mbl.reset();
  4822. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4823. // the planner will not perform any adjustments in the XY plane.
  4824. // Wait for the motors to stop and update the current position with the absolute values.
  4825. world2machine_revert_to_uncorrected();
  4826. // Move the print head close to the bed.
  4827. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4828. 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);
  4829. st_synchronize();
  4830. // Home in the XY plane.
  4831. set_destination_to_current();
  4832. int l_feedmultiply = setup_for_endstop_move();
  4833. home_xy();
  4834. int8_t verbosity_level = 0;
  4835. if (code_seen('V')) {
  4836. // Just 'V' without a number counts as V1.
  4837. char c = strchr_pointer[1];
  4838. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4839. }
  4840. bool success = scan_bed_induction_points(verbosity_level);
  4841. clean_up_after_endstop_move(l_feedmultiply);
  4842. // Print head up.
  4843. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4844. 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);
  4845. st_synchronize();
  4846. lcd_update_enable(true);
  4847. break;
  4848. }
  4849. #endif
  4850. #ifdef ENABLE_AUTO_BED_LEVELING
  4851. #ifdef Z_PROBE_REPEATABILITY_TEST
  4852. //! ### M48 - Z-Probe repeatability measurement function.
  4853. // ------------------------------------------------------
  4854. //!
  4855. //! _Usage:_
  4856. //!
  4857. //! M48 <n #_samples> <X X_position_for_samples> <Y Y_position_for_samples> <V Verbose_Level> <L legs_of_movement_prior_to_doing_probe>
  4858. //!
  4859. //! This function assumes the bed has been homed. Specifically, that a G28 command
  4860. //! as been issued prior to invoking the M48 Z-Probe repeatability measurement function.
  4861. //! Any information generated by a prior G29 Bed leveling command will be lost and need to be
  4862. //! regenerated.
  4863. //!
  4864. //! The number of samples will default to 10 if not specified. You can use upper or lower case
  4865. //! letters for any of the options EXCEPT n. n must be in lower case because Marlin uses a capital
  4866. //! N for its communication protocol and will get horribly confused if you send it a capital N.
  4867. //!
  4868. case 48: // M48 Z-Probe repeatability
  4869. {
  4870. #if Z_MIN_PIN == -1
  4871. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  4872. #endif
  4873. double sum=0.0;
  4874. double mean=0.0;
  4875. double sigma=0.0;
  4876. double sample_set[50];
  4877. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  4878. double X_current, Y_current, Z_current;
  4879. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  4880. if (code_seen('V') || code_seen('v')) {
  4881. verbose_level = code_value();
  4882. if (verbose_level<0 || verbose_level>4 ) {
  4883. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  4884. goto Sigma_Exit;
  4885. }
  4886. }
  4887. if (verbose_level > 0) {
  4888. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  4889. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  4890. }
  4891. if (code_seen('n')) {
  4892. n_samples = code_value();
  4893. if (n_samples<4 || n_samples>50 ) {
  4894. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  4895. goto Sigma_Exit;
  4896. }
  4897. }
  4898. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  4899. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  4900. Z_current = st_get_position_mm(Z_AXIS);
  4901. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  4902. ext_position = st_get_position_mm(E_AXIS);
  4903. if (code_seen('X') || code_seen('x') ) {
  4904. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  4905. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  4906. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  4907. goto Sigma_Exit;
  4908. }
  4909. }
  4910. if (code_seen('Y') || code_seen('y') ) {
  4911. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  4912. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  4913. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  4914. goto Sigma_Exit;
  4915. }
  4916. }
  4917. if (code_seen('L') || code_seen('l') ) {
  4918. n_legs = code_value();
  4919. if ( n_legs==1 )
  4920. n_legs = 2;
  4921. if ( n_legs<0 || n_legs>15 ) {
  4922. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  4923. goto Sigma_Exit;
  4924. }
  4925. }
  4926. //
  4927. // Do all the preliminary setup work. First raise the probe.
  4928. //
  4929. st_synchronize();
  4930. plan_bed_level_matrix.set_to_identity();
  4931. plan_buffer_line( X_current, Y_current, Z_start_location,
  4932. ext_position,
  4933. homing_feedrate[Z_AXIS]/60,
  4934. active_extruder);
  4935. st_synchronize();
  4936. //
  4937. // Now get everything to the specified probe point So we can safely do a probe to
  4938. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  4939. // use that as a starting point for each probe.
  4940. //
  4941. if (verbose_level > 2)
  4942. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  4943. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  4944. ext_position,
  4945. homing_feedrate[X_AXIS]/60,
  4946. active_extruder);
  4947. st_synchronize();
  4948. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  4949. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  4950. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  4951. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  4952. //
  4953. // OK, do the inital probe to get us close to the bed.
  4954. // Then retrace the right amount and use that in subsequent probes
  4955. //
  4956. int l_feedmultiply = setup_for_endstop_move();
  4957. run_z_probe();
  4958. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  4959. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  4960. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  4961. ext_position,
  4962. homing_feedrate[X_AXIS]/60,
  4963. active_extruder);
  4964. st_synchronize();
  4965. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  4966. for( n=0; n<n_samples; n++) {
  4967. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  4968. if ( n_legs) {
  4969. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  4970. int rotational_direction, l;
  4971. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  4972. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  4973. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  4974. //SERIAL_ECHOPAIR("starting radius: ",radius);
  4975. //SERIAL_ECHOPAIR(" theta: ",theta);
  4976. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  4977. //SERIAL_PROTOCOLLNPGM("");
  4978. for( l=0; l<n_legs-1; l++) {
  4979. if (rotational_direction==1)
  4980. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  4981. else
  4982. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  4983. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  4984. if ( radius<0.0 )
  4985. radius = -radius;
  4986. X_current = X_probe_location + cos(theta) * radius;
  4987. Y_current = Y_probe_location + sin(theta) * radius;
  4988. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  4989. X_current = X_MIN_POS;
  4990. if ( X_current>X_MAX_POS)
  4991. X_current = X_MAX_POS;
  4992. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  4993. Y_current = Y_MIN_POS;
  4994. if ( Y_current>Y_MAX_POS)
  4995. Y_current = Y_MAX_POS;
  4996. if (verbose_level>3 ) {
  4997. SERIAL_ECHOPAIR("x: ", X_current);
  4998. SERIAL_ECHOPAIR("y: ", Y_current);
  4999. SERIAL_PROTOCOLLNPGM("");
  5000. }
  5001. do_blocking_move_to( X_current, Y_current, Z_current );
  5002. }
  5003. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5004. }
  5005. int l_feedmultiply = setup_for_endstop_move();
  5006. run_z_probe();
  5007. sample_set[n] = current_position[Z_AXIS];
  5008. //
  5009. // Get the current mean for the data points we have so far
  5010. //
  5011. sum=0.0;
  5012. for( j=0; j<=n; j++) {
  5013. sum = sum + sample_set[j];
  5014. }
  5015. mean = sum / (double (n+1));
  5016. //
  5017. // Now, use that mean to calculate the standard deviation for the
  5018. // data points we have so far
  5019. //
  5020. sum=0.0;
  5021. for( j=0; j<=n; j++) {
  5022. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5023. }
  5024. sigma = sqrt( sum / (double (n+1)) );
  5025. if (verbose_level > 1) {
  5026. SERIAL_PROTOCOL(n+1);
  5027. SERIAL_PROTOCOL(" of ");
  5028. SERIAL_PROTOCOL(n_samples);
  5029. SERIAL_PROTOCOLPGM(" z: ");
  5030. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5031. }
  5032. if (verbose_level > 2) {
  5033. SERIAL_PROTOCOL(" mean: ");
  5034. SERIAL_PROTOCOL_F(mean,6);
  5035. SERIAL_PROTOCOL(" sigma: ");
  5036. SERIAL_PROTOCOL_F(sigma,6);
  5037. }
  5038. if (verbose_level > 0)
  5039. SERIAL_PROTOCOLPGM("\n");
  5040. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5041. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5042. st_synchronize();
  5043. }
  5044. _delay(1000);
  5045. clean_up_after_endstop_move(l_feedmultiply);
  5046. // enable_endstops(true);
  5047. if (verbose_level > 0) {
  5048. SERIAL_PROTOCOLPGM("Mean: ");
  5049. SERIAL_PROTOCOL_F(mean, 6);
  5050. SERIAL_PROTOCOLPGM("\n");
  5051. }
  5052. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5053. SERIAL_PROTOCOL_F(sigma, 6);
  5054. SERIAL_PROTOCOLPGM("\n\n");
  5055. Sigma_Exit:
  5056. break;
  5057. }
  5058. #endif // Z_PROBE_REPEATABILITY_TEST
  5059. #endif // ENABLE_AUTO_BED_LEVELING
  5060. //! ### M73 - Set/get print progress
  5061. // -------------------------------------
  5062. //! _Usage:_
  5063. //!
  5064. //! M73 P<percent> R<time_remaining> Q<percent_silent> S<time_remaining_silent>
  5065. //!
  5066. case 73: //M73 show percent done and time remaining
  5067. if(code_seen('P')) print_percent_done_normal = code_value();
  5068. if(code_seen('R')) print_time_remaining_normal = code_value();
  5069. if(code_seen('Q')) print_percent_done_silent = code_value();
  5070. if(code_seen('S')) print_time_remaining_silent = code_value();
  5071. {
  5072. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %d; print time remaining in mins: %d\n");
  5073. printf_P(_msg_mode_done_remain, _N("NORMAL"), int(print_percent_done_normal), print_time_remaining_normal);
  5074. printf_P(_msg_mode_done_remain, _N("SILENT"), int(print_percent_done_silent), print_time_remaining_silent);
  5075. }
  5076. break;
  5077. //! ### M104 - Set hotend temperature
  5078. // -----------------------------------------
  5079. case 104: // M104
  5080. {
  5081. uint8_t extruder;
  5082. if(setTargetedHotend(104,extruder)){
  5083. break;
  5084. }
  5085. if (code_seen('S'))
  5086. {
  5087. setTargetHotendSafe(code_value(), extruder);
  5088. }
  5089. setWatch();
  5090. break;
  5091. }
  5092. //! ### M112 - Emergency stop
  5093. // -----------------------------------------
  5094. case 112:
  5095. kill(_n(""), 3);
  5096. break;
  5097. //! ### M140 - Set bed temperature
  5098. // -----------------------------------------
  5099. case 140:
  5100. if (code_seen('S')) setTargetBed(code_value());
  5101. break;
  5102. //! ### M105 - Report temperatures
  5103. // -----------------------------------------
  5104. case 105:
  5105. {
  5106. uint8_t extruder;
  5107. if(setTargetedHotend(105, extruder)){
  5108. break;
  5109. }
  5110. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  5111. SERIAL_PROTOCOLPGM("ok T:");
  5112. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  5113. SERIAL_PROTOCOLPGM(" /");
  5114. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  5115. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5116. SERIAL_PROTOCOLPGM(" B:");
  5117. SERIAL_PROTOCOL_F(degBed(),1);
  5118. SERIAL_PROTOCOLPGM(" /");
  5119. SERIAL_PROTOCOL_F(degTargetBed(),1);
  5120. #endif //TEMP_BED_PIN
  5121. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  5122. SERIAL_PROTOCOLPGM(" T");
  5123. SERIAL_PROTOCOL(cur_extruder);
  5124. SERIAL_PROTOCOLPGM(":");
  5125. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  5126. SERIAL_PROTOCOLPGM(" /");
  5127. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  5128. }
  5129. #else
  5130. SERIAL_ERROR_START;
  5131. SERIAL_ERRORLNRPGM(_i("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  5132. #endif
  5133. SERIAL_PROTOCOLPGM(" @:");
  5134. #ifdef EXTRUDER_WATTS
  5135. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  5136. SERIAL_PROTOCOLPGM("W");
  5137. #else
  5138. SERIAL_PROTOCOL(getHeaterPower(extruder));
  5139. #endif
  5140. SERIAL_PROTOCOLPGM(" B@:");
  5141. #ifdef BED_WATTS
  5142. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  5143. SERIAL_PROTOCOLPGM("W");
  5144. #else
  5145. SERIAL_PROTOCOL(getHeaterPower(-1));
  5146. #endif
  5147. #ifdef PINDA_THERMISTOR
  5148. SERIAL_PROTOCOLPGM(" P:");
  5149. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  5150. #endif //PINDA_THERMISTOR
  5151. #ifdef AMBIENT_THERMISTOR
  5152. SERIAL_PROTOCOLPGM(" A:");
  5153. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  5154. #endif //AMBIENT_THERMISTOR
  5155. #ifdef SHOW_TEMP_ADC_VALUES
  5156. {float raw = 0.0;
  5157. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5158. SERIAL_PROTOCOLPGM(" ADC B:");
  5159. SERIAL_PROTOCOL_F(degBed(),1);
  5160. SERIAL_PROTOCOLPGM("C->");
  5161. raw = rawBedTemp();
  5162. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  5163. SERIAL_PROTOCOLPGM(" Rb->");
  5164. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  5165. SERIAL_PROTOCOLPGM(" Rxb->");
  5166. SERIAL_PROTOCOL_F(raw, 5);
  5167. #endif
  5168. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  5169. SERIAL_PROTOCOLPGM(" T");
  5170. SERIAL_PROTOCOL(cur_extruder);
  5171. SERIAL_PROTOCOLPGM(":");
  5172. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  5173. SERIAL_PROTOCOLPGM("C->");
  5174. raw = rawHotendTemp(cur_extruder);
  5175. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  5176. SERIAL_PROTOCOLPGM(" Rt");
  5177. SERIAL_PROTOCOL(cur_extruder);
  5178. SERIAL_PROTOCOLPGM("->");
  5179. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  5180. SERIAL_PROTOCOLPGM(" Rx");
  5181. SERIAL_PROTOCOL(cur_extruder);
  5182. SERIAL_PROTOCOLPGM("->");
  5183. SERIAL_PROTOCOL_F(raw, 5);
  5184. }}
  5185. #endif
  5186. SERIAL_PROTOCOLLN("");
  5187. KEEPALIVE_STATE(NOT_BUSY);
  5188. return;
  5189. break;
  5190. }
  5191. //! ### M109 - Wait for extruder temperature
  5192. // -------------------------------------------------
  5193. case 109:
  5194. {
  5195. uint8_t extruder;
  5196. if(setTargetedHotend(109, extruder)){
  5197. break;
  5198. }
  5199. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5200. heating_status = 1;
  5201. if (farm_mode) { prusa_statistics(1); };
  5202. #ifdef AUTOTEMP
  5203. autotemp_enabled=false;
  5204. #endif
  5205. if (code_seen('S')) {
  5206. setTargetHotendSafe(code_value(), extruder);
  5207. CooldownNoWait = true;
  5208. } else if (code_seen('R')) {
  5209. setTargetHotendSafe(code_value(), extruder);
  5210. CooldownNoWait = false;
  5211. }
  5212. #ifdef AUTOTEMP
  5213. if (code_seen('S')) autotemp_min=code_value();
  5214. if (code_seen('B')) autotemp_max=code_value();
  5215. if (code_seen('F'))
  5216. {
  5217. autotemp_factor=code_value();
  5218. autotemp_enabled=true;
  5219. }
  5220. #endif
  5221. setWatch();
  5222. codenum = _millis();
  5223. /* See if we are heating up or cooling down */
  5224. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5225. KEEPALIVE_STATE(NOT_BUSY);
  5226. cancel_heatup = false;
  5227. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5228. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5229. KEEPALIVE_STATE(IN_HANDLER);
  5230. heating_status = 2;
  5231. if (farm_mode) { prusa_statistics(2); };
  5232. //starttime=_millis();
  5233. previous_millis_cmd = _millis();
  5234. }
  5235. break;
  5236. //! ### M190 - Wait for bed temperature
  5237. // ---------------------------------------
  5238. case 190:
  5239. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5240. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5241. heating_status = 3;
  5242. if (farm_mode) { prusa_statistics(1); };
  5243. if (code_seen('S'))
  5244. {
  5245. setTargetBed(code_value());
  5246. CooldownNoWait = true;
  5247. }
  5248. else if (code_seen('R'))
  5249. {
  5250. setTargetBed(code_value());
  5251. CooldownNoWait = false;
  5252. }
  5253. codenum = _millis();
  5254. cancel_heatup = false;
  5255. target_direction = isHeatingBed(); // true if heating, false if cooling
  5256. KEEPALIVE_STATE(NOT_BUSY);
  5257. while ( (target_direction)&&(!cancel_heatup) ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false)) )
  5258. {
  5259. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5260. {
  5261. if (!farm_mode) {
  5262. float tt = degHotend(active_extruder);
  5263. SERIAL_PROTOCOLPGM("T:");
  5264. SERIAL_PROTOCOL(tt);
  5265. SERIAL_PROTOCOLPGM(" E:");
  5266. SERIAL_PROTOCOL((int)active_extruder);
  5267. SERIAL_PROTOCOLPGM(" B:");
  5268. SERIAL_PROTOCOL_F(degBed(), 1);
  5269. SERIAL_PROTOCOLLN("");
  5270. }
  5271. codenum = _millis();
  5272. }
  5273. manage_heater();
  5274. manage_inactivity();
  5275. lcd_update(0);
  5276. }
  5277. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5278. KEEPALIVE_STATE(IN_HANDLER);
  5279. heating_status = 4;
  5280. previous_millis_cmd = _millis();
  5281. #endif
  5282. break;
  5283. #if defined(FAN_PIN) && FAN_PIN > -1
  5284. //! ### M106 - Set fan speed
  5285. // -------------------------------------------
  5286. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5287. if (code_seen('S')){
  5288. fanSpeed=constrain(code_value(),0,255);
  5289. }
  5290. else {
  5291. fanSpeed=255;
  5292. }
  5293. break;
  5294. //! ### M107 - Fan off
  5295. // -------------------------------
  5296. case 107:
  5297. fanSpeed = 0;
  5298. break;
  5299. #endif //FAN_PIN
  5300. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5301. //! ### M80 - Turn on the Power Supply
  5302. // -------------------------------
  5303. case 80:
  5304. SET_OUTPUT(PS_ON_PIN); //GND
  5305. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5306. // If you have a switch on suicide pin, this is useful
  5307. // if you want to start another print with suicide feature after
  5308. // a print without suicide...
  5309. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5310. SET_OUTPUT(SUICIDE_PIN);
  5311. WRITE(SUICIDE_PIN, HIGH);
  5312. #endif
  5313. powersupply = true;
  5314. LCD_MESSAGERPGM(_T(WELCOME_MSG));
  5315. lcd_update(0);
  5316. break;
  5317. #endif
  5318. //! ### M81 - Turn off Power Supply
  5319. // --------------------------------------
  5320. case 81:
  5321. disable_heater();
  5322. st_synchronize();
  5323. disable_e0();
  5324. disable_e1();
  5325. disable_e2();
  5326. finishAndDisableSteppers();
  5327. fanSpeed = 0;
  5328. _delay(1000); // Wait a little before to switch off
  5329. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5330. st_synchronize();
  5331. suicide();
  5332. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5333. SET_OUTPUT(PS_ON_PIN);
  5334. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5335. #endif
  5336. powersupply = false;
  5337. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5338. lcd_update(0);
  5339. break;
  5340. //! ### M82 - Set E axis to absolute mode
  5341. // ---------------------------------------
  5342. case 82:
  5343. axis_relative_modes[3] = false;
  5344. break;
  5345. //! ### M83 - Set E axis to relative mode
  5346. // ---------------------------------------
  5347. case 83:
  5348. axis_relative_modes[3] = true;
  5349. break;
  5350. //! ### M84, M18 - Disable steppers
  5351. //---------------------------------------
  5352. //! This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5353. //!
  5354. //! M84 [E<flag>] [S<seconds>] [X<flag>] [Y<flag>] [Z<flag>]
  5355. //!
  5356. case 18: //compatibility
  5357. case 84: // M84
  5358. if(code_seen('S')){
  5359. stepper_inactive_time = code_value() * 1000;
  5360. }
  5361. else
  5362. {
  5363. 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])));
  5364. if(all_axis)
  5365. {
  5366. st_synchronize();
  5367. disable_e0();
  5368. disable_e1();
  5369. disable_e2();
  5370. finishAndDisableSteppers();
  5371. }
  5372. else
  5373. {
  5374. st_synchronize();
  5375. if (code_seen('X')) disable_x();
  5376. if (code_seen('Y')) disable_y();
  5377. if (code_seen('Z')) disable_z();
  5378. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5379. if (code_seen('E')) {
  5380. disable_e0();
  5381. disable_e1();
  5382. disable_e2();
  5383. }
  5384. #endif
  5385. }
  5386. }
  5387. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  5388. print_time_remaining_init();
  5389. snmm_filaments_used = 0;
  5390. break;
  5391. //! ### M85 - Set max inactive time
  5392. // ---------------------------------------
  5393. case 85: // M85
  5394. if(code_seen('S')) {
  5395. max_inactive_time = code_value() * 1000;
  5396. }
  5397. break;
  5398. #ifdef SAFETYTIMER
  5399. //! ### M86 - Set safety timer expiration time
  5400. //!
  5401. //! _Usage:_
  5402. //! M86 S<seconds>
  5403. //!
  5404. //! Sets the safety timer expiration time in seconds. M86 S0 will disable safety timer.
  5405. //! When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5406. case 86:
  5407. if (code_seen('S')) {
  5408. safetytimer_inactive_time = code_value() * 1000;
  5409. safetyTimer.start();
  5410. }
  5411. break;
  5412. #endif
  5413. //! ### M92 Set Axis steps-per-unit
  5414. // ---------------------------------------
  5415. //! Same syntax as G92
  5416. case 92:
  5417. for(int8_t i=0; i < NUM_AXIS; i++)
  5418. {
  5419. if(code_seen(axis_codes[i]))
  5420. {
  5421. if(i == 3) { // E
  5422. float value = code_value();
  5423. if(value < 20.0) {
  5424. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5425. cs.max_jerk[E_AXIS] *= factor;
  5426. max_feedrate[i] *= factor;
  5427. axis_steps_per_sqr_second[i] *= factor;
  5428. }
  5429. cs.axis_steps_per_unit[i] = value;
  5430. }
  5431. else {
  5432. cs.axis_steps_per_unit[i] = code_value();
  5433. }
  5434. }
  5435. }
  5436. break;
  5437. //! ### M110 - Set Line number
  5438. // ---------------------------------------
  5439. case 110:
  5440. if (code_seen('N'))
  5441. gcode_LastN = code_value_long();
  5442. break;
  5443. //! ### M113 - Get or set host keep-alive interval
  5444. // ------------------------------------------
  5445. case 113:
  5446. if (code_seen('S')) {
  5447. host_keepalive_interval = (uint8_t)code_value_short();
  5448. // NOMORE(host_keepalive_interval, 60);
  5449. }
  5450. else {
  5451. SERIAL_ECHO_START;
  5452. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5453. SERIAL_PROTOCOLLN("");
  5454. }
  5455. break;
  5456. //! ### M115 - Firmware info
  5457. // --------------------------------------
  5458. //! Print the firmware info and capabilities
  5459. //!
  5460. //! M115 [V] [U<version>]
  5461. //!
  5462. //! Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5463. //! `M115 U` Checks the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5464. //! pause the print for 30s and ask the user to upgrade the firmware.
  5465. case 115: // M115
  5466. if (code_seen('V')) {
  5467. // Report the Prusa version number.
  5468. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5469. } else if (code_seen('U')) {
  5470. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5471. // pause the print for 30s and ask the user to upgrade the firmware.
  5472. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5473. } else {
  5474. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5475. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5476. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5477. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5478. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5479. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5480. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5481. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5482. SERIAL_ECHOPGM(" UUID:");
  5483. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5484. }
  5485. break;
  5486. //! ### M114 - Get current position
  5487. // -------------------------------------
  5488. case 114:
  5489. gcode_M114();
  5490. break;
  5491. //! ### M117 - Set LCD Message
  5492. // --------------------------------------
  5493. /*
  5494. M117 moved up to get the high priority
  5495. case 117: // M117 display message
  5496. starpos = (strchr(strchr_pointer + 5,'*'));
  5497. if(starpos!=NULL)
  5498. *(starpos)='\0';
  5499. lcd_setstatus(strchr_pointer + 5);
  5500. break;*/
  5501. //! ### M120 - Disable endstops
  5502. // ----------------------------------------
  5503. case 120:
  5504. enable_endstops(false) ;
  5505. break;
  5506. //! ### M121 - Enable endstops
  5507. // ----------------------------------------
  5508. case 121:
  5509. enable_endstops(true) ;
  5510. break;
  5511. //! ### M119 - Get endstop states
  5512. // ----------------------------------------
  5513. case 119:
  5514. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5515. SERIAL_PROTOCOLLN("");
  5516. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5517. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5518. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5519. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5520. }else{
  5521. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5522. }
  5523. SERIAL_PROTOCOLLN("");
  5524. #endif
  5525. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5526. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5527. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5528. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5529. }else{
  5530. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5531. }
  5532. SERIAL_PROTOCOLLN("");
  5533. #endif
  5534. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5535. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5536. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5537. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5538. }else{
  5539. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5540. }
  5541. SERIAL_PROTOCOLLN("");
  5542. #endif
  5543. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5544. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5545. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5546. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5547. }else{
  5548. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5549. }
  5550. SERIAL_PROTOCOLLN("");
  5551. #endif
  5552. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5553. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5554. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5555. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5556. }else{
  5557. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5558. }
  5559. SERIAL_PROTOCOLLN("");
  5560. #endif
  5561. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5562. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5563. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5564. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5565. }else{
  5566. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5567. }
  5568. SERIAL_PROTOCOLLN("");
  5569. #endif
  5570. break;
  5571. //TODO: update for all axis, use for loop
  5572. #ifdef BLINKM
  5573. //! ### M150 - Set RGB(W) Color
  5574. // -------------------------------------------
  5575. case 150:
  5576. {
  5577. byte red;
  5578. byte grn;
  5579. byte blu;
  5580. if(code_seen('R')) red = code_value();
  5581. if(code_seen('U')) grn = code_value();
  5582. if(code_seen('B')) blu = code_value();
  5583. SendColors(red,grn,blu);
  5584. }
  5585. break;
  5586. #endif //BLINKM
  5587. //! ### M200 - Set filament diameter
  5588. // ----------------------------------------
  5589. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5590. {
  5591. uint8_t extruder = active_extruder;
  5592. if(code_seen('T')) {
  5593. extruder = code_value();
  5594. if(extruder >= EXTRUDERS) {
  5595. SERIAL_ECHO_START;
  5596. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  5597. break;
  5598. }
  5599. }
  5600. if(code_seen('D')) {
  5601. float diameter = (float)code_value();
  5602. if (diameter == 0.0) {
  5603. // setting any extruder filament size disables volumetric on the assumption that
  5604. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5605. // for all extruders
  5606. cs.volumetric_enabled = false;
  5607. } else {
  5608. cs.filament_size[extruder] = (float)code_value();
  5609. // make sure all extruders have some sane value for the filament size
  5610. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5611. #if EXTRUDERS > 1
  5612. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5613. #if EXTRUDERS > 2
  5614. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5615. #endif
  5616. #endif
  5617. cs.volumetric_enabled = true;
  5618. }
  5619. } else {
  5620. //reserved for setting filament diameter via UFID or filament measuring device
  5621. break;
  5622. }
  5623. calculate_extruder_multipliers();
  5624. }
  5625. break;
  5626. //! ### M201 - Set Print Max Acceleration
  5627. // -------------------------------------------
  5628. case 201:
  5629. for (int8_t i = 0; i < NUM_AXIS; i++)
  5630. {
  5631. if (code_seen(axis_codes[i]))
  5632. {
  5633. unsigned long val = code_value();
  5634. #ifdef TMC2130
  5635. unsigned long val_silent = val;
  5636. if ((i == X_AXIS) || (i == Y_AXIS))
  5637. {
  5638. if (val > NORMAL_MAX_ACCEL_XY)
  5639. val = NORMAL_MAX_ACCEL_XY;
  5640. if (val_silent > SILENT_MAX_ACCEL_XY)
  5641. val_silent = SILENT_MAX_ACCEL_XY;
  5642. }
  5643. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  5644. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  5645. #else //TMC2130
  5646. max_acceleration_units_per_sq_second[i] = val;
  5647. #endif //TMC2130
  5648. }
  5649. }
  5650. // 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)
  5651. reset_acceleration_rates();
  5652. break;
  5653. #if 0 // Not used for Sprinter/grbl gen6
  5654. case 202: // M202
  5655. for(int8_t i=0; i < NUM_AXIS; i++) {
  5656. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  5657. }
  5658. break;
  5659. #endif
  5660. //! ### M203 - Set Max Feedrate
  5661. // ---------------------------------------
  5662. case 203: // M203 max feedrate mm/sec
  5663. for (int8_t i = 0; i < NUM_AXIS; i++)
  5664. {
  5665. if (code_seen(axis_codes[i]))
  5666. {
  5667. float val = code_value();
  5668. #ifdef TMC2130
  5669. float val_silent = val;
  5670. if ((i == X_AXIS) || (i == Y_AXIS))
  5671. {
  5672. if (val > NORMAL_MAX_FEEDRATE_XY)
  5673. val = NORMAL_MAX_FEEDRATE_XY;
  5674. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  5675. val_silent = SILENT_MAX_FEEDRATE_XY;
  5676. }
  5677. cs.max_feedrate_normal[i] = val;
  5678. cs.max_feedrate_silent[i] = val_silent;
  5679. #else //TMC2130
  5680. max_feedrate[i] = val;
  5681. #endif //TMC2130
  5682. }
  5683. }
  5684. break;
  5685. //! ### M204 - Acceleration settings
  5686. // ------------------------------------------
  5687. //! Supporting old format:
  5688. //!
  5689. //! M204 S[normal moves] T[filmanent only moves]
  5690. //!
  5691. //! and new format:
  5692. //!
  5693. //! M204 P[printing moves] R[filmanent only moves] T[travel moves] (as of now T is ignored)
  5694. case 204:
  5695. {
  5696. if(code_seen('S')) {
  5697. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  5698. // and it is also generated by Slic3r to control acceleration per extrusion type
  5699. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  5700. cs.acceleration = code_value();
  5701. // Interpret the T value as retract acceleration in the old Marlin format.
  5702. if(code_seen('T'))
  5703. cs.retract_acceleration = code_value();
  5704. } else {
  5705. // New acceleration format, compatible with the upstream Marlin.
  5706. if(code_seen('P'))
  5707. cs.acceleration = code_value();
  5708. if(code_seen('R'))
  5709. cs.retract_acceleration = code_value();
  5710. if(code_seen('T')) {
  5711. // Interpret the T value as the travel acceleration in the new Marlin format.
  5712. //FIXME Prusa3D firmware currently does not support travel acceleration value independent from the extruding acceleration value.
  5713. // travel_acceleration = code_value();
  5714. }
  5715. }
  5716. }
  5717. break;
  5718. //! ### M205 - Set advanced settings
  5719. // ---------------------------------------------
  5720. //! Set some advanced settings related to movement.
  5721. //!
  5722. //! M205 [S] [T] [B] [X] [Y] [Z] [E]
  5723. /*!
  5724. - `S` - Minimum feedrate for print moves (unit/s)
  5725. - `T` - Minimum feedrate for travel moves (units/s)
  5726. - `B` - Minimum segment time (us)
  5727. - `X` - Maximum X jerk (units/s), similarly for other axes
  5728. */
  5729. case 205:
  5730. {
  5731. if(code_seen('S')) cs.minimumfeedrate = code_value();
  5732. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  5733. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  5734. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  5735. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  5736. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  5737. if(code_seen('E')) cs.max_jerk[E_AXIS] = code_value();
  5738. if (cs.max_jerk[X_AXIS] > DEFAULT_XJERK) cs.max_jerk[X_AXIS] = DEFAULT_XJERK;
  5739. if (cs.max_jerk[Y_AXIS] > DEFAULT_YJERK) cs.max_jerk[Y_AXIS] = DEFAULT_YJERK;
  5740. }
  5741. break;
  5742. //! ### M206 - Set additional homing offsets
  5743. // ----------------------------------------------
  5744. case 206:
  5745. for(int8_t i=0; i < 3; i++)
  5746. {
  5747. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  5748. }
  5749. break;
  5750. #ifdef FWRETRACT
  5751. //! ### M207 - Set firmware retraction
  5752. // --------------------------------------------------
  5753. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  5754. {
  5755. if(code_seen('S'))
  5756. {
  5757. cs.retract_length = code_value() ;
  5758. }
  5759. if(code_seen('F'))
  5760. {
  5761. cs.retract_feedrate = code_value()/60 ;
  5762. }
  5763. if(code_seen('Z'))
  5764. {
  5765. cs.retract_zlift = code_value() ;
  5766. }
  5767. }break;
  5768. //! ### M208 - Set retract recover length
  5769. // --------------------------------------------
  5770. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  5771. {
  5772. if(code_seen('S'))
  5773. {
  5774. cs.retract_recover_length = code_value() ;
  5775. }
  5776. if(code_seen('F'))
  5777. {
  5778. cs.retract_recover_feedrate = code_value()/60 ;
  5779. }
  5780. }break;
  5781. //! ### M209 - Enable/disable automatict retract
  5782. // ---------------------------------------------
  5783. 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.
  5784. {
  5785. if(code_seen('S'))
  5786. {
  5787. int t= code_value() ;
  5788. switch(t)
  5789. {
  5790. case 0:
  5791. {
  5792. cs.autoretract_enabled=false;
  5793. retracted[0]=false;
  5794. #if EXTRUDERS > 1
  5795. retracted[1]=false;
  5796. #endif
  5797. #if EXTRUDERS > 2
  5798. retracted[2]=false;
  5799. #endif
  5800. }break;
  5801. case 1:
  5802. {
  5803. cs.autoretract_enabled=true;
  5804. retracted[0]=false;
  5805. #if EXTRUDERS > 1
  5806. retracted[1]=false;
  5807. #endif
  5808. #if EXTRUDERS > 2
  5809. retracted[2]=false;
  5810. #endif
  5811. }break;
  5812. default:
  5813. SERIAL_ECHO_START;
  5814. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  5815. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  5816. SERIAL_ECHOLNPGM("\"(1)");
  5817. }
  5818. }
  5819. }break;
  5820. #endif // FWRETRACT
  5821. #if EXTRUDERS > 1
  5822. // ### M218 - Set hotend offset
  5823. // ----------------------------------------
  5824. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  5825. {
  5826. uint8_t extruder;
  5827. if(setTargetedHotend(218, extruder)){
  5828. break;
  5829. }
  5830. if(code_seen('X'))
  5831. {
  5832. extruder_offset[X_AXIS][extruder] = code_value();
  5833. }
  5834. if(code_seen('Y'))
  5835. {
  5836. extruder_offset[Y_AXIS][extruder] = code_value();
  5837. }
  5838. SERIAL_ECHO_START;
  5839. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  5840. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  5841. {
  5842. SERIAL_ECHO(" ");
  5843. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  5844. SERIAL_ECHO(",");
  5845. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  5846. }
  5847. SERIAL_ECHOLN("");
  5848. }break;
  5849. #endif
  5850. //! ### M220 Set feedrate percentage
  5851. // -----------------------------------------------
  5852. case 220: // M220 S<factor in percent>- set speed factor override percentage
  5853. {
  5854. if (code_seen('B')) //backup current speed factor
  5855. {
  5856. saved_feedmultiply_mm = feedmultiply;
  5857. }
  5858. if(code_seen('S'))
  5859. {
  5860. feedmultiply = code_value() ;
  5861. }
  5862. if (code_seen('R')) { //restore previous feedmultiply
  5863. feedmultiply = saved_feedmultiply_mm;
  5864. }
  5865. }
  5866. break;
  5867. //! ### M221 - Set extrude factor override percentage
  5868. // ----------------------------------------------------
  5869. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  5870. {
  5871. if(code_seen('S'))
  5872. {
  5873. int tmp_code = code_value();
  5874. if (code_seen('T'))
  5875. {
  5876. uint8_t extruder;
  5877. if(setTargetedHotend(221, extruder)){
  5878. break;
  5879. }
  5880. extruder_multiply[extruder] = tmp_code;
  5881. }
  5882. else
  5883. {
  5884. extrudemultiply = tmp_code ;
  5885. }
  5886. }
  5887. calculate_extruder_multipliers();
  5888. }
  5889. break;
  5890. //! ### M226 - Wait for Pin state
  5891. // ------------------------------------------
  5892. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  5893. {
  5894. if(code_seen('P')){
  5895. int pin_number = code_value(); // pin number
  5896. int pin_state = -1; // required pin state - default is inverted
  5897. if(code_seen('S')) pin_state = code_value(); // required pin state
  5898. if(pin_state >= -1 && pin_state <= 1){
  5899. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  5900. {
  5901. if (sensitive_pins[i] == pin_number)
  5902. {
  5903. pin_number = -1;
  5904. break;
  5905. }
  5906. }
  5907. if (pin_number > -1)
  5908. {
  5909. int target = LOW;
  5910. st_synchronize();
  5911. pinMode(pin_number, INPUT);
  5912. switch(pin_state){
  5913. case 1:
  5914. target = HIGH;
  5915. break;
  5916. case 0:
  5917. target = LOW;
  5918. break;
  5919. case -1:
  5920. target = !digitalRead(pin_number);
  5921. break;
  5922. }
  5923. while(digitalRead(pin_number) != target){
  5924. manage_heater();
  5925. manage_inactivity();
  5926. lcd_update(0);
  5927. }
  5928. }
  5929. }
  5930. }
  5931. }
  5932. break;
  5933. #if NUM_SERVOS > 0
  5934. //! ### M280 - Set/Get servo position
  5935. // --------------------------------------------
  5936. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  5937. {
  5938. int servo_index = -1;
  5939. int servo_position = 0;
  5940. if (code_seen('P'))
  5941. servo_index = code_value();
  5942. if (code_seen('S')) {
  5943. servo_position = code_value();
  5944. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  5945. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  5946. servos[servo_index].attach(0);
  5947. #endif
  5948. servos[servo_index].write(servo_position);
  5949. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  5950. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  5951. servos[servo_index].detach();
  5952. #endif
  5953. }
  5954. else {
  5955. SERIAL_ECHO_START;
  5956. SERIAL_ECHO("Servo ");
  5957. SERIAL_ECHO(servo_index);
  5958. SERIAL_ECHOLN(" out of range");
  5959. }
  5960. }
  5961. else if (servo_index >= 0) {
  5962. SERIAL_PROTOCOL(MSG_OK);
  5963. SERIAL_PROTOCOL(" Servo ");
  5964. SERIAL_PROTOCOL(servo_index);
  5965. SERIAL_PROTOCOL(": ");
  5966. SERIAL_PROTOCOL(servos[servo_index].read());
  5967. SERIAL_PROTOCOLLN("");
  5968. }
  5969. }
  5970. break;
  5971. #endif // NUM_SERVOS > 0
  5972. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  5973. //! ### M300 - Play tone
  5974. // -----------------------
  5975. case 300: // M300
  5976. {
  5977. int beepS = code_seen('S') ? code_value() : 110;
  5978. int beepP = code_seen('P') ? code_value() : 1000;
  5979. if (beepS > 0)
  5980. {
  5981. #if BEEPER > 0
  5982. Sound_MakeCustom(beepP,beepS,false);
  5983. #endif
  5984. }
  5985. else
  5986. {
  5987. _delay(beepP);
  5988. }
  5989. }
  5990. break;
  5991. #endif // M300
  5992. #ifdef PIDTEMP
  5993. //! ### M301 - Set hotend PID
  5994. // ---------------------------------------
  5995. case 301:
  5996. {
  5997. if(code_seen('P')) cs.Kp = code_value();
  5998. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  5999. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6000. #ifdef PID_ADD_EXTRUSION_RATE
  6001. if(code_seen('C')) Kc = code_value();
  6002. #endif
  6003. updatePID();
  6004. SERIAL_PROTOCOLRPGM(MSG_OK);
  6005. SERIAL_PROTOCOL(" p:");
  6006. SERIAL_PROTOCOL(cs.Kp);
  6007. SERIAL_PROTOCOL(" i:");
  6008. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6009. SERIAL_PROTOCOL(" d:");
  6010. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6011. #ifdef PID_ADD_EXTRUSION_RATE
  6012. SERIAL_PROTOCOL(" c:");
  6013. //Kc does not have scaling applied above, or in resetting defaults
  6014. SERIAL_PROTOCOL(Kc);
  6015. #endif
  6016. SERIAL_PROTOCOLLN("");
  6017. }
  6018. break;
  6019. #endif //PIDTEMP
  6020. #ifdef PIDTEMPBED
  6021. //! ### M304 - Set bed PID
  6022. // --------------------------------------
  6023. case 304:
  6024. {
  6025. if(code_seen('P')) cs.bedKp = code_value();
  6026. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6027. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6028. updatePID();
  6029. SERIAL_PROTOCOLRPGM(MSG_OK);
  6030. SERIAL_PROTOCOL(" p:");
  6031. SERIAL_PROTOCOL(cs.bedKp);
  6032. SERIAL_PROTOCOL(" i:");
  6033. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6034. SERIAL_PROTOCOL(" d:");
  6035. SERIAL_PROTOCOL(unscalePID_d(cs.bedKd));
  6036. SERIAL_PROTOCOLLN("");
  6037. }
  6038. break;
  6039. #endif //PIDTEMP
  6040. //! ### M240 - Trigger camera
  6041. // --------------------------------------------
  6042. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6043. {
  6044. #ifdef CHDK
  6045. SET_OUTPUT(CHDK);
  6046. WRITE(CHDK, HIGH);
  6047. chdkHigh = _millis();
  6048. chdkActive = true;
  6049. #else
  6050. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6051. const uint8_t NUM_PULSES=16;
  6052. const float PULSE_LENGTH=0.01524;
  6053. for(int i=0; i < NUM_PULSES; i++) {
  6054. WRITE(PHOTOGRAPH_PIN, HIGH);
  6055. _delay_ms(PULSE_LENGTH);
  6056. WRITE(PHOTOGRAPH_PIN, LOW);
  6057. _delay_ms(PULSE_LENGTH);
  6058. }
  6059. _delay(7.33);
  6060. for(int i=0; i < NUM_PULSES; i++) {
  6061. WRITE(PHOTOGRAPH_PIN, HIGH);
  6062. _delay_ms(PULSE_LENGTH);
  6063. WRITE(PHOTOGRAPH_PIN, LOW);
  6064. _delay_ms(PULSE_LENGTH);
  6065. }
  6066. #endif
  6067. #endif //chdk end if
  6068. }
  6069. break;
  6070. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6071. //! ### M302 - Allow cold extrude, or set minimum extrude temperature
  6072. // -------------------------------------------------------------------
  6073. case 302:
  6074. {
  6075. float temp = .0;
  6076. if (code_seen('S')) temp=code_value();
  6077. set_extrude_min_temp(temp);
  6078. }
  6079. break;
  6080. #endif
  6081. //! ### M303 - PID autotune
  6082. // -------------------------------------
  6083. case 303:
  6084. {
  6085. float temp = 150.0;
  6086. int e=0;
  6087. int c=5;
  6088. if (code_seen('E')) e=code_value();
  6089. if (e<0)
  6090. temp=70;
  6091. if (code_seen('S')) temp=code_value();
  6092. if (code_seen('C')) c=code_value();
  6093. PID_autotune(temp, e, c);
  6094. }
  6095. break;
  6096. //! ### M400 - Wait for all moves to finish
  6097. // -----------------------------------------
  6098. case 400:
  6099. {
  6100. st_synchronize();
  6101. }
  6102. break;
  6103. //! ### M403 - Set filament type (material) for particular extruder and notify the MMU
  6104. // ----------------------------------------------
  6105. case 403:
  6106. {
  6107. // currently three different materials are needed (default, flex and PVA)
  6108. // add storing this information for different load/unload profiles etc. in the future
  6109. // firmware does not wait for "ok" from mmu
  6110. if (mmu_enabled)
  6111. {
  6112. uint8_t extruder = 255;
  6113. uint8_t filament = FILAMENT_UNDEFINED;
  6114. if(code_seen('E')) extruder = code_value();
  6115. if(code_seen('F')) filament = code_value();
  6116. mmu_set_filament_type(extruder, filament);
  6117. }
  6118. }
  6119. break;
  6120. //! ### M500 - Store settings in EEPROM
  6121. // -----------------------------------------
  6122. case 500:
  6123. {
  6124. Config_StoreSettings();
  6125. }
  6126. break;
  6127. //! ### M501 - Read settings from EEPROM
  6128. // ----------------------------------------
  6129. case 501:
  6130. {
  6131. Config_RetrieveSettings();
  6132. }
  6133. break;
  6134. //! ### M502 - Revert all settings to factory default
  6135. // -------------------------------------------------
  6136. case 502:
  6137. {
  6138. Config_ResetDefault();
  6139. }
  6140. break;
  6141. //! ### M503 - Repport all settings currently in memory
  6142. // -------------------------------------------------
  6143. case 503:
  6144. {
  6145. Config_PrintSettings();
  6146. }
  6147. break;
  6148. //! ### M509 - Force language selection
  6149. // ------------------------------------------------
  6150. case 509:
  6151. {
  6152. lang_reset();
  6153. SERIAL_ECHO_START;
  6154. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6155. }
  6156. break;
  6157. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6158. //! ### M540 - Abort print on endstop hit (enable/disable)
  6159. // -----------------------------------------------------
  6160. case 540:
  6161. {
  6162. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6163. }
  6164. break;
  6165. #endif
  6166. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6167. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6168. {
  6169. float value;
  6170. if (code_seen('Z'))
  6171. {
  6172. value = code_value();
  6173. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6174. {
  6175. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6176. SERIAL_ECHO_START;
  6177. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6178. SERIAL_PROTOCOLLN("");
  6179. }
  6180. else
  6181. {
  6182. SERIAL_ECHO_START;
  6183. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6184. SERIAL_ECHORPGM(MSG_Z_MIN);
  6185. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6186. SERIAL_ECHORPGM(MSG_Z_MAX);
  6187. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6188. SERIAL_PROTOCOLLN("");
  6189. }
  6190. }
  6191. else
  6192. {
  6193. SERIAL_ECHO_START;
  6194. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6195. SERIAL_ECHO(-cs.zprobe_zoffset);
  6196. SERIAL_PROTOCOLLN("");
  6197. }
  6198. break;
  6199. }
  6200. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6201. #ifdef FILAMENTCHANGEENABLE
  6202. //! ### M600 - Initiate Filament change procedure
  6203. // --------------------------------------
  6204. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6205. {
  6206. st_synchronize();
  6207. float x_position = current_position[X_AXIS];
  6208. float y_position = current_position[Y_AXIS];
  6209. float z_shift = 0; // is it necessary to be a float?
  6210. float e_shift_init = 0;
  6211. float e_shift_late = 0;
  6212. bool automatic = false;
  6213. //Retract extruder
  6214. if(code_seen('E'))
  6215. {
  6216. e_shift_init = code_value();
  6217. }
  6218. else
  6219. {
  6220. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6221. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6222. #endif
  6223. }
  6224. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6225. if (code_seen('L'))
  6226. {
  6227. e_shift_late = code_value();
  6228. }
  6229. else
  6230. {
  6231. #ifdef FILAMENTCHANGE_FINALRETRACT
  6232. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6233. #endif
  6234. }
  6235. //Lift Z
  6236. if(code_seen('Z'))
  6237. {
  6238. z_shift = code_value();
  6239. }
  6240. else
  6241. {
  6242. z_shift = gcode_M600_filament_change_z_shift<uint8_t>();
  6243. }
  6244. //Move XY to side
  6245. if(code_seen('X'))
  6246. {
  6247. x_position = code_value();
  6248. }
  6249. else
  6250. {
  6251. #ifdef FILAMENTCHANGE_XPOS
  6252. x_position = FILAMENTCHANGE_XPOS;
  6253. #endif
  6254. }
  6255. if(code_seen('Y'))
  6256. {
  6257. y_position = code_value();
  6258. }
  6259. else
  6260. {
  6261. #ifdef FILAMENTCHANGE_YPOS
  6262. y_position = FILAMENTCHANGE_YPOS ;
  6263. #endif
  6264. }
  6265. if (mmu_enabled && code_seen("AUTO"))
  6266. automatic = true;
  6267. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6268. }
  6269. break;
  6270. #endif //FILAMENTCHANGEENABLE
  6271. //! ### M601 - Pause print
  6272. // -------------------------------
  6273. case 601:
  6274. {
  6275. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  6276. lcd_pause_print();
  6277. }
  6278. break;
  6279. //! ### M602 - Resume print
  6280. // -------------------------------
  6281. case 602: {
  6282. lcd_resume_print();
  6283. }
  6284. break;
  6285. //! ### M603 - Stop print
  6286. // -------------------------------
  6287. case 603: {
  6288. lcd_print_stop();
  6289. }
  6290. #ifdef PINDA_THERMISTOR
  6291. //! ### M860 - Wait for extruder temperature (PINDA)
  6292. // --------------------------------------------------------------
  6293. /*!
  6294. Wait for PINDA thermistor to reach target temperature
  6295. M860 [S<target_temperature>]
  6296. */
  6297. case 860:
  6298. {
  6299. int set_target_pinda = 0;
  6300. if (code_seen('S')) {
  6301. set_target_pinda = code_value();
  6302. }
  6303. else {
  6304. break;
  6305. }
  6306. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  6307. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  6308. SERIAL_PROTOCOL(set_target_pinda);
  6309. SERIAL_PROTOCOLLN("");
  6310. codenum = _millis();
  6311. cancel_heatup = false;
  6312. bool is_pinda_cooling = false;
  6313. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  6314. is_pinda_cooling = true;
  6315. }
  6316. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  6317. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  6318. {
  6319. SERIAL_PROTOCOLPGM("P:");
  6320. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  6321. SERIAL_PROTOCOLPGM("/");
  6322. SERIAL_PROTOCOL(set_target_pinda);
  6323. SERIAL_PROTOCOLLN("");
  6324. codenum = _millis();
  6325. }
  6326. manage_heater();
  6327. manage_inactivity();
  6328. lcd_update(0);
  6329. }
  6330. LCD_MESSAGERPGM(MSG_OK);
  6331. break;
  6332. }
  6333. //! ### M861 - Set/Get PINDA temperature compensation offsets
  6334. // -----------------------------------------------------------
  6335. /*!
  6336. M861 [ ? | ! | Z | S<microsteps> [I<table_index>] ]
  6337. - `?` - Print current EEPROM offset values
  6338. - `!` - Set factory default values
  6339. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6340. - `S<microsteps>` `I<table_index>` - Set compensation ustep value S for compensation table index I
  6341. */
  6342. case 861:
  6343. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  6344. uint8_t cal_status = calibration_status_pinda();
  6345. int16_t usteps = 0;
  6346. cal_status ? SERIAL_PROTOCOLLN("PINDA cal status: 1") : SERIAL_PROTOCOLLN("PINDA cal status: 0");
  6347. SERIAL_PROTOCOLLN("index, temp, ustep, um");
  6348. for (uint8_t i = 0; i < 6; i++)
  6349. {
  6350. if(i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i-1) * 2, &usteps);
  6351. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6352. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6353. SERIAL_PROTOCOLPGM(", ");
  6354. SERIAL_PROTOCOL(35 + (i * 5));
  6355. SERIAL_PROTOCOLPGM(", ");
  6356. SERIAL_PROTOCOL(usteps);
  6357. SERIAL_PROTOCOLPGM(", ");
  6358. SERIAL_PROTOCOL(mm * 1000);
  6359. SERIAL_PROTOCOLLN("");
  6360. }
  6361. }
  6362. else if (code_seen('!')) { // ! - Set factory default values
  6363. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6364. int16_t z_shift = 8; //40C - 20um - 8usteps
  6365. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT, &z_shift);
  6366. z_shift = 24; //45C - 60um - 24usteps
  6367. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 2, &z_shift);
  6368. z_shift = 48; //50C - 120um - 48usteps
  6369. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 4, &z_shift);
  6370. z_shift = 80; //55C - 200um - 80usteps
  6371. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 6, &z_shift);
  6372. z_shift = 120; //60C - 300um - 120usteps
  6373. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 8, &z_shift);
  6374. SERIAL_PROTOCOLLN("factory restored");
  6375. }
  6376. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6377. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6378. int16_t z_shift = 0;
  6379. for (uint8_t i = 0; i < 5; i++) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  6380. SERIAL_PROTOCOLLN("zerorized");
  6381. }
  6382. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  6383. int16_t usteps = code_value();
  6384. if (code_seen('I')) {
  6385. uint8_t index = code_value();
  6386. if (index < 5) {
  6387. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + index * 2, &usteps);
  6388. SERIAL_PROTOCOLLN("OK");
  6389. SERIAL_PROTOCOLLN("index, temp, ustep, um");
  6390. for (uint8_t i = 0; i < 6; i++)
  6391. {
  6392. usteps = 0;
  6393. if (i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i - 1) * 2, &usteps);
  6394. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6395. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6396. SERIAL_PROTOCOLPGM(", ");
  6397. SERIAL_PROTOCOL(35 + (i * 5));
  6398. SERIAL_PROTOCOLPGM(", ");
  6399. SERIAL_PROTOCOL(usteps);
  6400. SERIAL_PROTOCOLPGM(", ");
  6401. SERIAL_PROTOCOL(mm * 1000);
  6402. SERIAL_PROTOCOLLN("");
  6403. }
  6404. }
  6405. }
  6406. }
  6407. else {
  6408. SERIAL_PROTOCOLPGM("no valid command");
  6409. }
  6410. break;
  6411. #endif //PINDA_THERMISTOR
  6412. //! ### M862 - Print checking
  6413. // ----------------------------------------------
  6414. /*!
  6415. Checks the parameters of the printer and gcode and performs compatibility check
  6416. - M862.1 { P<nozzle_diameter> | Q }
  6417. - M862.2 { P<model_code> | Q }
  6418. - M862.3 { P"<model_name>" | Q }
  6419. - M862.4 { P<fw_version> | Q }
  6420. - M862.5 { P<gcode_level> | Q }
  6421. When run with P<> argument, the check is performed against the input value.
  6422. When run with Q argument, the current value is shown.
  6423. M862.3 accepts text identifiers of printer types too.
  6424. The syntax of M862.3 is (note the quotes around the type):
  6425. M862.3 P "MK3S"
  6426. Accepted printer type identifiers and their numeric counterparts:
  6427. - MK1 (100)
  6428. - MK2 (200)
  6429. - MK2MM (201)
  6430. - MK2S (202)
  6431. - MK2SMM (203)
  6432. - MK2.5 (250)
  6433. - MK2.5MMU2 (20250)
  6434. - MK2.5S (252)
  6435. - MK2.5SMMU2S (20252)
  6436. - MK3 (300)
  6437. - MK3MMU2 (20300)
  6438. - MK3S (302)
  6439. - MK3SMMU2S (20302)
  6440. */
  6441. case 862: // M862: print checking
  6442. float nDummy;
  6443. uint8_t nCommand;
  6444. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  6445. switch((ClPrintChecking)nCommand)
  6446. {
  6447. case ClPrintChecking::_Nozzle: // ~ .1
  6448. uint16_t nDiameter;
  6449. if(code_seen('P'))
  6450. {
  6451. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  6452. nozzle_diameter_check(nDiameter);
  6453. }
  6454. /*
  6455. else if(code_seen('S')&&farm_mode)
  6456. {
  6457. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  6458. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  6459. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  6460. }
  6461. */
  6462. else if(code_seen('Q'))
  6463. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  6464. break;
  6465. case ClPrintChecking::_Model: // ~ .2
  6466. if(code_seen('P'))
  6467. {
  6468. uint16_t nPrinterModel;
  6469. nPrinterModel=(uint16_t)code_value_long();
  6470. printer_model_check(nPrinterModel);
  6471. }
  6472. else if(code_seen('Q'))
  6473. SERIAL_PROTOCOLLN(nPrinterType);
  6474. break;
  6475. case ClPrintChecking::_Smodel: // ~ .3
  6476. if(code_seen('P'))
  6477. printer_smodel_check(strchr_pointer);
  6478. else if(code_seen('Q'))
  6479. SERIAL_PROTOCOLLNRPGM(sPrinterName);
  6480. break;
  6481. case ClPrintChecking::_Version: // ~ .4
  6482. if(code_seen('P'))
  6483. fw_version_check(++strchr_pointer);
  6484. else if(code_seen('Q'))
  6485. SERIAL_PROTOCOLLN(FW_VERSION);
  6486. break;
  6487. case ClPrintChecking::_Gcode: // ~ .5
  6488. if(code_seen('P'))
  6489. {
  6490. uint16_t nGcodeLevel;
  6491. nGcodeLevel=(uint16_t)code_value_long();
  6492. gcode_level_check(nGcodeLevel);
  6493. }
  6494. else if(code_seen('Q'))
  6495. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  6496. break;
  6497. }
  6498. break;
  6499. #ifdef LIN_ADVANCE
  6500. //! ### M900 - Set Linear advance options
  6501. // ----------------------------------------------
  6502. case 900:
  6503. gcode_M900();
  6504. break;
  6505. #endif
  6506. //! ### M907 - Set digital trimpot motor current using axis codes
  6507. // ---------------------------------------------------------------
  6508. case 907:
  6509. {
  6510. #ifdef TMC2130
  6511. for (int i = 0; i < NUM_AXIS; i++)
  6512. if(code_seen(axis_codes[i]))
  6513. {
  6514. long cur_mA = code_value_long();
  6515. uint8_t val = tmc2130_cur2val(cur_mA);
  6516. tmc2130_set_current_h(i, val);
  6517. tmc2130_set_current_r(i, val);
  6518. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  6519. }
  6520. #else //TMC2130
  6521. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  6522. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  6523. if(code_seen('B')) st_current_set(4,code_value());
  6524. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  6525. #endif
  6526. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  6527. if(code_seen('X')) st_current_set(0, code_value());
  6528. #endif
  6529. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  6530. if(code_seen('Z')) st_current_set(1, code_value());
  6531. #endif
  6532. #ifdef MOTOR_CURRENT_PWM_E_PIN
  6533. if(code_seen('E')) st_current_set(2, code_value());
  6534. #endif
  6535. #endif //TMC2130
  6536. }
  6537. break;
  6538. //! ### M908 - Control digital trimpot directly
  6539. // ---------------------------------------------------------
  6540. case 908:
  6541. {
  6542. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  6543. uint8_t channel,current;
  6544. if(code_seen('P')) channel=code_value();
  6545. if(code_seen('S')) current=code_value();
  6546. digitalPotWrite(channel, current);
  6547. #endif
  6548. }
  6549. break;
  6550. #ifdef TMC2130_SERVICE_CODES_M910_M918
  6551. //! ### M910 - TMC2130 init
  6552. // -----------------------------------------------
  6553. case 910:
  6554. {
  6555. tmc2130_init();
  6556. }
  6557. break;
  6558. //! ### M911 - Set TMC2130 holding currents
  6559. // -------------------------------------------------
  6560. case 911:
  6561. {
  6562. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  6563. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  6564. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  6565. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  6566. }
  6567. break;
  6568. //! ### M912 - Set TMC2130 running currents
  6569. // -----------------------------------------------
  6570. case 912:
  6571. {
  6572. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  6573. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  6574. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  6575. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  6576. }
  6577. break;
  6578. //! ### M913 - Print TMC2130 currents
  6579. // -----------------------------
  6580. case 913:
  6581. {
  6582. tmc2130_print_currents();
  6583. }
  6584. break;
  6585. //! ### M914 - Set TMC2130 normal mode
  6586. // ------------------------------
  6587. case 914:
  6588. {
  6589. tmc2130_mode = TMC2130_MODE_NORMAL;
  6590. update_mode_profile();
  6591. tmc2130_init();
  6592. }
  6593. break;
  6594. //! ### M95 - Set TMC2130 silent mode
  6595. // ------------------------------
  6596. case 915:
  6597. {
  6598. tmc2130_mode = TMC2130_MODE_SILENT;
  6599. update_mode_profile();
  6600. tmc2130_init();
  6601. }
  6602. break;
  6603. //! ### M916 - Set TMC2130 Stallguard sensitivity threshold
  6604. // -------------------------------------------------------
  6605. case 916:
  6606. {
  6607. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  6608. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  6609. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  6610. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  6611. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  6612. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  6613. }
  6614. break;
  6615. //! ### M917 - Set TMC2130 PWM amplitude offset (pwm_ampl)
  6616. // --------------------------------------------------------------
  6617. case 917:
  6618. {
  6619. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  6620. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  6621. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  6622. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  6623. }
  6624. break;
  6625. //! ### M918 - Set TMC2130 PWM amplitude gradient (pwm_grad)
  6626. // -------------------------------------------------------------
  6627. case 918:
  6628. {
  6629. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  6630. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  6631. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  6632. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  6633. }
  6634. break;
  6635. #endif //TMC2130_SERVICE_CODES_M910_M918
  6636. //! ### M350 - Set microstepping mode
  6637. // ---------------------------------------------------
  6638. //! Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  6639. case 350:
  6640. {
  6641. #ifdef TMC2130
  6642. if(code_seen('E'))
  6643. {
  6644. uint16_t res_new = code_value();
  6645. if ((res_new == 8) || (res_new == 16) || (res_new == 32) || (res_new == 64) || (res_new == 128))
  6646. {
  6647. st_synchronize();
  6648. uint8_t axis = E_AXIS;
  6649. uint16_t res = tmc2130_get_res(axis);
  6650. tmc2130_set_res(axis, res_new);
  6651. cs.axis_ustep_resolution[axis] = res_new;
  6652. if (res_new > res)
  6653. {
  6654. uint16_t fac = (res_new / res);
  6655. cs.axis_steps_per_unit[axis] *= fac;
  6656. position[E_AXIS] *= fac;
  6657. }
  6658. else
  6659. {
  6660. uint16_t fac = (res / res_new);
  6661. cs.axis_steps_per_unit[axis] /= fac;
  6662. position[E_AXIS] /= fac;
  6663. }
  6664. }
  6665. }
  6666. #else //TMC2130
  6667. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  6668. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  6669. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  6670. if(code_seen('B')) microstep_mode(4,code_value());
  6671. microstep_readings();
  6672. #endif
  6673. #endif //TMC2130
  6674. }
  6675. break;
  6676. //! ### M351 - Toggle Microstep Pins
  6677. // -----------------------------------
  6678. //! Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  6679. //!
  6680. //! M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  6681. case 351:
  6682. {
  6683. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  6684. if(code_seen('S')) switch((int)code_value())
  6685. {
  6686. case 1:
  6687. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  6688. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  6689. break;
  6690. case 2:
  6691. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  6692. if(code_seen('B')) microstep_ms(4,-1,code_value());
  6693. break;
  6694. }
  6695. microstep_readings();
  6696. #endif
  6697. }
  6698. break;
  6699. //! ### M701 - Load filament
  6700. // -------------------------
  6701. case 701:
  6702. {
  6703. if (mmu_enabled && code_seen('E'))
  6704. tmp_extruder = code_value();
  6705. gcode_M701();
  6706. }
  6707. break;
  6708. //! ### M702 - Unload filament
  6709. // ------------------------
  6710. /*!
  6711. M702 [U C]
  6712. - `U` Unload all filaments used in current print
  6713. - `C` Unload just current filament
  6714. - without any parameters unload all filaments
  6715. */
  6716. case 702:
  6717. {
  6718. #ifdef SNMM
  6719. if (code_seen('U'))
  6720. extr_unload_used(); //! if "U" unload all filaments which were used in current print
  6721. else if (code_seen('C'))
  6722. extr_unload(); //! if "C" unload just current filament
  6723. else
  6724. extr_unload_all(); //! otherwise unload all filaments
  6725. #else
  6726. if (code_seen('C')) {
  6727. if(mmu_enabled) extr_unload(); //! if "C" unload current filament; if mmu is not present no action is performed
  6728. }
  6729. else {
  6730. if(mmu_enabled) extr_unload(); //! unload current filament
  6731. else unload_filament();
  6732. }
  6733. #endif //SNMM
  6734. }
  6735. break;
  6736. //! ### M999 - Restart after being stopped
  6737. // ------------------------------------
  6738. case 999:
  6739. Stopped = false;
  6740. lcd_reset_alert_level();
  6741. gcode_LastN = Stopped_gcode_LastN;
  6742. FlushSerialRequestResend();
  6743. break;
  6744. default:
  6745. printf_P(PSTR("Unknown M code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  6746. }
  6747. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  6748. mcode_in_progress = 0;
  6749. }
  6750. }
  6751. // end if(code_seen('M')) (end of M codes)
  6752. //! -----------------------------------------------------------------------------------------
  6753. //! T Codes
  6754. //!
  6755. //! T<extruder nr.> - select extruder in case of multi extruder printer
  6756. //! select filament in case of MMU_V2
  6757. //! if extruder is "?", open menu to let the user select extruder/filament
  6758. //!
  6759. //! For MMU_V2:
  6760. //! @n T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  6761. //! @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  6762. //! @n Tx Same as T?, except nozzle doesn't have to be preheated. Tc must be placed after extruder nozzle is preheated to finish filament load.
  6763. //! @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  6764. else if(code_seen('T'))
  6765. {
  6766. int index;
  6767. bool load_to_nozzle = false;
  6768. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  6769. *(strchr_pointer + index) = tolower(*(strchr_pointer + index));
  6770. if ((*(strchr_pointer + index) < '0' || *(strchr_pointer + index) > '4') && *(strchr_pointer + index) != '?' && *(strchr_pointer + index) != 'x' && *(strchr_pointer + index) != 'c') {
  6771. SERIAL_ECHOLNPGM("Invalid T code.");
  6772. }
  6773. else if (*(strchr_pointer + index) == 'x'){ //load to bondtech gears; if mmu is not present do nothing
  6774. if (mmu_enabled)
  6775. {
  6776. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_FILAMENT), _T(MSG_FILAMENT));
  6777. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  6778. {
  6779. printf_P(PSTR("Duplicate T-code ignored.\n"));
  6780. }
  6781. else
  6782. {
  6783. st_synchronize();
  6784. mmu_command(MmuCmd::T0 + tmp_extruder);
  6785. manage_response(true, true, MMU_TCODE_MOVE);
  6786. }
  6787. }
  6788. }
  6789. else if (*(strchr_pointer + index) == 'c') { //load to from bondtech gears to nozzle (nozzle should be preheated)
  6790. if (mmu_enabled)
  6791. {
  6792. st_synchronize();
  6793. mmu_continue_loading(is_usb_printing);
  6794. mmu_extruder = tmp_extruder; //filament change is finished
  6795. mmu_load_to_nozzle();
  6796. }
  6797. }
  6798. else {
  6799. if (*(strchr_pointer + index) == '?')
  6800. {
  6801. if(mmu_enabled)
  6802. {
  6803. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_FILAMENT), _T(MSG_FILAMENT));
  6804. load_to_nozzle = true;
  6805. } else
  6806. {
  6807. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_EXTRUDER), _T(MSG_EXTRUDER));
  6808. }
  6809. }
  6810. else {
  6811. tmp_extruder = code_value();
  6812. if (mmu_enabled && lcd_autoDepleteEnabled())
  6813. {
  6814. tmp_extruder = ad_getAlternative(tmp_extruder);
  6815. }
  6816. }
  6817. st_synchronize();
  6818. snmm_filaments_used |= (1 << tmp_extruder); //for stop print
  6819. if (mmu_enabled)
  6820. {
  6821. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  6822. {
  6823. printf_P(PSTR("Duplicate T-code ignored.\n"));
  6824. }
  6825. else
  6826. {
  6827. #if defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  6828. if (EEPROM_MMU_CUTTER_ENABLED_always == eeprom_read_byte((uint8_t*)EEPROM_MMU_CUTTER_ENABLED))
  6829. {
  6830. mmu_command(MmuCmd::K0 + tmp_extruder);
  6831. manage_response(true, true, MMU_UNLOAD_MOVE);
  6832. }
  6833. #endif //defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  6834. mmu_command(MmuCmd::T0 + tmp_extruder);
  6835. manage_response(true, true, MMU_TCODE_MOVE);
  6836. mmu_continue_loading(is_usb_printing);
  6837. mmu_extruder = tmp_extruder; //filament change is finished
  6838. if (load_to_nozzle)// for single material usage with mmu
  6839. {
  6840. mmu_load_to_nozzle();
  6841. }
  6842. }
  6843. }
  6844. else
  6845. {
  6846. #ifdef SNMM
  6847. #ifdef LIN_ADVANCE
  6848. if (mmu_extruder != tmp_extruder)
  6849. clear_current_adv_vars(); //Check if the selected extruder is not the active one and reset LIN_ADVANCE variables if so.
  6850. #endif
  6851. mmu_extruder = tmp_extruder;
  6852. _delay(100);
  6853. disable_e0();
  6854. disable_e1();
  6855. disable_e2();
  6856. pinMode(E_MUX0_PIN, OUTPUT);
  6857. pinMode(E_MUX1_PIN, OUTPUT);
  6858. _delay(100);
  6859. SERIAL_ECHO_START;
  6860. SERIAL_ECHO("T:");
  6861. SERIAL_ECHOLN((int)tmp_extruder);
  6862. switch (tmp_extruder) {
  6863. case 1:
  6864. WRITE(E_MUX0_PIN, HIGH);
  6865. WRITE(E_MUX1_PIN, LOW);
  6866. break;
  6867. case 2:
  6868. WRITE(E_MUX0_PIN, LOW);
  6869. WRITE(E_MUX1_PIN, HIGH);
  6870. break;
  6871. case 3:
  6872. WRITE(E_MUX0_PIN, HIGH);
  6873. WRITE(E_MUX1_PIN, HIGH);
  6874. break;
  6875. default:
  6876. WRITE(E_MUX0_PIN, LOW);
  6877. WRITE(E_MUX1_PIN, LOW);
  6878. break;
  6879. }
  6880. _delay(100);
  6881. #else //SNMM
  6882. if (tmp_extruder >= EXTRUDERS) {
  6883. SERIAL_ECHO_START;
  6884. SERIAL_ECHOPGM("T");
  6885. SERIAL_PROTOCOLLN((int)tmp_extruder);
  6886. SERIAL_ECHOLNRPGM(_n("Invalid extruder"));////MSG_INVALID_EXTRUDER
  6887. }
  6888. else {
  6889. #if EXTRUDERS > 1
  6890. boolean make_move = false;
  6891. #endif
  6892. if (code_seen('F')) {
  6893. #if EXTRUDERS > 1
  6894. make_move = true;
  6895. #endif
  6896. next_feedrate = code_value();
  6897. if (next_feedrate > 0.0) {
  6898. feedrate = next_feedrate;
  6899. }
  6900. }
  6901. #if EXTRUDERS > 1
  6902. if (tmp_extruder != active_extruder) {
  6903. // Save current position to return to after applying extruder offset
  6904. memcpy(destination, current_position, sizeof(destination));
  6905. // Offset extruder (only by XY)
  6906. int i;
  6907. for (i = 0; i < 2; i++) {
  6908. current_position[i] = current_position[i] -
  6909. extruder_offset[i][active_extruder] +
  6910. extruder_offset[i][tmp_extruder];
  6911. }
  6912. // Set the new active extruder and position
  6913. active_extruder = tmp_extruder;
  6914. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  6915. // Move to the old position if 'F' was in the parameters
  6916. if (make_move && Stopped == false) {
  6917. prepare_move();
  6918. }
  6919. }
  6920. #endif
  6921. SERIAL_ECHO_START;
  6922. SERIAL_ECHORPGM(_n("Active Extruder: "));////MSG_ACTIVE_EXTRUDER
  6923. SERIAL_PROTOCOLLN((int)active_extruder);
  6924. }
  6925. #endif //SNMM
  6926. }
  6927. }
  6928. } // end if(code_seen('T')) (end of T codes)
  6929. //! ----------------------------------------------------------------------------------------------
  6930. else if (code_seen('D')) // D codes (debug)
  6931. {
  6932. switch((int)code_value())
  6933. {
  6934. //! ### D-1 - Endless loop
  6935. // -------------------
  6936. case -1:
  6937. dcode__1(); break;
  6938. #ifdef DEBUG_DCODES
  6939. //! ### D0 - Reset
  6940. // --------------
  6941. case 0:
  6942. dcode_0(); break;
  6943. //! ### D1 - Clear EEPROM
  6944. // ------------------
  6945. case 1:
  6946. dcode_1(); break;
  6947. //! ### D2 - Read/Write RAM
  6948. // --------------------
  6949. case 2:
  6950. dcode_2(); break;
  6951. #endif //DEBUG_DCODES
  6952. #ifdef DEBUG_DCODE3
  6953. //! ### D3 - Read/Write EEPROM
  6954. // -----------------------
  6955. case 3:
  6956. dcode_3(); break;
  6957. #endif //DEBUG_DCODE3
  6958. #ifdef DEBUG_DCODES
  6959. //! ### D4 - Read/Write PIN
  6960. // ---------------------
  6961. case 4:
  6962. dcode_4(); break;
  6963. #endif //DEBUG_DCODES
  6964. #ifdef DEBUG_DCODE5
  6965. //! ### D5 - Read/Write FLASH
  6966. // ------------------------
  6967. case 5:
  6968. dcode_5(); break;
  6969. break;
  6970. #endif //DEBUG_DCODE5
  6971. #ifdef DEBUG_DCODES
  6972. //! ### D6 - Read/Write external FLASH
  6973. // ---------------------------------------
  6974. case 6:
  6975. dcode_6(); break;
  6976. //! ### D7 - Read/Write Bootloader
  6977. // -------------------------------
  6978. case 7:
  6979. dcode_7(); break;
  6980. //! ### D8 - Read/Write PINDA
  6981. // ---------------------------
  6982. case 8:
  6983. dcode_8(); break;
  6984. // ### D9 - Read/Write ADC
  6985. // ------------------------
  6986. case 9:
  6987. dcode_9(); break;
  6988. //! ### D10 - XYZ calibration = OK
  6989. // ------------------------------
  6990. case 10:
  6991. dcode_10(); break;
  6992. #endif //DEBUG_DCODES
  6993. #ifdef HEATBED_ANALYSIS
  6994. //! ### D80 - Bed check
  6995. // ---------------------
  6996. /*!
  6997. - `E` - dimension x
  6998. - `F` - dimention y
  6999. - `G` - points_x
  7000. - `H` - points_y
  7001. - `I` - offset_x
  7002. - `J` - offset_y
  7003. */
  7004. case 80:
  7005. {
  7006. float dimension_x = 40;
  7007. float dimension_y = 40;
  7008. int points_x = 40;
  7009. int points_y = 40;
  7010. float offset_x = 74;
  7011. float offset_y = 33;
  7012. if (code_seen('E')) dimension_x = code_value();
  7013. if (code_seen('F')) dimension_y = code_value();
  7014. if (code_seen('G')) {points_x = code_value(); }
  7015. if (code_seen('H')) {points_y = code_value(); }
  7016. if (code_seen('I')) {offset_x = code_value(); }
  7017. if (code_seen('J')) {offset_y = code_value(); }
  7018. printf_P(PSTR("DIM X: %f\n"), dimension_x);
  7019. printf_P(PSTR("DIM Y: %f\n"), dimension_y);
  7020. printf_P(PSTR("POINTS X: %d\n"), points_x);
  7021. printf_P(PSTR("POINTS Y: %d\n"), points_y);
  7022. printf_P(PSTR("OFFSET X: %f\n"), offset_x);
  7023. printf_P(PSTR("OFFSET Y: %f\n"), offset_y);
  7024. bed_check(dimension_x,dimension_y,points_x,points_y,offset_x,offset_y);
  7025. }break;
  7026. //! ### D81 - Bed analysis
  7027. // -----------------------------
  7028. /*!
  7029. - `E` - dimension x
  7030. - `F` - dimention y
  7031. - `G` - points_x
  7032. - `H` - points_y
  7033. - `I` - offset_x
  7034. - `J` - offset_y
  7035. */
  7036. case 81:
  7037. {
  7038. float dimension_x = 40;
  7039. float dimension_y = 40;
  7040. int points_x = 40;
  7041. int points_y = 40;
  7042. float offset_x = 74;
  7043. float offset_y = 33;
  7044. if (code_seen('E')) dimension_x = code_value();
  7045. if (code_seen('F')) dimension_y = code_value();
  7046. if (code_seen("G")) { strchr_pointer+=1; points_x = code_value(); }
  7047. if (code_seen("H")) { strchr_pointer+=1; points_y = code_value(); }
  7048. if (code_seen("I")) { strchr_pointer+=1; offset_x = code_value(); }
  7049. if (code_seen("J")) { strchr_pointer+=1; offset_y = code_value(); }
  7050. bed_analysis(dimension_x,dimension_y,points_x,points_y,offset_x,offset_y);
  7051. } break;
  7052. #endif //HEATBED_ANALYSIS
  7053. #ifdef DEBUG_DCODES
  7054. //! ### D106 print measured fan speed for different pwm values
  7055. // --------------------------------------------------------------
  7056. case 106:
  7057. {
  7058. for (int i = 255; i > 0; i = i - 5) {
  7059. fanSpeed = i;
  7060. //delay_keep_alive(2000);
  7061. for (int j = 0; j < 100; j++) {
  7062. delay_keep_alive(100);
  7063. }
  7064. printf_P(_N("%d: %d\n"), i, fan_speed[1]);
  7065. }
  7066. }break;
  7067. #ifdef TMC2130
  7068. //! ### D2130 - TMC2130 Trinamic stepper controller
  7069. // ---------------------------
  7070. /*!
  7071. D2130<axis><command>[subcommand][value]
  7072. - <command>:
  7073. - '0' current off
  7074. - '1' current on
  7075. - '+' single step
  7076. - * value sereval steps
  7077. - '-' dtto oposite direction
  7078. - '?' read register
  7079. - * "mres"
  7080. - * "step"
  7081. - * "mscnt"
  7082. - * "mscuract"
  7083. - * "wave"
  7084. - '!' set register
  7085. - * "mres"
  7086. - * "step"
  7087. - * "wave"
  7088. - '@' home calibrate axis
  7089. Example:
  7090. D2130E?wave ... print extruder microstep linearity compensation curve
  7091. D2130E!wave0 ... disable extruder linearity compensation curve, (sine curve is used)
  7092. D2130E!wave220 ... (sin(x))^1.1 extruder microstep compensation curve used
  7093. */
  7094. case 2130:
  7095. dcode_2130(); break;
  7096. #endif //TMC2130
  7097. #if (defined (FILAMENT_SENSOR) && defined(PAT9125))
  7098. //! ### D9125 - FILAMENT_SENSOR
  7099. // ---------------------------------
  7100. case 9125:
  7101. dcode_9125(); break;
  7102. #endif //FILAMENT_SENSOR
  7103. #endif //DEBUG_DCODES
  7104. }
  7105. }
  7106. else
  7107. {
  7108. SERIAL_ECHO_START;
  7109. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  7110. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  7111. SERIAL_ECHOLNPGM("\"(2)");
  7112. }
  7113. KEEPALIVE_STATE(NOT_BUSY);
  7114. ClearToSend();
  7115. }
  7116. /** @defgroup GCodes G-Code List
  7117. */
  7118. // ---------------------------------------------------
  7119. void FlushSerialRequestResend()
  7120. {
  7121. //char cmdbuffer[bufindr][100]="Resend:";
  7122. MYSERIAL.flush();
  7123. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  7124. }
  7125. // Confirm the execution of a command, if sent from a serial line.
  7126. // Execution of a command from a SD card will not be confirmed.
  7127. void ClearToSend()
  7128. {
  7129. previous_millis_cmd = _millis();
  7130. if ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR))
  7131. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7132. }
  7133. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7134. void update_currents() {
  7135. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  7136. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  7137. float tmp_motor[3];
  7138. //SERIAL_ECHOLNPGM("Currents updated: ");
  7139. if (destination[Z_AXIS] < Z_SILENT) {
  7140. //SERIAL_ECHOLNPGM("LOW");
  7141. for (uint8_t i = 0; i < 3; i++) {
  7142. st_current_set(i, current_low[i]);
  7143. /*MYSERIAL.print(int(i));
  7144. SERIAL_ECHOPGM(": ");
  7145. MYSERIAL.println(current_low[i]);*/
  7146. }
  7147. }
  7148. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  7149. //SERIAL_ECHOLNPGM("HIGH");
  7150. for (uint8_t i = 0; i < 3; i++) {
  7151. st_current_set(i, current_high[i]);
  7152. /*MYSERIAL.print(int(i));
  7153. SERIAL_ECHOPGM(": ");
  7154. MYSERIAL.println(current_high[i]);*/
  7155. }
  7156. }
  7157. else {
  7158. for (uint8_t i = 0; i < 3; i++) {
  7159. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  7160. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  7161. st_current_set(i, tmp_motor[i]);
  7162. /*MYSERIAL.print(int(i));
  7163. SERIAL_ECHOPGM(": ");
  7164. MYSERIAL.println(tmp_motor[i]);*/
  7165. }
  7166. }
  7167. }
  7168. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7169. void get_coordinates()
  7170. {
  7171. bool seen[4]={false,false,false,false};
  7172. for(int8_t i=0; i < NUM_AXIS; i++) {
  7173. if(code_seen(axis_codes[i]))
  7174. {
  7175. bool relative = axis_relative_modes[i] || relative_mode;
  7176. destination[i] = (float)code_value();
  7177. if (i == E_AXIS) {
  7178. float emult = extruder_multiplier[active_extruder];
  7179. if (emult != 1.) {
  7180. if (! relative) {
  7181. destination[i] -= current_position[i];
  7182. relative = true;
  7183. }
  7184. destination[i] *= emult;
  7185. }
  7186. }
  7187. if (relative)
  7188. destination[i] += current_position[i];
  7189. seen[i]=true;
  7190. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7191. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  7192. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7193. }
  7194. else destination[i] = current_position[i]; //Are these else lines really needed?
  7195. }
  7196. if(code_seen('F')) {
  7197. next_feedrate = code_value();
  7198. #ifdef MAX_SILENT_FEEDRATE
  7199. if (tmc2130_mode == TMC2130_MODE_SILENT)
  7200. if (next_feedrate > MAX_SILENT_FEEDRATE) next_feedrate = MAX_SILENT_FEEDRATE;
  7201. #endif //MAX_SILENT_FEEDRATE
  7202. if(next_feedrate > 0.0) feedrate = next_feedrate;
  7203. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  7204. {
  7205. // float e_max_speed =
  7206. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  7207. }
  7208. }
  7209. }
  7210. void get_arc_coordinates()
  7211. {
  7212. #ifdef SF_ARC_FIX
  7213. bool relative_mode_backup = relative_mode;
  7214. relative_mode = true;
  7215. #endif
  7216. get_coordinates();
  7217. #ifdef SF_ARC_FIX
  7218. relative_mode=relative_mode_backup;
  7219. #endif
  7220. if(code_seen('I')) {
  7221. offset[0] = code_value();
  7222. }
  7223. else {
  7224. offset[0] = 0.0;
  7225. }
  7226. if(code_seen('J')) {
  7227. offset[1] = code_value();
  7228. }
  7229. else {
  7230. offset[1] = 0.0;
  7231. }
  7232. }
  7233. void clamp_to_software_endstops(float target[3])
  7234. {
  7235. #ifdef DEBUG_DISABLE_SWLIMITS
  7236. return;
  7237. #endif //DEBUG_DISABLE_SWLIMITS
  7238. world2machine_clamp(target[0], target[1]);
  7239. // Clamp the Z coordinate.
  7240. if (min_software_endstops) {
  7241. float negative_z_offset = 0;
  7242. #ifdef ENABLE_AUTO_BED_LEVELING
  7243. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  7244. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  7245. #endif
  7246. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  7247. }
  7248. if (max_software_endstops) {
  7249. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  7250. }
  7251. }
  7252. #ifdef MESH_BED_LEVELING
  7253. 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) {
  7254. float dx = x - current_position[X_AXIS];
  7255. float dy = y - current_position[Y_AXIS];
  7256. float dz = z - current_position[Z_AXIS];
  7257. int n_segments = 0;
  7258. if (mbl.active) {
  7259. float len = abs(dx) + abs(dy);
  7260. if (len > 0)
  7261. // Split to 3cm segments or shorter.
  7262. n_segments = int(ceil(len / 30.f));
  7263. }
  7264. if (n_segments > 1) {
  7265. float de = e - current_position[E_AXIS];
  7266. for (int i = 1; i < n_segments; ++ i) {
  7267. float t = float(i) / float(n_segments);
  7268. if (saved_printing || (mbl.active == false)) return;
  7269. plan_buffer_line(
  7270. current_position[X_AXIS] + t * dx,
  7271. current_position[Y_AXIS] + t * dy,
  7272. current_position[Z_AXIS] + t * dz,
  7273. current_position[E_AXIS] + t * de,
  7274. feed_rate, extruder);
  7275. }
  7276. }
  7277. // The rest of the path.
  7278. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  7279. current_position[X_AXIS] = x;
  7280. current_position[Y_AXIS] = y;
  7281. current_position[Z_AXIS] = z;
  7282. current_position[E_AXIS] = e;
  7283. }
  7284. #endif // MESH_BED_LEVELING
  7285. void prepare_move()
  7286. {
  7287. clamp_to_software_endstops(destination);
  7288. previous_millis_cmd = _millis();
  7289. // Do not use feedmultiply for E or Z only moves
  7290. if( (current_position[X_AXIS] == destination [X_AXIS]) && (current_position[Y_AXIS] == destination [Y_AXIS])) {
  7291. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  7292. }
  7293. else {
  7294. #ifdef MESH_BED_LEVELING
  7295. 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);
  7296. #else
  7297. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate*feedmultiply*(1./(60.f*100.f)), active_extruder);
  7298. #endif
  7299. }
  7300. for(int8_t i=0; i < NUM_AXIS; i++) {
  7301. current_position[i] = destination[i];
  7302. }
  7303. }
  7304. void prepare_arc_move(char isclockwise) {
  7305. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  7306. // Trace the arc
  7307. mc_arc(current_position, destination, offset, X_AXIS, Y_AXIS, Z_AXIS, feedrate*feedmultiply/60/100.0, r, isclockwise, active_extruder);
  7308. // As far as the parser is concerned, the position is now == target. In reality the
  7309. // motion control system might still be processing the action and the real tool position
  7310. // in any intermediate location.
  7311. for(int8_t i=0; i < NUM_AXIS; i++) {
  7312. current_position[i] = destination[i];
  7313. }
  7314. previous_millis_cmd = _millis();
  7315. }
  7316. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  7317. #if defined(FAN_PIN)
  7318. #if CONTROLLERFAN_PIN == FAN_PIN
  7319. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  7320. #endif
  7321. #endif
  7322. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  7323. unsigned long lastMotorCheck = 0;
  7324. void controllerFan()
  7325. {
  7326. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  7327. {
  7328. lastMotorCheck = _millis();
  7329. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  7330. #if EXTRUDERS > 2
  7331. || !READ(E2_ENABLE_PIN)
  7332. #endif
  7333. #if EXTRUDER > 1
  7334. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  7335. || !READ(X2_ENABLE_PIN)
  7336. #endif
  7337. || !READ(E1_ENABLE_PIN)
  7338. #endif
  7339. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  7340. {
  7341. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  7342. }
  7343. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  7344. {
  7345. digitalWrite(CONTROLLERFAN_PIN, 0);
  7346. analogWrite(CONTROLLERFAN_PIN, 0);
  7347. }
  7348. else
  7349. {
  7350. // allows digital or PWM fan output to be used (see M42 handling)
  7351. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  7352. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  7353. }
  7354. }
  7355. }
  7356. #endif
  7357. #ifdef TEMP_STAT_LEDS
  7358. static bool blue_led = false;
  7359. static bool red_led = false;
  7360. static uint32_t stat_update = 0;
  7361. void handle_status_leds(void) {
  7362. float max_temp = 0.0;
  7363. if(_millis() > stat_update) {
  7364. stat_update += 500; // Update every 0.5s
  7365. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  7366. max_temp = max(max_temp, degHotend(cur_extruder));
  7367. max_temp = max(max_temp, degTargetHotend(cur_extruder));
  7368. }
  7369. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  7370. max_temp = max(max_temp, degTargetBed());
  7371. max_temp = max(max_temp, degBed());
  7372. #endif
  7373. if((max_temp > 55.0) && (red_led == false)) {
  7374. digitalWrite(STAT_LED_RED, 1);
  7375. digitalWrite(STAT_LED_BLUE, 0);
  7376. red_led = true;
  7377. blue_led = false;
  7378. }
  7379. if((max_temp < 54.0) && (blue_led == false)) {
  7380. digitalWrite(STAT_LED_RED, 0);
  7381. digitalWrite(STAT_LED_BLUE, 1);
  7382. red_led = false;
  7383. blue_led = true;
  7384. }
  7385. }
  7386. }
  7387. #endif
  7388. #ifdef SAFETYTIMER
  7389. /**
  7390. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  7391. *
  7392. * Full screen blocking notification message is shown after heater turning off.
  7393. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  7394. * damage print.
  7395. *
  7396. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  7397. */
  7398. static void handleSafetyTimer()
  7399. {
  7400. #if (EXTRUDERS > 1)
  7401. #error Implemented only for one extruder.
  7402. #endif //(EXTRUDERS > 1)
  7403. if ((PRINTER_ACTIVE) || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  7404. {
  7405. safetyTimer.stop();
  7406. }
  7407. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  7408. {
  7409. safetyTimer.start();
  7410. }
  7411. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  7412. {
  7413. setTargetBed(0);
  7414. setAllTargetHotends(0);
  7415. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED
  7416. }
  7417. }
  7418. #endif //SAFETYTIMER
  7419. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  7420. {
  7421. bool bInhibitFlag;
  7422. #ifdef FILAMENT_SENSOR
  7423. if (mmu_enabled == false)
  7424. {
  7425. //-// if (mcode_in_progress != 600) //M600 not in progress
  7426. #ifdef PAT9125
  7427. bInhibitFlag=(menu_menu==lcd_menu_extruder_info); // Support::ExtruderInfo menu active
  7428. #endif // PAT9125
  7429. #ifdef IR_SENSOR
  7430. bInhibitFlag=(menu_menu==lcd_menu_show_sensors_state); // Support::SensorInfo menu active
  7431. #endif // IR_SENSOR
  7432. if ((mcode_in_progress != 600) && (eFilamentAction != FilamentAction::AutoLoad) && (!bInhibitFlag)) //M600 not in progress, preHeat @ autoLoad menu not active, Support::ExtruderInfo/SensorInfo menu not active
  7433. {
  7434. if (!moves_planned() && !IS_SD_PRINTING && !is_usb_printing && (lcd_commands_type != LcdCommands::Layer1Cal) && !wizard_active)
  7435. {
  7436. if (fsensor_check_autoload())
  7437. {
  7438. #ifdef PAT9125
  7439. fsensor_autoload_check_stop();
  7440. #endif //PAT9125
  7441. //-// if (degHotend0() > EXTRUDE_MINTEMP)
  7442. if(0)
  7443. {
  7444. Sound_MakeCustom(50,1000,false);
  7445. loading_flag = true;
  7446. enquecommand_front_P((PSTR("M701")));
  7447. }
  7448. else
  7449. {
  7450. /*
  7451. lcd_update_enable(false);
  7452. show_preheat_nozzle_warning();
  7453. lcd_update_enable(true);
  7454. */
  7455. eFilamentAction=FilamentAction::AutoLoad;
  7456. bFilamentFirstRun=false;
  7457. if(target_temperature[0]>=EXTRUDE_MINTEMP)
  7458. {
  7459. bFilamentPreheatState=true;
  7460. // mFilamentItem(target_temperature[0],target_temperature_bed);
  7461. menu_submenu(mFilamentItemForce);
  7462. }
  7463. else
  7464. {
  7465. menu_submenu(mFilamentMenu);
  7466. lcd_timeoutToStatus.start();
  7467. }
  7468. }
  7469. }
  7470. }
  7471. else
  7472. {
  7473. #ifdef PAT9125
  7474. fsensor_autoload_check_stop();
  7475. #endif //PAT9125
  7476. fsensor_update();
  7477. }
  7478. }
  7479. }
  7480. #endif //FILAMENT_SENSOR
  7481. #ifdef SAFETYTIMER
  7482. handleSafetyTimer();
  7483. #endif //SAFETYTIMER
  7484. #if defined(KILL_PIN) && KILL_PIN > -1
  7485. static int killCount = 0; // make the inactivity button a bit less responsive
  7486. const int KILL_DELAY = 10000;
  7487. #endif
  7488. if(buflen < (BUFSIZE-1)){
  7489. get_command();
  7490. }
  7491. if( (_millis() - previous_millis_cmd) > max_inactive_time )
  7492. if(max_inactive_time)
  7493. kill(_n(""), 4);
  7494. if(stepper_inactive_time) {
  7495. if( (_millis() - previous_millis_cmd) > stepper_inactive_time )
  7496. {
  7497. if(blocks_queued() == false && ignore_stepper_queue == false) {
  7498. disable_x();
  7499. disable_y();
  7500. disable_z();
  7501. disable_e0();
  7502. disable_e1();
  7503. disable_e2();
  7504. }
  7505. }
  7506. }
  7507. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  7508. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  7509. {
  7510. chdkActive = false;
  7511. WRITE(CHDK, LOW);
  7512. }
  7513. #endif
  7514. #if defined(KILL_PIN) && KILL_PIN > -1
  7515. // Check if the kill button was pressed and wait just in case it was an accidental
  7516. // key kill key press
  7517. // -------------------------------------------------------------------------------
  7518. if( 0 == READ(KILL_PIN) )
  7519. {
  7520. killCount++;
  7521. }
  7522. else if (killCount > 0)
  7523. {
  7524. killCount--;
  7525. }
  7526. // Exceeded threshold and we can confirm that it was not accidental
  7527. // KILL the machine
  7528. // ----------------------------------------------------------------
  7529. if ( killCount >= KILL_DELAY)
  7530. {
  7531. kill("", 5);
  7532. }
  7533. #endif
  7534. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  7535. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  7536. #endif
  7537. #ifdef EXTRUDER_RUNOUT_PREVENT
  7538. if( (_millis() - previous_millis_cmd) > EXTRUDER_RUNOUT_SECONDS*1000 )
  7539. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  7540. {
  7541. bool oldstatus=READ(E0_ENABLE_PIN);
  7542. enable_e0();
  7543. float oldepos=current_position[E_AXIS];
  7544. float oldedes=destination[E_AXIS];
  7545. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  7546. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  7547. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  7548. current_position[E_AXIS]=oldepos;
  7549. destination[E_AXIS]=oldedes;
  7550. plan_set_e_position(oldepos);
  7551. previous_millis_cmd=_millis();
  7552. st_synchronize();
  7553. WRITE(E0_ENABLE_PIN,oldstatus);
  7554. }
  7555. #endif
  7556. #ifdef TEMP_STAT_LEDS
  7557. handle_status_leds();
  7558. #endif
  7559. check_axes_activity();
  7560. mmu_loop();
  7561. }
  7562. void kill(const char *full_screen_message, unsigned char id)
  7563. {
  7564. printf_P(_N("KILL: %d\n"), id);
  7565. //return;
  7566. cli(); // Stop interrupts
  7567. disable_heater();
  7568. disable_x();
  7569. // SERIAL_ECHOLNPGM("kill - disable Y");
  7570. disable_y();
  7571. disable_z();
  7572. disable_e0();
  7573. disable_e1();
  7574. disable_e2();
  7575. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  7576. pinMode(PS_ON_PIN,INPUT);
  7577. #endif
  7578. SERIAL_ERROR_START;
  7579. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  7580. if (full_screen_message != NULL) {
  7581. SERIAL_ERRORLNRPGM(full_screen_message);
  7582. lcd_display_message_fullscreen_P(full_screen_message);
  7583. } else {
  7584. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  7585. }
  7586. // FMC small patch to update the LCD before ending
  7587. sei(); // enable interrupts
  7588. for ( int i=5; i--; lcd_update(0))
  7589. {
  7590. _delay(200);
  7591. }
  7592. cli(); // disable interrupts
  7593. suicide();
  7594. while(1)
  7595. {
  7596. #ifdef WATCHDOG
  7597. wdt_reset();
  7598. #endif //WATCHDOG
  7599. /* Intentionally left empty */
  7600. } // Wait for reset
  7601. }
  7602. void Stop()
  7603. {
  7604. disable_heater();
  7605. if(Stopped == false) {
  7606. Stopped = true;
  7607. lcd_print_stop();
  7608. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  7609. SERIAL_ERROR_START;
  7610. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  7611. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  7612. }
  7613. }
  7614. bool IsStopped() { return Stopped; };
  7615. #ifdef FAST_PWM_FAN
  7616. void setPwmFrequency(uint8_t pin, int val)
  7617. {
  7618. val &= 0x07;
  7619. switch(digitalPinToTimer(pin))
  7620. {
  7621. #if defined(TCCR0A)
  7622. case TIMER0A:
  7623. case TIMER0B:
  7624. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  7625. // TCCR0B |= val;
  7626. break;
  7627. #endif
  7628. #if defined(TCCR1A)
  7629. case TIMER1A:
  7630. case TIMER1B:
  7631. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  7632. // TCCR1B |= val;
  7633. break;
  7634. #endif
  7635. #if defined(TCCR2)
  7636. case TIMER2:
  7637. case TIMER2:
  7638. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  7639. TCCR2 |= val;
  7640. break;
  7641. #endif
  7642. #if defined(TCCR2A)
  7643. case TIMER2A:
  7644. case TIMER2B:
  7645. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  7646. TCCR2B |= val;
  7647. break;
  7648. #endif
  7649. #if defined(TCCR3A)
  7650. case TIMER3A:
  7651. case TIMER3B:
  7652. case TIMER3C:
  7653. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  7654. TCCR3B |= val;
  7655. break;
  7656. #endif
  7657. #if defined(TCCR4A)
  7658. case TIMER4A:
  7659. case TIMER4B:
  7660. case TIMER4C:
  7661. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  7662. TCCR4B |= val;
  7663. break;
  7664. #endif
  7665. #if defined(TCCR5A)
  7666. case TIMER5A:
  7667. case TIMER5B:
  7668. case TIMER5C:
  7669. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  7670. TCCR5B |= val;
  7671. break;
  7672. #endif
  7673. }
  7674. }
  7675. #endif //FAST_PWM_FAN
  7676. //! @brief Get and validate extruder number
  7677. //!
  7678. //! If it is not specified, active_extruder is returned in parameter extruder.
  7679. //! @param [in] code M code number
  7680. //! @param [out] extruder
  7681. //! @return error
  7682. //! @retval true Invalid extruder specified in T code
  7683. //! @retval false Valid extruder specified in T code, or not specifiead
  7684. bool setTargetedHotend(int code, uint8_t &extruder)
  7685. {
  7686. extruder = active_extruder;
  7687. if(code_seen('T')) {
  7688. extruder = code_value();
  7689. if(extruder >= EXTRUDERS) {
  7690. SERIAL_ECHO_START;
  7691. switch(code){
  7692. case 104:
  7693. SERIAL_ECHORPGM(_n("M104 Invalid extruder "));////MSG_M104_INVALID_EXTRUDER
  7694. break;
  7695. case 105:
  7696. SERIAL_ECHO(_n("M105 Invalid extruder "));////MSG_M105_INVALID_EXTRUDER
  7697. break;
  7698. case 109:
  7699. SERIAL_ECHO(_n("M109 Invalid extruder "));////MSG_M109_INVALID_EXTRUDER
  7700. break;
  7701. case 218:
  7702. SERIAL_ECHO(_n("M218 Invalid extruder "));////MSG_M218_INVALID_EXTRUDER
  7703. break;
  7704. case 221:
  7705. SERIAL_ECHO(_n("M221 Invalid extruder "));////MSG_M221_INVALID_EXTRUDER
  7706. break;
  7707. }
  7708. SERIAL_PROTOCOLLN((int)extruder);
  7709. return true;
  7710. }
  7711. }
  7712. return false;
  7713. }
  7714. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  7715. {
  7716. 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)
  7717. {
  7718. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  7719. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  7720. }
  7721. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  7722. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  7723. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  7724. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  7725. total_filament_used = 0;
  7726. }
  7727. float calculate_extruder_multiplier(float diameter) {
  7728. float out = 1.f;
  7729. if (cs.volumetric_enabled && diameter > 0.f) {
  7730. float area = M_PI * diameter * diameter * 0.25;
  7731. out = 1.f / area;
  7732. }
  7733. if (extrudemultiply != 100)
  7734. out *= float(extrudemultiply) * 0.01f;
  7735. return out;
  7736. }
  7737. void calculate_extruder_multipliers() {
  7738. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  7739. #if EXTRUDERS > 1
  7740. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  7741. #if EXTRUDERS > 2
  7742. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  7743. #endif
  7744. #endif
  7745. }
  7746. void delay_keep_alive(unsigned int ms)
  7747. {
  7748. for (;;) {
  7749. manage_heater();
  7750. // Manage inactivity, but don't disable steppers on timeout.
  7751. manage_inactivity(true);
  7752. lcd_update(0);
  7753. if (ms == 0)
  7754. break;
  7755. else if (ms >= 50) {
  7756. _delay(50);
  7757. ms -= 50;
  7758. } else {
  7759. _delay(ms);
  7760. ms = 0;
  7761. }
  7762. }
  7763. }
  7764. static void wait_for_heater(long codenum, uint8_t extruder) {
  7765. #ifdef TEMP_RESIDENCY_TIME
  7766. long residencyStart;
  7767. residencyStart = -1;
  7768. /* continue to loop until we have reached the target temp
  7769. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  7770. while ((!cancel_heatup) && ((residencyStart == -1) ||
  7771. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  7772. #else
  7773. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  7774. #endif //TEMP_RESIDENCY_TIME
  7775. if ((_millis() - codenum) > 1000UL)
  7776. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  7777. if (!farm_mode) {
  7778. SERIAL_PROTOCOLPGM("T:");
  7779. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  7780. SERIAL_PROTOCOLPGM(" E:");
  7781. SERIAL_PROTOCOL((int)extruder);
  7782. #ifdef TEMP_RESIDENCY_TIME
  7783. SERIAL_PROTOCOLPGM(" W:");
  7784. if (residencyStart > -1)
  7785. {
  7786. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  7787. SERIAL_PROTOCOLLN(codenum);
  7788. }
  7789. else
  7790. {
  7791. SERIAL_PROTOCOLLN("?");
  7792. }
  7793. }
  7794. #else
  7795. SERIAL_PROTOCOLLN("");
  7796. #endif
  7797. codenum = _millis();
  7798. }
  7799. manage_heater();
  7800. manage_inactivity(true); //do not disable steppers
  7801. lcd_update(0);
  7802. #ifdef TEMP_RESIDENCY_TIME
  7803. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  7804. or when current temp falls outside the hysteresis after target temp was reached */
  7805. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  7806. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  7807. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  7808. {
  7809. residencyStart = _millis();
  7810. }
  7811. #endif //TEMP_RESIDENCY_TIME
  7812. }
  7813. }
  7814. void check_babystep()
  7815. {
  7816. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  7817. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  7818. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  7819. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  7820. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  7821. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  7822. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  7823. babystep_z);
  7824. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  7825. lcd_update_enable(true);
  7826. }
  7827. }
  7828. #ifdef HEATBED_ANALYSIS
  7829. void d_setup()
  7830. {
  7831. pinMode(D_DATACLOCK, INPUT_PULLUP);
  7832. pinMode(D_DATA, INPUT_PULLUP);
  7833. pinMode(D_REQUIRE, OUTPUT);
  7834. digitalWrite(D_REQUIRE, HIGH);
  7835. }
  7836. float d_ReadData()
  7837. {
  7838. int digit[13];
  7839. String mergeOutput;
  7840. float output;
  7841. digitalWrite(D_REQUIRE, HIGH);
  7842. for (int i = 0; i<13; i++)
  7843. {
  7844. for (int j = 0; j < 4; j++)
  7845. {
  7846. while (digitalRead(D_DATACLOCK) == LOW) {}
  7847. while (digitalRead(D_DATACLOCK) == HIGH) {}
  7848. bitWrite(digit[i], j, digitalRead(D_DATA));
  7849. }
  7850. }
  7851. digitalWrite(D_REQUIRE, LOW);
  7852. mergeOutput = "";
  7853. output = 0;
  7854. for (int r = 5; r <= 10; r++) //Merge digits
  7855. {
  7856. mergeOutput += digit[r];
  7857. }
  7858. output = mergeOutput.toFloat();
  7859. if (digit[4] == 8) //Handle sign
  7860. {
  7861. output *= -1;
  7862. }
  7863. for (int i = digit[11]; i > 0; i--) //Handle floating point
  7864. {
  7865. output /= 10;
  7866. }
  7867. return output;
  7868. }
  7869. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  7870. int t1 = 0;
  7871. int t_delay = 0;
  7872. int digit[13];
  7873. int m;
  7874. char str[3];
  7875. //String mergeOutput;
  7876. char mergeOutput[15];
  7877. float output;
  7878. int mesh_point = 0; //index number of calibration point
  7879. 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
  7880. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  7881. float mesh_home_z_search = 4;
  7882. float measure_z_height = 0.2f;
  7883. float row[x_points_num];
  7884. int ix = 0;
  7885. int iy = 0;
  7886. const char* filename_wldsd = "mesh.txt";
  7887. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  7888. char numb_wldsd[8]; // (" -A.BCD" + null)
  7889. #ifdef MICROMETER_LOGGING
  7890. d_setup();
  7891. #endif //MICROMETER_LOGGING
  7892. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  7893. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  7894. unsigned int custom_message_type_old = custom_message_type;
  7895. unsigned int custom_message_state_old = custom_message_state;
  7896. custom_message_type = CustomMsg::MeshBedLeveling;
  7897. custom_message_state = (x_points_num * y_points_num) + 10;
  7898. lcd_update(1);
  7899. //mbl.reset();
  7900. babystep_undo();
  7901. card.openFile(filename_wldsd, false);
  7902. /*destination[Z_AXIS] = mesh_home_z_search;
  7903. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  7904. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  7905. for(int8_t i=0; i < NUM_AXIS; i++) {
  7906. current_position[i] = destination[i];
  7907. }
  7908. st_synchronize();
  7909. */
  7910. destination[Z_AXIS] = measure_z_height;
  7911. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  7912. for(int8_t i=0; i < NUM_AXIS; i++) {
  7913. current_position[i] = destination[i];
  7914. }
  7915. st_synchronize();
  7916. /*int l_feedmultiply = */setup_for_endstop_move(false);
  7917. SERIAL_PROTOCOLPGM("Num X,Y: ");
  7918. SERIAL_PROTOCOL(x_points_num);
  7919. SERIAL_PROTOCOLPGM(",");
  7920. SERIAL_PROTOCOL(y_points_num);
  7921. SERIAL_PROTOCOLPGM("\nZ search height: ");
  7922. SERIAL_PROTOCOL(mesh_home_z_search);
  7923. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  7924. SERIAL_PROTOCOL(x_dimension);
  7925. SERIAL_PROTOCOLPGM(",");
  7926. SERIAL_PROTOCOL(y_dimension);
  7927. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  7928. while (mesh_point != x_points_num * y_points_num) {
  7929. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  7930. iy = mesh_point / x_points_num;
  7931. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  7932. float z0 = 0.f;
  7933. /*destination[Z_AXIS] = mesh_home_z_search;
  7934. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  7935. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  7936. for(int8_t i=0; i < NUM_AXIS; i++) {
  7937. current_position[i] = destination[i];
  7938. }
  7939. st_synchronize();*/
  7940. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  7941. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  7942. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  7943. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  7944. mesh_plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], XY_AXIS_FEEDRATE/6, active_extruder);
  7945. for(int8_t i=0; i < NUM_AXIS; i++) {
  7946. current_position[i] = destination[i];
  7947. }
  7948. st_synchronize();
  7949. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  7950. delay_keep_alive(1000);
  7951. #ifdef MICROMETER_LOGGING
  7952. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  7953. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  7954. //strcat(data_wldsd, numb_wldsd);
  7955. //MYSERIAL.println(data_wldsd);
  7956. //delay(1000);
  7957. //delay(3000);
  7958. //t1 = millis();
  7959. //while (digitalRead(D_DATACLOCK) == LOW) {}
  7960. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  7961. memset(digit, 0, sizeof(digit));
  7962. //cli();
  7963. digitalWrite(D_REQUIRE, LOW);
  7964. for (int i = 0; i<13; i++)
  7965. {
  7966. //t1 = millis();
  7967. for (int j = 0; j < 4; j++)
  7968. {
  7969. while (digitalRead(D_DATACLOCK) == LOW) {}
  7970. while (digitalRead(D_DATACLOCK) == HIGH) {}
  7971. //printf_P(PSTR("Done %d\n"), j);
  7972. bitWrite(digit[i], j, digitalRead(D_DATA));
  7973. }
  7974. //t_delay = (millis() - t1);
  7975. //SERIAL_PROTOCOLPGM(" ");
  7976. //SERIAL_PROTOCOL_F(t_delay, 5);
  7977. //SERIAL_PROTOCOLPGM(" ");
  7978. }
  7979. //sei();
  7980. digitalWrite(D_REQUIRE, HIGH);
  7981. mergeOutput[0] = '\0';
  7982. output = 0;
  7983. for (int r = 5; r <= 10; r++) //Merge digits
  7984. {
  7985. sprintf(str, "%d", digit[r]);
  7986. strcat(mergeOutput, str);
  7987. }
  7988. output = atof(mergeOutput);
  7989. if (digit[4] == 8) //Handle sign
  7990. {
  7991. output *= -1;
  7992. }
  7993. for (int i = digit[11]; i > 0; i--) //Handle floating point
  7994. {
  7995. output *= 0.1;
  7996. }
  7997. //output = d_ReadData();
  7998. //row[ix] = current_position[Z_AXIS];
  7999. //row[ix] = d_ReadData();
  8000. row[ix] = output;
  8001. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8002. memset(data_wldsd, 0, sizeof(data_wldsd));
  8003. for (int i = 0; i < x_points_num; i++) {
  8004. SERIAL_PROTOCOLPGM(" ");
  8005. SERIAL_PROTOCOL_F(row[i], 5);
  8006. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8007. dtostrf(row[i], 7, 3, numb_wldsd);
  8008. strcat(data_wldsd, numb_wldsd);
  8009. }
  8010. card.write_command(data_wldsd);
  8011. SERIAL_PROTOCOLPGM("\n");
  8012. }
  8013. custom_message_state--;
  8014. mesh_point++;
  8015. lcd_update(1);
  8016. }
  8017. #endif //MICROMETER_LOGGING
  8018. card.closefile();
  8019. //clean_up_after_endstop_move(l_feedmultiply);
  8020. }
  8021. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8022. int t1 = 0;
  8023. int t_delay = 0;
  8024. int digit[13];
  8025. int m;
  8026. char str[3];
  8027. //String mergeOutput;
  8028. char mergeOutput[15];
  8029. float output;
  8030. int mesh_point = 0; //index number of calibration point
  8031. 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
  8032. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8033. float mesh_home_z_search = 4;
  8034. float row[x_points_num];
  8035. int ix = 0;
  8036. int iy = 0;
  8037. const char* filename_wldsd = "wldsd.txt";
  8038. char data_wldsd[70];
  8039. char numb_wldsd[10];
  8040. d_setup();
  8041. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  8042. // We don't know where we are! HOME!
  8043. // Push the commands to the front of the message queue in the reverse order!
  8044. // There shall be always enough space reserved for these commands.
  8045. repeatcommand_front(); // repeat G80 with all its parameters
  8046. enquecommand_front_P((PSTR("G28 W0")));
  8047. enquecommand_front_P((PSTR("G1 Z5")));
  8048. return;
  8049. }
  8050. unsigned int custom_message_type_old = custom_message_type;
  8051. unsigned int custom_message_state_old = custom_message_state;
  8052. custom_message_type = CustomMsg::MeshBedLeveling;
  8053. custom_message_state = (x_points_num * y_points_num) + 10;
  8054. lcd_update(1);
  8055. mbl.reset();
  8056. babystep_undo();
  8057. card.openFile(filename_wldsd, false);
  8058. current_position[Z_AXIS] = mesh_home_z_search;
  8059. 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);
  8060. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8061. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8062. int l_feedmultiply = setup_for_endstop_move(false);
  8063. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8064. SERIAL_PROTOCOL(x_points_num);
  8065. SERIAL_PROTOCOLPGM(",");
  8066. SERIAL_PROTOCOL(y_points_num);
  8067. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8068. SERIAL_PROTOCOL(mesh_home_z_search);
  8069. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8070. SERIAL_PROTOCOL(x_dimension);
  8071. SERIAL_PROTOCOLPGM(",");
  8072. SERIAL_PROTOCOL(y_dimension);
  8073. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8074. while (mesh_point != x_points_num * y_points_num) {
  8075. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8076. iy = mesh_point / x_points_num;
  8077. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8078. float z0 = 0.f;
  8079. current_position[Z_AXIS] = mesh_home_z_search;
  8080. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  8081. st_synchronize();
  8082. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8083. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8084. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], XY_AXIS_FEEDRATE, active_extruder);
  8085. st_synchronize();
  8086. 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
  8087. break;
  8088. card.closefile();
  8089. }
  8090. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8091. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8092. //strcat(data_wldsd, numb_wldsd);
  8093. //MYSERIAL.println(data_wldsd);
  8094. //_delay(1000);
  8095. //_delay(3000);
  8096. //t1 = _millis();
  8097. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8098. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8099. memset(digit, 0, sizeof(digit));
  8100. //cli();
  8101. digitalWrite(D_REQUIRE, LOW);
  8102. for (int i = 0; i<13; i++)
  8103. {
  8104. //t1 = _millis();
  8105. for (int j = 0; j < 4; j++)
  8106. {
  8107. while (digitalRead(D_DATACLOCK) == LOW) {}
  8108. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8109. bitWrite(digit[i], j, digitalRead(D_DATA));
  8110. }
  8111. //t_delay = (_millis() - t1);
  8112. //SERIAL_PROTOCOLPGM(" ");
  8113. //SERIAL_PROTOCOL_F(t_delay, 5);
  8114. //SERIAL_PROTOCOLPGM(" ");
  8115. }
  8116. //sei();
  8117. digitalWrite(D_REQUIRE, HIGH);
  8118. mergeOutput[0] = '\0';
  8119. output = 0;
  8120. for (int r = 5; r <= 10; r++) //Merge digits
  8121. {
  8122. sprintf(str, "%d", digit[r]);
  8123. strcat(mergeOutput, str);
  8124. }
  8125. output = atof(mergeOutput);
  8126. if (digit[4] == 8) //Handle sign
  8127. {
  8128. output *= -1;
  8129. }
  8130. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8131. {
  8132. output *= 0.1;
  8133. }
  8134. //output = d_ReadData();
  8135. //row[ix] = current_position[Z_AXIS];
  8136. memset(data_wldsd, 0, sizeof(data_wldsd));
  8137. for (int i = 0; i <3; i++) {
  8138. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8139. dtostrf(current_position[i], 8, 5, numb_wldsd);
  8140. strcat(data_wldsd, numb_wldsd);
  8141. strcat(data_wldsd, ";");
  8142. }
  8143. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8144. dtostrf(output, 8, 5, numb_wldsd);
  8145. strcat(data_wldsd, numb_wldsd);
  8146. //strcat(data_wldsd, ";");
  8147. card.write_command(data_wldsd);
  8148. //row[ix] = d_ReadData();
  8149. row[ix] = output; // current_position[Z_AXIS];
  8150. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8151. for (int i = 0; i < x_points_num; i++) {
  8152. SERIAL_PROTOCOLPGM(" ");
  8153. SERIAL_PROTOCOL_F(row[i], 5);
  8154. }
  8155. SERIAL_PROTOCOLPGM("\n");
  8156. }
  8157. custom_message_state--;
  8158. mesh_point++;
  8159. lcd_update(1);
  8160. }
  8161. card.closefile();
  8162. clean_up_after_endstop_move(l_feedmultiply);
  8163. }
  8164. #endif //HEATBED_ANALYSIS
  8165. void temp_compensation_start() {
  8166. custom_message_type = CustomMsg::TempCompPreheat;
  8167. custom_message_state = PINDA_HEAT_T + 1;
  8168. lcd_update(2);
  8169. if (degHotend(active_extruder) > EXTRUDE_MINTEMP) {
  8170. current_position[E_AXIS] -= default_retraction;
  8171. }
  8172. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  8173. current_position[X_AXIS] = PINDA_PREHEAT_X;
  8174. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  8175. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  8176. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  8177. st_synchronize();
  8178. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  8179. for (int i = 0; i < PINDA_HEAT_T; i++) {
  8180. delay_keep_alive(1000);
  8181. custom_message_state = PINDA_HEAT_T - i;
  8182. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  8183. else lcd_update(1);
  8184. }
  8185. custom_message_type = CustomMsg::Status;
  8186. custom_message_state = 0;
  8187. }
  8188. void temp_compensation_apply() {
  8189. int i_add;
  8190. int z_shift = 0;
  8191. float z_shift_mm;
  8192. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  8193. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  8194. i_add = (target_temperature_bed - 60) / 10;
  8195. EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + i_add * 2, &z_shift);
  8196. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  8197. }else {
  8198. //interpolation
  8199. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  8200. }
  8201. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  8202. 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);
  8203. st_synchronize();
  8204. plan_set_z_position(current_position[Z_AXIS]);
  8205. }
  8206. else {
  8207. //we have no temp compensation data
  8208. }
  8209. }
  8210. float temp_comp_interpolation(float inp_temperature) {
  8211. //cubic spline interpolation
  8212. int n, i, j;
  8213. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  8214. int shift[10];
  8215. int temp_C[10];
  8216. n = 6; //number of measured points
  8217. shift[0] = 0;
  8218. for (i = 0; i < n; i++) {
  8219. if (i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i-1) * 2, &shift[i]); //read shift in steps from EEPROM
  8220. temp_C[i] = 50 + i * 10; //temperature in C
  8221. #ifdef PINDA_THERMISTOR
  8222. temp_C[i] = 35 + i * 5; //temperature in C
  8223. #else
  8224. temp_C[i] = 50 + i * 10; //temperature in C
  8225. #endif
  8226. x[i] = (float)temp_C[i];
  8227. f[i] = (float)shift[i];
  8228. }
  8229. if (inp_temperature < x[0]) return 0;
  8230. for (i = n - 1; i>0; i--) {
  8231. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  8232. h[i - 1] = x[i] - x[i - 1];
  8233. }
  8234. //*********** formation of h, s , f matrix **************
  8235. for (i = 1; i<n - 1; i++) {
  8236. m[i][i] = 2 * (h[i - 1] + h[i]);
  8237. if (i != 1) {
  8238. m[i][i - 1] = h[i - 1];
  8239. m[i - 1][i] = h[i - 1];
  8240. }
  8241. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  8242. }
  8243. //*********** forward elimination **************
  8244. for (i = 1; i<n - 2; i++) {
  8245. temp = (m[i + 1][i] / m[i][i]);
  8246. for (j = 1; j <= n - 1; j++)
  8247. m[i + 1][j] -= temp*m[i][j];
  8248. }
  8249. //*********** backward substitution *********
  8250. for (i = n - 2; i>0; i--) {
  8251. sum = 0;
  8252. for (j = i; j <= n - 2; j++)
  8253. sum += m[i][j] * s[j];
  8254. s[i] = (m[i][n - 1] - sum) / m[i][i];
  8255. }
  8256. for (i = 0; i<n - 1; i++)
  8257. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  8258. a = (s[i + 1] - s[i]) / (6 * h[i]);
  8259. b = s[i] / 2;
  8260. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  8261. d = f[i];
  8262. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  8263. }
  8264. return sum;
  8265. }
  8266. #ifdef PINDA_THERMISTOR
  8267. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  8268. {
  8269. if (!temp_cal_active) return 0;
  8270. if (!calibration_status_pinda()) return 0;
  8271. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  8272. }
  8273. #endif //PINDA_THERMISTOR
  8274. void long_pause() //long pause print
  8275. {
  8276. st_synchronize();
  8277. start_pause_print = _millis();
  8278. //retract
  8279. current_position[E_AXIS] -= default_retraction;
  8280. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  8281. //lift z
  8282. current_position[Z_AXIS] += Z_PAUSE_LIFT;
  8283. if (current_position[Z_AXIS] > Z_MAX_POS) current_position[Z_AXIS] = Z_MAX_POS;
  8284. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 15, active_extruder);
  8285. //Move XY to side
  8286. current_position[X_AXIS] = X_PAUSE_POS;
  8287. current_position[Y_AXIS] = Y_PAUSE_POS;
  8288. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 50, active_extruder);
  8289. // Turn off the print fan
  8290. fanSpeed = 0;
  8291. st_synchronize();
  8292. }
  8293. void serialecho_temperatures() {
  8294. float tt = degHotend(active_extruder);
  8295. SERIAL_PROTOCOLPGM("T:");
  8296. SERIAL_PROTOCOL(tt);
  8297. SERIAL_PROTOCOLPGM(" E:");
  8298. SERIAL_PROTOCOL((int)active_extruder);
  8299. SERIAL_PROTOCOLPGM(" B:");
  8300. SERIAL_PROTOCOL_F(degBed(), 1);
  8301. SERIAL_PROTOCOLLN("");
  8302. }
  8303. extern uint32_t sdpos_atomic;
  8304. #ifdef UVLO_SUPPORT
  8305. void uvlo_()
  8306. {
  8307. unsigned long time_start = _millis();
  8308. bool sd_print = card.sdprinting;
  8309. // Conserve power as soon as possible.
  8310. disable_x();
  8311. disable_y();
  8312. #ifdef TMC2130
  8313. tmc2130_set_current_h(Z_AXIS, 20);
  8314. tmc2130_set_current_r(Z_AXIS, 20);
  8315. tmc2130_set_current_h(E_AXIS, 20);
  8316. tmc2130_set_current_r(E_AXIS, 20);
  8317. #endif //TMC2130
  8318. // Indicate that the interrupt has been triggered.
  8319. // SERIAL_ECHOLNPGM("UVLO");
  8320. // Read out the current Z motor microstep counter. This will be later used
  8321. // for reaching the zero full step before powering off.
  8322. uint16_t z_microsteps = 0;
  8323. #ifdef TMC2130
  8324. z_microsteps = tmc2130_rd_MSCNT(Z_TMC2130_CS);
  8325. #endif //TMC2130
  8326. // Calculate the file position, from which to resume this print.
  8327. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  8328. {
  8329. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  8330. sd_position -= sdlen_planner;
  8331. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  8332. sd_position -= sdlen_cmdqueue;
  8333. if (sd_position < 0) sd_position = 0;
  8334. }
  8335. // Backup the feedrate in mm/min.
  8336. int feedrate_bckp = blocks_queued() ? (block_buffer[block_buffer_tail].nominal_speed * 60.f) : feedrate;
  8337. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  8338. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  8339. // are in action.
  8340. planner_abort_hard();
  8341. // Store the current extruder position.
  8342. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), st_get_position_mm(E_AXIS));
  8343. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, axis_relative_modes[3]?0:1);
  8344. // Clean the input command queue.
  8345. cmdqueue_reset();
  8346. card.sdprinting = false;
  8347. // card.closefile();
  8348. // Enable stepper driver interrupt to move Z axis.
  8349. // This should be fine as the planner and command queues are empty and the SD card printing is disabled.
  8350. //FIXME one may want to disable serial lines at this point of time to avoid interfering with the command queue,
  8351. // though it should not happen that the command queue is touched as the plan_buffer_line always succeed without blocking.
  8352. sei();
  8353. plan_buffer_line(
  8354. current_position[X_AXIS],
  8355. current_position[Y_AXIS],
  8356. current_position[Z_AXIS],
  8357. current_position[E_AXIS] - default_retraction,
  8358. 95, active_extruder);
  8359. st_synchronize();
  8360. disable_e0();
  8361. plan_buffer_line(
  8362. current_position[X_AXIS],
  8363. current_position[Y_AXIS],
  8364. current_position[Z_AXIS] + UVLO_Z_AXIS_SHIFT + float((1024 - z_microsteps + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS],
  8365. current_position[E_AXIS] - default_retraction,
  8366. 40, active_extruder);
  8367. st_synchronize();
  8368. disable_e0();
  8369. plan_buffer_line(
  8370. current_position[X_AXIS],
  8371. current_position[Y_AXIS],
  8372. current_position[Z_AXIS] + UVLO_Z_AXIS_SHIFT + float((1024 - z_microsteps + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS],
  8373. current_position[E_AXIS] - default_retraction,
  8374. 40, active_extruder);
  8375. st_synchronize();
  8376. disable_e0();
  8377. disable_z();
  8378. // Move Z up to the next 0th full step.
  8379. // Write the file position.
  8380. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  8381. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  8382. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  8383. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  8384. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  8385. // Scale the z value to 1u resolution.
  8386. int16_t v = mbl.active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  8387. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  8388. }
  8389. // Read out the current Z motor microstep counter. This will be later used
  8390. // for reaching the zero full step before powering off.
  8391. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  8392. // Store the current position.
  8393. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  8394. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  8395. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z , current_position[Z_AXIS]);
  8396. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  8397. EEPROM_save_B(EEPROM_UVLO_FEEDRATE, &feedrate_bckp);
  8398. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_HOTEND, target_temperature[active_extruder]);
  8399. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, target_temperature_bed);
  8400. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  8401. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  8402. #if EXTRUDERS > 1
  8403. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  8404. #if EXTRUDERS > 2
  8405. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  8406. #endif
  8407. #endif
  8408. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  8409. // Finaly store the "power outage" flag.
  8410. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  8411. st_synchronize();
  8412. printf_P(_N("stps%d\n"), tmc2130_rd_MSCNT(Z_AXIS));
  8413. disable_z();
  8414. // Increment power failure counter
  8415. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  8416. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  8417. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  8418. #if 0
  8419. // Move the print head to the side of the print until all the power stored in the power supply capacitors is depleted.
  8420. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  8421. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 500, active_extruder);
  8422. st_synchronize();
  8423. #endif
  8424. wdt_enable(WDTO_500MS);
  8425. WRITE(BEEPER,HIGH);
  8426. while(1)
  8427. ;
  8428. }
  8429. void uvlo_tiny()
  8430. {
  8431. uint16_t z_microsteps=0;
  8432. // Conserve power as soon as possible.
  8433. disable_x();
  8434. disable_y();
  8435. disable_e0();
  8436. #ifdef TMC2130
  8437. tmc2130_set_current_h(Z_AXIS, 20);
  8438. tmc2130_set_current_r(Z_AXIS, 20);
  8439. #endif //TMC2130
  8440. // Read out the current Z motor microstep counter
  8441. #ifdef TMC2130
  8442. z_microsteps=tmc2130_rd_MSCNT(Z_TMC2130_CS);
  8443. #endif //TMC2130
  8444. planner_abort_hard();
  8445. disable_z();
  8446. //save current position only in case, where the printer is moving on Z axis, which is only when EEPROM_UVLO is 1
  8447. //EEPROM_UVLO is 1 after normal uvlo or after recover_print(), when the extruder is moving on Z axis after rehome
  8448. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)!=2){
  8449. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  8450. eeprom_update_word((uint16_t*)(EEPROM_UVLO_TINY_Z_MICROSTEPS),z_microsteps);
  8451. }
  8452. //after multiple power panics current Z axis is unknow
  8453. //in this case we set EEPROM_UVLO_TINY_CURRENT_POSITION_Z to last know position which is EEPROM_UVLO_CURRENT_POSITION_Z
  8454. if(eeprom_read_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z) < 0.001f){
  8455. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), eeprom_read_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z));
  8456. eeprom_update_word((uint16_t*)(EEPROM_UVLO_TINY_Z_MICROSTEPS), eeprom_read_word((uint16_t*)EEPROM_UVLO_Z_MICROSTEPS));
  8457. }
  8458. // Finaly store the "power outage" flag.
  8459. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  8460. // Increment power failure counter
  8461. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  8462. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  8463. wdt_enable(WDTO_500MS);
  8464. WRITE(BEEPER,HIGH);
  8465. while(1)
  8466. ;
  8467. }
  8468. #endif //UVLO_SUPPORT
  8469. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  8470. void setup_fan_interrupt() {
  8471. //INT7
  8472. DDRE &= ~(1 << 7); //input pin
  8473. PORTE &= ~(1 << 7); //no internal pull-up
  8474. //start with sensing rising edge
  8475. EICRB &= ~(1 << 6);
  8476. EICRB |= (1 << 7);
  8477. //enable INT7 interrupt
  8478. EIMSK |= (1 << 7);
  8479. }
  8480. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  8481. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  8482. ISR(INT7_vect) {
  8483. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  8484. #ifdef FAN_SOFT_PWM
  8485. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  8486. #else //FAN_SOFT_PWM
  8487. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  8488. #endif //FAN_SOFT_PWM
  8489. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  8490. t_fan_rising_edge = millis_nc();
  8491. }
  8492. else { //interrupt was triggered by falling edge
  8493. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  8494. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  8495. }
  8496. }
  8497. EICRB ^= (1 << 6); //change edge
  8498. }
  8499. #endif
  8500. #ifdef UVLO_SUPPORT
  8501. void setup_uvlo_interrupt() {
  8502. DDRE &= ~(1 << 4); //input pin
  8503. PORTE &= ~(1 << 4); //no internal pull-up
  8504. //sensing falling edge
  8505. EICRB |= (1 << 0);
  8506. EICRB &= ~(1 << 1);
  8507. //enable INT4 interrupt
  8508. EIMSK |= (1 << 4);
  8509. }
  8510. ISR(INT4_vect) {
  8511. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  8512. SERIAL_ECHOLNPGM("INT4");
  8513. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  8514. if(PRINTER_ACTIVE && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  8515. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  8516. }
  8517. void recover_print(uint8_t automatic) {
  8518. char cmd[30];
  8519. lcd_update_enable(true);
  8520. lcd_update(2);
  8521. lcd_setstatuspgm(_i("Recovering print "));////MSG_RECOVERING_PRINT c=20 r=1
  8522. bool bTiny=(eeprom_read_byte((uint8_t*)EEPROM_UVLO)==2);
  8523. recover_machine_state_after_power_panic(bTiny); //recover position, temperatures and extrude_multipliers
  8524. // Lift the print head, so one may remove the excess priming material.
  8525. if(!bTiny&&(current_position[Z_AXIS]<25))
  8526. enquecommand_P(PSTR("G1 Z25 F800"));
  8527. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine transformation status.
  8528. enquecommand_P(PSTR("G28 X Y"));
  8529. // Set the target bed and nozzle temperatures and wait.
  8530. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  8531. enquecommand(cmd);
  8532. sprintf_P(cmd, PSTR("M190 S%d"), target_temperature_bed);
  8533. enquecommand(cmd);
  8534. enquecommand_P(PSTR("M83")); //E axis relative mode
  8535. //enquecommand_P(PSTR("G1 E5 F120")); //Extrude some filament to stabilize pessure
  8536. // If not automatically recoreverd (long power loss), extrude extra filament to stabilize
  8537. if(automatic == 0){
  8538. enquecommand_P(PSTR("G1 E5 F120")); //Extrude some filament to stabilize pessure
  8539. }
  8540. enquecommand_P(PSTR("G1 E" STRINGIFY(-default_retraction)" F480"));
  8541. printf_P(_N("After waiting for temp:\nCurrent pos X_AXIS:%.3f\nCurrent pos Y_AXIS:%.3f\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  8542. // Restart the print.
  8543. restore_print_from_eeprom();
  8544. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  8545. }
  8546. void recover_machine_state_after_power_panic(bool bTiny)
  8547. {
  8548. char cmd[30];
  8549. // 1) Recover the logical cordinates at the time of the power panic.
  8550. // The logical XY coordinates are needed to recover the machine Z coordinate corrected by the mesh bed leveling.
  8551. current_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  8552. current_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  8553. // 2) Restore the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  8554. mbl.active = false;
  8555. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  8556. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  8557. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  8558. // Scale the z value to 10u resolution.
  8559. int16_t v;
  8560. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  8561. if (v != 0)
  8562. mbl.active = true;
  8563. mbl.z_values[iy][ix] = float(v) * 0.001f;
  8564. }
  8565. // Recover the logical coordinate of the Z axis at the time of the power panic.
  8566. // The current position after power panic is moved to the next closest 0th full step.
  8567. if(bTiny){
  8568. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z))
  8569. + float((1024 - eeprom_read_word((uint16_t*)(EEPROM_UVLO_TINY_Z_MICROSTEPS))
  8570. + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS];
  8571. //after multiple power panics the print is slightly in the air so get it little bit down.
  8572. //Not exactly sure why is this happening, but it has something to do with bed leveling and world2machine coordinates
  8573. current_position[Z_AXIS] -= 0.4*mbl.get_z(current_position[X_AXIS], current_position[Y_AXIS]);
  8574. }
  8575. else{
  8576. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)) +
  8577. UVLO_Z_AXIS_SHIFT + float((1024 - eeprom_read_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS))
  8578. + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS];
  8579. }
  8580. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS)) {
  8581. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  8582. sprintf_P(cmd, PSTR("G92 E"));
  8583. dtostrf(current_position[E_AXIS], 6, 3, cmd + strlen(cmd));
  8584. enquecommand(cmd);
  8585. }
  8586. memcpy(destination, current_position, sizeof(destination));
  8587. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  8588. print_world_coordinates();
  8589. // 3) Initialize the logical to physical coordinate system transformation.
  8590. world2machine_initialize();
  8591. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  8592. // print_mesh_bed_leveling_table();
  8593. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  8594. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  8595. babystep_load();
  8596. // 5) Set the physical positions from the logical positions using the world2machine transformation and the active bed leveling.
  8597. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  8598. // 6) Power up the motors, mark their positions as known.
  8599. //FIXME Verfiy, whether the X and Y axes should be powered up here, as they will later be re-homed anyway.
  8600. axis_known_position[X_AXIS] = true; enable_x();
  8601. axis_known_position[Y_AXIS] = true; enable_y();
  8602. axis_known_position[Z_AXIS] = true; enable_z();
  8603. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  8604. print_physical_coordinates();
  8605. // 7) Recover the target temperatures.
  8606. target_temperature[active_extruder] = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_HOTEND);
  8607. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  8608. // 8) Recover extruder multipilers
  8609. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  8610. #if EXTRUDERS > 1
  8611. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  8612. #if EXTRUDERS > 2
  8613. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  8614. #endif
  8615. #endif
  8616. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  8617. }
  8618. void restore_print_from_eeprom() {
  8619. int feedrate_rec;
  8620. uint8_t fan_speed_rec;
  8621. char cmd[30];
  8622. char filename[13];
  8623. uint8_t depth = 0;
  8624. char dir_name[9];
  8625. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  8626. EEPROM_read_B(EEPROM_UVLO_FEEDRATE, &feedrate_rec);
  8627. SERIAL_ECHOPGM("Feedrate:");
  8628. MYSERIAL.println(feedrate_rec);
  8629. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  8630. MYSERIAL.println(int(depth));
  8631. for (int i = 0; i < depth; i++) {
  8632. for (int j = 0; j < 8; j++) {
  8633. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  8634. }
  8635. dir_name[8] = '\0';
  8636. MYSERIAL.println(dir_name);
  8637. strcpy(dir_names[i], dir_name);
  8638. card.chdir(dir_name);
  8639. }
  8640. for (int i = 0; i < 8; i++) {
  8641. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  8642. }
  8643. filename[8] = '\0';
  8644. MYSERIAL.print(filename);
  8645. strcat_P(filename, PSTR(".gco"));
  8646. sprintf_P(cmd, PSTR("M23 %s"), filename);
  8647. enquecommand(cmd);
  8648. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  8649. SERIAL_ECHOPGM("Position read from eeprom:");
  8650. MYSERIAL.println(position);
  8651. // E axis relative mode.
  8652. enquecommand_P(PSTR("M83"));
  8653. // Move to the XY print position in logical coordinates, where the print has been killed.
  8654. strcpy_P(cmd, PSTR("G1 X")); strcat(cmd, ftostr32(eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0))));
  8655. strcat_P(cmd, PSTR(" Y")); strcat(cmd, ftostr32(eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4))));
  8656. strcat_P(cmd, PSTR(" F2000"));
  8657. enquecommand(cmd);
  8658. //moving on Z axis ahead, set EEPROM_UVLO to 1, so normal uvlo can fire
  8659. eeprom_update_byte((uint8_t*)EEPROM_UVLO,1);
  8660. // Move the Z axis down to the print, in logical coordinates.
  8661. strcpy_P(cmd, PSTR("G1 Z")); strcat(cmd, ftostr32(eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z))));
  8662. enquecommand(cmd);
  8663. // Unretract.
  8664. enquecommand_P(PSTR("G1 E" STRINGIFY(2*default_retraction)" F480"));
  8665. // Set the feedrate saved at the power panic.
  8666. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  8667. enquecommand(cmd);
  8668. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  8669. {
  8670. enquecommand_P(PSTR("M82")); //E axis abslute mode
  8671. }
  8672. // Set the fan speed saved at the power panic.
  8673. strcpy_P(cmd, PSTR("M106 S"));
  8674. strcat(cmd, itostr3(int(fan_speed_rec)));
  8675. enquecommand(cmd);
  8676. // Set a position in the file.
  8677. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  8678. enquecommand(cmd);
  8679. enquecommand_P(PSTR("G4 S0"));
  8680. enquecommand_P(PSTR("PRUSA uvlo"));
  8681. }
  8682. #endif //UVLO_SUPPORT
  8683. //! @brief Immediately stop print moves
  8684. //!
  8685. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  8686. //! If printing from sd card, position in file is saved.
  8687. //! If printing from USB, line number is saved.
  8688. //!
  8689. //! @param z_move
  8690. //! @param e_move
  8691. void stop_and_save_print_to_ram(float z_move, float e_move)
  8692. {
  8693. if (saved_printing) return;
  8694. #if 0
  8695. unsigned char nplanner_blocks;
  8696. #endif
  8697. unsigned char nlines;
  8698. uint16_t sdlen_planner;
  8699. uint16_t sdlen_cmdqueue;
  8700. cli();
  8701. if (card.sdprinting) {
  8702. #if 0
  8703. nplanner_blocks = number_of_blocks();
  8704. #endif
  8705. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  8706. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  8707. saved_sdpos -= sdlen_planner;
  8708. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  8709. saved_sdpos -= sdlen_cmdqueue;
  8710. saved_printing_type = PRINTING_TYPE_SD;
  8711. }
  8712. else if (is_usb_printing) { //reuse saved_sdpos for storing line number
  8713. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  8714. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  8715. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  8716. saved_sdpos -= nlines;
  8717. saved_sdpos -= buflen; //number of blocks in cmd buffer
  8718. saved_printing_type = PRINTING_TYPE_USB;
  8719. }
  8720. else {
  8721. saved_printing_type = PRINTING_TYPE_NONE;
  8722. //not sd printing nor usb printing
  8723. }
  8724. #if 0
  8725. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  8726. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  8727. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  8728. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  8729. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  8730. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  8731. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  8732. {
  8733. card.setIndex(saved_sdpos);
  8734. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  8735. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  8736. MYSERIAL.print(char(card.get()));
  8737. SERIAL_ECHOLNPGM("Content of command buffer: ");
  8738. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  8739. MYSERIAL.print(char(card.get()));
  8740. SERIAL_ECHOLNPGM("End of command buffer");
  8741. }
  8742. {
  8743. // Print the content of the planner buffer, line by line:
  8744. card.setIndex(saved_sdpos);
  8745. int8_t iline = 0;
  8746. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  8747. SERIAL_ECHOPGM("Planner line (from file): ");
  8748. MYSERIAL.print(int(iline), DEC);
  8749. SERIAL_ECHOPGM(", length: ");
  8750. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  8751. SERIAL_ECHOPGM(", steps: (");
  8752. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  8753. SERIAL_ECHOPGM(",");
  8754. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  8755. SERIAL_ECHOPGM(",");
  8756. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  8757. SERIAL_ECHOPGM(",");
  8758. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  8759. SERIAL_ECHOPGM("), events: ");
  8760. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  8761. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  8762. MYSERIAL.print(char(card.get()));
  8763. }
  8764. }
  8765. {
  8766. // Print the content of the command buffer, line by line:
  8767. int8_t iline = 0;
  8768. union {
  8769. struct {
  8770. char lo;
  8771. char hi;
  8772. } lohi;
  8773. uint16_t value;
  8774. } sdlen_single;
  8775. int _bufindr = bufindr;
  8776. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  8777. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  8778. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  8779. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  8780. }
  8781. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  8782. MYSERIAL.print(int(iline), DEC);
  8783. SERIAL_ECHOPGM(", type: ");
  8784. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  8785. SERIAL_ECHOPGM(", len: ");
  8786. MYSERIAL.println(sdlen_single.value, DEC);
  8787. // Print the content of the buffer line.
  8788. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  8789. SERIAL_ECHOPGM("Buffer line (from file): ");
  8790. MYSERIAL.println(int(iline), DEC);
  8791. for (; sdlen_single.value > 0; -- sdlen_single.value)
  8792. MYSERIAL.print(char(card.get()));
  8793. if (-- _buflen == 0)
  8794. break;
  8795. // First skip the current command ID and iterate up to the end of the string.
  8796. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  8797. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  8798. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  8799. // If the end of the buffer was empty,
  8800. if (_bufindr == sizeof(cmdbuffer)) {
  8801. // skip to the start and find the nonzero command.
  8802. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  8803. }
  8804. }
  8805. }
  8806. #endif
  8807. #if 0
  8808. saved_feedrate2 = feedrate; //save feedrate
  8809. #else
  8810. // Try to deduce the feedrate from the first block of the planner.
  8811. // Speed is in mm/min.
  8812. saved_feedrate2 = blocks_queued() ? (block_buffer[block_buffer_tail].nominal_speed * 60.f) : feedrate;
  8813. #endif
  8814. planner_abort_hard(); //abort printing
  8815. memcpy(saved_pos, current_position, sizeof(saved_pos));
  8816. saved_active_extruder = active_extruder; //save active_extruder
  8817. saved_extruder_temperature = degTargetHotend(active_extruder);
  8818. saved_extruder_under_pressure = extruder_under_pressure; //extruder under pressure flag - currently unused
  8819. saved_extruder_relative_mode = axis_relative_modes[E_AXIS];
  8820. saved_fanSpeed = fanSpeed;
  8821. cmdqueue_reset(); //empty cmdqueue
  8822. card.sdprinting = false;
  8823. // card.closefile();
  8824. saved_printing = true;
  8825. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  8826. st_reset_timer();
  8827. sei();
  8828. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  8829. #if 1
  8830. // Rather than calling plan_buffer_line directly, push the move into the command queue,
  8831. char buf[48];
  8832. // First unretract (relative extrusion)
  8833. if(!saved_extruder_relative_mode){
  8834. enquecommand(PSTR("M83"), true);
  8835. }
  8836. //retract 45mm/s
  8837. // A single sprintf may not be faster, but is definitely 20B shorter
  8838. // than a sequence of commands building the string piece by piece
  8839. // A snprintf would have been a safer call, but since it is not used
  8840. // in the whole program, its implementation would bring more bytes to the total size
  8841. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  8842. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  8843. enquecommand(buf, false);
  8844. // Then lift Z axis
  8845. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  8846. // At this point the command queue is empty.
  8847. enquecommand(buf, false);
  8848. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  8849. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  8850. repeatcommand_front();
  8851. #else
  8852. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS] + z_move, saved_pos[E_AXIS] + e_move, homing_feedrate[Z_AXIS], active_extruder);
  8853. st_synchronize(); //wait moving
  8854. memcpy(current_position, saved_pos, sizeof(saved_pos));
  8855. memcpy(destination, current_position, sizeof(destination));
  8856. #endif
  8857. }
  8858. }
  8859. //! @brief Restore print from ram
  8860. //!
  8861. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  8862. //! print fan speed, waits for extruder temperature restore, then restores
  8863. //! position and continues print moves.
  8864. //!
  8865. //! Internally lcd_update() is called by wait_for_heater().
  8866. //!
  8867. //! @param e_move
  8868. void restore_print_from_ram_and_continue(float e_move)
  8869. {
  8870. if (!saved_printing) return;
  8871. #ifdef FANCHECK
  8872. // Do not allow resume printing if fans are still not ok
  8873. if( fan_check_error != EFCE_OK )return;
  8874. #endif
  8875. // for (int axis = X_AXIS; axis <= E_AXIS; axis++)
  8876. // current_position[axis] = st_get_position_mm(axis);
  8877. active_extruder = saved_active_extruder; //restore active_extruder
  8878. fanSpeed = saved_fanSpeed;
  8879. if (degTargetHotend(saved_active_extruder) != saved_extruder_temperature)
  8880. {
  8881. setTargetHotendSafe(saved_extruder_temperature, saved_active_extruder);
  8882. heating_status = 1;
  8883. wait_for_heater(_millis(), saved_active_extruder);
  8884. heating_status = 2;
  8885. }
  8886. feedrate = saved_feedrate2; //restore feedrate
  8887. axis_relative_modes[E_AXIS] = saved_extruder_relative_mode;
  8888. float e = saved_pos[E_AXIS] - e_move;
  8889. plan_set_e_position(e);
  8890. #ifdef FANCHECK
  8891. fans_check_enabled = false;
  8892. #endif
  8893. //first move print head in XY to the saved position:
  8894. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], current_position[Z_AXIS], saved_pos[E_AXIS] - e_move, homing_feedrate[Z_AXIS]/13, active_extruder);
  8895. st_synchronize();
  8896. //then move Z
  8897. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS] - e_move, homing_feedrate[Z_AXIS]/13, active_extruder);
  8898. st_synchronize();
  8899. //and finaly unretract (35mm/s)
  8900. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], 35, active_extruder);
  8901. st_synchronize();
  8902. #ifdef FANCHECK
  8903. fans_check_enabled = true;
  8904. #endif
  8905. memcpy(current_position, saved_pos, sizeof(saved_pos));
  8906. memcpy(destination, current_position, sizeof(destination));
  8907. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  8908. card.setIndex(saved_sdpos);
  8909. sdpos_atomic = saved_sdpos;
  8910. card.sdprinting = true;
  8911. }
  8912. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  8913. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  8914. serial_count = 0;
  8915. FlushSerialRequestResend();
  8916. }
  8917. else {
  8918. //not sd printing nor usb printing
  8919. }
  8920. printf_P(PSTR("ok\n")); //dummy response because of octoprint is waiting for this
  8921. lcd_setstatuspgm(_T(WELCOME_MSG));
  8922. saved_printing = false;
  8923. }
  8924. void print_world_coordinates()
  8925. {
  8926. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  8927. }
  8928. void print_physical_coordinates()
  8929. {
  8930. printf_P(_N("physical coordinates: (%.3f, %.3f, %.3f)\n"), st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS), st_get_position_mm(Z_AXIS));
  8931. }
  8932. void print_mesh_bed_leveling_table()
  8933. {
  8934. SERIAL_ECHOPGM("mesh bed leveling: ");
  8935. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  8936. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  8937. MYSERIAL.print(mbl.z_values[y][x], 3);
  8938. SERIAL_ECHOPGM(" ");
  8939. }
  8940. SERIAL_ECHOLNPGM("");
  8941. }
  8942. uint16_t print_time_remaining() {
  8943. uint16_t print_t = PRINT_TIME_REMAINING_INIT;
  8944. #ifdef TMC2130
  8945. if (SilentModeMenu == SILENT_MODE_OFF) print_t = print_time_remaining_normal;
  8946. else print_t = print_time_remaining_silent;
  8947. #else
  8948. print_t = print_time_remaining_normal;
  8949. #endif //TMC2130
  8950. if ((print_t != PRINT_TIME_REMAINING_INIT) && (feedmultiply != 0)) print_t = 100ul * print_t / feedmultiply;
  8951. return print_t;
  8952. }
  8953. uint8_t calc_percent_done()
  8954. {
  8955. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  8956. uint8_t percent_done = 0;
  8957. #ifdef TMC2130
  8958. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100) {
  8959. percent_done = print_percent_done_normal;
  8960. }
  8961. else if (print_percent_done_silent <= 100) {
  8962. percent_done = print_percent_done_silent;
  8963. }
  8964. #else
  8965. if (print_percent_done_normal <= 100) {
  8966. percent_done = print_percent_done_normal;
  8967. }
  8968. #endif //TMC2130
  8969. else {
  8970. percent_done = card.percentDone();
  8971. }
  8972. return percent_done;
  8973. }
  8974. static void print_time_remaining_init()
  8975. {
  8976. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  8977. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  8978. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  8979. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  8980. }
  8981. void load_filament_final_feed()
  8982. {
  8983. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  8984. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_EFEED_FINAL, active_extruder);
  8985. }
  8986. //! @brief Wait for user to check the state
  8987. //! @par nozzle_temp nozzle temperature to load filament
  8988. void M600_check_state(float nozzle_temp)
  8989. {
  8990. lcd_change_fil_state = 0;
  8991. while (lcd_change_fil_state != 1)
  8992. {
  8993. lcd_change_fil_state = 0;
  8994. KEEPALIVE_STATE(PAUSED_FOR_USER);
  8995. lcd_alright();
  8996. KEEPALIVE_STATE(IN_HANDLER);
  8997. switch(lcd_change_fil_state)
  8998. {
  8999. // Filament failed to load so load it again
  9000. case 2:
  9001. if (mmu_enabled)
  9002. mmu_M600_load_filament(false, nozzle_temp); //nonautomatic load; change to "wrong filament loaded" option?
  9003. else
  9004. M600_load_filament_movements();
  9005. break;
  9006. // Filament loaded properly but color is not clear
  9007. case 3:
  9008. st_synchronize();
  9009. load_filament_final_feed();
  9010. lcd_loading_color();
  9011. st_synchronize();
  9012. break;
  9013. // Everything good
  9014. default:
  9015. lcd_change_success();
  9016. break;
  9017. }
  9018. }
  9019. }
  9020. //! @brief Wait for user action
  9021. //!
  9022. //! Beep, manage nozzle heater and wait for user to start unload filament
  9023. //! If times out, active extruder temperature is set to 0.
  9024. //!
  9025. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  9026. void M600_wait_for_user(float HotendTempBckp) {
  9027. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9028. int counterBeep = 0;
  9029. unsigned long waiting_start_time = _millis();
  9030. uint8_t wait_for_user_state = 0;
  9031. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9032. bool bFirst=true;
  9033. while (!(wait_for_user_state == 0 && lcd_clicked())){
  9034. manage_heater();
  9035. manage_inactivity(true);
  9036. #if BEEPER > 0
  9037. if (counterBeep == 500) {
  9038. counterBeep = 0;
  9039. }
  9040. SET_OUTPUT(BEEPER);
  9041. if (counterBeep == 0) {
  9042. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  9043. {
  9044. bFirst=false;
  9045. WRITE(BEEPER, HIGH);
  9046. }
  9047. }
  9048. if (counterBeep == 20) {
  9049. WRITE(BEEPER, LOW);
  9050. }
  9051. counterBeep++;
  9052. #endif //BEEPER > 0
  9053. switch (wait_for_user_state) {
  9054. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  9055. delay_keep_alive(4);
  9056. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  9057. lcd_display_message_fullscreen_P(_i("Press knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  9058. wait_for_user_state = 1;
  9059. setAllTargetHotends(0);
  9060. st_synchronize();
  9061. disable_e0();
  9062. disable_e1();
  9063. disable_e2();
  9064. }
  9065. break;
  9066. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  9067. delay_keep_alive(4);
  9068. if (lcd_clicked()) {
  9069. setTargetHotend(HotendTempBckp, active_extruder);
  9070. lcd_wait_for_heater();
  9071. wait_for_user_state = 2;
  9072. }
  9073. break;
  9074. case 2: //waiting for nozzle to reach target temperature
  9075. if (abs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  9076. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9077. waiting_start_time = _millis();
  9078. wait_for_user_state = 0;
  9079. }
  9080. else {
  9081. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  9082. lcd_set_cursor(1, 4);
  9083. lcd_print(ftostr3(degHotend(active_extruder)));
  9084. }
  9085. break;
  9086. }
  9087. }
  9088. WRITE(BEEPER, LOW);
  9089. }
  9090. void M600_load_filament_movements()
  9091. {
  9092. #ifdef SNMM
  9093. display_loading();
  9094. do
  9095. {
  9096. current_position[E_AXIS] += 0.002;
  9097. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 500, active_extruder);
  9098. delay_keep_alive(2);
  9099. }
  9100. while (!lcd_clicked());
  9101. st_synchronize();
  9102. current_position[E_AXIS] += bowden_length[mmu_extruder];
  9103. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000, active_extruder);
  9104. current_position[E_AXIS] += FIL_LOAD_LENGTH - 60;
  9105. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 1400, active_extruder);
  9106. current_position[E_AXIS] += 40;
  9107. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  9108. current_position[E_AXIS] += 10;
  9109. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 50, active_extruder);
  9110. #else
  9111. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  9112. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_EFEED_FIRST, active_extruder);
  9113. #endif
  9114. load_filament_final_feed();
  9115. lcd_loading_filament();
  9116. st_synchronize();
  9117. }
  9118. void M600_load_filament() {
  9119. //load filament for single material and SNMM
  9120. lcd_wait_interact();
  9121. //load_filament_time = _millis();
  9122. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9123. #ifdef PAT9125
  9124. fsensor_autoload_check_start();
  9125. #endif //PAT9125
  9126. while(!lcd_clicked())
  9127. {
  9128. manage_heater();
  9129. manage_inactivity(true);
  9130. #ifdef FILAMENT_SENSOR
  9131. if (fsensor_check_autoload())
  9132. {
  9133. Sound_MakeCustom(50,1000,false);
  9134. break;
  9135. }
  9136. #endif //FILAMENT_SENSOR
  9137. }
  9138. #ifdef PAT9125
  9139. fsensor_autoload_check_stop();
  9140. #endif //PAT9125
  9141. KEEPALIVE_STATE(IN_HANDLER);
  9142. #ifdef FSENSOR_QUALITY
  9143. fsensor_oq_meassure_start(70);
  9144. #endif //FSENSOR_QUALITY
  9145. M600_load_filament_movements();
  9146. Sound_MakeCustom(50,1000,false);
  9147. #ifdef FSENSOR_QUALITY
  9148. fsensor_oq_meassure_stop();
  9149. if (!fsensor_oq_result())
  9150. {
  9151. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Fil. sensor response is poor, disable it?"), false, true);
  9152. lcd_update_enable(true);
  9153. lcd_update(2);
  9154. if (disable)
  9155. fsensor_disable();
  9156. }
  9157. #endif //FSENSOR_QUALITY
  9158. lcd_update_enable(false);
  9159. }
  9160. //! @brief Wait for click
  9161. //!
  9162. //! Set
  9163. void marlin_wait_for_click()
  9164. {
  9165. int8_t busy_state_backup = busy_state;
  9166. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9167. lcd_consume_click();
  9168. while(!lcd_clicked())
  9169. {
  9170. manage_heater();
  9171. manage_inactivity(true);
  9172. lcd_update(0);
  9173. }
  9174. KEEPALIVE_STATE(busy_state_backup);
  9175. }
  9176. #define FIL_LOAD_LENGTH 60
  9177. #ifdef PSU_Delta
  9178. bool bEnableForce_z;
  9179. void init_force_z()
  9180. {
  9181. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  9182. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  9183. disable_force_z();
  9184. }
  9185. void check_force_z()
  9186. {
  9187. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  9188. init_force_z(); // causes enforced switching into disable-state
  9189. }
  9190. void disable_force_z()
  9191. {
  9192. uint16_t z_microsteps=0;
  9193. if(!bEnableForce_z)
  9194. return; // motor already disabled (may be ;-p )
  9195. bEnableForce_z=false;
  9196. // alignment to full-step
  9197. #ifdef TMC2130
  9198. z_microsteps=tmc2130_rd_MSCNT(Z_TMC2130_CS);
  9199. #endif // TMC2130
  9200. planner_abort_hard();
  9201. sei();
  9202. plan_buffer_line(
  9203. current_position[X_AXIS],
  9204. current_position[Y_AXIS],
  9205. current_position[Z_AXIS]+float((1024-z_microsteps+7)>>4)/cs.axis_steps_per_unit[Z_AXIS],
  9206. current_position[E_AXIS],
  9207. 40, active_extruder);
  9208. st_synchronize();
  9209. // switching to silent mode
  9210. #ifdef TMC2130
  9211. tmc2130_mode=TMC2130_MODE_SILENT;
  9212. update_mode_profile();
  9213. tmc2130_init(true);
  9214. #endif // TMC2130
  9215. axis_known_position[Z_AXIS]=false;
  9216. }
  9217. void enable_force_z()
  9218. {
  9219. if(bEnableForce_z)
  9220. return; // motor already enabled (may be ;-p )
  9221. bEnableForce_z=true;
  9222. // mode recovering
  9223. #ifdef TMC2130
  9224. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  9225. update_mode_profile();
  9226. tmc2130_init(true);
  9227. #endif // TMC2130
  9228. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  9229. }
  9230. #endif // PSU_Delta