Marlin_main.cpp 332 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742
  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. #include "Marlin.h"
  45. #ifdef ENABLE_AUTO_BED_LEVELING
  46. #include "vector_3.h"
  47. #ifdef AUTO_BED_LEVELING_GRID
  48. #include "qr_solve.h"
  49. #endif
  50. #endif // ENABLE_AUTO_BED_LEVELING
  51. #ifdef MESH_BED_LEVELING
  52. #include "mesh_bed_leveling.h"
  53. #include "mesh_bed_calibration.h"
  54. #endif
  55. #include "printers.h"
  56. #include "menu.h"
  57. #include "ultralcd.h"
  58. #include "planner.h"
  59. #include "stepper.h"
  60. #include "temperature.h"
  61. #include "motion_control.h"
  62. #include "cardreader.h"
  63. #include "ConfigurationStore.h"
  64. #include "language.h"
  65. #include "pins_arduino.h"
  66. #include "math.h"
  67. #include "util.h"
  68. #include "Timer.h"
  69. #include <avr/wdt.h>
  70. #include <avr/pgmspace.h>
  71. #include "Dcodes.h"
  72. #include "AutoDeplete.h"
  73. #ifdef SWSPI
  74. #include "swspi.h"
  75. #endif //SWSPI
  76. #include "spi.h"
  77. #ifdef SWI2C
  78. #include "swi2c.h"
  79. #endif //SWI2C
  80. #ifdef FILAMENT_SENSOR
  81. #include "fsensor.h"
  82. #endif //FILAMENT_SENSOR
  83. #ifdef TMC2130
  84. #include "tmc2130.h"
  85. #endif //TMC2130
  86. #ifdef W25X20CL
  87. #include "w25x20cl.h"
  88. #include "optiboot_w25x20cl.h"
  89. #endif //W25X20CL
  90. #ifdef BLINKM
  91. #include "BlinkM.h"
  92. #include "Wire.h"
  93. #endif
  94. #ifdef ULTRALCD
  95. #include "ultralcd.h"
  96. #endif
  97. #if NUM_SERVOS > 0
  98. #include "Servo.h"
  99. #endif
  100. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  101. #include <SPI.h>
  102. #endif
  103. #include "mmu.h"
  104. #define VERSION_STRING "1.0.2"
  105. #include "ultralcd.h"
  106. #include "sound.h"
  107. #include "cmdqueue.h"
  108. #include "io_atmega2560.h"
  109. // Macros for bit masks
  110. #define BIT(b) (1<<(b))
  111. #define TEST(n,b) (((n)&BIT(b))!=0)
  112. #define SET_BIT(n,b,value) (n) ^= ((-value)^(n)) & (BIT(b))
  113. //Macro for print fan speed
  114. #define FAN_PULSE_WIDTH_LIMIT ((fanSpeed > 100) ? 3 : 4) //time in ms
  115. #define PRINTING_TYPE_SD 0
  116. #define PRINTING_TYPE_USB 1
  117. #define PRINTING_TYPE_NONE 2
  118. //filament types
  119. #define FILAMENT_DEFAULT 0
  120. #define FILAMENT_FLEX 1
  121. #define FILAMENT_PVA 2
  122. #define FILAMENT_UNDEFINED 255
  123. //Stepper Movement Variables
  124. //===========================================================================
  125. //=============================imported variables============================
  126. //===========================================================================
  127. //===========================================================================
  128. //=============================public variables=============================
  129. //===========================================================================
  130. #ifdef SDSUPPORT
  131. CardReader card;
  132. #endif
  133. unsigned long PingTime = _millis();
  134. unsigned long NcTime;
  135. uint8_t mbl_z_probe_nr = 3; //numer of Z measurements for each point in mesh bed leveling calibration
  136. //used for PINDA temp calibration and pause print
  137. #define DEFAULT_RETRACTION 1
  138. #define DEFAULT_RETRACTION_MM 4 //MM
  139. float default_retraction = DEFAULT_RETRACTION;
  140. float homing_feedrate[] = HOMING_FEEDRATE;
  141. // Currently only the extruder axis may be switched to a relative mode.
  142. // Other axes are always absolute or relative based on the common relative_mode flag.
  143. bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
  144. int feedmultiply=100; //100->1 200->2
  145. int extrudemultiply=100; //100->1 200->2
  146. int extruder_multiply[EXTRUDERS] = {100
  147. #if EXTRUDERS > 1
  148. , 100
  149. #if EXTRUDERS > 2
  150. , 100
  151. #endif
  152. #endif
  153. };
  154. int bowden_length[4] = {385, 385, 385, 385};
  155. bool is_usb_printing = false;
  156. bool homing_flag = false;
  157. bool temp_cal_active = false;
  158. unsigned long kicktime = _millis()+100000;
  159. unsigned int usb_printing_counter;
  160. int8_t lcd_change_fil_state = 0;
  161. unsigned long pause_time = 0;
  162. unsigned long start_pause_print = _millis();
  163. unsigned long t_fan_rising_edge = _millis();
  164. LongTimer safetyTimer;
  165. static LongTimer crashDetTimer;
  166. //unsigned long load_filament_time;
  167. bool mesh_bed_leveling_flag = false;
  168. bool mesh_bed_run_from_menu = false;
  169. bool prusa_sd_card_upload = false;
  170. unsigned int status_number = 0;
  171. unsigned long total_filament_used;
  172. unsigned int heating_status;
  173. unsigned int heating_status_counter;
  174. bool loading_flag = false;
  175. char snmm_filaments_used = 0;
  176. bool fan_state[2];
  177. int fan_edge_counter[2];
  178. int fan_speed[2];
  179. char dir_names[3][9];
  180. bool sortAlpha = false;
  181. float extruder_multiplier[EXTRUDERS] = {1.0
  182. #if EXTRUDERS > 1
  183. , 1.0
  184. #if EXTRUDERS > 2
  185. , 1.0
  186. #endif
  187. #endif
  188. };
  189. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  190. //shortcuts for more readable code
  191. #define _x current_position[X_AXIS]
  192. #define _y current_position[Y_AXIS]
  193. #define _z current_position[Z_AXIS]
  194. #define _e current_position[E_AXIS]
  195. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  196. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  197. bool axis_known_position[3] = {false, false, false};
  198. // Extruder offset
  199. #if EXTRUDERS > 1
  200. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  201. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  202. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  203. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  204. #endif
  205. };
  206. #endif
  207. uint8_t active_extruder = 0;
  208. int fanSpeed=0;
  209. #ifdef FWRETRACT
  210. bool retracted[EXTRUDERS]={false
  211. #if EXTRUDERS > 1
  212. , false
  213. #if EXTRUDERS > 2
  214. , false
  215. #endif
  216. #endif
  217. };
  218. bool retracted_swap[EXTRUDERS]={false
  219. #if EXTRUDERS > 1
  220. , false
  221. #if EXTRUDERS > 2
  222. , false
  223. #endif
  224. #endif
  225. };
  226. float retract_length_swap = RETRACT_LENGTH_SWAP;
  227. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  228. #endif
  229. #ifdef PS_DEFAULT_OFF
  230. bool powersupply = false;
  231. #else
  232. bool powersupply = true;
  233. #endif
  234. bool cancel_heatup = false ;
  235. int8_t busy_state = NOT_BUSY;
  236. static long prev_busy_signal_ms = -1;
  237. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  238. const char errormagic[] PROGMEM = "Error:";
  239. const char echomagic[] PROGMEM = "echo:";
  240. bool no_response = false;
  241. uint8_t important_status;
  242. uint8_t saved_filament_type;
  243. // save/restore printing in case that mmu was not responding
  244. bool mmu_print_saved = false;
  245. // storing estimated time to end of print counted by slicer
  246. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  247. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  248. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  249. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  250. bool wizard_active = false; //autoload temporarily disabled during wizard
  251. //===========================================================================
  252. //=============================Private Variables=============================
  253. //===========================================================================
  254. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  255. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  256. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  257. // For tracing an arc
  258. static float offset[3] = {0.0, 0.0, 0.0};
  259. static float feedrate = 1500.0, next_feedrate, saved_feedrate;
  260. // Determines Absolute or Relative Coordinates.
  261. // Also there is bool axis_relative_modes[] per axis flag.
  262. static bool relative_mode = false;
  263. const int sensitive_pins[] = SENSITIVE_PINS; // Sensitive pin list for M42
  264. //static float tt = 0;
  265. //static float bt = 0;
  266. //Inactivity shutdown variables
  267. static unsigned long previous_millis_cmd = 0;
  268. unsigned long max_inactive_time = 0;
  269. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  270. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  271. unsigned long starttime=0;
  272. unsigned long stoptime=0;
  273. unsigned long _usb_timer = 0;
  274. bool extruder_under_pressure = true;
  275. bool Stopped=false;
  276. #if NUM_SERVOS > 0
  277. Servo servos[NUM_SERVOS];
  278. #endif
  279. bool CooldownNoWait = true;
  280. bool target_direction;
  281. //Insert variables if CHDK is defined
  282. #ifdef CHDK
  283. unsigned long chdkHigh = 0;
  284. boolean chdkActive = false;
  285. #endif
  286. //! @name RAM save/restore printing
  287. //! @{
  288. bool saved_printing = false; //!< Print is paused and saved in RAM
  289. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  290. static uint8_t saved_printing_type = PRINTING_TYPE_SD;
  291. static float saved_pos[4] = { 0, 0, 0, 0 };
  292. //! Feedrate hopefully derived from an active block of the planner at the time the print has been canceled, in mm/min.
  293. static float saved_feedrate2 = 0;
  294. static uint8_t saved_active_extruder = 0;
  295. static float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  296. static bool saved_extruder_under_pressure = false;
  297. static bool saved_extruder_relative_mode = false;
  298. static int saved_fanSpeed = 0; //!< Print fan speed
  299. //! @}
  300. static int saved_feedmultiply_mm = 100;
  301. //===========================================================================
  302. //=============================Routines======================================
  303. //===========================================================================
  304. static void get_arc_coordinates();
  305. static bool setTargetedHotend(int code, uint8_t &extruder);
  306. static void print_time_remaining_init();
  307. static void wait_for_heater(long codenum, uint8_t extruder);
  308. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
  309. uint16_t gcode_in_progress = 0;
  310. uint16_t mcode_in_progress = 0;
  311. void serial_echopair_P(const char *s_P, float v)
  312. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  313. void serial_echopair_P(const char *s_P, double v)
  314. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  315. void serial_echopair_P(const char *s_P, unsigned long v)
  316. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  317. #ifdef SDSUPPORT
  318. #include "SdFatUtil.h"
  319. int freeMemory() { return SdFatUtil::FreeRam(); }
  320. #else
  321. extern "C" {
  322. extern unsigned int __bss_end;
  323. extern unsigned int __heap_start;
  324. extern void *__brkval;
  325. int freeMemory() {
  326. int free_memory;
  327. if ((int)__brkval == 0)
  328. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  329. else
  330. free_memory = ((int)&free_memory) - ((int)__brkval);
  331. return free_memory;
  332. }
  333. }
  334. #endif //!SDSUPPORT
  335. void setup_killpin()
  336. {
  337. #if defined(KILL_PIN) && KILL_PIN > -1
  338. SET_INPUT(KILL_PIN);
  339. WRITE(KILL_PIN,HIGH);
  340. #endif
  341. }
  342. // Set home pin
  343. void setup_homepin(void)
  344. {
  345. #if defined(HOME_PIN) && HOME_PIN > -1
  346. SET_INPUT(HOME_PIN);
  347. WRITE(HOME_PIN,HIGH);
  348. #endif
  349. }
  350. void setup_photpin()
  351. {
  352. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  353. SET_OUTPUT(PHOTOGRAPH_PIN);
  354. WRITE(PHOTOGRAPH_PIN, LOW);
  355. #endif
  356. }
  357. void setup_powerhold()
  358. {
  359. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  360. SET_OUTPUT(SUICIDE_PIN);
  361. WRITE(SUICIDE_PIN, HIGH);
  362. #endif
  363. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  364. SET_OUTPUT(PS_ON_PIN);
  365. #if defined(PS_DEFAULT_OFF)
  366. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  367. #else
  368. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  369. #endif
  370. #endif
  371. }
  372. void suicide()
  373. {
  374. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  375. SET_OUTPUT(SUICIDE_PIN);
  376. WRITE(SUICIDE_PIN, LOW);
  377. #endif
  378. }
  379. void servo_init()
  380. {
  381. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  382. servos[0].attach(SERVO0_PIN);
  383. #endif
  384. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  385. servos[1].attach(SERVO1_PIN);
  386. #endif
  387. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  388. servos[2].attach(SERVO2_PIN);
  389. #endif
  390. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  391. servos[3].attach(SERVO3_PIN);
  392. #endif
  393. #if (NUM_SERVOS >= 5)
  394. #error "TODO: enter initalisation code for more servos"
  395. #endif
  396. }
  397. bool fans_check_enabled = true;
  398. #ifdef TMC2130
  399. extern int8_t CrashDetectMenu;
  400. void crashdet_enable()
  401. {
  402. tmc2130_sg_stop_on_crash = true;
  403. eeprom_update_byte((uint8_t*)EEPROM_CRASH_DET, 0xFF);
  404. CrashDetectMenu = 1;
  405. }
  406. void crashdet_disable()
  407. {
  408. tmc2130_sg_stop_on_crash = false;
  409. tmc2130_sg_crash = 0;
  410. eeprom_update_byte((uint8_t*)EEPROM_CRASH_DET, 0x00);
  411. CrashDetectMenu = 0;
  412. }
  413. void crashdet_stop_and_save_print()
  414. {
  415. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  416. }
  417. void crashdet_restore_print_and_continue()
  418. {
  419. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  420. // babystep_apply();
  421. }
  422. void crashdet_stop_and_save_print2()
  423. {
  424. cli();
  425. planner_abort_hard(); //abort printing
  426. cmdqueue_reset(); //empty cmdqueue
  427. card.sdprinting = false;
  428. card.closefile();
  429. // Reset and re-enable the stepper timer just before the global interrupts are enabled.
  430. st_reset_timer();
  431. sei();
  432. }
  433. void crashdet_detected(uint8_t mask)
  434. {
  435. st_synchronize();
  436. static uint8_t crashDet_counter = 0;
  437. bool automatic_recovery_after_crash = true;
  438. if (crashDet_counter++ == 0) {
  439. crashDetTimer.start();
  440. }
  441. else if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)){
  442. crashDetTimer.stop();
  443. crashDet_counter = 0;
  444. }
  445. else if(crashDet_counter == CRASHDET_COUNTER_MAX){
  446. automatic_recovery_after_crash = false;
  447. crashDetTimer.stop();
  448. crashDet_counter = 0;
  449. }
  450. else {
  451. crashDetTimer.start();
  452. }
  453. lcd_update_enable(true);
  454. lcd_clear();
  455. lcd_update(2);
  456. if (mask & X_AXIS_MASK)
  457. {
  458. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_X, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_X) + 1);
  459. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT) + 1);
  460. }
  461. if (mask & Y_AXIS_MASK)
  462. {
  463. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_Y, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_Y) + 1);
  464. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT) + 1);
  465. }
  466. lcd_update_enable(true);
  467. lcd_update(2);
  468. lcd_setstatuspgm(_T(MSG_CRASH_DETECTED));
  469. gcode_G28(true, true, false); //home X and Y
  470. st_synchronize();
  471. if (automatic_recovery_after_crash) {
  472. enquecommand_P(PSTR("CRASH_RECOVER"));
  473. }else{
  474. setTargetHotend(0, active_extruder);
  475. bool yesno = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Crash detected. Resume print?"), false);
  476. lcd_update_enable(true);
  477. if (yesno)
  478. {
  479. enquecommand_P(PSTR("CRASH_RECOVER"));
  480. }
  481. else
  482. {
  483. enquecommand_P(PSTR("CRASH_CANCEL"));
  484. }
  485. }
  486. }
  487. void crashdet_recover()
  488. {
  489. crashdet_restore_print_and_continue();
  490. tmc2130_sg_stop_on_crash = true;
  491. }
  492. void crashdet_cancel()
  493. {
  494. saved_printing = false;
  495. tmc2130_sg_stop_on_crash = true;
  496. if (saved_printing_type == PRINTING_TYPE_SD) {
  497. lcd_print_stop();
  498. }else if(saved_printing_type == PRINTING_TYPE_USB){
  499. SERIAL_ECHOLNPGM("// action:cancel"); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  500. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  501. }
  502. }
  503. #endif //TMC2130
  504. void failstats_reset_print()
  505. {
  506. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  507. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  508. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  509. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  510. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  511. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  512. }
  513. #ifdef MESH_BED_LEVELING
  514. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  515. #endif
  516. // Factory reset function
  517. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  518. // Level input parameter sets depth of reset
  519. int er_progress = 0;
  520. static void factory_reset(char level)
  521. {
  522. lcd_clear();
  523. switch (level) {
  524. // Level 0: Language reset
  525. case 0:
  526. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  527. WRITE(BEEPER, HIGH);
  528. _delay_ms(100);
  529. WRITE(BEEPER, LOW);
  530. lang_reset();
  531. break;
  532. //Level 1: Reset statistics
  533. case 1:
  534. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  535. WRITE(BEEPER, HIGH);
  536. _delay_ms(100);
  537. WRITE(BEEPER, LOW);
  538. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  539. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  540. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  541. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  542. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  543. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  544. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  545. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  546. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  547. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  548. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  549. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  550. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  551. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  552. lcd_menu_statistics();
  553. break;
  554. // Level 2: Prepare for shipping
  555. case 2:
  556. //lcd_puts_P(PSTR("Factory RESET"));
  557. //lcd_puts_at_P(1,2,PSTR("Shipping prep"));
  558. // Force language selection at the next boot up.
  559. lang_reset();
  560. // Force the "Follow calibration flow" message at the next boot up.
  561. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  562. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  563. farm_no = 0;
  564. farm_mode = false;
  565. eeprom_update_byte((uint8_t*)EEPROM_FARM_MODE, farm_mode);
  566. EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
  567. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  568. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  569. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  570. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  571. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  572. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  573. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  574. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  575. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  576. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  577. #ifdef FILAMENT_SENSOR
  578. fsensor_enable();
  579. fsensor_autoload_set(true);
  580. #endif //FILAMENT_SENSOR
  581. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  582. WRITE(BEEPER, HIGH);
  583. _delay_ms(100);
  584. WRITE(BEEPER, LOW);
  585. //_delay_ms(2000);
  586. break;
  587. // Level 3: erase everything, whole EEPROM will be set to 0xFF
  588. case 3:
  589. lcd_puts_P(PSTR("Factory RESET"));
  590. lcd_puts_at_P(1, 2, PSTR("ERASING all data"));
  591. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  592. WRITE(BEEPER, HIGH);
  593. _delay_ms(100);
  594. WRITE(BEEPER, LOW);
  595. er_progress = 0;
  596. lcd_puts_at_P(3, 3, PSTR(" "));
  597. lcd_set_cursor(3, 3);
  598. lcd_print(er_progress);
  599. // Erase EEPROM
  600. for (int i = 0; i < 4096; i++) {
  601. eeprom_update_byte((uint8_t*)i, 0xFF);
  602. if (i % 41 == 0) {
  603. er_progress++;
  604. lcd_puts_at_P(3, 3, PSTR(" "));
  605. lcd_set_cursor(3, 3);
  606. lcd_print(er_progress);
  607. lcd_puts_P(PSTR("%"));
  608. }
  609. }
  610. break;
  611. case 4:
  612. bowden_menu();
  613. break;
  614. default:
  615. break;
  616. }
  617. }
  618. extern "C" {
  619. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  620. }
  621. int uart_putchar(char c, FILE *)
  622. {
  623. MYSERIAL.write(c);
  624. return 0;
  625. }
  626. void lcd_splash()
  627. {
  628. // lcd_puts_at_P(0, 1, PSTR(" Original Prusa "));
  629. // lcd_puts_at_P(0, 2, PSTR(" 3D Printers "));
  630. // lcd_puts_P(PSTR("\x1b[1;3HOriginal Prusa\x1b[2;4H3D Printers"));
  631. // fputs_P(PSTR(ESC_2J ESC_H(1,1) "Original Prusa i3" ESC_H(3,2) "Prusa Research"), lcdout);
  632. lcd_puts_P(PSTR(ESC_2J ESC_H(1,1) "Original Prusa i3" ESC_H(3,2) "Prusa Research"));
  633. // lcd_printf_P(_N(ESC_2J "x:%.3f\ny:%.3f\nz:%.3f\ne:%.3f"), _x, _y, _z, _e);
  634. }
  635. void factory_reset()
  636. {
  637. KEEPALIVE_STATE(PAUSED_FOR_USER);
  638. if (!READ(BTN_ENC))
  639. {
  640. _delay_ms(1000);
  641. if (!READ(BTN_ENC))
  642. {
  643. lcd_clear();
  644. lcd_puts_P(PSTR("Factory RESET"));
  645. SET_OUTPUT(BEEPER);
  646. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  647. WRITE(BEEPER, HIGH);
  648. while (!READ(BTN_ENC));
  649. WRITE(BEEPER, LOW);
  650. _delay_ms(2000);
  651. char level = reset_menu();
  652. factory_reset(level);
  653. switch (level) {
  654. case 0: _delay_ms(0); break;
  655. case 1: _delay_ms(0); break;
  656. case 2: _delay_ms(0); break;
  657. case 3: _delay_ms(0); break;
  658. }
  659. }
  660. }
  661. KEEPALIVE_STATE(IN_HANDLER);
  662. }
  663. void show_fw_version_warnings() {
  664. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  665. switch (FW_DEV_VERSION) {
  666. 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
  667. 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
  668. case(FW_VERSION_DEVEL):
  669. case(FW_VERSION_DEBUG):
  670. lcd_update_enable(false);
  671. lcd_clear();
  672. #if FW_DEV_VERSION == FW_VERSION_DEVEL
  673. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  674. #else
  675. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  676. #endif
  677. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  678. lcd_puts_at_P(0, 2, PSTR("ver ")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  679. lcd_puts_at_P(0, 3, PSTR(FW_REPOSITORY));
  680. lcd_wait_for_click();
  681. break;
  682. // 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
  683. }
  684. lcd_update_enable(true);
  685. }
  686. //! @brief try to check if firmware is on right type of printer
  687. static void check_if_fw_is_on_right_printer(){
  688. #ifdef FILAMENT_SENSOR
  689. if((PRINTER_TYPE == PRINTER_MK3) || (PRINTER_TYPE == PRINTER_MK3S)){
  690. #ifdef IR_SENSOR
  691. swi2c_init();
  692. const uint8_t pat9125_detected = swi2c_readByte_A8(PAT9125_I2C_ADDR,0x00,NULL);
  693. if (pat9125_detected){
  694. lcd_show_fullscreen_message_and_wait_P(_i("MK3S firmware detected on MK3 printer"));}
  695. #endif //IR_SENSOR
  696. #ifdef PAT9125
  697. //will return 1 only if IR can detect filament in bondtech extruder so this may fail even when we have IR sensor
  698. const uint8_t ir_detected = !(PIN_GET(IR_SENSOR_PIN));
  699. if (ir_detected){
  700. lcd_show_fullscreen_message_and_wait_P(_i("MK3 firmware detected on MK3S printer"));}
  701. #endif //PAT9125
  702. }
  703. #endif //FILAMENT_SENSOR
  704. }
  705. uint8_t check_printer_version()
  706. {
  707. uint8_t version_changed = 0;
  708. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  709. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  710. if (printer_type != PRINTER_TYPE) {
  711. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  712. else version_changed |= 0b10;
  713. }
  714. if (motherboard != MOTHERBOARD) {
  715. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  716. else version_changed |= 0b01;
  717. }
  718. return version_changed;
  719. }
  720. #ifdef BOOTAPP
  721. #include "bootapp.h" //bootloader support
  722. #endif //BOOTAPP
  723. #if (LANG_MODE != 0) //secondary language support
  724. #ifdef W25X20CL
  725. // language update from external flash
  726. #define LANGBOOT_BLOCKSIZE 0x1000u
  727. #define LANGBOOT_RAMBUFFER 0x0800
  728. void update_sec_lang_from_external_flash()
  729. {
  730. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  731. {
  732. uint8_t lang = boot_reserved >> 4;
  733. uint8_t state = boot_reserved & 0xf;
  734. lang_table_header_t header;
  735. uint32_t src_addr;
  736. if (lang_get_header(lang, &header, &src_addr))
  737. {
  738. fputs_P(PSTR(ESC_H(1,3) "Language update."), lcdout);
  739. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  740. _delay(100);
  741. boot_reserved = (state + 1) | (lang << 4);
  742. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  743. {
  744. cli();
  745. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  746. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  747. w25x20cl_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  748. if (state == 0)
  749. {
  750. //TODO - check header integrity
  751. }
  752. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  753. }
  754. else
  755. {
  756. //TODO - check sec lang data integrity
  757. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  758. }
  759. }
  760. }
  761. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  762. }
  763. #ifdef DEBUG_W25X20CL
  764. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  765. {
  766. lang_table_header_t header;
  767. uint8_t count = 0;
  768. uint32_t addr = 0x00000;
  769. while (1)
  770. {
  771. printf_P(_n("LANGTABLE%d:"), count);
  772. w25x20cl_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  773. if (header.magic != LANG_MAGIC)
  774. {
  775. printf_P(_n("NG!\n"));
  776. break;
  777. }
  778. printf_P(_n("OK\n"));
  779. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  780. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  781. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  782. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  783. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  784. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  785. addr += header.size;
  786. codes[count] = header.code;
  787. count ++;
  788. }
  789. return count;
  790. }
  791. void list_sec_lang_from_external_flash()
  792. {
  793. uint16_t codes[8];
  794. uint8_t count = lang_xflash_enum_codes(codes);
  795. printf_P(_n("XFlash lang count = %hhd\n"), count);
  796. }
  797. #endif //DEBUG_W25X20CL
  798. #endif //W25X20CL
  799. #endif //(LANG_MODE != 0)
  800. static void w25x20cl_err_msg()
  801. {
  802. lcd_puts_P(_n(ESC_2J ESC_H(0,0) "External SPI flash" ESC_H(0,1) "W25X20CL is not res-"
  803. ESC_H(0,2) "ponding. Language" ESC_H(0,3) "switch unavailable."));
  804. }
  805. // "Setup" function is called by the Arduino framework on startup.
  806. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  807. // are initialized by the main() routine provided by the Arduino framework.
  808. void setup()
  809. {
  810. mmu_init();
  811. ultralcd_init();
  812. #if (LCD_BL_PIN != -1) && defined (LCD_BL_PIN)
  813. analogWrite(LCD_BL_PIN, 255); //set full brightnes
  814. #endif //(LCD_BL_PIN != -1) && defined (LCD_BL_PIN)
  815. spi_init();
  816. lcd_splash();
  817. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  818. #ifdef W25X20CL
  819. bool w25x20cl_success = w25x20cl_init();
  820. if (w25x20cl_success)
  821. {
  822. optiboot_w25x20cl_enter();
  823. #if (LANG_MODE != 0) //secondary language support
  824. update_sec_lang_from_external_flash();
  825. #endif //(LANG_MODE != 0)
  826. }
  827. else
  828. {
  829. w25x20cl_err_msg();
  830. }
  831. #else
  832. const bool w25x20cl_success = true;
  833. #endif //W25X20CL
  834. setup_killpin();
  835. setup_powerhold();
  836. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  837. EEPROM_read_B(EEPROM_FARM_NUMBER, &farm_no);
  838. if ((farm_mode == 0xFF && farm_no == 0) || ((uint16_t)farm_no == 0xFFFF))
  839. 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
  840. if ((uint16_t)farm_no == 0xFFFF) farm_no = 0;
  841. selectedSerialPort = eeprom_read_byte((uint8_t*)EEPROM_SECOND_SERIAL_ACTIVE);
  842. if (selectedSerialPort == 0xFF) selectedSerialPort = 0;
  843. if (farm_mode)
  844. {
  845. no_response = true; //we need confirmation by recieving PRUSA thx
  846. important_status = 8;
  847. prusa_statistics(8);
  848. selectedSerialPort = 1;
  849. #ifdef TMC2130
  850. //increased extruder current (PFW363)
  851. tmc2130_current_h[E_AXIS] = 36;
  852. tmc2130_current_r[E_AXIS] = 36;
  853. #endif //TMC2130
  854. #ifdef FILAMENT_SENSOR
  855. //disabled filament autoload (PFW360)
  856. fsensor_autoload_set(false);
  857. #endif //FILAMENT_SENSOR
  858. // ~ FanCheck -> on
  859. if(!(eeprom_read_byte((uint8_t*)EEPROM_FAN_CHECK_ENABLED)))
  860. eeprom_update_byte((unsigned char *)EEPROM_FAN_CHECK_ENABLED,true);
  861. }
  862. MYSERIAL.begin(BAUDRATE);
  863. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  864. #ifndef W25X20CL
  865. SERIAL_PROTOCOLLNPGM("start");
  866. #endif //W25X20CL
  867. stdout = uartout;
  868. SERIAL_ECHO_START;
  869. printf_P(PSTR(" " FW_VERSION_FULL "\n"));
  870. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  871. #ifdef DEBUG_SEC_LANG
  872. lang_table_header_t header;
  873. uint32_t src_addr = 0x00000;
  874. if (lang_get_header(1, &header, &src_addr))
  875. {
  876. //this is comparsion of some printing-methods regarding to flash space usage and code size/readability
  877. #define LT_PRINT_TEST 2
  878. // flash usage
  879. // total p.test
  880. //0 252718 t+c text code
  881. //1 253142 424 170 254
  882. //2 253040 322 164 158
  883. //3 253248 530 135 395
  884. #if (LT_PRINT_TEST==1) //not optimized printf
  885. printf_P(_n(" _src_addr = 0x%08lx\n"), src_addr);
  886. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  887. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  888. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  889. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  890. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  891. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  892. #elif (LT_PRINT_TEST==2) //optimized printf
  893. printf_P(
  894. _n(
  895. " _src_addr = 0x%08lx\n"
  896. " _lt_magic = 0x%08lx %S\n"
  897. " _lt_size = 0x%04x (%d)\n"
  898. " _lt_count = 0x%04x (%d)\n"
  899. " _lt_chsum = 0x%04x\n"
  900. " _lt_code = 0x%04x (%c%c)\n"
  901. " _lt_resv1 = 0x%08lx\n"
  902. ),
  903. src_addr,
  904. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  905. header.size, header.size,
  906. header.count, header.count,
  907. header.checksum,
  908. header.code, header.code >> 8, header.code & 0xff,
  909. header.signature
  910. );
  911. #elif (LT_PRINT_TEST==3) //arduino print/println (leading zeros not solved)
  912. MYSERIAL.print(" _src_addr = 0x");
  913. MYSERIAL.println(src_addr, 16);
  914. MYSERIAL.print(" _lt_magic = 0x");
  915. MYSERIAL.print(header.magic, 16);
  916. MYSERIAL.println((header.magic==LANG_MAGIC)?" OK":" NA");
  917. MYSERIAL.print(" _lt_size = 0x");
  918. MYSERIAL.print(header.size, 16);
  919. MYSERIAL.print(" (");
  920. MYSERIAL.print(header.size, 10);
  921. MYSERIAL.println(")");
  922. MYSERIAL.print(" _lt_count = 0x");
  923. MYSERIAL.print(header.count, 16);
  924. MYSERIAL.print(" (");
  925. MYSERIAL.print(header.count, 10);
  926. MYSERIAL.println(")");
  927. MYSERIAL.print(" _lt_chsum = 0x");
  928. MYSERIAL.println(header.checksum, 16);
  929. MYSERIAL.print(" _lt_code = 0x");
  930. MYSERIAL.print(header.code, 16);
  931. MYSERIAL.print(" (");
  932. MYSERIAL.print((char)(header.code >> 8), 0);
  933. MYSERIAL.print((char)(header.code & 0xff), 0);
  934. MYSERIAL.println(")");
  935. MYSERIAL.print(" _lt_resv1 = 0x");
  936. MYSERIAL.println(header.signature, 16);
  937. #endif //(LT_PRINT_TEST==)
  938. #undef LT_PRINT_TEST
  939. #if 0
  940. w25x20cl_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  941. for (uint16_t i = 0; i < 1024; i++)
  942. {
  943. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  944. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  945. if ((i % 16) == 15) putchar('\n');
  946. }
  947. #endif
  948. uint16_t sum = 0;
  949. for (uint16_t i = 0; i < header.size; i++)
  950. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  951. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  952. sum -= header.checksum; //subtract checksum
  953. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  954. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  955. if (sum == header.checksum)
  956. printf_P(_n("Checksum OK\n"), sum);
  957. else
  958. printf_P(_n("Checksum NG\n"), sum);
  959. }
  960. else
  961. printf_P(_n("lang_get_header failed!\n"));
  962. #if 0
  963. for (uint16_t i = 0; i < 1024*10; i++)
  964. {
  965. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  966. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  967. if ((i % 16) == 15) putchar('\n');
  968. }
  969. #endif
  970. #if 0
  971. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  972. for (int i = 0; i < 4096; ++i) {
  973. int b = eeprom_read_byte((unsigned char*)i);
  974. if (b != 255) {
  975. SERIAL_ECHO(i);
  976. SERIAL_ECHO(":");
  977. SERIAL_ECHO(b);
  978. SERIAL_ECHOLN("");
  979. }
  980. }
  981. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  982. #endif
  983. #endif //DEBUG_SEC_LANG
  984. // Check startup - does nothing if bootloader sets MCUSR to 0
  985. byte mcu = MCUSR;
  986. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  987. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  988. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  989. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  990. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  991. if (mcu & 1) puts_P(MSG_POWERUP);
  992. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  993. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  994. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  995. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  996. MCUSR = 0;
  997. //SERIAL_ECHORPGM(MSG_MARLIN);
  998. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  999. #ifdef STRING_VERSION_CONFIG_H
  1000. #ifdef STRING_CONFIG_H_AUTHOR
  1001. SERIAL_ECHO_START;
  1002. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  1003. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  1004. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  1005. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  1006. SERIAL_ECHOPGM("Compiled: ");
  1007. SERIAL_ECHOLNPGM(__DATE__);
  1008. #endif
  1009. #endif
  1010. SERIAL_ECHO_START;
  1011. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1012. SERIAL_ECHO(freeMemory());
  1013. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1014. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1015. //lcd_update_enable(false); // why do we need this?? - andre
  1016. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1017. bool previous_settings_retrieved = false;
  1018. uint8_t hw_changed = check_printer_version();
  1019. 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
  1020. previous_settings_retrieved = Config_RetrieveSettings();
  1021. }
  1022. else { //printer version was changed so use default settings
  1023. Config_ResetDefault();
  1024. }
  1025. SdFatUtil::set_stack_guard(); //writes magic number at the end of static variables to protect against overwriting static memory by stack
  1026. tp_init(); // Initialize temperature loop
  1027. if (w25x20cl_success) lcd_splash(); // we need to do this again, because tp_init() kills lcd
  1028. else
  1029. {
  1030. w25x20cl_err_msg();
  1031. printf_P(_n("W25X20CL not responding.\n"));
  1032. }
  1033. plan_init(); // Initialize planner;
  1034. factory_reset();
  1035. lcd_encoder_diff=0;
  1036. #ifdef TMC2130
  1037. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1038. if (silentMode == 0xff) silentMode = 0;
  1039. tmc2130_mode = TMC2130_MODE_NORMAL;
  1040. uint8_t crashdet = eeprom_read_byte((uint8_t*)EEPROM_CRASH_DET);
  1041. if (crashdet && !farm_mode)
  1042. {
  1043. crashdet_enable();
  1044. puts_P(_N("CrashDetect ENABLED!"));
  1045. }
  1046. else
  1047. {
  1048. crashdet_disable();
  1049. puts_P(_N("CrashDetect DISABLED"));
  1050. }
  1051. #ifdef TMC2130_LINEARITY_CORRECTION
  1052. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1053. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1054. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1055. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1056. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1057. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1058. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1059. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1060. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1061. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1062. #endif //TMC2130_LINEARITY_CORRECTION
  1063. #ifdef TMC2130_VARIABLE_RESOLUTION
  1064. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1065. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1066. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1067. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1068. #else //TMC2130_VARIABLE_RESOLUTION
  1069. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1070. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1071. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1072. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1073. #endif //TMC2130_VARIABLE_RESOLUTION
  1074. #endif //TMC2130
  1075. st_init(); // Initialize stepper, this enables interrupts!
  1076. #ifdef UVLO_SUPPORT
  1077. setup_uvlo_interrupt();
  1078. #endif //UVLO_SUPPORT
  1079. #ifdef TMC2130
  1080. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1081. update_mode_profile();
  1082. tmc2130_init();
  1083. #endif //TMC2130
  1084. setup_photpin();
  1085. servo_init();
  1086. // Reset the machine correction matrix.
  1087. // It does not make sense to load the correction matrix until the machine is homed.
  1088. world2machine_reset();
  1089. #ifdef FILAMENT_SENSOR
  1090. fsensor_init();
  1091. #endif //FILAMENT_SENSOR
  1092. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1093. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1094. #endif
  1095. setup_homepin();
  1096. #ifdef TMC2130
  1097. if (1) {
  1098. // try to run to zero phase before powering the Z motor.
  1099. // Move in negative direction
  1100. WRITE(Z_DIR_PIN,INVERT_Z_DIR);
  1101. // Round the current micro-micro steps to micro steps.
  1102. for (uint16_t phase = (tmc2130_rd_MSCNT(Z_AXIS) + 8) >> 4; phase > 0; -- phase) {
  1103. // Until the phase counter is reset to zero.
  1104. WRITE(Z_STEP_PIN, !INVERT_Z_STEP_PIN);
  1105. _delay(2);
  1106. WRITE(Z_STEP_PIN, INVERT_Z_STEP_PIN);
  1107. _delay(2);
  1108. }
  1109. }
  1110. #endif //TMC2130
  1111. #if defined(Z_AXIS_ALWAYS_ON)
  1112. enable_z();
  1113. #endif
  1114. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  1115. EEPROM_read_B(EEPROM_FARM_NUMBER, &farm_no);
  1116. 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
  1117. if (farm_no == static_cast<int>(0xFFFF)) farm_no = 0;
  1118. if (farm_mode)
  1119. {
  1120. prusa_statistics(8);
  1121. }
  1122. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1123. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1124. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  1125. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff) {
  1126. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  1127. // where all the EEPROM entries are set to 0x0ff.
  1128. // Once a firmware boots up, it forces at least a language selection, which changes
  1129. // EEPROM_LANG to number lower than 0x0ff.
  1130. // 1) Set a high power mode.
  1131. #ifdef TMC2130
  1132. eeprom_write_byte((uint8_t*)EEPROM_SILENT, 0);
  1133. tmc2130_mode = TMC2130_MODE_NORMAL;
  1134. #endif //TMC2130
  1135. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  1136. }
  1137. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1138. // but this times out if a blocking dialog is shown in setup().
  1139. card.initsd();
  1140. #ifdef DEBUG_SD_SPEED_TEST
  1141. if (card.cardOK)
  1142. {
  1143. uint8_t* buff = (uint8_t*)block_buffer;
  1144. uint32_t block = 0;
  1145. uint32_t sumr = 0;
  1146. uint32_t sumw = 0;
  1147. for (int i = 0; i < 1024; i++)
  1148. {
  1149. uint32_t u = _micros();
  1150. bool res = card.card.readBlock(i, buff);
  1151. u = _micros() - u;
  1152. if (res)
  1153. {
  1154. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1155. sumr += u;
  1156. u = _micros();
  1157. res = card.card.writeBlock(i, buff);
  1158. u = _micros() - u;
  1159. if (res)
  1160. {
  1161. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1162. sumw += u;
  1163. }
  1164. else
  1165. {
  1166. printf_P(PSTR("writeBlock %4d error\n"), i);
  1167. break;
  1168. }
  1169. }
  1170. else
  1171. {
  1172. printf_P(PSTR("readBlock %4d error\n"), i);
  1173. break;
  1174. }
  1175. }
  1176. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1177. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1178. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1179. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1180. }
  1181. else
  1182. printf_P(PSTR("Card NG!\n"));
  1183. #endif //DEBUG_SD_SPEED_TEST
  1184. eeprom_init();
  1185. #ifdef SNMM
  1186. if (eeprom_read_dword((uint32_t*)EEPROM_BOWDEN_LENGTH) == 0x0ffffffff) { //bowden length used for SNMM
  1187. int _z = BOWDEN_LENGTH;
  1188. for(int i = 0; i<4; i++) EEPROM_save_B(EEPROM_BOWDEN_LENGTH + i * 2, &_z);
  1189. }
  1190. #endif
  1191. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1192. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1193. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1194. #if (LANG_MODE != 0) //secondary language support
  1195. #ifdef DEBUG_W25X20CL
  1196. W25X20CL_SPI_ENTER();
  1197. uint8_t uid[8]; // 64bit unique id
  1198. w25x20cl_rd_uid(uid);
  1199. puts_P(_n("W25X20CL UID="));
  1200. for (uint8_t i = 0; i < 8; i ++)
  1201. printf_P(PSTR("%02hhx"), uid[i]);
  1202. putchar('\n');
  1203. list_sec_lang_from_external_flash();
  1204. #endif //DEBUG_W25X20CL
  1205. // lang_reset();
  1206. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1207. lcd_language();
  1208. #ifdef DEBUG_SEC_LANG
  1209. uint16_t sec_lang_code = lang_get_code(1);
  1210. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1211. 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);
  1212. lang_print_sec_lang(uartout);
  1213. #endif //DEBUG_SEC_LANG
  1214. #endif //(LANG_MODE != 0)
  1215. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  1216. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1217. temp_cal_active = false;
  1218. } else temp_cal_active = eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE);
  1219. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1220. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1221. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1222. int16_t z_shift = 0;
  1223. for (uint8_t i = 0; i < 5; i++) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  1224. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1225. temp_cal_active = false;
  1226. }
  1227. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 255) {
  1228. eeprom_write_byte((uint8_t*)EEPROM_UVLO, 0);
  1229. }
  1230. if (eeprom_read_byte((uint8_t*)EEPROM_SD_SORT) == 255) {
  1231. eeprom_write_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1232. }
  1233. //mbl_mode_init();
  1234. mbl_settings_init();
  1235. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1236. if (SilentModeMenu_MMU == 255) {
  1237. SilentModeMenu_MMU = 1;
  1238. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1239. }
  1240. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1241. setup_fan_interrupt();
  1242. #endif //DEBUG_DISABLE_FANCHECK
  1243. #ifdef PAT9125
  1244. fsensor_setup_interrupt();
  1245. #endif //PAT9125
  1246. for (int i = 0; i<4; i++) EEPROM_read_B(EEPROM_BOWDEN_LENGTH + i * 2, &bowden_length[i]);
  1247. #ifndef DEBUG_DISABLE_STARTMSGS
  1248. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1249. check_if_fw_is_on_right_printer();
  1250. show_fw_version_warnings();
  1251. switch (hw_changed) {
  1252. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1253. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1254. case(0b01):
  1255. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1256. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1257. break;
  1258. case(0b10):
  1259. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1260. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1261. break;
  1262. case(0b11):
  1263. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1264. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1265. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1266. break;
  1267. default: break; //no change, show no message
  1268. }
  1269. if (!previous_settings_retrieved) {
  1270. 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
  1271. Config_StoreSettings();
  1272. }
  1273. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 1) {
  1274. lcd_wizard(WizState::Run);
  1275. }
  1276. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1277. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1278. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1279. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1280. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1281. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z, 0);
  1282. // Show the message.
  1283. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1284. }
  1285. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1286. // Show the message.
  1287. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1288. lcd_update_enable(true);
  1289. }
  1290. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && temp_cal_active == true && calibration_status_pinda() == false) {
  1291. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1292. lcd_update_enable(true);
  1293. }
  1294. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1295. // Show the message.
  1296. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1297. }
  1298. }
  1299. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1300. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1301. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1302. update_current_firmware_version_to_eeprom();
  1303. lcd_selftest();
  1304. }
  1305. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1306. KEEPALIVE_STATE(IN_PROCESS);
  1307. #endif //DEBUG_DISABLE_STARTMSGS
  1308. lcd_update_enable(true);
  1309. lcd_clear();
  1310. lcd_update(2);
  1311. // Store the currently running firmware into an eeprom,
  1312. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1313. update_current_firmware_version_to_eeprom();
  1314. #ifdef TMC2130
  1315. tmc2130_home_origin[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN);
  1316. tmc2130_home_bsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS);
  1317. tmc2130_home_fsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS);
  1318. if (tmc2130_home_origin[X_AXIS] == 0xff) tmc2130_home_origin[X_AXIS] = 0;
  1319. if (tmc2130_home_bsteps[X_AXIS] == 0xff) tmc2130_home_bsteps[X_AXIS] = 48;
  1320. if (tmc2130_home_fsteps[X_AXIS] == 0xff) tmc2130_home_fsteps[X_AXIS] = 48;
  1321. tmc2130_home_origin[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN);
  1322. tmc2130_home_bsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS);
  1323. tmc2130_home_fsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS);
  1324. if (tmc2130_home_origin[Y_AXIS] == 0xff) tmc2130_home_origin[Y_AXIS] = 0;
  1325. if (tmc2130_home_bsteps[Y_AXIS] == 0xff) tmc2130_home_bsteps[Y_AXIS] = 48;
  1326. if (tmc2130_home_fsteps[Y_AXIS] == 0xff) tmc2130_home_fsteps[Y_AXIS] = 48;
  1327. tmc2130_home_enabled = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED);
  1328. if (tmc2130_home_enabled == 0xff) tmc2130_home_enabled = 0;
  1329. #endif //TMC2130
  1330. #ifdef UVLO_SUPPORT
  1331. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1332. /*
  1333. if (lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1334. else {
  1335. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1336. lcd_update_enable(true);
  1337. lcd_update(2);
  1338. lcd_setstatuspgm(_T(WELCOME_MSG));
  1339. }
  1340. */
  1341. manage_heater(); // Update temperatures
  1342. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1343. 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));
  1344. #endif
  1345. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1346. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1347. puts_P(_N("Automatic recovery!"));
  1348. #endif
  1349. recover_print(1);
  1350. }
  1351. else{
  1352. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1353. puts_P(_N("Normal recovery!"));
  1354. #endif
  1355. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) ) recover_print(0);
  1356. else {
  1357. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1358. lcd_update_enable(true);
  1359. lcd_update(2);
  1360. lcd_setstatuspgm(_T(WELCOME_MSG));
  1361. }
  1362. }
  1363. }
  1364. #endif //UVLO_SUPPORT
  1365. fCheckModeInit();
  1366. KEEPALIVE_STATE(NOT_BUSY);
  1367. #ifdef WATCHDOG
  1368. wdt_enable(WDTO_4S);
  1369. #endif //WATCHDOG
  1370. }
  1371. void trace();
  1372. #define CHUNK_SIZE 64 // bytes
  1373. #define SAFETY_MARGIN 1
  1374. char chunk[CHUNK_SIZE+SAFETY_MARGIN];
  1375. int chunkHead = 0;
  1376. void serial_read_stream() {
  1377. setAllTargetHotends(0);
  1378. setTargetBed(0);
  1379. lcd_clear();
  1380. lcd_puts_P(PSTR(" Upload in progress"));
  1381. // first wait for how many bytes we will receive
  1382. uint32_t bytesToReceive;
  1383. // receive the four bytes
  1384. char bytesToReceiveBuffer[4];
  1385. for (int i=0; i<4; i++) {
  1386. int data;
  1387. while ((data = MYSERIAL.read()) == -1) {};
  1388. bytesToReceiveBuffer[i] = data;
  1389. }
  1390. // make it a uint32
  1391. memcpy(&bytesToReceive, &bytesToReceiveBuffer, 4);
  1392. // we're ready, notify the sender
  1393. MYSERIAL.write('+');
  1394. // lock in the routine
  1395. uint32_t receivedBytes = 0;
  1396. while (prusa_sd_card_upload) {
  1397. int i;
  1398. for (i=0; i<CHUNK_SIZE; i++) {
  1399. int data;
  1400. // check if we're not done
  1401. if (receivedBytes == bytesToReceive) {
  1402. break;
  1403. }
  1404. // read the next byte
  1405. while ((data = MYSERIAL.read()) == -1) {};
  1406. receivedBytes++;
  1407. // save it to the chunk
  1408. chunk[i] = data;
  1409. }
  1410. // write the chunk to SD
  1411. card.write_command_no_newline(&chunk[0]);
  1412. // notify the sender we're ready for more data
  1413. MYSERIAL.write('+');
  1414. // for safety
  1415. manage_heater();
  1416. // check if we're done
  1417. if(receivedBytes == bytesToReceive) {
  1418. trace(); // beep
  1419. card.closefile();
  1420. prusa_sd_card_upload = false;
  1421. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1422. }
  1423. }
  1424. }
  1425. /**
  1426. * Output a "busy" message at regular intervals
  1427. * while the machine is not accepting commands.
  1428. */
  1429. void host_keepalive() {
  1430. #ifndef HOST_KEEPALIVE_FEATURE
  1431. return;
  1432. #endif //HOST_KEEPALIVE_FEATURE
  1433. if (farm_mode) return;
  1434. long ms = _millis();
  1435. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1436. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1437. switch (busy_state) {
  1438. case IN_HANDLER:
  1439. case IN_PROCESS:
  1440. SERIAL_ECHO_START;
  1441. SERIAL_ECHOLNPGM("busy: processing");
  1442. break;
  1443. case PAUSED_FOR_USER:
  1444. SERIAL_ECHO_START;
  1445. SERIAL_ECHOLNPGM("busy: paused for user");
  1446. break;
  1447. case PAUSED_FOR_INPUT:
  1448. SERIAL_ECHO_START;
  1449. SERIAL_ECHOLNPGM("busy: paused for input");
  1450. break;
  1451. default:
  1452. break;
  1453. }
  1454. }
  1455. prev_busy_signal_ms = ms;
  1456. }
  1457. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1458. // Before loop(), the setup() function is called by the main() routine.
  1459. void loop()
  1460. {
  1461. KEEPALIVE_STATE(NOT_BUSY);
  1462. if ((usb_printing_counter > 0) && ((_millis()-_usb_timer) > 1000))
  1463. {
  1464. is_usb_printing = true;
  1465. usb_printing_counter--;
  1466. _usb_timer = _millis();
  1467. }
  1468. if (usb_printing_counter == 0)
  1469. {
  1470. is_usb_printing = false;
  1471. }
  1472. if (prusa_sd_card_upload)
  1473. {
  1474. //we read byte-by byte
  1475. serial_read_stream();
  1476. } else
  1477. {
  1478. get_command();
  1479. #ifdef SDSUPPORT
  1480. card.checkautostart(false);
  1481. #endif
  1482. if(buflen)
  1483. {
  1484. cmdbuffer_front_already_processed = false;
  1485. #ifdef SDSUPPORT
  1486. if(card.saving)
  1487. {
  1488. // Saving a G-code file onto an SD-card is in progress.
  1489. // Saving starts with M28, saving until M29 is seen.
  1490. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1491. card.write_command(CMDBUFFER_CURRENT_STRING);
  1492. if(card.logging)
  1493. process_commands();
  1494. else
  1495. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1496. } else {
  1497. card.closefile();
  1498. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1499. }
  1500. } else {
  1501. process_commands();
  1502. }
  1503. #else
  1504. process_commands();
  1505. #endif //SDSUPPORT
  1506. if (! cmdbuffer_front_already_processed && buflen)
  1507. {
  1508. // ptr points to the start of the block currently being processed.
  1509. // The first character in the block is the block type.
  1510. char *ptr = cmdbuffer + bufindr;
  1511. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1512. // To support power panic, move the lenght of the command on the SD card to a planner buffer.
  1513. union {
  1514. struct {
  1515. char lo;
  1516. char hi;
  1517. } lohi;
  1518. uint16_t value;
  1519. } sdlen;
  1520. sdlen.value = 0;
  1521. {
  1522. // This block locks the interrupts globally for 3.25 us,
  1523. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1524. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1525. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1526. cli();
  1527. // Reset the command to something, which will be ignored by the power panic routine,
  1528. // so this buffer length will not be counted twice.
  1529. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1530. // Extract the current buffer length.
  1531. sdlen.lohi.lo = *ptr ++;
  1532. sdlen.lohi.hi = *ptr;
  1533. // and pass it to the planner queue.
  1534. planner_add_sd_length(sdlen.value);
  1535. sei();
  1536. }
  1537. }
  1538. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1539. cli();
  1540. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1541. // and one for each command to previous block in the planner queue.
  1542. planner_add_sd_length(1);
  1543. sei();
  1544. }
  1545. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1546. // this block's SD card length will not be counted twice as its command type has been replaced
  1547. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1548. cmdqueue_pop_front();
  1549. }
  1550. host_keepalive();
  1551. }
  1552. }
  1553. //check heater every n milliseconds
  1554. manage_heater();
  1555. isPrintPaused ? manage_inactivity(true) : manage_inactivity(false);
  1556. checkHitEndstops();
  1557. lcd_update(0);
  1558. #ifdef TMC2130
  1559. tmc2130_check_overtemp();
  1560. if (tmc2130_sg_crash)
  1561. {
  1562. uint8_t crash = tmc2130_sg_crash;
  1563. tmc2130_sg_crash = 0;
  1564. // crashdet_stop_and_save_print();
  1565. switch (crash)
  1566. {
  1567. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1568. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1569. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1570. }
  1571. }
  1572. #endif //TMC2130
  1573. mmu_loop();
  1574. }
  1575. #define DEFINE_PGM_READ_ANY(type, reader) \
  1576. static inline type pgm_read_any(const type *p) \
  1577. { return pgm_read_##reader##_near(p); }
  1578. DEFINE_PGM_READ_ANY(float, float);
  1579. DEFINE_PGM_READ_ANY(signed char, byte);
  1580. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1581. static const PROGMEM type array##_P[3] = \
  1582. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1583. static inline type array(int axis) \
  1584. { return pgm_read_any(&array##_P[axis]); } \
  1585. type array##_ext(int axis) \
  1586. { return pgm_read_any(&array##_P[axis]); }
  1587. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1588. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1589. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1590. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1591. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1592. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1593. static void axis_is_at_home(int axis) {
  1594. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1595. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1596. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1597. }
  1598. inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); }
  1599. inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); }
  1600. //! @return original feedmultiply
  1601. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1602. saved_feedrate = feedrate;
  1603. int l_feedmultiply = feedmultiply;
  1604. feedmultiply = 100;
  1605. previous_millis_cmd = _millis();
  1606. enable_endstops(enable_endstops_now);
  1607. return l_feedmultiply;
  1608. }
  1609. //! @param original_feedmultiply feedmultiply to restore
  1610. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1611. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1612. enable_endstops(false);
  1613. #endif
  1614. feedrate = saved_feedrate;
  1615. feedmultiply = original_feedmultiply;
  1616. previous_millis_cmd = _millis();
  1617. }
  1618. #ifdef ENABLE_AUTO_BED_LEVELING
  1619. #ifdef AUTO_BED_LEVELING_GRID
  1620. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1621. {
  1622. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1623. planeNormal.debug("planeNormal");
  1624. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1625. //bedLevel.debug("bedLevel");
  1626. //plan_bed_level_matrix.debug("bed level before");
  1627. //vector_3 uncorrected_position = plan_get_position_mm();
  1628. //uncorrected_position.debug("position before");
  1629. vector_3 corrected_position = plan_get_position();
  1630. // corrected_position.debug("position after");
  1631. current_position[X_AXIS] = corrected_position.x;
  1632. current_position[Y_AXIS] = corrected_position.y;
  1633. current_position[Z_AXIS] = corrected_position.z;
  1634. // put the bed at 0 so we don't go below it.
  1635. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1636. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1637. }
  1638. #else // not AUTO_BED_LEVELING_GRID
  1639. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1640. plan_bed_level_matrix.set_to_identity();
  1641. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1642. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1643. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1644. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1645. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1646. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1647. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1648. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1649. vector_3 corrected_position = plan_get_position();
  1650. current_position[X_AXIS] = corrected_position.x;
  1651. current_position[Y_AXIS] = corrected_position.y;
  1652. current_position[Z_AXIS] = corrected_position.z;
  1653. // put the bed at 0 so we don't go below it.
  1654. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1655. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1656. }
  1657. #endif // AUTO_BED_LEVELING_GRID
  1658. static void run_z_probe() {
  1659. plan_bed_level_matrix.set_to_identity();
  1660. feedrate = homing_feedrate[Z_AXIS];
  1661. // move down until you find the bed
  1662. float zPosition = -10;
  1663. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1664. st_synchronize();
  1665. // we have to let the planner know where we are right now as it is not where we said to go.
  1666. zPosition = st_get_position_mm(Z_AXIS);
  1667. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1668. // move up the retract distance
  1669. zPosition += home_retract_mm(Z_AXIS);
  1670. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1671. st_synchronize();
  1672. // move back down slowly to find bed
  1673. feedrate = homing_feedrate[Z_AXIS]/4;
  1674. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1675. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1676. st_synchronize();
  1677. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1678. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1679. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1680. }
  1681. static void do_blocking_move_to(float x, float y, float z) {
  1682. float oldFeedRate = feedrate;
  1683. feedrate = homing_feedrate[Z_AXIS];
  1684. current_position[Z_AXIS] = z;
  1685. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder);
  1686. st_synchronize();
  1687. feedrate = XY_TRAVEL_SPEED;
  1688. current_position[X_AXIS] = x;
  1689. current_position[Y_AXIS] = y;
  1690. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder);
  1691. st_synchronize();
  1692. feedrate = oldFeedRate;
  1693. }
  1694. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1695. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1696. }
  1697. /// Probe bed height at position (x,y), returns the measured z value
  1698. static float probe_pt(float x, float y, float z_before) {
  1699. // move to right place
  1700. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1701. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1702. run_z_probe();
  1703. float measured_z = current_position[Z_AXIS];
  1704. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1705. SERIAL_PROTOCOLPGM(" x: ");
  1706. SERIAL_PROTOCOL(x);
  1707. SERIAL_PROTOCOLPGM(" y: ");
  1708. SERIAL_PROTOCOL(y);
  1709. SERIAL_PROTOCOLPGM(" z: ");
  1710. SERIAL_PROTOCOL(measured_z);
  1711. SERIAL_PROTOCOLPGM("\n");
  1712. return measured_z;
  1713. }
  1714. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1715. #ifdef LIN_ADVANCE
  1716. /**
  1717. * M900: Set and/or Get advance K factor and WH/D ratio
  1718. *
  1719. * K<factor> Set advance K factor
  1720. * R<ratio> Set ratio directly (overrides WH/D)
  1721. * W<width> H<height> D<diam> Set ratio from WH/D
  1722. */
  1723. inline void gcode_M900() {
  1724. st_synchronize();
  1725. const float newK = code_seen('K') ? code_value_float() : -1;
  1726. if (newK >= 0) extruder_advance_k = newK;
  1727. float newR = code_seen('R') ? code_value_float() : -1;
  1728. if (newR < 0) {
  1729. const float newD = code_seen('D') ? code_value_float() : -1,
  1730. newW = code_seen('W') ? code_value_float() : -1,
  1731. newH = code_seen('H') ? code_value_float() : -1;
  1732. if (newD >= 0 && newW >= 0 && newH >= 0)
  1733. newR = newD ? (newW * newH) / (sq(newD * 0.5) * M_PI) : 0;
  1734. }
  1735. if (newR >= 0) advance_ed_ratio = newR;
  1736. SERIAL_ECHO_START;
  1737. SERIAL_ECHOPGM("Advance K=");
  1738. SERIAL_ECHOLN(extruder_advance_k);
  1739. SERIAL_ECHOPGM(" E/D=");
  1740. const float ratio = advance_ed_ratio;
  1741. if (ratio) SERIAL_ECHOLN(ratio); else SERIAL_ECHOLNPGM("Auto");
  1742. }
  1743. #endif // LIN_ADVANCE
  1744. bool check_commands() {
  1745. bool end_command_found = false;
  1746. while (buflen)
  1747. {
  1748. if ((code_seen("M84")) || (code_seen("M 84"))) end_command_found = true;
  1749. if (!cmdbuffer_front_already_processed)
  1750. cmdqueue_pop_front();
  1751. cmdbuffer_front_already_processed = false;
  1752. }
  1753. return end_command_found;
  1754. }
  1755. #ifdef TMC2130
  1756. bool calibrate_z_auto()
  1757. {
  1758. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1759. lcd_clear();
  1760. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1761. bool endstops_enabled = enable_endstops(true);
  1762. int axis_up_dir = -home_dir(Z_AXIS);
  1763. tmc2130_home_enter(Z_AXIS_MASK);
  1764. current_position[Z_AXIS] = 0;
  1765. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1766. set_destination_to_current();
  1767. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1768. feedrate = homing_feedrate[Z_AXIS];
  1769. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / 60, active_extruder);
  1770. st_synchronize();
  1771. // current_position[axis] = 0;
  1772. // plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1773. tmc2130_home_exit();
  1774. enable_endstops(false);
  1775. current_position[Z_AXIS] = 0;
  1776. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1777. set_destination_to_current();
  1778. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1779. feedrate = homing_feedrate[Z_AXIS] / 2;
  1780. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / 60, active_extruder);
  1781. st_synchronize();
  1782. enable_endstops(endstops_enabled);
  1783. if (PRINTER_TYPE == PRINTER_MK3) {
  1784. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1785. }
  1786. else {
  1787. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1788. }
  1789. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1790. return true;
  1791. }
  1792. #endif //TMC2130
  1793. #ifdef TMC2130
  1794. void homeaxis(int axis, uint8_t cnt, uint8_t* pstep)
  1795. #else
  1796. void homeaxis(int axis, uint8_t cnt)
  1797. #endif //TMC2130
  1798. {
  1799. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1800. #define HOMEAXIS_DO(LETTER) \
  1801. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1802. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1803. {
  1804. int axis_home_dir = home_dir(axis);
  1805. feedrate = homing_feedrate[axis];
  1806. #ifdef TMC2130
  1807. tmc2130_home_enter(X_AXIS_MASK << axis);
  1808. #endif //TMC2130
  1809. // Move away a bit, so that the print head does not touch the end position,
  1810. // and the following movement to endstop has a chance to achieve the required velocity
  1811. // for the stall guard to work.
  1812. current_position[axis] = 0;
  1813. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1814. set_destination_to_current();
  1815. // destination[axis] = 11.f;
  1816. destination[axis] = -3.f * axis_home_dir;
  1817. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1818. st_synchronize();
  1819. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1820. endstops_hit_on_purpose();
  1821. enable_endstops(false);
  1822. current_position[axis] = 0;
  1823. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1824. destination[axis] = 1. * axis_home_dir;
  1825. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1826. st_synchronize();
  1827. // Now continue to move up to the left end stop with the collision detection enabled.
  1828. enable_endstops(true);
  1829. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1830. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1831. st_synchronize();
  1832. for (uint8_t i = 0; i < cnt; i++)
  1833. {
  1834. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1835. endstops_hit_on_purpose();
  1836. enable_endstops(false);
  1837. current_position[axis] = 0;
  1838. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1839. destination[axis] = -10.f * axis_home_dir;
  1840. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1841. st_synchronize();
  1842. endstops_hit_on_purpose();
  1843. // Now move left up to the collision, this time with a repeatable velocity.
  1844. enable_endstops(true);
  1845. destination[axis] = 11.f * axis_home_dir;
  1846. #ifdef TMC2130
  1847. feedrate = homing_feedrate[axis];
  1848. #else //TMC2130
  1849. feedrate = homing_feedrate[axis] / 2;
  1850. #endif //TMC2130
  1851. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1852. st_synchronize();
  1853. #ifdef TMC2130
  1854. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1855. if (pstep) pstep[i] = mscnt >> 4;
  1856. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1857. #endif //TMC2130
  1858. }
  1859. endstops_hit_on_purpose();
  1860. enable_endstops(false);
  1861. #ifdef TMC2130
  1862. uint8_t orig = tmc2130_home_origin[axis];
  1863. uint8_t back = tmc2130_home_bsteps[axis];
  1864. if (tmc2130_home_enabled && (orig <= 63))
  1865. {
  1866. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1867. if (back > 0)
  1868. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1869. }
  1870. else
  1871. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1872. tmc2130_home_exit();
  1873. #endif //TMC2130
  1874. axis_is_at_home(axis);
  1875. axis_known_position[axis] = true;
  1876. // Move from minimum
  1877. #ifdef TMC2130
  1878. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1879. #else //TMC2130
  1880. float dist = - axis_home_dir * 0.01f * 64;
  1881. #endif //TMC2130
  1882. current_position[axis] -= dist;
  1883. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1884. current_position[axis] += dist;
  1885. destination[axis] = current_position[axis];
  1886. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], 0.5f*feedrate/60, active_extruder);
  1887. st_synchronize();
  1888. feedrate = 0.0;
  1889. }
  1890. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1891. {
  1892. #ifdef TMC2130
  1893. FORCE_HIGH_POWER_START;
  1894. #endif
  1895. int axis_home_dir = home_dir(axis);
  1896. current_position[axis] = 0;
  1897. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1898. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1899. feedrate = homing_feedrate[axis];
  1900. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1901. st_synchronize();
  1902. #ifdef TMC2130
  1903. if (READ(Z_TMC2130_DIAG) != 0) { //Z crash
  1904. FORCE_HIGH_POWER_END;
  1905. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1906. return;
  1907. }
  1908. #endif //TMC2130
  1909. current_position[axis] = 0;
  1910. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1911. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1912. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1913. st_synchronize();
  1914. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1915. feedrate = homing_feedrate[axis]/2 ;
  1916. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1917. st_synchronize();
  1918. #ifdef TMC2130
  1919. if (READ(Z_TMC2130_DIAG) != 0) { //Z crash
  1920. FORCE_HIGH_POWER_END;
  1921. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1922. return;
  1923. }
  1924. #endif //TMC2130
  1925. axis_is_at_home(axis);
  1926. destination[axis] = current_position[axis];
  1927. feedrate = 0.0;
  1928. endstops_hit_on_purpose();
  1929. axis_known_position[axis] = true;
  1930. #ifdef TMC2130
  1931. FORCE_HIGH_POWER_END;
  1932. #endif
  1933. }
  1934. enable_endstops(endstops_enabled);
  1935. }
  1936. /**/
  1937. void home_xy()
  1938. {
  1939. set_destination_to_current();
  1940. homeaxis(X_AXIS);
  1941. homeaxis(Y_AXIS);
  1942. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1943. endstops_hit_on_purpose();
  1944. }
  1945. void refresh_cmd_timeout(void)
  1946. {
  1947. previous_millis_cmd = _millis();
  1948. }
  1949. #ifdef FWRETRACT
  1950. void retract(bool retracting, bool swapretract = false) {
  1951. if(retracting && !retracted[active_extruder]) {
  1952. destination[X_AXIS]=current_position[X_AXIS];
  1953. destination[Y_AXIS]=current_position[Y_AXIS];
  1954. destination[Z_AXIS]=current_position[Z_AXIS];
  1955. destination[E_AXIS]=current_position[E_AXIS];
  1956. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  1957. plan_set_e_position(current_position[E_AXIS]);
  1958. float oldFeedrate = feedrate;
  1959. feedrate=cs.retract_feedrate*60;
  1960. retracted[active_extruder]=true;
  1961. prepare_move();
  1962. current_position[Z_AXIS]-=cs.retract_zlift;
  1963. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1964. prepare_move();
  1965. feedrate = oldFeedrate;
  1966. } else if(!retracting && retracted[active_extruder]) {
  1967. destination[X_AXIS]=current_position[X_AXIS];
  1968. destination[Y_AXIS]=current_position[Y_AXIS];
  1969. destination[Z_AXIS]=current_position[Z_AXIS];
  1970. destination[E_AXIS]=current_position[E_AXIS];
  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. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  1974. plan_set_e_position(current_position[E_AXIS]);
  1975. float oldFeedrate = feedrate;
  1976. feedrate=cs.retract_recover_feedrate*60;
  1977. retracted[active_extruder]=false;
  1978. prepare_move();
  1979. feedrate = oldFeedrate;
  1980. }
  1981. } //retract
  1982. #endif //FWRETRACT
  1983. void trace() {
  1984. //if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  1985. _tone(BEEPER, 440);
  1986. _delay(25);
  1987. _noTone(BEEPER);
  1988. _delay(20);
  1989. }
  1990. /*
  1991. void ramming() {
  1992. // float tmp[4] = DEFAULT_MAX_FEEDRATE;
  1993. if (current_temperature[0] < 230) {
  1994. //PLA
  1995. max_feedrate[E_AXIS] = 50;
  1996. //current_position[E_AXIS] -= 8;
  1997. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  1998. //current_position[E_AXIS] += 8;
  1999. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  2000. current_position[E_AXIS] += 5.4;
  2001. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2800 / 60, active_extruder);
  2002. current_position[E_AXIS] += 3.2;
  2003. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2004. current_position[E_AXIS] += 3;
  2005. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3400 / 60, active_extruder);
  2006. st_synchronize();
  2007. max_feedrate[E_AXIS] = 80;
  2008. current_position[E_AXIS] -= 82;
  2009. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 9500 / 60, active_extruder);
  2010. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  2011. current_position[E_AXIS] -= 20;
  2012. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 1200 / 60, active_extruder);
  2013. current_position[E_AXIS] += 5;
  2014. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400 / 60, active_extruder);
  2015. current_position[E_AXIS] += 5;
  2016. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2017. current_position[E_AXIS] -= 10;
  2018. st_synchronize();
  2019. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2020. current_position[E_AXIS] += 10;
  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. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  2024. current_position[E_AXIS] += 10;
  2025. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  2026. current_position[E_AXIS] -= 10;
  2027. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  2028. st_synchronize();
  2029. }
  2030. else {
  2031. //ABS
  2032. max_feedrate[E_AXIS] = 50;
  2033. //current_position[E_AXIS] -= 8;
  2034. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  2035. //current_position[E_AXIS] += 8;
  2036. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  2037. current_position[E_AXIS] += 3.1;
  2038. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2000 / 60, active_extruder);
  2039. current_position[E_AXIS] += 3.1;
  2040. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2500 / 60, active_extruder);
  2041. current_position[E_AXIS] += 4;
  2042. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2043. st_synchronize();
  2044. //current_position[X_AXIS] += 23; //delay
  2045. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600/60, active_extruder); //delay
  2046. //current_position[X_AXIS] -= 23; //delay
  2047. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600/60, active_extruder); //delay
  2048. _delay(4700);
  2049. max_feedrate[E_AXIS] = 80;
  2050. current_position[E_AXIS] -= 92;
  2051. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 9900 / 60, active_extruder);
  2052. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  2053. current_position[E_AXIS] -= 5;
  2054. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  2055. current_position[E_AXIS] += 5;
  2056. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400 / 60, active_extruder);
  2057. current_position[E_AXIS] -= 5;
  2058. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2059. st_synchronize();
  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], 600 / 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. current_position[E_AXIS] += 5;
  2065. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2066. current_position[E_AXIS] -= 5;
  2067. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2068. st_synchronize();
  2069. }
  2070. }
  2071. */
  2072. #ifdef TMC2130
  2073. void force_high_power_mode(bool start_high_power_section) {
  2074. uint8_t silent;
  2075. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2076. if (silent == 1) {
  2077. //we are in silent mode, set to normal mode to enable crash detection
  2078. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2079. st_synchronize();
  2080. cli();
  2081. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2082. update_mode_profile();
  2083. tmc2130_init();
  2084. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2085. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2086. st_reset_timer();
  2087. sei();
  2088. }
  2089. }
  2090. #endif //TMC2130
  2091. #ifdef TMC2130
  2092. 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)
  2093. #else
  2094. 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)
  2095. #endif //TMC2130
  2096. {
  2097. st_synchronize();
  2098. #if 0
  2099. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2100. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2101. #endif
  2102. // Flag for the display update routine and to disable the print cancelation during homing.
  2103. homing_flag = true;
  2104. // Which axes should be homed?
  2105. bool home_x = home_x_axis;
  2106. bool home_y = home_y_axis;
  2107. bool home_z = home_z_axis;
  2108. // Either all X,Y,Z codes are present, or none of them.
  2109. bool home_all_axes = home_x == home_y && home_x == home_z;
  2110. if (home_all_axes)
  2111. // No X/Y/Z code provided means to home all axes.
  2112. home_x = home_y = home_z = true;
  2113. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2114. if (home_all_axes) {
  2115. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  2116. feedrate = homing_feedrate[Z_AXIS];
  2117. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate / 60, active_extruder);
  2118. st_synchronize();
  2119. }
  2120. #ifdef ENABLE_AUTO_BED_LEVELING
  2121. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2122. #endif //ENABLE_AUTO_BED_LEVELING
  2123. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2124. // the planner will not perform any adjustments in the XY plane.
  2125. // Wait for the motors to stop and update the current position with the absolute values.
  2126. world2machine_revert_to_uncorrected();
  2127. // For mesh bed leveling deactivate the matrix temporarily.
  2128. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2129. // in a single axis only.
  2130. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2131. #ifdef MESH_BED_LEVELING
  2132. uint8_t mbl_was_active = mbl.active;
  2133. mbl.active = 0;
  2134. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2135. #endif
  2136. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  2137. // consumed during the first movements following this statement.
  2138. if (home_z)
  2139. babystep_undo();
  2140. saved_feedrate = feedrate;
  2141. int l_feedmultiply = feedmultiply;
  2142. feedmultiply = 100;
  2143. previous_millis_cmd = _millis();
  2144. enable_endstops(true);
  2145. memcpy(destination, current_position, sizeof(destination));
  2146. feedrate = 0.0;
  2147. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2148. if(home_z)
  2149. homeaxis(Z_AXIS);
  2150. #endif
  2151. #ifdef QUICK_HOME
  2152. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2153. if(home_x && home_y) //first diagonal move
  2154. {
  2155. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2156. int x_axis_home_dir = home_dir(X_AXIS);
  2157. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2158. 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);
  2159. feedrate = homing_feedrate[X_AXIS];
  2160. if(homing_feedrate[Y_AXIS]<feedrate)
  2161. feedrate = homing_feedrate[Y_AXIS];
  2162. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2163. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2164. } else {
  2165. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2166. }
  2167. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  2168. st_synchronize();
  2169. axis_is_at_home(X_AXIS);
  2170. axis_is_at_home(Y_AXIS);
  2171. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2172. destination[X_AXIS] = current_position[X_AXIS];
  2173. destination[Y_AXIS] = current_position[Y_AXIS];
  2174. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  2175. feedrate = 0.0;
  2176. st_synchronize();
  2177. endstops_hit_on_purpose();
  2178. current_position[X_AXIS] = destination[X_AXIS];
  2179. current_position[Y_AXIS] = destination[Y_AXIS];
  2180. current_position[Z_AXIS] = destination[Z_AXIS];
  2181. }
  2182. #endif /* QUICK_HOME */
  2183. #ifdef TMC2130
  2184. if(home_x)
  2185. {
  2186. if (!calib)
  2187. homeaxis(X_AXIS);
  2188. else
  2189. tmc2130_home_calibrate(X_AXIS);
  2190. }
  2191. if(home_y)
  2192. {
  2193. if (!calib)
  2194. homeaxis(Y_AXIS);
  2195. else
  2196. tmc2130_home_calibrate(Y_AXIS);
  2197. }
  2198. #else //TMC2130
  2199. if(home_x) homeaxis(X_AXIS);
  2200. if(home_y) homeaxis(Y_AXIS);
  2201. #endif //TMC2130
  2202. if(home_x_axis && home_x_value != 0)
  2203. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2204. if(home_y_axis && home_y_value != 0)
  2205. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2206. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2207. #ifndef Z_SAFE_HOMING
  2208. if(home_z) {
  2209. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2210. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2211. feedrate = max_feedrate[Z_AXIS];
  2212. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2213. st_synchronize();
  2214. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2215. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP)) // If Mesh bed leveling, move X&Y to safe position for home
  2216. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] ))
  2217. {
  2218. homeaxis(X_AXIS);
  2219. homeaxis(Y_AXIS);
  2220. }
  2221. // 1st mesh bed leveling measurement point, corrected.
  2222. world2machine_initialize();
  2223. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2224. world2machine_reset();
  2225. if (destination[Y_AXIS] < Y_MIN_POS)
  2226. destination[Y_AXIS] = Y_MIN_POS;
  2227. destination[Z_AXIS] = MESH_HOME_Z_SEARCH; // Set destination away from bed
  2228. feedrate = homing_feedrate[Z_AXIS]/10;
  2229. current_position[Z_AXIS] = 0;
  2230. enable_endstops(false);
  2231. #ifdef DEBUG_BUILD
  2232. SERIAL_ECHOLNPGM("plan_set_position()");
  2233. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2234. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2235. #endif
  2236. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2237. #ifdef DEBUG_BUILD
  2238. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2239. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2240. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2241. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2242. #endif
  2243. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2244. st_synchronize();
  2245. current_position[X_AXIS] = destination[X_AXIS];
  2246. current_position[Y_AXIS] = destination[Y_AXIS];
  2247. enable_endstops(true);
  2248. endstops_hit_on_purpose();
  2249. homeaxis(Z_AXIS);
  2250. #else // MESH_BED_LEVELING
  2251. homeaxis(Z_AXIS);
  2252. #endif // MESH_BED_LEVELING
  2253. }
  2254. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2255. if(home_all_axes) {
  2256. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2257. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2258. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2259. feedrate = XY_TRAVEL_SPEED/60;
  2260. current_position[Z_AXIS] = 0;
  2261. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2262. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2263. st_synchronize();
  2264. current_position[X_AXIS] = destination[X_AXIS];
  2265. current_position[Y_AXIS] = destination[Y_AXIS];
  2266. homeaxis(Z_AXIS);
  2267. }
  2268. // Let's see if X and Y are homed and probe is inside bed area.
  2269. if(home_z) {
  2270. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2271. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2272. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2273. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2274. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2275. current_position[Z_AXIS] = 0;
  2276. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2277. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2278. feedrate = max_feedrate[Z_AXIS];
  2279. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2280. st_synchronize();
  2281. homeaxis(Z_AXIS);
  2282. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2283. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2284. SERIAL_ECHO_START;
  2285. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2286. } else {
  2287. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2288. SERIAL_ECHO_START;
  2289. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2290. }
  2291. }
  2292. #endif // Z_SAFE_HOMING
  2293. #endif // Z_HOME_DIR < 0
  2294. if(home_z_axis && home_z_value != 0)
  2295. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2296. #ifdef ENABLE_AUTO_BED_LEVELING
  2297. if(home_z)
  2298. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2299. #endif
  2300. // Set the planner and stepper routine positions.
  2301. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2302. // contains the machine coordinates.
  2303. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2304. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  2305. enable_endstops(false);
  2306. #endif
  2307. feedrate = saved_feedrate;
  2308. feedmultiply = l_feedmultiply;
  2309. previous_millis_cmd = _millis();
  2310. endstops_hit_on_purpose();
  2311. #ifndef MESH_BED_LEVELING
  2312. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  2313. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  2314. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  2315. lcd_adjust_z();
  2316. #endif
  2317. // Load the machine correction matrix
  2318. world2machine_initialize();
  2319. // and correct the current_position XY axes to match the transformed coordinate system.
  2320. world2machine_update_current();
  2321. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP))
  2322. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2323. {
  2324. if (! home_z && mbl_was_active) {
  2325. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2326. mbl.active = true;
  2327. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2328. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2329. }
  2330. }
  2331. else
  2332. {
  2333. st_synchronize();
  2334. homing_flag = false;
  2335. }
  2336. #endif
  2337. if (farm_mode) { prusa_statistics(20); };
  2338. homing_flag = false;
  2339. #if 0
  2340. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2341. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2342. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2343. #endif
  2344. }
  2345. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2346. {
  2347. #ifdef TMC2130
  2348. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2349. #else
  2350. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2351. #endif //TMC2130
  2352. }
  2353. void adjust_bed_reset()
  2354. {
  2355. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2356. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2357. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2358. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2359. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2360. }
  2361. //! @brief Calibrate XYZ
  2362. //! @param onlyZ if true, calibrate only Z axis
  2363. //! @param verbosity_level
  2364. //! @retval true Succeeded
  2365. //! @retval false Failed
  2366. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2367. {
  2368. bool final_result = false;
  2369. #ifdef TMC2130
  2370. FORCE_HIGH_POWER_START;
  2371. #endif // TMC2130
  2372. // Only Z calibration?
  2373. if (!onlyZ)
  2374. {
  2375. setTargetBed(0);
  2376. setAllTargetHotends(0);
  2377. adjust_bed_reset(); //reset bed level correction
  2378. }
  2379. // Disable the default update procedure of the display. We will do a modal dialog.
  2380. lcd_update_enable(false);
  2381. // Let the planner use the uncorrected coordinates.
  2382. mbl.reset();
  2383. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2384. // the planner will not perform any adjustments in the XY plane.
  2385. // Wait for the motors to stop and update the current position with the absolute values.
  2386. world2machine_revert_to_uncorrected();
  2387. // Reset the baby step value applied without moving the axes.
  2388. babystep_reset();
  2389. // Mark all axes as in a need for homing.
  2390. memset(axis_known_position, 0, sizeof(axis_known_position));
  2391. // Home in the XY plane.
  2392. //set_destination_to_current();
  2393. int l_feedmultiply = setup_for_endstop_move();
  2394. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2395. home_xy();
  2396. enable_endstops(false);
  2397. current_position[X_AXIS] += 5;
  2398. current_position[Y_AXIS] += 5;
  2399. 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);
  2400. st_synchronize();
  2401. // Let the user move the Z axes up to the end stoppers.
  2402. #ifdef TMC2130
  2403. if (calibrate_z_auto())
  2404. {
  2405. #else //TMC2130
  2406. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2407. {
  2408. #endif //TMC2130
  2409. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2410. if(onlyZ){
  2411. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2412. lcd_set_cursor(0, 3);
  2413. lcd_print(1);
  2414. lcd_puts_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE2));
  2415. }else{
  2416. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2417. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2418. lcd_set_cursor(0, 2);
  2419. lcd_print(1);
  2420. lcd_puts_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE2));
  2421. }
  2422. refresh_cmd_timeout();
  2423. #ifndef STEEL_SHEET
  2424. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2425. {
  2426. lcd_wait_for_cool_down();
  2427. }
  2428. #endif //STEEL_SHEET
  2429. if(!onlyZ)
  2430. {
  2431. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2432. #ifdef STEEL_SHEET
  2433. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  2434. if(result) lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2435. #endif //STEEL_SHEET
  2436. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2437. KEEPALIVE_STATE(IN_HANDLER);
  2438. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2439. lcd_set_cursor(0, 2);
  2440. lcd_print(1);
  2441. lcd_puts_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE2));
  2442. }
  2443. bool endstops_enabled = enable_endstops(false);
  2444. current_position[Z_AXIS] -= 1; //move 1mm down with disabled endstop
  2445. 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);
  2446. st_synchronize();
  2447. // Move the print head close to the bed.
  2448. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2449. enable_endstops(true);
  2450. #ifdef TMC2130
  2451. tmc2130_home_enter(Z_AXIS_MASK);
  2452. #endif //TMC2130
  2453. 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);
  2454. st_synchronize();
  2455. #ifdef TMC2130
  2456. tmc2130_home_exit();
  2457. #endif //TMC2130
  2458. enable_endstops(endstops_enabled);
  2459. if (st_get_position_mm(Z_AXIS) == MESH_HOME_Z_SEARCH)
  2460. {
  2461. if (onlyZ)
  2462. {
  2463. clean_up_after_endstop_move(l_feedmultiply);
  2464. // Z only calibration.
  2465. // Load the machine correction matrix
  2466. world2machine_initialize();
  2467. // and correct the current_position to match the transformed coordinate system.
  2468. world2machine_update_current();
  2469. //FIXME
  2470. bool result = sample_mesh_and_store_reference();
  2471. if (result)
  2472. {
  2473. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2474. // Shipped, the nozzle height has been set already. The user can start printing now.
  2475. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2476. final_result = true;
  2477. // babystep_apply();
  2478. }
  2479. }
  2480. else
  2481. {
  2482. // Reset the baby step value and the baby step applied flag.
  2483. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2484. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z, 0);
  2485. // Complete XYZ calibration.
  2486. uint8_t point_too_far_mask = 0;
  2487. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2488. clean_up_after_endstop_move(l_feedmultiply);
  2489. // Print head up.
  2490. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2491. 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);
  2492. st_synchronize();
  2493. //#ifndef NEW_XYZCAL
  2494. if (result >= 0)
  2495. {
  2496. #ifdef HEATBED_V2
  2497. sample_z();
  2498. #else //HEATBED_V2
  2499. point_too_far_mask = 0;
  2500. // Second half: The fine adjustment.
  2501. // Let the planner use the uncorrected coordinates.
  2502. mbl.reset();
  2503. world2machine_reset();
  2504. // Home in the XY plane.
  2505. int l_feedmultiply = setup_for_endstop_move();
  2506. home_xy();
  2507. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2508. clean_up_after_endstop_move(l_feedmultiply);
  2509. // Print head up.
  2510. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2511. 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);
  2512. st_synchronize();
  2513. // if (result >= 0) babystep_apply();
  2514. #endif //HEATBED_V2
  2515. }
  2516. //#endif //NEW_XYZCAL
  2517. lcd_update_enable(true);
  2518. lcd_update(2);
  2519. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2520. if (result >= 0)
  2521. {
  2522. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2523. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2524. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2525. final_result = true;
  2526. }
  2527. }
  2528. #ifdef TMC2130
  2529. tmc2130_home_exit();
  2530. #endif
  2531. }
  2532. else
  2533. {
  2534. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2535. final_result = false;
  2536. }
  2537. }
  2538. else
  2539. {
  2540. // Timeouted.
  2541. }
  2542. lcd_update_enable(true);
  2543. #ifdef TMC2130
  2544. FORCE_HIGH_POWER_END;
  2545. #endif // TMC2130
  2546. return final_result;
  2547. }
  2548. void gcode_M114()
  2549. {
  2550. SERIAL_PROTOCOLPGM("X:");
  2551. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2552. SERIAL_PROTOCOLPGM(" Y:");
  2553. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2554. SERIAL_PROTOCOLPGM(" Z:");
  2555. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2556. SERIAL_PROTOCOLPGM(" E:");
  2557. SERIAL_PROTOCOL(current_position[E_AXIS]);
  2558. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  2559. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  2560. SERIAL_PROTOCOLPGM(" Y:");
  2561. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  2562. SERIAL_PROTOCOLPGM(" Z:");
  2563. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  2564. SERIAL_PROTOCOLPGM(" E:");
  2565. SERIAL_PROTOCOL(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  2566. SERIAL_PROTOCOLLN("");
  2567. }
  2568. //! extracted code to compute z_shift for M600 in case of filament change operation
  2569. //! requested from fsensors.
  2570. //! The function ensures, that the printhead lifts to at least 25mm above the heat bed
  2571. //! unlike the previous implementation, which was adding 25mm even when the head was
  2572. //! printing at e.g. 24mm height.
  2573. //! A safety margin of FILAMENTCHANGE_ZADD is added in all cases to avoid touching
  2574. //! the printout.
  2575. //! This function is templated to enable fast change of computation data type.
  2576. //! @return new z_shift value
  2577. template<typename T>
  2578. static T gcode_M600_filament_change_z_shift()
  2579. {
  2580. #ifdef FILAMENTCHANGE_ZADD
  2581. static_assert(Z_MAX_POS < (255 - FILAMENTCHANGE_ZADD), "Z-range too high, change the T type from uint8_t to uint16_t");
  2582. // avoid floating point arithmetics when not necessary - results in shorter code
  2583. T ztmp = T( current_position[Z_AXIS] );
  2584. T z_shift = 0;
  2585. if(ztmp < T(25)){
  2586. z_shift = T(25) - ztmp; // make sure to be at least 25mm above the heat bed
  2587. }
  2588. return z_shift + T(FILAMENTCHANGE_ZADD); // always move above printout
  2589. #else
  2590. return T(0);
  2591. #endif
  2592. }
  2593. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/)
  2594. {
  2595. st_synchronize();
  2596. float lastpos[4];
  2597. if (farm_mode)
  2598. {
  2599. prusa_statistics(22);
  2600. }
  2601. //First backup current position and settings
  2602. int feedmultiplyBckp = feedmultiply;
  2603. float HotendTempBckp = degTargetHotend(active_extruder);
  2604. int fanSpeedBckp = fanSpeed;
  2605. lastpos[X_AXIS] = current_position[X_AXIS];
  2606. lastpos[Y_AXIS] = current_position[Y_AXIS];
  2607. lastpos[Z_AXIS] = current_position[Z_AXIS];
  2608. lastpos[E_AXIS] = current_position[E_AXIS];
  2609. //Retract E
  2610. current_position[E_AXIS] += e_shift;
  2611. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  2612. current_position[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  2613. st_synchronize();
  2614. //Lift Z
  2615. current_position[Z_AXIS] += z_shift;
  2616. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  2617. current_position[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  2618. st_synchronize();
  2619. //Move XY to side
  2620. current_position[X_AXIS] = x_position;
  2621. current_position[Y_AXIS] = y_position;
  2622. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  2623. current_position[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  2624. st_synchronize();
  2625. //Beep, manage nozzle heater and wait for user to start unload filament
  2626. if(!mmu_enabled) M600_wait_for_user(HotendTempBckp);
  2627. lcd_change_fil_state = 0;
  2628. // Unload filament
  2629. if (mmu_enabled) extr_unload(); //unload just current filament for multimaterial printers (used also in M702)
  2630. else unload_filament(); //unload filament for single material (used also in M702)
  2631. //finish moves
  2632. st_synchronize();
  2633. if (!mmu_enabled)
  2634. {
  2635. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2636. lcd_change_fil_state = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Was filament unload successful?"),
  2637. false, true); ////MSG_UNLOAD_SUCCESSFUL c=20 r=2
  2638. if (lcd_change_fil_state == 0)
  2639. {
  2640. lcd_clear();
  2641. lcd_set_cursor(0, 2);
  2642. lcd_puts_P(_T(MSG_PLEASE_WAIT));
  2643. current_position[X_AXIS] -= 100;
  2644. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  2645. current_position[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  2646. st_synchronize();
  2647. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually."));////MSG_CHECK_IDLER c=20 r=4
  2648. }
  2649. }
  2650. if (mmu_enabled)
  2651. {
  2652. if (!automatic) {
  2653. 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
  2654. mmu_M600_wait_and_beep();
  2655. if (saved_printing) {
  2656. lcd_clear();
  2657. lcd_set_cursor(0, 2);
  2658. lcd_puts_P(_T(MSG_PLEASE_WAIT));
  2659. mmu_command(MmuCmd::R0);
  2660. manage_response(false, false);
  2661. }
  2662. }
  2663. mmu_M600_load_filament(automatic, HotendTempBckp);
  2664. }
  2665. else
  2666. M600_load_filament();
  2667. if (!automatic) M600_check_state(HotendTempBckp);
  2668. lcd_update_enable(true);
  2669. //Not let's go back to print
  2670. fanSpeed = fanSpeedBckp;
  2671. //Feed a little of filament to stabilize pressure
  2672. if (!automatic)
  2673. {
  2674. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  2675. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  2676. current_position[E_AXIS], FILAMENTCHANGE_EXFEED, active_extruder);
  2677. }
  2678. //Move XY back
  2679. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  2680. FILAMENTCHANGE_XYFEED, active_extruder);
  2681. st_synchronize();
  2682. //Move Z back
  2683. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS],
  2684. FILAMENTCHANGE_ZFEED, active_extruder);
  2685. st_synchronize();
  2686. //Set E position to original
  2687. plan_set_e_position(lastpos[E_AXIS]);
  2688. memcpy(current_position, lastpos, sizeof(lastpos));
  2689. memcpy(destination, current_position, sizeof(current_position));
  2690. //Recover feed rate
  2691. feedmultiply = feedmultiplyBckp;
  2692. char cmd[9];
  2693. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  2694. enquecommand(cmd);
  2695. #ifdef IR_SENSOR
  2696. //this will set fsensor_watch_autoload to correct value and prevent possible M701 gcode enqueuing when M600 is finished
  2697. fsensor_check_autoload();
  2698. #endif //IR_SENSOR
  2699. lcd_setstatuspgm(_T(WELCOME_MSG));
  2700. custom_message_type = CustomMsg::Status;
  2701. }
  2702. //! @brief Rise Z if too low to avoid blob/jam before filament loading
  2703. //!
  2704. //! It doesn't plan_buffer_line(), as it expects plan_buffer_line() to be called after
  2705. //! during extruding (loading) filament.
  2706. void marlin_rise_z(void)
  2707. {
  2708. if (current_position[Z_AXIS] < 20) current_position[Z_AXIS] += 30;
  2709. }
  2710. void gcode_M701()
  2711. {
  2712. printf_P(PSTR("gcode_M701 begin\n"));
  2713. if (farm_mode)
  2714. {
  2715. prusa_statistics(22);
  2716. }
  2717. if (mmu_enabled)
  2718. {
  2719. extr_adj(tmp_extruder);//loads current extruder
  2720. mmu_extruder = tmp_extruder;
  2721. }
  2722. else
  2723. {
  2724. enable_z();
  2725. custom_message_type = CustomMsg::FilamentLoading;
  2726. #ifdef FSENSOR_QUALITY
  2727. fsensor_oq_meassure_start(40);
  2728. #endif //FSENSOR_QUALITY
  2729. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  2730. current_position[E_AXIS] += 40;
  2731. 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
  2732. st_synchronize();
  2733. marlin_rise_z();
  2734. current_position[E_AXIS] += 30;
  2735. 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
  2736. load_filament_final_feed(); //slow sequence
  2737. st_synchronize();
  2738. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE)) _tone(BEEPER, 500);
  2739. delay_keep_alive(50);
  2740. _noTone(BEEPER);
  2741. if (!farm_mode && loading_flag) {
  2742. lcd_load_filament_color_check();
  2743. }
  2744. lcd_update_enable(true);
  2745. lcd_update(2);
  2746. lcd_setstatuspgm(_T(WELCOME_MSG));
  2747. disable_z();
  2748. loading_flag = false;
  2749. custom_message_type = CustomMsg::Status;
  2750. #ifdef FSENSOR_QUALITY
  2751. fsensor_oq_meassure_stop();
  2752. if (!fsensor_oq_result())
  2753. {
  2754. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Fil. sensor response is poor, disable it?"), false, true);
  2755. lcd_update_enable(true);
  2756. lcd_update(2);
  2757. if (disable)
  2758. fsensor_disable();
  2759. }
  2760. #endif //FSENSOR_QUALITY
  2761. }
  2762. }
  2763. /**
  2764. * @brief Get serial number from 32U2 processor
  2765. *
  2766. * Typical format of S/N is:CZPX0917X003XC13518
  2767. *
  2768. * Command operates only in farm mode, if not in farm mode, "Not in farm mode." is written to MYSERIAL.
  2769. *
  2770. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  2771. * reply is transmitted to serial port 1 character by character.
  2772. * Operation takes typically 23 ms. If the retransmit is not finished until 100 ms,
  2773. * it is interrupted, so less, or no characters are retransmitted, only newline character is send
  2774. * in any case.
  2775. */
  2776. static void gcode_PRUSA_SN()
  2777. {
  2778. if (farm_mode) {
  2779. selectedSerialPort = 0;
  2780. putchar(';');
  2781. putchar('S');
  2782. int numbersRead = 0;
  2783. ShortTimer timeout;
  2784. timeout.start();
  2785. while (numbersRead < 19) {
  2786. while (MSerial.available() > 0) {
  2787. uint8_t serial_char = MSerial.read();
  2788. selectedSerialPort = 1;
  2789. putchar(serial_char);
  2790. numbersRead++;
  2791. selectedSerialPort = 0;
  2792. }
  2793. if (timeout.expired(100u)) break;
  2794. }
  2795. selectedSerialPort = 1;
  2796. putchar('\n');
  2797. #if 0
  2798. for (int b = 0; b < 3; b++) {
  2799. _tone(BEEPER, 110);
  2800. _delay(50);
  2801. _noTone(BEEPER);
  2802. _delay(50);
  2803. }
  2804. #endif
  2805. } else {
  2806. puts_P(_N("Not in farm mode."));
  2807. }
  2808. }
  2809. #ifdef BACKLASH_X
  2810. extern uint8_t st_backlash_x;
  2811. #endif //BACKLASH_X
  2812. #ifdef BACKLASH_Y
  2813. extern uint8_t st_backlash_y;
  2814. #endif //BACKLASH_Y
  2815. //! @brief Parse and process commands
  2816. //!
  2817. //! look here for descriptions of G-codes: http://linuxcnc.org/handbook/gcode/g-code.html
  2818. //! http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  2819. //!
  2820. //! Implemented Codes
  2821. //! -------------------
  2822. //!
  2823. //!@n PRUSA CODES
  2824. //!@n P F - Returns FW versions
  2825. //!@n P R - Returns revision of printer
  2826. //!
  2827. //!@n G0 -> G1
  2828. //!@n G1 - Coordinated Movement X Y Z E
  2829. //!@n G2 - CW ARC
  2830. //!@n G3 - CCW ARC
  2831. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  2832. //!@n G10 - retract filament according to settings of M207
  2833. //!@n G11 - retract recover filament according to settings of M208
  2834. //!@n G28 - Home all Axis
  2835. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  2836. //!@n G30 - Single Z Probe, probes bed at current XY location.
  2837. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  2838. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  2839. //!@n G80 - Automatic mesh bed leveling
  2840. //!@n G81 - Print bed profile
  2841. //!@n G90 - Use Absolute Coordinates
  2842. //!@n G91 - Use Relative Coordinates
  2843. //!@n G92 - Set current position to coordinates given
  2844. //!
  2845. //!@n M Codes
  2846. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  2847. //!@n M1 - Same as M0
  2848. //!@n M17 - Enable/Power all stepper motors
  2849. //!@n M18 - Disable all stepper motors; same as M84
  2850. //!@n M20 - List SD card
  2851. //!@n M21 - Init SD card
  2852. //!@n M22 - Release SD card
  2853. //!@n M23 - Select SD file (M23 filename.g)
  2854. //!@n M24 - Start/resume SD print
  2855. //!@n M25 - Pause SD print
  2856. //!@n M26 - Set SD position in bytes (M26 S12345)
  2857. //!@n M27 - Report SD print status
  2858. //!@n M28 - Start SD write (M28 filename.g)
  2859. //!@n M29 - Stop SD write
  2860. //!@n M30 - Delete file from SD (M30 filename.g)
  2861. //!@n M31 - Output time since last M109 or SD card start to serial
  2862. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  2863. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  2864. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  2865. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  2866. //!@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.
  2867. //!@n M73 - Show percent done and print time remaining
  2868. //!@n M80 - Turn on Power Supply
  2869. //!@n M81 - Turn off Power Supply
  2870. //!@n M82 - Set E codes absolute (default)
  2871. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  2872. //!@n M84 - Disable steppers until next move,
  2873. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  2874. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  2875. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  2876. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  2877. //!@n M104 - Set extruder target temp
  2878. //!@n M105 - Read current temp
  2879. //!@n M106 - Fan on
  2880. //!@n M107 - Fan off
  2881. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  2882. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  2883. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  2884. //!@n M112 - Emergency stop
  2885. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  2886. //!@n M114 - Output current position to serial port
  2887. //!@n M115 - Capabilities string
  2888. //!@n M117 - display message
  2889. //!@n M119 - Output Endstop status to serial port
  2890. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  2891. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  2892. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  2893. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  2894. //!@n M140 - Set bed target temp
  2895. //!@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.
  2896. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  2897. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  2898. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  2899. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  2900. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  2901. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  2902. //!@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
  2903. //!@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
  2904. //!@n M206 - set additional homing offset
  2905. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  2906. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  2907. //!@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.
  2908. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  2909. //!@n M220 S<factor in percent>- set speed factor override percentage
  2910. //!@n M221 S<factor in percent>- set extrude factor override percentage
  2911. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  2912. //!@n M240 - Trigger a camera to take a photograph
  2913. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  2914. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  2915. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  2916. //!@n M301 - Set PID parameters P I and D
  2917. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  2918. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  2919. //!@n M304 - Set bed PID parameters P I and D
  2920. //!@n M400 - Finish all moves
  2921. //!@n M401 - Lower z-probe if present
  2922. //!@n M402 - Raise z-probe if present
  2923. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  2924. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  2925. //!@n M406 - Turn off Filament Sensor extrusion control
  2926. //!@n M407 - Displays measured filament diameter
  2927. //!@n M500 - stores parameters in EEPROM
  2928. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  2929. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  2930. //!@n M503 - print the current settings (from memory not from EEPROM)
  2931. //!@n M509 - force language selection on next restart
  2932. //!@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)
  2933. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  2934. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  2935. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  2936. //!@n M861 - Set / Read PINDA temperature compensation offsets
  2937. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  2938. //!@n M907 - Set digital trimpot motor current using axis codes.
  2939. //!@n M908 - Control digital trimpot directly.
  2940. //!@n M350 - Set microstepping mode.
  2941. //!@n M351 - Toggle MS1 MS2 pins directly.
  2942. //!
  2943. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  2944. //!@n M999 - Restart after being stopped by error
  2945. void process_commands()
  2946. {
  2947. #ifdef FANCHECK
  2948. if (fan_check_error){
  2949. if( fan_check_error == EFCE_DETECTED ){
  2950. fan_check_error = EFCE_REPORTED;
  2951. lcd_pause_print();
  2952. } // otherwise it has already been reported, so just ignore further processing
  2953. return;
  2954. }
  2955. #endif
  2956. if (!buflen) return; //empty command
  2957. #ifdef FILAMENT_RUNOUT_SUPPORT
  2958. SET_INPUT(FR_SENS);
  2959. #endif
  2960. #ifdef CMDBUFFER_DEBUG
  2961. SERIAL_ECHOPGM("Processing a GCODE command: ");
  2962. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  2963. SERIAL_ECHOLNPGM("");
  2964. SERIAL_ECHOPGM("In cmdqueue: ");
  2965. SERIAL_ECHO(buflen);
  2966. SERIAL_ECHOLNPGM("");
  2967. #endif /* CMDBUFFER_DEBUG */
  2968. unsigned long codenum; //throw away variable
  2969. char *starpos = NULL;
  2970. #ifdef ENABLE_AUTO_BED_LEVELING
  2971. float x_tmp, y_tmp, z_tmp, real_z;
  2972. #endif
  2973. // PRUSA GCODES
  2974. KEEPALIVE_STATE(IN_HANDLER);
  2975. #ifdef SNMM
  2976. float tmp_motor[3] = DEFAULT_PWM_MOTOR_CURRENT;
  2977. float tmp_motor_loud[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  2978. int8_t SilentMode;
  2979. #endif
  2980. if (code_seen("M117")) { //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  2981. starpos = (strchr(strchr_pointer + 5, '*'));
  2982. if (starpos != NULL)
  2983. *(starpos) = '\0';
  2984. lcd_setstatus(strchr_pointer + 5);
  2985. }
  2986. #ifdef TMC2130
  2987. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  2988. {
  2989. if(code_seen("CRASH_DETECTED")) //! CRASH_DETECTED
  2990. {
  2991. uint8_t mask = 0;
  2992. if (code_seen('X')) mask |= X_AXIS_MASK;
  2993. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  2994. crashdet_detected(mask);
  2995. }
  2996. else if(code_seen("CRASH_RECOVER")) //! CRASH_RECOVER
  2997. crashdet_recover();
  2998. else if(code_seen("CRASH_CANCEL")) //! CRASH_CANCEL
  2999. crashdet_cancel();
  3000. }
  3001. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3002. {
  3003. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0) //! TMC_SET_WAVE_
  3004. {
  3005. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3006. axis = (axis == 'E')?3:(axis - 'X');
  3007. if (axis < 4)
  3008. {
  3009. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3010. tmc2130_set_wave(axis, 247, fac);
  3011. }
  3012. }
  3013. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0) //! TMC_SET_STEP_
  3014. {
  3015. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3016. axis = (axis == 'E')?3:(axis - 'X');
  3017. if (axis < 4)
  3018. {
  3019. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3020. uint16_t res = tmc2130_get_res(axis);
  3021. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3022. }
  3023. }
  3024. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0) //! TMC_SET_CHOP_
  3025. {
  3026. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3027. axis = (axis == 'E')?3:(axis - 'X');
  3028. if (axis < 4)
  3029. {
  3030. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  3031. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3032. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3033. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3034. char* str_end = 0;
  3035. if (CMDBUFFER_CURRENT_STRING[14])
  3036. {
  3037. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3038. if (str_end && *str_end)
  3039. {
  3040. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3041. if (str_end && *str_end)
  3042. {
  3043. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3044. if (str_end && *str_end)
  3045. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3046. }
  3047. }
  3048. }
  3049. tmc2130_chopper_config[axis].toff = chop0;
  3050. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3051. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3052. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3053. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3054. //printf_P(_N("TMC_SET_CHOP_%c %hhd %hhd %hhd %hhd\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3055. }
  3056. }
  3057. }
  3058. #ifdef BACKLASH_X
  3059. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3060. {
  3061. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3062. st_backlash_x = bl;
  3063. printf_P(_N("st_backlash_x = %hhd\n"), st_backlash_x);
  3064. }
  3065. #endif //BACKLASH_X
  3066. #ifdef BACKLASH_Y
  3067. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3068. {
  3069. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3070. st_backlash_y = bl;
  3071. printf_P(_N("st_backlash_y = %hhd\n"), st_backlash_y);
  3072. }
  3073. #endif //BACKLASH_Y
  3074. #endif //TMC2130
  3075. else if(code_seen("PRUSA")){
  3076. if (code_seen("Ping")) { //! PRUSA Ping
  3077. if (farm_mode) {
  3078. PingTime = _millis();
  3079. //MYSERIAL.print(farm_no); MYSERIAL.println(": OK");
  3080. }
  3081. }
  3082. else if (code_seen("PRN")) { //! PRUSA PRN
  3083. printf_P(_N("%d"), status_number);
  3084. }else if (code_seen("FAN")) { //! PRUSA FAN
  3085. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3086. }else if (code_seen("fn")) { //! PRUSA fn
  3087. if (farm_mode) {
  3088. printf_P(_N("%d"), farm_no);
  3089. }
  3090. else {
  3091. puts_P(_N("Not in farm mode."));
  3092. }
  3093. }
  3094. else if (code_seen("thx")) //! PRUSA thx
  3095. {
  3096. no_response = false;
  3097. }
  3098. else if (code_seen("uvlo")) //! PRUSA uvlo
  3099. {
  3100. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3101. enquecommand_P(PSTR("M24"));
  3102. }
  3103. #ifdef FILAMENT_SENSOR
  3104. else if (code_seen("fsensor_recover")) //! PRUSA fsensor_recover
  3105. {
  3106. fsensor_restore_print_and_continue();
  3107. }
  3108. #endif //FILAMENT_SENSOR
  3109. else if (code_seen("MMURES")) //! PRUSA MMURES
  3110. {
  3111. mmu_reset();
  3112. }
  3113. else if (code_seen("RESET")) { //! PRUSA RESET
  3114. // careful!
  3115. if (farm_mode) {
  3116. #if (defined(WATCHDOG) && (MOTHERBOARD == BOARD_EINSY_1_0a))
  3117. boot_app_magic = BOOT_APP_MAGIC;
  3118. boot_app_flags = BOOT_APP_FLG_RUN;
  3119. wdt_enable(WDTO_15MS);
  3120. cli();
  3121. while(1);
  3122. #else //WATCHDOG
  3123. asm volatile("jmp 0x3E000");
  3124. #endif //WATCHDOG
  3125. }
  3126. else {
  3127. MYSERIAL.println("Not in farm mode.");
  3128. }
  3129. }else if (code_seen("fv")) { //! PRUSA fv
  3130. // get file version
  3131. #ifdef SDSUPPORT
  3132. card.openFile(strchr_pointer + 3,true);
  3133. while (true) {
  3134. uint16_t readByte = card.get();
  3135. MYSERIAL.write(readByte);
  3136. if (readByte=='\n') {
  3137. break;
  3138. }
  3139. }
  3140. card.closefile();
  3141. #endif // SDSUPPORT
  3142. } else if (code_seen("M28")) { //! PRUSA M28
  3143. trace();
  3144. prusa_sd_card_upload = true;
  3145. card.openFile(strchr_pointer+4,false);
  3146. } else if (code_seen("SN")) { //! PRUSA SN
  3147. gcode_PRUSA_SN();
  3148. } else if(code_seen("Fir")){ //! PRUSA Fir
  3149. SERIAL_PROTOCOLLN(FW_VERSION_FULL);
  3150. } else if(code_seen("Rev")){ //! PRUSA Rev
  3151. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3152. } else if(code_seen("Lang")) { //! PRUSA Lang
  3153. lang_reset();
  3154. } else if(code_seen("Lz")) { //! PRUSA Lz
  3155. EEPROM_save_B(EEPROM_BABYSTEP_Z,0);
  3156. } else if(code_seen("Beat")) { //! PRUSA Beat
  3157. // Kick farm link timer
  3158. kicktime = _millis();
  3159. } else if(code_seen("FR")) { //! PRUSA FR
  3160. // Factory full reset
  3161. factory_reset(0);
  3162. //-//
  3163. /*
  3164. } else if(code_seen("qqq")) {
  3165. MYSERIAL.println("=== checking ===");
  3166. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_CHECK_MODE),DEC);
  3167. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER),DEC);
  3168. MYSERIAL.println(eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM),DEC);
  3169. MYSERIAL.println(farm_mode,DEC);
  3170. MYSERIAL.println(eCheckMode,DEC);
  3171. } else if(code_seen("www")) {
  3172. MYSERIAL.println("=== @ FF ===");
  3173. eeprom_update_byte((uint8_t*)EEPROM_CHECK_MODE,0xFF);
  3174. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,0xFF);
  3175. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,0xFFFF);
  3176. */
  3177. } else if (code_seen("nozzle")) { //! PRUSA nozzle
  3178. uint16_t nDiameter;
  3179. if(code_seen('D'))
  3180. {
  3181. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3182. nozzle_diameter_check(nDiameter);
  3183. }
  3184. else if(code_seen("set") && farm_mode)
  3185. {
  3186. strchr_pointer++; // skip 2nd char (~ 'e')
  3187. strchr_pointer++; // skip 3rd char (~ 't')
  3188. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3189. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)e_NOZZLE_DIAMETER_NULL); // for correct synchronization after farm-mode exiting
  3190. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  3191. }
  3192. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  3193. }
  3194. //else if (code_seen('Cal')) {
  3195. // lcd_calibration();
  3196. // }
  3197. }
  3198. else if (code_seen('^')) {
  3199. // nothing, this is a version line
  3200. } else if(code_seen('G'))
  3201. {
  3202. gcode_in_progress = (int)code_value();
  3203. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3204. switch (gcode_in_progress)
  3205. {
  3206. case 0: // G0 -> G1
  3207. case 1: // G1
  3208. if(Stopped == false) {
  3209. #ifdef FILAMENT_RUNOUT_SUPPORT
  3210. if(READ(FR_SENS)){
  3211. int feedmultiplyBckp=feedmultiply;
  3212. float target[4];
  3213. float lastpos[4];
  3214. target[X_AXIS]=current_position[X_AXIS];
  3215. target[Y_AXIS]=current_position[Y_AXIS];
  3216. target[Z_AXIS]=current_position[Z_AXIS];
  3217. target[E_AXIS]=current_position[E_AXIS];
  3218. lastpos[X_AXIS]=current_position[X_AXIS];
  3219. lastpos[Y_AXIS]=current_position[Y_AXIS];
  3220. lastpos[Z_AXIS]=current_position[Z_AXIS];
  3221. lastpos[E_AXIS]=current_position[E_AXIS];
  3222. //retract by E
  3223. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT ;
  3224. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  3225. target[Z_AXIS]+= FILAMENTCHANGE_ZADD ;
  3226. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 300, active_extruder);
  3227. target[X_AXIS]= FILAMENTCHANGE_XPOS ;
  3228. target[Y_AXIS]= FILAMENTCHANGE_YPOS ;
  3229. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder);
  3230. target[E_AXIS]+= FILAMENTCHANGE_FINALRETRACT ;
  3231. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3232. //finish moves
  3233. st_synchronize();
  3234. //disable extruder steppers so filament can be removed
  3235. disable_e0();
  3236. disable_e1();
  3237. disable_e2();
  3238. _delay(100);
  3239. //LCD_ALERTMESSAGEPGM(_T(MSG_FILAMENTCHANGE));
  3240. uint8_t cnt=0;
  3241. int counterBeep = 0;
  3242. lcd_wait_interact();
  3243. while(!lcd_clicked()){
  3244. cnt++;
  3245. manage_heater();
  3246. manage_inactivity(true);
  3247. //lcd_update(0);
  3248. if(cnt==0)
  3249. {
  3250. #if BEEPER > 0
  3251. if (counterBeep== 500){
  3252. counterBeep = 0;
  3253. }
  3254. SET_OUTPUT(BEEPER);
  3255. if (counterBeep== 0){
  3256. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  3257. WRITE(BEEPER,HIGH);
  3258. }
  3259. if (counterBeep== 20){
  3260. WRITE(BEEPER,LOW);
  3261. }
  3262. counterBeep++;
  3263. #else
  3264. #endif
  3265. }
  3266. }
  3267. WRITE(BEEPER,LOW);
  3268. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3269. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3270. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3271. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3272. lcd_change_fil_state = 0;
  3273. lcd_loading_filament();
  3274. while ((lcd_change_fil_state == 0)||(lcd_change_fil_state != 1)){
  3275. lcd_change_fil_state = 0;
  3276. lcd_alright();
  3277. switch(lcd_change_fil_state){
  3278. case 2:
  3279. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3280. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3281. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3282. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3283. lcd_loading_filament();
  3284. break;
  3285. case 3:
  3286. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3287. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3288. lcd_loading_color();
  3289. break;
  3290. default:
  3291. lcd_change_success();
  3292. break;
  3293. }
  3294. }
  3295. target[E_AXIS]+= 5;
  3296. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3297. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT;
  3298. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  3299. //current_position[E_AXIS]=target[E_AXIS]; //the long retract of L is compensated by manual filament feeding
  3300. //plan_set_e_position(current_position[E_AXIS]);
  3301. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //should do nothing
  3302. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //move xy back
  3303. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 200, active_extruder); //move z back
  3304. target[E_AXIS]= target[E_AXIS] - FILAMENTCHANGE_FIRSTRETRACT;
  3305. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 5, active_extruder); //final untretract
  3306. plan_set_e_position(lastpos[E_AXIS]);
  3307. feedmultiply=feedmultiplyBckp;
  3308. char cmd[9];
  3309. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3310. enquecommand(cmd);
  3311. }
  3312. #endif
  3313. get_coordinates(); // For X Y Z E F
  3314. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3315. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3316. }
  3317. #ifdef FWRETRACT
  3318. if(cs.autoretract_enabled)
  3319. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3320. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3321. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3322. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3323. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3324. retract(!retracted[active_extruder]);
  3325. return;
  3326. }
  3327. }
  3328. #endif //FWRETRACT
  3329. prepare_move();
  3330. //ClearToSend();
  3331. }
  3332. break;
  3333. case 2: // G2 - CW ARC
  3334. if(Stopped == false) {
  3335. get_arc_coordinates();
  3336. prepare_arc_move(true);
  3337. }
  3338. break;
  3339. case 3: // G3 - CCW ARC
  3340. if(Stopped == false) {
  3341. get_arc_coordinates();
  3342. prepare_arc_move(false);
  3343. }
  3344. break;
  3345. case 4: // G4 dwell
  3346. codenum = 0;
  3347. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3348. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3349. if(codenum != 0) LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  3350. st_synchronize();
  3351. codenum += _millis(); // keep track of when we started waiting
  3352. previous_millis_cmd = _millis();
  3353. while(_millis() < codenum) {
  3354. manage_heater();
  3355. manage_inactivity();
  3356. lcd_update(0);
  3357. }
  3358. break;
  3359. #ifdef FWRETRACT
  3360. case 10: // G10 retract
  3361. #if EXTRUDERS > 1
  3362. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  3363. retract(true,retracted_swap[active_extruder]);
  3364. #else
  3365. retract(true);
  3366. #endif
  3367. break;
  3368. case 11: // G11 retract_recover
  3369. #if EXTRUDERS > 1
  3370. retract(false,retracted_swap[active_extruder]);
  3371. #else
  3372. retract(false);
  3373. #endif
  3374. break;
  3375. #endif //FWRETRACT
  3376. case 28: //G28 Home all Axis one at a time
  3377. {
  3378. long home_x_value = 0;
  3379. long home_y_value = 0;
  3380. long home_z_value = 0;
  3381. // Which axes should be homed?
  3382. bool home_x = code_seen(axis_codes[X_AXIS]);
  3383. home_x_value = code_value_long();
  3384. bool home_y = code_seen(axis_codes[Y_AXIS]);
  3385. home_y_value = code_value_long();
  3386. bool home_z = code_seen(axis_codes[Z_AXIS]);
  3387. home_z_value = code_value_long();
  3388. bool without_mbl = code_seen('W');
  3389. // calibrate?
  3390. #ifdef TMC2130
  3391. bool calib = code_seen('C');
  3392. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  3393. #else
  3394. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  3395. #endif //TMC2130
  3396. if ((home_x || home_y || without_mbl || home_z) == false) {
  3397. // Push the commands to the front of the message queue in the reverse order!
  3398. // There shall be always enough space reserved for these commands.
  3399. goto case_G80;
  3400. }
  3401. break;
  3402. }
  3403. #ifdef ENABLE_AUTO_BED_LEVELING
  3404. case 29: // G29 Detailed Z-Probe, probes the bed at 3 or more points.
  3405. {
  3406. #if Z_MIN_PIN == -1
  3407. #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."
  3408. #endif
  3409. // Prevent user from running a G29 without first homing in X and Y
  3410. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  3411. {
  3412. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  3413. SERIAL_ECHO_START;
  3414. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  3415. break; // abort G29, since we don't know where we are
  3416. }
  3417. st_synchronize();
  3418. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  3419. //vector_3 corrected_position = plan_get_position_mm();
  3420. //corrected_position.debug("position before G29");
  3421. plan_bed_level_matrix.set_to_identity();
  3422. vector_3 uncorrected_position = plan_get_position();
  3423. //uncorrected_position.debug("position durring G29");
  3424. current_position[X_AXIS] = uncorrected_position.x;
  3425. current_position[Y_AXIS] = uncorrected_position.y;
  3426. current_position[Z_AXIS] = uncorrected_position.z;
  3427. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  3428. int l_feedmultiply = setup_for_endstop_move();
  3429. feedrate = homing_feedrate[Z_AXIS];
  3430. #ifdef AUTO_BED_LEVELING_GRID
  3431. // probe at the points of a lattice grid
  3432. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  3433. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  3434. // solve the plane equation ax + by + d = z
  3435. // A is the matrix with rows [x y 1] for all the probed points
  3436. // B is the vector of the Z positions
  3437. // 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
  3438. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  3439. // "A" matrix of the linear system of equations
  3440. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  3441. // "B" vector of Z points
  3442. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  3443. int probePointCounter = 0;
  3444. bool zig = true;
  3445. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  3446. {
  3447. int xProbe, xInc;
  3448. if (zig)
  3449. {
  3450. xProbe = LEFT_PROBE_BED_POSITION;
  3451. //xEnd = RIGHT_PROBE_BED_POSITION;
  3452. xInc = xGridSpacing;
  3453. zig = false;
  3454. } else // zag
  3455. {
  3456. xProbe = RIGHT_PROBE_BED_POSITION;
  3457. //xEnd = LEFT_PROBE_BED_POSITION;
  3458. xInc = -xGridSpacing;
  3459. zig = true;
  3460. }
  3461. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  3462. {
  3463. float z_before;
  3464. if (probePointCounter == 0)
  3465. {
  3466. // raise before probing
  3467. z_before = Z_RAISE_BEFORE_PROBING;
  3468. } else
  3469. {
  3470. // raise extruder
  3471. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  3472. }
  3473. float measured_z = probe_pt(xProbe, yProbe, z_before);
  3474. eqnBVector[probePointCounter] = measured_z;
  3475. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  3476. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  3477. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  3478. probePointCounter++;
  3479. xProbe += xInc;
  3480. }
  3481. }
  3482. clean_up_after_endstop_move(l_feedmultiply);
  3483. // solve lsq problem
  3484. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  3485. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  3486. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  3487. SERIAL_PROTOCOLPGM(" b: ");
  3488. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  3489. SERIAL_PROTOCOLPGM(" d: ");
  3490. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  3491. set_bed_level_equation_lsq(plane_equation_coefficients);
  3492. free(plane_equation_coefficients);
  3493. #else // AUTO_BED_LEVELING_GRID not defined
  3494. // Probe at 3 arbitrary points
  3495. // probe 1
  3496. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  3497. // probe 2
  3498. 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);
  3499. // probe 3
  3500. 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);
  3501. clean_up_after_endstop_move(l_feedmultiply);
  3502. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  3503. #endif // AUTO_BED_LEVELING_GRID
  3504. st_synchronize();
  3505. // The following code correct the Z height difference from z-probe position and hotend tip position.
  3506. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  3507. // When the bed is uneven, this height must be corrected.
  3508. 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)
  3509. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  3510. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  3511. z_tmp = current_position[Z_AXIS];
  3512. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  3513. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  3514. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  3515. }
  3516. break;
  3517. #ifndef Z_PROBE_SLED
  3518. case 30: // G30 Single Z Probe
  3519. {
  3520. st_synchronize();
  3521. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  3522. int l_feedmultiply = setup_for_endstop_move();
  3523. feedrate = homing_feedrate[Z_AXIS];
  3524. run_z_probe();
  3525. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  3526. SERIAL_PROTOCOLPGM(" X: ");
  3527. SERIAL_PROTOCOL(current_position[X_AXIS]);
  3528. SERIAL_PROTOCOLPGM(" Y: ");
  3529. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3530. SERIAL_PROTOCOLPGM(" Z: ");
  3531. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3532. SERIAL_PROTOCOLPGM("\n");
  3533. clean_up_after_endstop_move(l_feedmultiply);
  3534. }
  3535. break;
  3536. #else
  3537. case 31: // dock the sled
  3538. dock_sled(true);
  3539. break;
  3540. case 32: // undock the sled
  3541. dock_sled(false);
  3542. break;
  3543. #endif // Z_PROBE_SLED
  3544. #endif // ENABLE_AUTO_BED_LEVELING
  3545. #ifdef MESH_BED_LEVELING
  3546. case 30: // G30 Single Z Probe
  3547. {
  3548. st_synchronize();
  3549. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  3550. int l_feedmultiply = setup_for_endstop_move();
  3551. feedrate = homing_feedrate[Z_AXIS];
  3552. find_bed_induction_sensor_point_z(-10.f, 3);
  3553. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  3554. clean_up_after_endstop_move(l_feedmultiply);
  3555. }
  3556. break;
  3557. case 75:
  3558. {
  3559. for (int i = 40; i <= 110; i++)
  3560. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  3561. }
  3562. break;
  3563. case 76: //! G76 - PINDA probe temperature calibration
  3564. {
  3565. #ifdef PINDA_THERMISTOR
  3566. if (true)
  3567. {
  3568. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  3569. //we need to know accurate position of first calibration point
  3570. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  3571. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first."));
  3572. break;
  3573. }
  3574. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  3575. {
  3576. // We don't know where we are! HOME!
  3577. // Push the commands to the front of the message queue in the reverse order!
  3578. // There shall be always enough space reserved for these commands.
  3579. repeatcommand_front(); // repeat G76 with all its parameters
  3580. enquecommand_front_P((PSTR("G28 W0")));
  3581. break;
  3582. }
  3583. 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
  3584. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  3585. if (result)
  3586. {
  3587. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3588. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3589. current_position[Z_AXIS] = 50;
  3590. current_position[Y_AXIS] = 180;
  3591. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3592. st_synchronize();
  3593. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  3594. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  3595. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  3596. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3597. st_synchronize();
  3598. gcode_G28(false, false, true);
  3599. }
  3600. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  3601. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  3602. current_position[Z_AXIS] = 100;
  3603. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3604. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  3605. lcd_temp_cal_show_result(false);
  3606. break;
  3607. }
  3608. }
  3609. lcd_update_enable(true);
  3610. KEEPALIVE_STATE(NOT_BUSY); //no need to print busy messages as we print current temperatures periodicaly
  3611. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  3612. float zero_z;
  3613. int z_shift = 0; //unit: steps
  3614. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  3615. if (start_temp < 35) start_temp = 35;
  3616. if (start_temp < current_temperature_pinda) start_temp += 5;
  3617. printf_P(_N("start temperature: %.1f\n"), start_temp);
  3618. // setTargetHotend(200, 0);
  3619. setTargetBed(70 + (start_temp - 30));
  3620. custom_message_type = CustomMsg::TempCal;
  3621. custom_message_state = 1;
  3622. lcd_setstatuspgm(_T(MSG_TEMP_CALIBRATION));
  3623. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3624. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3625. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3626. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3627. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3628. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3629. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3630. st_synchronize();
  3631. while (current_temperature_pinda < start_temp)
  3632. {
  3633. delay_keep_alive(1000);
  3634. serialecho_temperatures();
  3635. }
  3636. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  3637. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3638. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3639. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  3640. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  3641. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3642. st_synchronize();
  3643. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  3644. if (find_z_result == false) {
  3645. lcd_temp_cal_show_result(find_z_result);
  3646. break;
  3647. }
  3648. zero_z = current_position[Z_AXIS];
  3649. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  3650. int i = -1; for (; i < 5; i++)
  3651. {
  3652. float temp = (40 + i * 5);
  3653. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  3654. if (i >= 0) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  3655. if (start_temp <= temp) break;
  3656. }
  3657. for (i++; i < 5; i++)
  3658. {
  3659. float temp = (40 + i * 5);
  3660. printf_P(_N("\nStep: %d/6\n"), i + 2);
  3661. custom_message_state = i + 2;
  3662. setTargetBed(50 + 10 * (temp - 30) / 5);
  3663. // setTargetHotend(255, 0);
  3664. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3665. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3666. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3667. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3668. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3669. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3670. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3671. st_synchronize();
  3672. while (current_temperature_pinda < temp)
  3673. {
  3674. delay_keep_alive(1000);
  3675. serialecho_temperatures();
  3676. }
  3677. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3678. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3679. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  3680. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  3681. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3682. st_synchronize();
  3683. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  3684. if (find_z_result == false) {
  3685. lcd_temp_cal_show_result(find_z_result);
  3686. break;
  3687. }
  3688. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  3689. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  3690. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  3691. }
  3692. lcd_temp_cal_show_result(true);
  3693. break;
  3694. }
  3695. #endif //PINDA_THERMISTOR
  3696. setTargetBed(PINDA_MIN_T);
  3697. float zero_z;
  3698. int z_shift = 0; //unit: steps
  3699. int t_c; // temperature
  3700. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  3701. // We don't know where we are! HOME!
  3702. // Push the commands to the front of the message queue in the reverse order!
  3703. // There shall be always enough space reserved for these commands.
  3704. repeatcommand_front(); // repeat G76 with all its parameters
  3705. enquecommand_front_P((PSTR("G28 W0")));
  3706. break;
  3707. }
  3708. puts_P(_N("PINDA probe calibration start"));
  3709. custom_message_type = CustomMsg::TempCal;
  3710. custom_message_state = 1;
  3711. lcd_setstatuspgm(_T(MSG_TEMP_CALIBRATION));
  3712. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3713. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3714. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3715. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3716. st_synchronize();
  3717. while (abs(degBed() - PINDA_MIN_T) > 1) {
  3718. delay_keep_alive(1000);
  3719. serialecho_temperatures();
  3720. }
  3721. //enquecommand_P(PSTR("M190 S50"));
  3722. for (int i = 0; i < PINDA_HEAT_T; i++) {
  3723. delay_keep_alive(1000);
  3724. serialecho_temperatures();
  3725. }
  3726. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  3727. current_position[Z_AXIS] = 5;
  3728. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3729. current_position[X_AXIS] = BED_X0;
  3730. current_position[Y_AXIS] = BED_Y0;
  3731. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3732. st_synchronize();
  3733. find_bed_induction_sensor_point_z(-1.f);
  3734. zero_z = current_position[Z_AXIS];
  3735. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  3736. for (int i = 0; i<5; i++) {
  3737. printf_P(_N("\nStep: %d/6\n"), i + 2);
  3738. custom_message_state = i + 2;
  3739. t_c = 60 + i * 10;
  3740. setTargetBed(t_c);
  3741. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3742. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3743. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3744. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3745. st_synchronize();
  3746. while (degBed() < t_c) {
  3747. delay_keep_alive(1000);
  3748. serialecho_temperatures();
  3749. }
  3750. for (int i = 0; i < PINDA_HEAT_T; i++) {
  3751. delay_keep_alive(1000);
  3752. serialecho_temperatures();
  3753. }
  3754. current_position[Z_AXIS] = 5;
  3755. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3756. current_position[X_AXIS] = BED_X0;
  3757. current_position[Y_AXIS] = BED_Y0;
  3758. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3759. st_synchronize();
  3760. find_bed_induction_sensor_point_z(-1.f);
  3761. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  3762. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  3763. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i*2, &z_shift);
  3764. }
  3765. custom_message_type = CustomMsg::Status;
  3766. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  3767. puts_P(_N("Temperature calibration done."));
  3768. disable_x();
  3769. disable_y();
  3770. disable_z();
  3771. disable_e0();
  3772. disable_e1();
  3773. disable_e2();
  3774. setTargetBed(0); //set bed target temperature back to 0
  3775. lcd_show_fullscreen_message_and_wait_P(_T(MSG_TEMP_CALIBRATION_DONE));
  3776. temp_cal_active = true;
  3777. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  3778. lcd_update_enable(true);
  3779. lcd_update(2);
  3780. }
  3781. break;
  3782. /**
  3783. * G80: Mesh-based Z probe, probes a grid and produces a
  3784. * mesh to compensate for variable bed height
  3785. *
  3786. * The S0 report the points as below
  3787. * @code{.unparsed}
  3788. * +----> X-axis
  3789. * |
  3790. * |
  3791. * v Y-axis
  3792. * @endcode
  3793. */
  3794. case 80:
  3795. #ifdef MK1BP
  3796. break;
  3797. #endif //MK1BP
  3798. case_G80:
  3799. {
  3800. mesh_bed_leveling_flag = true;
  3801. static bool run = false;
  3802. #ifdef SUPPORT_VERBOSITY
  3803. int8_t verbosity_level = 0;
  3804. if (code_seen('V')) {
  3805. // Just 'V' without a number counts as V1.
  3806. char c = strchr_pointer[1];
  3807. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  3808. }
  3809. #endif //SUPPORT_VERBOSITY
  3810. // Firstly check if we know where we are
  3811. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  3812. // We don't know where we are! HOME!
  3813. // Push the commands to the front of the message queue in the reverse order!
  3814. // There shall be always enough space reserved for these commands.
  3815. if (lcd_commands_type != LcdCommands::StopPrint) {
  3816. repeatcommand_front(); // repeat G80 with all its parameters
  3817. enquecommand_front_P((PSTR("G28 W0")));
  3818. }
  3819. else {
  3820. mesh_bed_leveling_flag = false;
  3821. }
  3822. break;
  3823. }
  3824. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  3825. if (code_seen('N')) {
  3826. nMeasPoints = code_value_uint8();
  3827. if (nMeasPoints != 7) {
  3828. nMeasPoints = 3;
  3829. }
  3830. }
  3831. else {
  3832. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  3833. }
  3834. uint8_t nProbeRetry = 3;
  3835. if (code_seen('R')) {
  3836. nProbeRetry = code_value_uint8();
  3837. if (nProbeRetry > 10) {
  3838. nProbeRetry = 10;
  3839. }
  3840. }
  3841. else {
  3842. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  3843. }
  3844. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  3845. bool temp_comp_start = true;
  3846. #ifdef PINDA_THERMISTOR
  3847. temp_comp_start = false;
  3848. #endif //PINDA_THERMISTOR
  3849. if (temp_comp_start)
  3850. if (run == false && temp_cal_active == true && calibration_status_pinda() == true && target_temperature_bed >= 50) {
  3851. if (lcd_commands_type != LcdCommands::StopPrint) {
  3852. temp_compensation_start();
  3853. run = true;
  3854. repeatcommand_front(); // repeat G80 with all its parameters
  3855. enquecommand_front_P((PSTR("G28 W0")));
  3856. }
  3857. else {
  3858. mesh_bed_leveling_flag = false;
  3859. }
  3860. break;
  3861. }
  3862. run = false;
  3863. if (lcd_commands_type == LcdCommands::StopPrint) {
  3864. mesh_bed_leveling_flag = false;
  3865. break;
  3866. }
  3867. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  3868. CustomMsg custom_message_type_old = custom_message_type;
  3869. unsigned int custom_message_state_old = custom_message_state;
  3870. custom_message_type = CustomMsg::MeshBedLeveling;
  3871. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  3872. lcd_update(1);
  3873. mbl.reset(); //reset mesh bed leveling
  3874. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  3875. // consumed during the first movements following this statement.
  3876. babystep_undo();
  3877. // Cycle through all points and probe them
  3878. // First move up. During this first movement, the babystepping will be reverted.
  3879. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3880. 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);
  3881. // The move to the first calibration point.
  3882. current_position[X_AXIS] = BED_X0;
  3883. current_position[Y_AXIS] = BED_Y0;
  3884. #ifdef SUPPORT_VERBOSITY
  3885. if (verbosity_level >= 1)
  3886. {
  3887. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  3888. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  3889. }
  3890. #else //SUPPORT_VERBOSITY
  3891. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  3892. #endif //SUPPORT_VERBOSITY
  3893. 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);
  3894. // Wait until the move is finished.
  3895. st_synchronize();
  3896. uint8_t mesh_point = 0; //index number of calibration point
  3897. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  3898. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  3899. 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)
  3900. #ifdef SUPPORT_VERBOSITY
  3901. if (verbosity_level >= 1) {
  3902. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  3903. }
  3904. #endif // SUPPORT_VERBOSITY
  3905. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  3906. const char *kill_message = NULL;
  3907. while (mesh_point != nMeasPoints * nMeasPoints) {
  3908. // Get coords of a measuring point.
  3909. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  3910. uint8_t iy = mesh_point / nMeasPoints;
  3911. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  3912. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  3913. custom_message_state--;
  3914. mesh_point++;
  3915. continue; //skip
  3916. }*/
  3917. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  3918. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  3919. {
  3920. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  3921. }
  3922. float z0 = 0.f;
  3923. if (has_z && (mesh_point > 0)) {
  3924. uint16_t z_offset_u = 0;
  3925. if (nMeasPoints == 7) {
  3926. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  3927. }
  3928. else {
  3929. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  3930. }
  3931. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  3932. #ifdef SUPPORT_VERBOSITY
  3933. if (verbosity_level >= 1) {
  3934. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  3935. }
  3936. #endif // SUPPORT_VERBOSITY
  3937. }
  3938. // Move Z up to MESH_HOME_Z_SEARCH.
  3939. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3940. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  3941. float init_z_bckp = current_position[Z_AXIS];
  3942. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  3943. st_synchronize();
  3944. // Move to XY position of the sensor point.
  3945. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  3946. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  3947. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  3948. #ifdef SUPPORT_VERBOSITY
  3949. if (verbosity_level >= 1) {
  3950. clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  3951. SERIAL_PROTOCOL(mesh_point);
  3952. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  3953. }
  3954. #else //SUPPORT_VERBOSITY
  3955. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  3956. #endif // SUPPORT_VERBOSITY
  3957. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  3958. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], XY_AXIS_FEEDRATE, active_extruder);
  3959. st_synchronize();
  3960. // Go down until endstop is hit
  3961. const float Z_CALIBRATION_THRESHOLD = 1.f;
  3962. 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
  3963. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  3964. break;
  3965. }
  3966. 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.
  3967. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  3968. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3969. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  3970. st_synchronize();
  3971. 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
  3972. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  3973. break;
  3974. }
  3975. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  3976. printf_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken.\n"));
  3977. break;
  3978. }
  3979. }
  3980. 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
  3981. printf_P(PSTR("Bed leveling failed. Sensor triggered too high.\n"));
  3982. break;
  3983. }
  3984. #ifdef SUPPORT_VERBOSITY
  3985. if (verbosity_level >= 10) {
  3986. SERIAL_ECHOPGM("X: ");
  3987. MYSERIAL.print(current_position[X_AXIS], 5);
  3988. SERIAL_ECHOLNPGM("");
  3989. SERIAL_ECHOPGM("Y: ");
  3990. MYSERIAL.print(current_position[Y_AXIS], 5);
  3991. SERIAL_PROTOCOLPGM("\n");
  3992. }
  3993. #endif // SUPPORT_VERBOSITY
  3994. float offset_z = 0;
  3995. #ifdef PINDA_THERMISTOR
  3996. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  3997. #endif //PINDA_THERMISTOR
  3998. // #ifdef SUPPORT_VERBOSITY
  3999. /* if (verbosity_level >= 1)
  4000. {
  4001. SERIAL_ECHOPGM("mesh bed leveling: ");
  4002. MYSERIAL.print(current_position[Z_AXIS], 5);
  4003. SERIAL_ECHOPGM(" offset: ");
  4004. MYSERIAL.print(offset_z, 5);
  4005. SERIAL_ECHOLNPGM("");
  4006. }*/
  4007. // #endif // SUPPORT_VERBOSITY
  4008. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  4009. custom_message_state--;
  4010. mesh_point++;
  4011. lcd_update(1);
  4012. }
  4013. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4014. #ifdef SUPPORT_VERBOSITY
  4015. if (verbosity_level >= 20) {
  4016. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  4017. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  4018. MYSERIAL.print(current_position[Z_AXIS], 5);
  4019. }
  4020. #endif // SUPPORT_VERBOSITY
  4021. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  4022. st_synchronize();
  4023. if (mesh_point != nMeasPoints * nMeasPoints) {
  4024. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  4025. bool bState;
  4026. do { // repeat until Z-leveling o.k.
  4027. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ..."));
  4028. #ifdef TMC2130
  4029. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  4030. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  4031. #else // TMC2130
  4032. lcd_wait_for_click_delay(0); // ~ no timeout
  4033. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  4034. #endif // TMC2130
  4035. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  4036. bState=enable_z_endstop(false);
  4037. current_position[Z_AXIS] -= 1;
  4038. 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);
  4039. st_synchronize();
  4040. enable_z_endstop(true);
  4041. #ifdef TMC2130
  4042. tmc2130_home_enter(Z_AXIS_MASK);
  4043. #endif // TMC2130
  4044. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4045. 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);
  4046. st_synchronize();
  4047. #ifdef TMC2130
  4048. tmc2130_home_exit();
  4049. #endif // TMC2130
  4050. enable_z_endstop(bState);
  4051. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  4052. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  4053. custom_message_type=CustomMsg::Status; // display / status-line recovery
  4054. lcd_update_enable(true); // display / status-line recovery
  4055. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  4056. repeatcommand_front(); // re-run (i.e. of "G80")
  4057. break;
  4058. }
  4059. clean_up_after_endstop_move(l_feedmultiply);
  4060. // SERIAL_ECHOLNPGM("clean up finished ");
  4061. bool apply_temp_comp = true;
  4062. #ifdef PINDA_THERMISTOR
  4063. apply_temp_comp = false;
  4064. #endif
  4065. if (apply_temp_comp)
  4066. if(temp_cal_active == true && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  4067. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  4068. // SERIAL_ECHOLNPGM("babystep applied");
  4069. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  4070. #ifdef SUPPORT_VERBOSITY
  4071. if (verbosity_level >= 1) {
  4072. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  4073. }
  4074. #endif // SUPPORT_VERBOSITY
  4075. for (uint8_t i = 0; i < 4; ++i) {
  4076. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  4077. long correction = 0;
  4078. if (code_seen(codes[i]))
  4079. correction = code_value_long();
  4080. else if (eeprom_bed_correction_valid) {
  4081. unsigned char *addr = (i < 2) ?
  4082. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  4083. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  4084. correction = eeprom_read_int8(addr);
  4085. }
  4086. if (correction == 0)
  4087. continue;
  4088. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  4089. SERIAL_ERROR_START;
  4090. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  4091. SERIAL_ECHO(correction);
  4092. SERIAL_ECHOLNPGM(" microns");
  4093. }
  4094. else {
  4095. float offset = float(correction) * 0.001f;
  4096. switch (i) {
  4097. case 0:
  4098. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  4099. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  4100. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  4101. }
  4102. }
  4103. break;
  4104. case 1:
  4105. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  4106. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  4107. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  4108. }
  4109. }
  4110. break;
  4111. case 2:
  4112. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  4113. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  4114. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  4115. }
  4116. }
  4117. break;
  4118. case 3:
  4119. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  4120. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  4121. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  4122. }
  4123. }
  4124. break;
  4125. }
  4126. }
  4127. }
  4128. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  4129. if (nMeasPoints == 3) {
  4130. 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)
  4131. }
  4132. /*
  4133. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4134. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4135. SERIAL_PROTOCOLPGM(",");
  4136. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4137. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4138. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4139. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4140. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4141. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4142. SERIAL_PROTOCOLPGM(" ");
  4143. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4144. }
  4145. SERIAL_PROTOCOLPGM("\n");
  4146. }
  4147. */
  4148. if (nMeasPoints == 7 && magnet_elimination) {
  4149. mbl_interpolation(nMeasPoints);
  4150. }
  4151. /*
  4152. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4153. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4154. SERIAL_PROTOCOLPGM(",");
  4155. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4156. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4157. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4158. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4159. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4160. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4161. SERIAL_PROTOCOLPGM(" ");
  4162. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4163. }
  4164. SERIAL_PROTOCOLPGM("\n");
  4165. }
  4166. */
  4167. // SERIAL_ECHOLNPGM("Upsample finished");
  4168. mbl.active = 1; //activate mesh bed leveling
  4169. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  4170. go_home_with_z_lift();
  4171. // SERIAL_ECHOLNPGM("Go home finished");
  4172. //unretract (after PINDA preheat retraction)
  4173. if (degHotend(active_extruder) > EXTRUDE_MINTEMP && temp_cal_active == true && calibration_status_pinda() == true && target_temperature_bed >= 50) {
  4174. current_position[E_AXIS] += default_retraction;
  4175. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  4176. }
  4177. KEEPALIVE_STATE(NOT_BUSY);
  4178. // Restore custom message state
  4179. lcd_setstatuspgm(_T(WELCOME_MSG));
  4180. custom_message_type = custom_message_type_old;
  4181. custom_message_state = custom_message_state_old;
  4182. mesh_bed_leveling_flag = false;
  4183. mesh_bed_run_from_menu = false;
  4184. lcd_update(2);
  4185. }
  4186. break;
  4187. /**
  4188. * G81: Print mesh bed leveling status and bed profile if activated
  4189. */
  4190. case 81:
  4191. if (mbl.active) {
  4192. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4193. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4194. SERIAL_PROTOCOLPGM(",");
  4195. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4196. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4197. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4198. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4199. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4200. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4201. SERIAL_PROTOCOLPGM(" ");
  4202. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4203. }
  4204. SERIAL_PROTOCOLPGM("\n");
  4205. }
  4206. }
  4207. else
  4208. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4209. break;
  4210. #if 0
  4211. /**
  4212. * G82: Single Z probe at current location
  4213. *
  4214. * WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4215. *
  4216. */
  4217. case 82:
  4218. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4219. int l_feedmultiply = setup_for_endstop_move();
  4220. find_bed_induction_sensor_point_z();
  4221. clean_up_after_endstop_move(l_feedmultiply);
  4222. SERIAL_PROTOCOLPGM("Bed found at: ");
  4223. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4224. SERIAL_PROTOCOLPGM("\n");
  4225. break;
  4226. /**
  4227. * G83: Prusa3D specific: Babystep in Z and store to EEPROM
  4228. */
  4229. case 83:
  4230. {
  4231. int babystepz = code_seen('S') ? code_value() : 0;
  4232. int BabyPosition = code_seen('P') ? code_value() : 0;
  4233. if (babystepz != 0) {
  4234. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4235. // Is the axis indexed starting with zero or one?
  4236. if (BabyPosition > 4) {
  4237. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4238. }else{
  4239. // Save it to the eeprom
  4240. babystepLoadZ = babystepz;
  4241. EEPROM_save_B(EEPROM_BABYSTEP_Z0+(BabyPosition*2),&babystepLoadZ);
  4242. // adjust the Z
  4243. babystepsTodoZadd(babystepLoadZ);
  4244. }
  4245. }
  4246. }
  4247. break;
  4248. /**
  4249. * G84: Prusa3D specific: UNDO Babystep Z (move Z axis back)
  4250. */
  4251. case 84:
  4252. babystepsTodoZsubtract(babystepLoadZ);
  4253. // babystepLoadZ = 0;
  4254. break;
  4255. /**
  4256. * G85: Prusa3D specific: Pick best babystep
  4257. */
  4258. case 85:
  4259. lcd_pick_babystep();
  4260. break;
  4261. #endif
  4262. /**
  4263. * G86: Prusa3D specific: Disable babystep correction after home.
  4264. * This G-code will be performed at the start of a calibration script.
  4265. */
  4266. case 86:
  4267. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4268. break;
  4269. /**
  4270. * G87: Prusa3D specific: Enable babystep correction after home
  4271. * This G-code will be performed at the end of a calibration script.
  4272. */
  4273. case 87:
  4274. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4275. break;
  4276. /**
  4277. * G88: Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4278. */
  4279. case 88:
  4280. break;
  4281. #endif // ENABLE_MESH_BED_LEVELING
  4282. case 90: // G90
  4283. relative_mode = false;
  4284. break;
  4285. case 91: // G91
  4286. relative_mode = true;
  4287. break;
  4288. case 92: // G92
  4289. if(!code_seen(axis_codes[E_AXIS]))
  4290. st_synchronize();
  4291. for(int8_t i=0; i < NUM_AXIS; i++) {
  4292. if(code_seen(axis_codes[i])) {
  4293. if(i == E_AXIS) {
  4294. current_position[i] = code_value();
  4295. plan_set_e_position(current_position[E_AXIS]);
  4296. }
  4297. else {
  4298. current_position[i] = code_value()+cs.add_homing[i];
  4299. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  4300. }
  4301. }
  4302. }
  4303. break;
  4304. case 98: //! G98 (activate farm mode)
  4305. farm_mode = 1;
  4306. PingTime = _millis();
  4307. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  4308. EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
  4309. SilentModeMenu = SILENT_MODE_OFF;
  4310. eeprom_update_byte((unsigned char *)EEPROM_SILENT, SilentModeMenu);
  4311. fCheckModeInit(); // alternatively invoke printer reset
  4312. break;
  4313. case 99: //! G99 (deactivate farm mode)
  4314. farm_mode = 0;
  4315. lcd_printer_connected();
  4316. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  4317. lcd_update(2);
  4318. fCheckModeInit(); // alternatively invoke printer reset
  4319. break;
  4320. default:
  4321. printf_P(PSTR("Unknown G code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4322. }
  4323. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4324. gcode_in_progress = 0;
  4325. } // end if(code_seen('G'))
  4326. else if(code_seen('M'))
  4327. {
  4328. int index;
  4329. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4330. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4331. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4332. printf_P(PSTR("Invalid M code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4333. } else
  4334. {
  4335. mcode_in_progress = (int)code_value();
  4336. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4337. switch(mcode_in_progress)
  4338. {
  4339. case 0: // M0 - Unconditional stop - Wait for user button press on LCD
  4340. case 1: // M1 - Conditional stop - Wait for user button press on LCD
  4341. {
  4342. char *src = strchr_pointer + 2;
  4343. codenum = 0;
  4344. bool hasP = false, hasS = false;
  4345. if (code_seen('P')) {
  4346. codenum = code_value(); // milliseconds to wait
  4347. hasP = codenum > 0;
  4348. }
  4349. if (code_seen('S')) {
  4350. codenum = code_value() * 1000; // seconds to wait
  4351. hasS = codenum > 0;
  4352. }
  4353. starpos = strchr(src, '*');
  4354. if (starpos != NULL) *(starpos) = '\0';
  4355. while (*src == ' ') ++src;
  4356. if (!hasP && !hasS && *src != '\0') {
  4357. lcd_setstatus(src);
  4358. } else {
  4359. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT
  4360. }
  4361. lcd_ignore_click(); //call lcd_ignore_click aslo for else ???
  4362. st_synchronize();
  4363. previous_millis_cmd = _millis();
  4364. if (codenum > 0){
  4365. codenum += _millis(); // keep track of when we started waiting
  4366. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4367. while(_millis() < codenum && !lcd_clicked()){
  4368. manage_heater();
  4369. manage_inactivity(true);
  4370. lcd_update(0);
  4371. }
  4372. KEEPALIVE_STATE(IN_HANDLER);
  4373. lcd_ignore_click(false);
  4374. }else{
  4375. marlin_wait_for_click();
  4376. }
  4377. if (IS_SD_PRINTING)
  4378. LCD_MESSAGERPGM(_T(MSG_RESUMING_PRINT));
  4379. else
  4380. LCD_MESSAGERPGM(_T(WELCOME_MSG));
  4381. }
  4382. break;
  4383. case 17:
  4384. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE
  4385. enable_x();
  4386. enable_y();
  4387. enable_z();
  4388. enable_e0();
  4389. enable_e1();
  4390. enable_e2();
  4391. break;
  4392. #ifdef SDSUPPORT
  4393. case 20: // M20 - list SD card
  4394. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4395. card.ls();
  4396. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4397. break;
  4398. case 21: // M21 - init SD card
  4399. card.initsd();
  4400. break;
  4401. case 22: //M22 - release SD card
  4402. card.release();
  4403. break;
  4404. case 23: //M23 - Select file
  4405. starpos = (strchr(strchr_pointer + 4,'*'));
  4406. if(starpos!=NULL)
  4407. *(starpos)='\0';
  4408. card.openFile(strchr_pointer + 4,true);
  4409. break;
  4410. case 24: //M24 - Start SD print
  4411. if (!card.paused)
  4412. failstats_reset_print();
  4413. card.startFileprint();
  4414. starttime=_millis();
  4415. break;
  4416. case 25: //M25 - Pause SD print
  4417. card.pauseSDPrint();
  4418. break;
  4419. case 26: //M26 - Set SD index
  4420. if(card.cardOK && code_seen('S')) {
  4421. card.setIndex(code_value_long());
  4422. }
  4423. break;
  4424. case 27: //M27 - Get SD status
  4425. card.getStatus();
  4426. break;
  4427. case 28: //M28 - Start SD write
  4428. starpos = (strchr(strchr_pointer + 4,'*'));
  4429. if(starpos != NULL){
  4430. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4431. strchr_pointer = strchr(npos,' ') + 1;
  4432. *(starpos) = '\0';
  4433. }
  4434. card.openFile(strchr_pointer+4,false);
  4435. break;
  4436. case 29: //M29 - Stop SD write
  4437. //processed in write to file routine above
  4438. //card,saving = false;
  4439. break;
  4440. case 30: //M30 <filename> Delete File
  4441. if (card.cardOK){
  4442. card.closefile();
  4443. starpos = (strchr(strchr_pointer + 4,'*'));
  4444. if(starpos != NULL){
  4445. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4446. strchr_pointer = strchr(npos,' ') + 1;
  4447. *(starpos) = '\0';
  4448. }
  4449. card.removeFile(strchr_pointer + 4);
  4450. }
  4451. break;
  4452. case 32: //M32 - Select file and start SD print
  4453. {
  4454. if(card.sdprinting) {
  4455. st_synchronize();
  4456. }
  4457. starpos = (strchr(strchr_pointer + 4,'*'));
  4458. char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4459. if(namestartpos==NULL)
  4460. {
  4461. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4462. }
  4463. else
  4464. namestartpos++; //to skip the '!'
  4465. if(starpos!=NULL)
  4466. *(starpos)='\0';
  4467. bool call_procedure=(code_seen('P'));
  4468. if(strchr_pointer>namestartpos)
  4469. call_procedure=false; //false alert, 'P' found within filename
  4470. if( card.cardOK )
  4471. {
  4472. card.openFile(namestartpos,true,!call_procedure);
  4473. if(code_seen('S'))
  4474. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4475. card.setIndex(code_value_long());
  4476. card.startFileprint();
  4477. if(!call_procedure)
  4478. starttime=_millis(); //procedure calls count as normal print time.
  4479. }
  4480. } break;
  4481. case 928: //M928 - Start SD write
  4482. starpos = (strchr(strchr_pointer + 5,'*'));
  4483. if(starpos != NULL){
  4484. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4485. strchr_pointer = strchr(npos,' ') + 1;
  4486. *(starpos) = '\0';
  4487. }
  4488. card.openLogFile(strchr_pointer+5);
  4489. break;
  4490. #endif //SDSUPPORT
  4491. case 31: //M31 take time since the start of the SD print or an M109 command
  4492. {
  4493. stoptime=_millis();
  4494. char time[30];
  4495. unsigned long t=(stoptime-starttime)/1000;
  4496. int sec,min;
  4497. min=t/60;
  4498. sec=t%60;
  4499. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4500. SERIAL_ECHO_START;
  4501. SERIAL_ECHOLN(time);
  4502. lcd_setstatus(time);
  4503. autotempShutdown();
  4504. }
  4505. break;
  4506. case 42: //M42 -Change pin status via gcode
  4507. if (code_seen('S'))
  4508. {
  4509. int pin_status = code_value();
  4510. int pin_number = LED_PIN;
  4511. if (code_seen('P') && pin_status >= 0 && pin_status <= 255)
  4512. pin_number = code_value();
  4513. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  4514. {
  4515. if (sensitive_pins[i] == pin_number)
  4516. {
  4517. pin_number = -1;
  4518. break;
  4519. }
  4520. }
  4521. #if defined(FAN_PIN) && FAN_PIN > -1
  4522. if (pin_number == FAN_PIN)
  4523. fanSpeed = pin_status;
  4524. #endif
  4525. if (pin_number > -1)
  4526. {
  4527. pinMode(pin_number, OUTPUT);
  4528. digitalWrite(pin_number, pin_status);
  4529. analogWrite(pin_number, pin_status);
  4530. }
  4531. }
  4532. break;
  4533. case 44: //! M44: Prusa3D: Reset the bed skew and offset calibration.
  4534. // Reset the baby step value and the baby step applied flag.
  4535. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4536. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z, 0);
  4537. // Reset the skew and offset in both RAM and EEPROM.
  4538. reset_bed_offset_and_skew();
  4539. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4540. // the planner will not perform any adjustments in the XY plane.
  4541. // Wait for the motors to stop and update the current position with the absolute values.
  4542. world2machine_revert_to_uncorrected();
  4543. break;
  4544. case 45: //! M45: Prusa3D: bed skew and offset with manual Z up
  4545. {
  4546. int8_t verbosity_level = 0;
  4547. bool only_Z = code_seen('Z');
  4548. #ifdef SUPPORT_VERBOSITY
  4549. if (code_seen('V'))
  4550. {
  4551. // Just 'V' without a number counts as V1.
  4552. char c = strchr_pointer[1];
  4553. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4554. }
  4555. #endif //SUPPORT_VERBOSITY
  4556. gcode_M45(only_Z, verbosity_level);
  4557. }
  4558. break;
  4559. /*
  4560. case 46:
  4561. {
  4562. // M46: Prusa3D: Show the assigned IP address.
  4563. uint8_t ip[4];
  4564. bool hasIP = card.ToshibaFlashAir_GetIP(ip);
  4565. if (hasIP) {
  4566. SERIAL_ECHOPGM("Toshiba FlashAir current IP: ");
  4567. SERIAL_ECHO(int(ip[0]));
  4568. SERIAL_ECHOPGM(".");
  4569. SERIAL_ECHO(int(ip[1]));
  4570. SERIAL_ECHOPGM(".");
  4571. SERIAL_ECHO(int(ip[2]));
  4572. SERIAL_ECHOPGM(".");
  4573. SERIAL_ECHO(int(ip[3]));
  4574. SERIAL_ECHOLNPGM("");
  4575. } else {
  4576. SERIAL_ECHOLNPGM("Toshiba FlashAir GetIP failed");
  4577. }
  4578. break;
  4579. }
  4580. */
  4581. case 47:
  4582. //! M47: Prusa3D: Show end stops dialog on the display.
  4583. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4584. lcd_diag_show_end_stops();
  4585. KEEPALIVE_STATE(IN_HANDLER);
  4586. break;
  4587. #if 0
  4588. case 48: //! M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  4589. {
  4590. // Disable the default update procedure of the display. We will do a modal dialog.
  4591. lcd_update_enable(false);
  4592. // Let the planner use the uncorrected coordinates.
  4593. mbl.reset();
  4594. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4595. // the planner will not perform any adjustments in the XY plane.
  4596. // Wait for the motors to stop and update the current position with the absolute values.
  4597. world2machine_revert_to_uncorrected();
  4598. // Move the print head close to the bed.
  4599. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4600. 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);
  4601. st_synchronize();
  4602. // Home in the XY plane.
  4603. set_destination_to_current();
  4604. int l_feedmultiply = setup_for_endstop_move();
  4605. home_xy();
  4606. int8_t verbosity_level = 0;
  4607. if (code_seen('V')) {
  4608. // Just 'V' without a number counts as V1.
  4609. char c = strchr_pointer[1];
  4610. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4611. }
  4612. bool success = scan_bed_induction_points(verbosity_level);
  4613. clean_up_after_endstop_move(l_feedmultiply);
  4614. // Print head up.
  4615. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4616. 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);
  4617. st_synchronize();
  4618. lcd_update_enable(true);
  4619. break;
  4620. }
  4621. #endif
  4622. #ifdef ENABLE_AUTO_BED_LEVELING
  4623. #ifdef Z_PROBE_REPEATABILITY_TEST
  4624. //! M48 Z-Probe repeatability measurement function.
  4625. //!
  4626. //! Usage: M48 <n #_samples> <X X_position_for_samples> <Y Y_position_for_samples> <V Verbose_Level> <L legs_of_movement_prior_to_doing_probe>
  4627. //!
  4628. //! This function assumes the bed has been homed. Specificaly, that a G28 command
  4629. //! as been issued prior to invoking the M48 Z-Probe repeatability measurement function.
  4630. //! Any information generated by a prior G29 Bed leveling command will be lost and need to be
  4631. //! regenerated.
  4632. //!
  4633. //! The number of samples will default to 10 if not specified. You can use upper or lower case
  4634. //! letters for any of the options EXCEPT n. n must be in lower case because Marlin uses a capital
  4635. //! N for its communication protocol and will get horribly confused if you send it a capital N.
  4636. //!
  4637. case 48: // M48 Z-Probe repeatability
  4638. {
  4639. #if Z_MIN_PIN == -1
  4640. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  4641. #endif
  4642. double sum=0.0;
  4643. double mean=0.0;
  4644. double sigma=0.0;
  4645. double sample_set[50];
  4646. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  4647. double X_current, Y_current, Z_current;
  4648. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  4649. if (code_seen('V') || code_seen('v')) {
  4650. verbose_level = code_value();
  4651. if (verbose_level<0 || verbose_level>4 ) {
  4652. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  4653. goto Sigma_Exit;
  4654. }
  4655. }
  4656. if (verbose_level > 0) {
  4657. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  4658. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  4659. }
  4660. if (code_seen('n')) {
  4661. n_samples = code_value();
  4662. if (n_samples<4 || n_samples>50 ) {
  4663. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  4664. goto Sigma_Exit;
  4665. }
  4666. }
  4667. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  4668. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  4669. Z_current = st_get_position_mm(Z_AXIS);
  4670. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  4671. ext_position = st_get_position_mm(E_AXIS);
  4672. if (code_seen('X') || code_seen('x') ) {
  4673. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  4674. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  4675. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  4676. goto Sigma_Exit;
  4677. }
  4678. }
  4679. if (code_seen('Y') || code_seen('y') ) {
  4680. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  4681. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  4682. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  4683. goto Sigma_Exit;
  4684. }
  4685. }
  4686. if (code_seen('L') || code_seen('l') ) {
  4687. n_legs = code_value();
  4688. if ( n_legs==1 )
  4689. n_legs = 2;
  4690. if ( n_legs<0 || n_legs>15 ) {
  4691. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  4692. goto Sigma_Exit;
  4693. }
  4694. }
  4695. //
  4696. // Do all the preliminary setup work. First raise the probe.
  4697. //
  4698. st_synchronize();
  4699. plan_bed_level_matrix.set_to_identity();
  4700. plan_buffer_line( X_current, Y_current, Z_start_location,
  4701. ext_position,
  4702. homing_feedrate[Z_AXIS]/60,
  4703. active_extruder);
  4704. st_synchronize();
  4705. //
  4706. // Now get everything to the specified probe point So we can safely do a probe to
  4707. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  4708. // use that as a starting point for each probe.
  4709. //
  4710. if (verbose_level > 2)
  4711. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  4712. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  4713. ext_position,
  4714. homing_feedrate[X_AXIS]/60,
  4715. active_extruder);
  4716. st_synchronize();
  4717. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  4718. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  4719. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  4720. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  4721. //
  4722. // OK, do the inital probe to get us close to the bed.
  4723. // Then retrace the right amount and use that in subsequent probes
  4724. //
  4725. int l_feedmultiply = setup_for_endstop_move();
  4726. run_z_probe();
  4727. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  4728. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  4729. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  4730. ext_position,
  4731. homing_feedrate[X_AXIS]/60,
  4732. active_extruder);
  4733. st_synchronize();
  4734. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  4735. for( n=0; n<n_samples; n++) {
  4736. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  4737. if ( n_legs) {
  4738. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  4739. int rotational_direction, l;
  4740. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  4741. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  4742. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  4743. //SERIAL_ECHOPAIR("starting radius: ",radius);
  4744. //SERIAL_ECHOPAIR(" theta: ",theta);
  4745. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  4746. //SERIAL_PROTOCOLLNPGM("");
  4747. for( l=0; l<n_legs-1; l++) {
  4748. if (rotational_direction==1)
  4749. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  4750. else
  4751. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  4752. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  4753. if ( radius<0.0 )
  4754. radius = -radius;
  4755. X_current = X_probe_location + cos(theta) * radius;
  4756. Y_current = Y_probe_location + sin(theta) * radius;
  4757. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  4758. X_current = X_MIN_POS;
  4759. if ( X_current>X_MAX_POS)
  4760. X_current = X_MAX_POS;
  4761. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  4762. Y_current = Y_MIN_POS;
  4763. if ( Y_current>Y_MAX_POS)
  4764. Y_current = Y_MAX_POS;
  4765. if (verbose_level>3 ) {
  4766. SERIAL_ECHOPAIR("x: ", X_current);
  4767. SERIAL_ECHOPAIR("y: ", Y_current);
  4768. SERIAL_PROTOCOLLNPGM("");
  4769. }
  4770. do_blocking_move_to( X_current, Y_current, Z_current );
  4771. }
  4772. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  4773. }
  4774. int l_feedmultiply = setup_for_endstop_move();
  4775. run_z_probe();
  4776. sample_set[n] = current_position[Z_AXIS];
  4777. //
  4778. // Get the current mean for the data points we have so far
  4779. //
  4780. sum=0.0;
  4781. for( j=0; j<=n; j++) {
  4782. sum = sum + sample_set[j];
  4783. }
  4784. mean = sum / (double (n+1));
  4785. //
  4786. // Now, use that mean to calculate the standard deviation for the
  4787. // data points we have so far
  4788. //
  4789. sum=0.0;
  4790. for( j=0; j<=n; j++) {
  4791. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  4792. }
  4793. sigma = sqrt( sum / (double (n+1)) );
  4794. if (verbose_level > 1) {
  4795. SERIAL_PROTOCOL(n+1);
  4796. SERIAL_PROTOCOL(" of ");
  4797. SERIAL_PROTOCOL(n_samples);
  4798. SERIAL_PROTOCOLPGM(" z: ");
  4799. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  4800. }
  4801. if (verbose_level > 2) {
  4802. SERIAL_PROTOCOL(" mean: ");
  4803. SERIAL_PROTOCOL_F(mean,6);
  4804. SERIAL_PROTOCOL(" sigma: ");
  4805. SERIAL_PROTOCOL_F(sigma,6);
  4806. }
  4807. if (verbose_level > 0)
  4808. SERIAL_PROTOCOLPGM("\n");
  4809. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  4810. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  4811. st_synchronize();
  4812. }
  4813. _delay(1000);
  4814. clean_up_after_endstop_move(l_feedmultiply);
  4815. // enable_endstops(true);
  4816. if (verbose_level > 0) {
  4817. SERIAL_PROTOCOLPGM("Mean: ");
  4818. SERIAL_PROTOCOL_F(mean, 6);
  4819. SERIAL_PROTOCOLPGM("\n");
  4820. }
  4821. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  4822. SERIAL_PROTOCOL_F(sigma, 6);
  4823. SERIAL_PROTOCOLPGM("\n\n");
  4824. Sigma_Exit:
  4825. break;
  4826. }
  4827. #endif // Z_PROBE_REPEATABILITY_TEST
  4828. #endif // ENABLE_AUTO_BED_LEVELING
  4829. case 73: //M73 show percent done and time remaining
  4830. if(code_seen('P')) print_percent_done_normal = code_value();
  4831. if(code_seen('R')) print_time_remaining_normal = code_value();
  4832. if(code_seen('Q')) print_percent_done_silent = code_value();
  4833. if(code_seen('S')) print_time_remaining_silent = code_value();
  4834. {
  4835. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %d; print time remaining in mins: %d\n");
  4836. printf_P(_msg_mode_done_remain, _N("NORMAL"), int(print_percent_done_normal), print_time_remaining_normal);
  4837. printf_P(_msg_mode_done_remain, _N("SILENT"), int(print_percent_done_silent), print_time_remaining_silent);
  4838. }
  4839. break;
  4840. case 104: // M104
  4841. {
  4842. uint8_t extruder;
  4843. if(setTargetedHotend(104,extruder)){
  4844. break;
  4845. }
  4846. if (code_seen('S'))
  4847. {
  4848. setTargetHotendSafe(code_value(), extruder);
  4849. }
  4850. setWatch();
  4851. break;
  4852. }
  4853. case 112: // M112 -Emergency Stop
  4854. kill(_n(""), 3);
  4855. break;
  4856. case 140: // M140 set bed temp
  4857. if (code_seen('S')) setTargetBed(code_value());
  4858. break;
  4859. case 105 : // M105
  4860. {
  4861. uint8_t extruder;
  4862. if(setTargetedHotend(105, extruder)){
  4863. break;
  4864. }
  4865. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  4866. SERIAL_PROTOCOLPGM("ok T:");
  4867. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  4868. SERIAL_PROTOCOLPGM(" /");
  4869. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  4870. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  4871. SERIAL_PROTOCOLPGM(" B:");
  4872. SERIAL_PROTOCOL_F(degBed(),1);
  4873. SERIAL_PROTOCOLPGM(" /");
  4874. SERIAL_PROTOCOL_F(degTargetBed(),1);
  4875. #endif //TEMP_BED_PIN
  4876. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  4877. SERIAL_PROTOCOLPGM(" T");
  4878. SERIAL_PROTOCOL(cur_extruder);
  4879. SERIAL_PROTOCOLPGM(":");
  4880. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  4881. SERIAL_PROTOCOLPGM(" /");
  4882. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  4883. }
  4884. #else
  4885. SERIAL_ERROR_START;
  4886. SERIAL_ERRORLNRPGM(_i("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  4887. #endif
  4888. SERIAL_PROTOCOLPGM(" @:");
  4889. #ifdef EXTRUDER_WATTS
  4890. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  4891. SERIAL_PROTOCOLPGM("W");
  4892. #else
  4893. SERIAL_PROTOCOL(getHeaterPower(extruder));
  4894. #endif
  4895. SERIAL_PROTOCOLPGM(" B@:");
  4896. #ifdef BED_WATTS
  4897. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  4898. SERIAL_PROTOCOLPGM("W");
  4899. #else
  4900. SERIAL_PROTOCOL(getHeaterPower(-1));
  4901. #endif
  4902. #ifdef PINDA_THERMISTOR
  4903. SERIAL_PROTOCOLPGM(" P:");
  4904. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  4905. #endif //PINDA_THERMISTOR
  4906. #ifdef AMBIENT_THERMISTOR
  4907. SERIAL_PROTOCOLPGM(" A:");
  4908. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  4909. #endif //AMBIENT_THERMISTOR
  4910. #ifdef SHOW_TEMP_ADC_VALUES
  4911. {float raw = 0.0;
  4912. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  4913. SERIAL_PROTOCOLPGM(" ADC B:");
  4914. SERIAL_PROTOCOL_F(degBed(),1);
  4915. SERIAL_PROTOCOLPGM("C->");
  4916. raw = rawBedTemp();
  4917. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  4918. SERIAL_PROTOCOLPGM(" Rb->");
  4919. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  4920. SERIAL_PROTOCOLPGM(" Rxb->");
  4921. SERIAL_PROTOCOL_F(raw, 5);
  4922. #endif
  4923. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  4924. SERIAL_PROTOCOLPGM(" T");
  4925. SERIAL_PROTOCOL(cur_extruder);
  4926. SERIAL_PROTOCOLPGM(":");
  4927. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  4928. SERIAL_PROTOCOLPGM("C->");
  4929. raw = rawHotendTemp(cur_extruder);
  4930. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  4931. SERIAL_PROTOCOLPGM(" Rt");
  4932. SERIAL_PROTOCOL(cur_extruder);
  4933. SERIAL_PROTOCOLPGM("->");
  4934. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  4935. SERIAL_PROTOCOLPGM(" Rx");
  4936. SERIAL_PROTOCOL(cur_extruder);
  4937. SERIAL_PROTOCOLPGM("->");
  4938. SERIAL_PROTOCOL_F(raw, 5);
  4939. }}
  4940. #endif
  4941. SERIAL_PROTOCOLLN("");
  4942. KEEPALIVE_STATE(NOT_BUSY);
  4943. return;
  4944. break;
  4945. }
  4946. case 109:
  4947. {// M109 - Wait for extruder heater to reach target.
  4948. uint8_t extruder;
  4949. if(setTargetedHotend(109, extruder)){
  4950. break;
  4951. }
  4952. LCD_MESSAGERPGM(_T(MSG_HEATING));
  4953. heating_status = 1;
  4954. if (farm_mode) { prusa_statistics(1); };
  4955. #ifdef AUTOTEMP
  4956. autotemp_enabled=false;
  4957. #endif
  4958. if (code_seen('S')) {
  4959. setTargetHotendSafe(code_value(), extruder);
  4960. CooldownNoWait = true;
  4961. } else if (code_seen('R')) {
  4962. setTargetHotendSafe(code_value(), extruder);
  4963. CooldownNoWait = false;
  4964. }
  4965. #ifdef AUTOTEMP
  4966. if (code_seen('S')) autotemp_min=code_value();
  4967. if (code_seen('B')) autotemp_max=code_value();
  4968. if (code_seen('F'))
  4969. {
  4970. autotemp_factor=code_value();
  4971. autotemp_enabled=true;
  4972. }
  4973. #endif
  4974. setWatch();
  4975. codenum = _millis();
  4976. /* See if we are heating up or cooling down */
  4977. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  4978. KEEPALIVE_STATE(NOT_BUSY);
  4979. cancel_heatup = false;
  4980. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  4981. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  4982. KEEPALIVE_STATE(IN_HANDLER);
  4983. heating_status = 2;
  4984. if (farm_mode) { prusa_statistics(2); };
  4985. //starttime=_millis();
  4986. previous_millis_cmd = _millis();
  4987. }
  4988. break;
  4989. case 190: // M190 - Wait for bed heater to reach target.
  4990. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  4991. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  4992. heating_status = 3;
  4993. if (farm_mode) { prusa_statistics(1); };
  4994. if (code_seen('S'))
  4995. {
  4996. setTargetBed(code_value());
  4997. CooldownNoWait = true;
  4998. }
  4999. else if (code_seen('R'))
  5000. {
  5001. setTargetBed(code_value());
  5002. CooldownNoWait = false;
  5003. }
  5004. codenum = _millis();
  5005. cancel_heatup = false;
  5006. target_direction = isHeatingBed(); // true if heating, false if cooling
  5007. KEEPALIVE_STATE(NOT_BUSY);
  5008. while ( (target_direction)&&(!cancel_heatup) ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false)) )
  5009. {
  5010. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5011. {
  5012. if (!farm_mode) {
  5013. float tt = degHotend(active_extruder);
  5014. SERIAL_PROTOCOLPGM("T:");
  5015. SERIAL_PROTOCOL(tt);
  5016. SERIAL_PROTOCOLPGM(" E:");
  5017. SERIAL_PROTOCOL((int)active_extruder);
  5018. SERIAL_PROTOCOLPGM(" B:");
  5019. SERIAL_PROTOCOL_F(degBed(), 1);
  5020. SERIAL_PROTOCOLLN("");
  5021. }
  5022. codenum = _millis();
  5023. }
  5024. manage_heater();
  5025. manage_inactivity();
  5026. lcd_update(0);
  5027. }
  5028. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5029. KEEPALIVE_STATE(IN_HANDLER);
  5030. heating_status = 4;
  5031. previous_millis_cmd = _millis();
  5032. #endif
  5033. break;
  5034. #if defined(FAN_PIN) && FAN_PIN > -1
  5035. case 106: //!M106 Sxxx Fan On S<speed> 0 .. 255
  5036. if (code_seen('S')){
  5037. fanSpeed=constrain(code_value(),0,255);
  5038. }
  5039. else {
  5040. fanSpeed=255;
  5041. }
  5042. break;
  5043. case 107: //M107 Fan Off
  5044. fanSpeed = 0;
  5045. break;
  5046. #endif //FAN_PIN
  5047. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5048. case 80: // M80 - Turn on Power Supply
  5049. SET_OUTPUT(PS_ON_PIN); //GND
  5050. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5051. // If you have a switch on suicide pin, this is useful
  5052. // if you want to start another print with suicide feature after
  5053. // a print without suicide...
  5054. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5055. SET_OUTPUT(SUICIDE_PIN);
  5056. WRITE(SUICIDE_PIN, HIGH);
  5057. #endif
  5058. powersupply = true;
  5059. LCD_MESSAGERPGM(_T(WELCOME_MSG));
  5060. lcd_update(0);
  5061. break;
  5062. #endif
  5063. case 81: // M81 - Turn off Power Supply
  5064. disable_heater();
  5065. st_synchronize();
  5066. disable_e0();
  5067. disable_e1();
  5068. disable_e2();
  5069. finishAndDisableSteppers();
  5070. fanSpeed = 0;
  5071. _delay(1000); // Wait a little before to switch off
  5072. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5073. st_synchronize();
  5074. suicide();
  5075. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5076. SET_OUTPUT(PS_ON_PIN);
  5077. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5078. #endif
  5079. powersupply = false;
  5080. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5081. lcd_update(0);
  5082. break;
  5083. case 82:
  5084. axis_relative_modes[3] = false;
  5085. break;
  5086. case 83:
  5087. axis_relative_modes[3] = true;
  5088. break;
  5089. case 18: //compatibility
  5090. case 84: // M84
  5091. if(code_seen('S')){
  5092. stepper_inactive_time = code_value() * 1000;
  5093. }
  5094. else
  5095. {
  5096. 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])));
  5097. if(all_axis)
  5098. {
  5099. st_synchronize();
  5100. disable_e0();
  5101. disable_e1();
  5102. disable_e2();
  5103. finishAndDisableSteppers();
  5104. }
  5105. else
  5106. {
  5107. st_synchronize();
  5108. if (code_seen('X')) disable_x();
  5109. if (code_seen('Y')) disable_y();
  5110. if (code_seen('Z')) disable_z();
  5111. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5112. if (code_seen('E')) {
  5113. disable_e0();
  5114. disable_e1();
  5115. disable_e2();
  5116. }
  5117. #endif
  5118. }
  5119. }
  5120. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  5121. print_time_remaining_init();
  5122. snmm_filaments_used = 0;
  5123. break;
  5124. case 85: // M85
  5125. if(code_seen('S')) {
  5126. max_inactive_time = code_value() * 1000;
  5127. }
  5128. break;
  5129. #ifdef SAFETYTIMER
  5130. case 86: // M86 - set safety timer expiration time in seconds; M86 S0 will disable safety timer
  5131. //when safety timer expires heatbed and nozzle target temperatures are set to zero
  5132. if (code_seen('S')) {
  5133. safetytimer_inactive_time = code_value() * 1000;
  5134. safetyTimer.start();
  5135. }
  5136. break;
  5137. #endif
  5138. case 92: // M92
  5139. for(int8_t i=0; i < NUM_AXIS; i++)
  5140. {
  5141. if(code_seen(axis_codes[i]))
  5142. {
  5143. if(i == 3) { // E
  5144. float value = code_value();
  5145. if(value < 20.0) {
  5146. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5147. cs.max_jerk[E_AXIS] *= factor;
  5148. max_feedrate[i] *= factor;
  5149. axis_steps_per_sqr_second[i] *= factor;
  5150. }
  5151. cs.axis_steps_per_unit[i] = value;
  5152. }
  5153. else {
  5154. cs.axis_steps_per_unit[i] = code_value();
  5155. }
  5156. }
  5157. }
  5158. break;
  5159. case 110: //! M110 N<line number> - reset line pos
  5160. if (code_seen('N'))
  5161. gcode_LastN = code_value_long();
  5162. break;
  5163. case 113: // M113 - Get or set Host Keepalive interval
  5164. if (code_seen('S')) {
  5165. host_keepalive_interval = (uint8_t)code_value_short();
  5166. // NOMORE(host_keepalive_interval, 60);
  5167. }
  5168. else {
  5169. SERIAL_ECHO_START;
  5170. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5171. SERIAL_PROTOCOLLN("");
  5172. }
  5173. break;
  5174. case 115: // M115
  5175. if (code_seen('V')) {
  5176. // Report the Prusa version number.
  5177. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5178. } else if (code_seen('U')) {
  5179. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5180. // pause the print for 30s and ask the user to upgrade the firmware.
  5181. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5182. } else {
  5183. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5184. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5185. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5186. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5187. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5188. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5189. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5190. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5191. SERIAL_ECHOPGM(" UUID:");
  5192. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5193. }
  5194. break;
  5195. /* case 117: // M117 display message
  5196. starpos = (strchr(strchr_pointer + 5,'*'));
  5197. if(starpos!=NULL)
  5198. *(starpos)='\0';
  5199. lcd_setstatus(strchr_pointer + 5);
  5200. break;*/
  5201. case 114: // M114
  5202. gcode_M114();
  5203. break;
  5204. case 120: //! M120 - Disable endstops
  5205. enable_endstops(false) ;
  5206. break;
  5207. case 121: //! M121 - Enable endstops
  5208. enable_endstops(true) ;
  5209. break;
  5210. case 119: // M119
  5211. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5212. SERIAL_PROTOCOLLN("");
  5213. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5214. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5215. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5216. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5217. }else{
  5218. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5219. }
  5220. SERIAL_PROTOCOLLN("");
  5221. #endif
  5222. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5223. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5224. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5225. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5226. }else{
  5227. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5228. }
  5229. SERIAL_PROTOCOLLN("");
  5230. #endif
  5231. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5232. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5233. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5234. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5235. }else{
  5236. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5237. }
  5238. SERIAL_PROTOCOLLN("");
  5239. #endif
  5240. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5241. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5242. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5243. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5244. }else{
  5245. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5246. }
  5247. SERIAL_PROTOCOLLN("");
  5248. #endif
  5249. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5250. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5251. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5252. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5253. }else{
  5254. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5255. }
  5256. SERIAL_PROTOCOLLN("");
  5257. #endif
  5258. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5259. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5260. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5261. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5262. }else{
  5263. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5264. }
  5265. SERIAL_PROTOCOLLN("");
  5266. #endif
  5267. break;
  5268. //TODO: update for all axis, use for loop
  5269. #ifdef BLINKM
  5270. case 150: // M150
  5271. {
  5272. byte red;
  5273. byte grn;
  5274. byte blu;
  5275. if(code_seen('R')) red = code_value();
  5276. if(code_seen('U')) grn = code_value();
  5277. if(code_seen('B')) blu = code_value();
  5278. SendColors(red,grn,blu);
  5279. }
  5280. break;
  5281. #endif //BLINKM
  5282. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5283. {
  5284. uint8_t extruder = active_extruder;
  5285. if(code_seen('T')) {
  5286. extruder = code_value();
  5287. if(extruder >= EXTRUDERS) {
  5288. SERIAL_ECHO_START;
  5289. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  5290. break;
  5291. }
  5292. }
  5293. if(code_seen('D')) {
  5294. float diameter = (float)code_value();
  5295. if (diameter == 0.0) {
  5296. // setting any extruder filament size disables volumetric on the assumption that
  5297. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5298. // for all extruders
  5299. cs.volumetric_enabled = false;
  5300. } else {
  5301. cs.filament_size[extruder] = (float)code_value();
  5302. // make sure all extruders have some sane value for the filament size
  5303. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5304. #if EXTRUDERS > 1
  5305. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5306. #if EXTRUDERS > 2
  5307. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5308. #endif
  5309. #endif
  5310. cs.volumetric_enabled = true;
  5311. }
  5312. } else {
  5313. //reserved for setting filament diameter via UFID or filament measuring device
  5314. break;
  5315. }
  5316. calculate_extruder_multipliers();
  5317. }
  5318. break;
  5319. case 201: // M201
  5320. for (int8_t i = 0; i < NUM_AXIS; i++)
  5321. {
  5322. if (code_seen(axis_codes[i]))
  5323. {
  5324. unsigned long val = code_value();
  5325. #ifdef TMC2130
  5326. unsigned long val_silent = val;
  5327. if ((i == X_AXIS) || (i == Y_AXIS))
  5328. {
  5329. if (val > NORMAL_MAX_ACCEL_XY)
  5330. val = NORMAL_MAX_ACCEL_XY;
  5331. if (val_silent > SILENT_MAX_ACCEL_XY)
  5332. val_silent = SILENT_MAX_ACCEL_XY;
  5333. }
  5334. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  5335. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  5336. #else //TMC2130
  5337. max_acceleration_units_per_sq_second[i] = val;
  5338. #endif //TMC2130
  5339. }
  5340. }
  5341. // 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)
  5342. reset_acceleration_rates();
  5343. break;
  5344. #if 0 // Not used for Sprinter/grbl gen6
  5345. case 202: // M202
  5346. for(int8_t i=0; i < NUM_AXIS; i++) {
  5347. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  5348. }
  5349. break;
  5350. #endif
  5351. case 203: // M203 max feedrate mm/sec
  5352. for (int8_t i = 0; i < NUM_AXIS; i++)
  5353. {
  5354. if (code_seen(axis_codes[i]))
  5355. {
  5356. float val = code_value();
  5357. #ifdef TMC2130
  5358. float val_silent = val;
  5359. if ((i == X_AXIS) || (i == Y_AXIS))
  5360. {
  5361. if (val > NORMAL_MAX_FEEDRATE_XY)
  5362. val = NORMAL_MAX_FEEDRATE_XY;
  5363. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  5364. val_silent = SILENT_MAX_FEEDRATE_XY;
  5365. }
  5366. cs.max_feedrate_normal[i] = val;
  5367. cs.max_feedrate_silent[i] = val_silent;
  5368. #else //TMC2130
  5369. max_feedrate[i] = val;
  5370. #endif //TMC2130
  5371. }
  5372. }
  5373. break;
  5374. case 204:
  5375. //! M204 acclereration settings.
  5376. //!@n Supporting old format: M204 S[normal moves] T[filmanent only moves]
  5377. //!@n and new format: M204 P[printing moves] R[filmanent only moves] T[travel moves] (as of now T is ignored)
  5378. {
  5379. if(code_seen('S')) {
  5380. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  5381. // and it is also generated by Slic3r to control acceleration per extrusion type
  5382. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  5383. cs.acceleration = code_value();
  5384. // Interpret the T value as retract acceleration in the old Marlin format.
  5385. if(code_seen('T'))
  5386. cs.retract_acceleration = code_value();
  5387. } else {
  5388. // New acceleration format, compatible with the upstream Marlin.
  5389. if(code_seen('P'))
  5390. cs.acceleration = code_value();
  5391. if(code_seen('R'))
  5392. cs.retract_acceleration = code_value();
  5393. if(code_seen('T')) {
  5394. // Interpret the T value as the travel acceleration in the new Marlin format.
  5395. //FIXME Prusa3D firmware currently does not support travel acceleration value independent from the extruding acceleration value.
  5396. // travel_acceleration = code_value();
  5397. }
  5398. }
  5399. }
  5400. break;
  5401. case 205: //M205 advanced settings: minimum travel speed S=while printing T=travel only, B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk
  5402. {
  5403. if(code_seen('S')) cs.minimumfeedrate = code_value();
  5404. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  5405. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  5406. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  5407. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  5408. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  5409. if(code_seen('E')) cs.max_jerk[E_AXIS] = code_value();
  5410. if (cs.max_jerk[X_AXIS] > DEFAULT_XJERK) cs.max_jerk[X_AXIS] = DEFAULT_XJERK;
  5411. if (cs.max_jerk[Y_AXIS] > DEFAULT_YJERK) cs.max_jerk[Y_AXIS] = DEFAULT_YJERK;
  5412. }
  5413. break;
  5414. case 206: // M206 additional homing offset
  5415. for(int8_t i=0; i < 3; i++)
  5416. {
  5417. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  5418. }
  5419. break;
  5420. #ifdef FWRETRACT
  5421. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  5422. {
  5423. if(code_seen('S'))
  5424. {
  5425. cs.retract_length = code_value() ;
  5426. }
  5427. if(code_seen('F'))
  5428. {
  5429. cs.retract_feedrate = code_value()/60 ;
  5430. }
  5431. if(code_seen('Z'))
  5432. {
  5433. cs.retract_zlift = code_value() ;
  5434. }
  5435. }break;
  5436. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  5437. {
  5438. if(code_seen('S'))
  5439. {
  5440. cs.retract_recover_length = code_value() ;
  5441. }
  5442. if(code_seen('F'))
  5443. {
  5444. cs.retract_recover_feedrate = code_value()/60 ;
  5445. }
  5446. }break;
  5447. 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.
  5448. {
  5449. if(code_seen('S'))
  5450. {
  5451. int t= code_value() ;
  5452. switch(t)
  5453. {
  5454. case 0:
  5455. {
  5456. cs.autoretract_enabled=false;
  5457. retracted[0]=false;
  5458. #if EXTRUDERS > 1
  5459. retracted[1]=false;
  5460. #endif
  5461. #if EXTRUDERS > 2
  5462. retracted[2]=false;
  5463. #endif
  5464. }break;
  5465. case 1:
  5466. {
  5467. cs.autoretract_enabled=true;
  5468. retracted[0]=false;
  5469. #if EXTRUDERS > 1
  5470. retracted[1]=false;
  5471. #endif
  5472. #if EXTRUDERS > 2
  5473. retracted[2]=false;
  5474. #endif
  5475. }break;
  5476. default:
  5477. SERIAL_ECHO_START;
  5478. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  5479. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  5480. SERIAL_ECHOLNPGM("\"(1)");
  5481. }
  5482. }
  5483. }break;
  5484. #endif // FWRETRACT
  5485. #if EXTRUDERS > 1
  5486. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  5487. {
  5488. uint8_t extruder;
  5489. if(setTargetedHotend(218, extruder)){
  5490. break;
  5491. }
  5492. if(code_seen('X'))
  5493. {
  5494. extruder_offset[X_AXIS][extruder] = code_value();
  5495. }
  5496. if(code_seen('Y'))
  5497. {
  5498. extruder_offset[Y_AXIS][extruder] = code_value();
  5499. }
  5500. SERIAL_ECHO_START;
  5501. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  5502. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  5503. {
  5504. SERIAL_ECHO(" ");
  5505. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  5506. SERIAL_ECHO(",");
  5507. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  5508. }
  5509. SERIAL_ECHOLN("");
  5510. }break;
  5511. #endif
  5512. case 220: // M220 S<factor in percent>- set speed factor override percentage
  5513. {
  5514. if (code_seen('B')) //backup current speed factor
  5515. {
  5516. saved_feedmultiply_mm = feedmultiply;
  5517. }
  5518. if(code_seen('S'))
  5519. {
  5520. feedmultiply = code_value() ;
  5521. }
  5522. if (code_seen('R')) { //restore previous feedmultiply
  5523. feedmultiply = saved_feedmultiply_mm;
  5524. }
  5525. }
  5526. break;
  5527. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  5528. {
  5529. if(code_seen('S'))
  5530. {
  5531. int tmp_code = code_value();
  5532. if (code_seen('T'))
  5533. {
  5534. uint8_t extruder;
  5535. if(setTargetedHotend(221, extruder)){
  5536. break;
  5537. }
  5538. extruder_multiply[extruder] = tmp_code;
  5539. }
  5540. else
  5541. {
  5542. extrudemultiply = tmp_code ;
  5543. }
  5544. }
  5545. calculate_extruder_multipliers();
  5546. }
  5547. break;
  5548. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  5549. {
  5550. if(code_seen('P')){
  5551. int pin_number = code_value(); // pin number
  5552. int pin_state = -1; // required pin state - default is inverted
  5553. if(code_seen('S')) pin_state = code_value(); // required pin state
  5554. if(pin_state >= -1 && pin_state <= 1){
  5555. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  5556. {
  5557. if (sensitive_pins[i] == pin_number)
  5558. {
  5559. pin_number = -1;
  5560. break;
  5561. }
  5562. }
  5563. if (pin_number > -1)
  5564. {
  5565. int target = LOW;
  5566. st_synchronize();
  5567. pinMode(pin_number, INPUT);
  5568. switch(pin_state){
  5569. case 1:
  5570. target = HIGH;
  5571. break;
  5572. case 0:
  5573. target = LOW;
  5574. break;
  5575. case -1:
  5576. target = !digitalRead(pin_number);
  5577. break;
  5578. }
  5579. while(digitalRead(pin_number) != target){
  5580. manage_heater();
  5581. manage_inactivity();
  5582. lcd_update(0);
  5583. }
  5584. }
  5585. }
  5586. }
  5587. }
  5588. break;
  5589. #if NUM_SERVOS > 0
  5590. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  5591. {
  5592. int servo_index = -1;
  5593. int servo_position = 0;
  5594. if (code_seen('P'))
  5595. servo_index = code_value();
  5596. if (code_seen('S')) {
  5597. servo_position = code_value();
  5598. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  5599. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  5600. servos[servo_index].attach(0);
  5601. #endif
  5602. servos[servo_index].write(servo_position);
  5603. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  5604. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  5605. servos[servo_index].detach();
  5606. #endif
  5607. }
  5608. else {
  5609. SERIAL_ECHO_START;
  5610. SERIAL_ECHO("Servo ");
  5611. SERIAL_ECHO(servo_index);
  5612. SERIAL_ECHOLN(" out of range");
  5613. }
  5614. }
  5615. else if (servo_index >= 0) {
  5616. SERIAL_PROTOCOL(MSG_OK);
  5617. SERIAL_PROTOCOL(" Servo ");
  5618. SERIAL_PROTOCOL(servo_index);
  5619. SERIAL_PROTOCOL(": ");
  5620. SERIAL_PROTOCOL(servos[servo_index].read());
  5621. SERIAL_PROTOCOLLN("");
  5622. }
  5623. }
  5624. break;
  5625. #endif // NUM_SERVOS > 0
  5626. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  5627. case 300: // M300
  5628. {
  5629. int beepS = code_seen('S') ? code_value() : 110;
  5630. int beepP = code_seen('P') ? code_value() : 1000;
  5631. if (beepS > 0)
  5632. {
  5633. #if BEEPER > 0
  5634. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  5635. _tone(BEEPER, beepS);
  5636. _delay(beepP);
  5637. _noTone(BEEPER);
  5638. #endif
  5639. }
  5640. else
  5641. {
  5642. _delay(beepP);
  5643. }
  5644. }
  5645. break;
  5646. #endif // M300
  5647. #ifdef PIDTEMP
  5648. case 301: // M301
  5649. {
  5650. if(code_seen('P')) cs.Kp = code_value();
  5651. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  5652. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  5653. #ifdef PID_ADD_EXTRUSION_RATE
  5654. if(code_seen('C')) Kc = code_value();
  5655. #endif
  5656. updatePID();
  5657. SERIAL_PROTOCOLRPGM(MSG_OK);
  5658. SERIAL_PROTOCOL(" p:");
  5659. SERIAL_PROTOCOL(cs.Kp);
  5660. SERIAL_PROTOCOL(" i:");
  5661. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  5662. SERIAL_PROTOCOL(" d:");
  5663. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  5664. #ifdef PID_ADD_EXTRUSION_RATE
  5665. SERIAL_PROTOCOL(" c:");
  5666. //Kc does not have scaling applied above, or in resetting defaults
  5667. SERIAL_PROTOCOL(Kc);
  5668. #endif
  5669. SERIAL_PROTOCOLLN("");
  5670. }
  5671. break;
  5672. #endif //PIDTEMP
  5673. #ifdef PIDTEMPBED
  5674. case 304: // M304
  5675. {
  5676. if(code_seen('P')) cs.bedKp = code_value();
  5677. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  5678. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  5679. updatePID();
  5680. SERIAL_PROTOCOLRPGM(MSG_OK);
  5681. SERIAL_PROTOCOL(" p:");
  5682. SERIAL_PROTOCOL(cs.bedKp);
  5683. SERIAL_PROTOCOL(" i:");
  5684. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  5685. SERIAL_PROTOCOL(" d:");
  5686. SERIAL_PROTOCOL(unscalePID_d(cs.bedKd));
  5687. SERIAL_PROTOCOLLN("");
  5688. }
  5689. break;
  5690. #endif //PIDTEMP
  5691. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  5692. {
  5693. #ifdef CHDK
  5694. SET_OUTPUT(CHDK);
  5695. WRITE(CHDK, HIGH);
  5696. chdkHigh = _millis();
  5697. chdkActive = true;
  5698. #else
  5699. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  5700. const uint8_t NUM_PULSES=16;
  5701. const float PULSE_LENGTH=0.01524;
  5702. for(int i=0; i < NUM_PULSES; i++) {
  5703. WRITE(PHOTOGRAPH_PIN, HIGH);
  5704. _delay_ms(PULSE_LENGTH);
  5705. WRITE(PHOTOGRAPH_PIN, LOW);
  5706. _delay_ms(PULSE_LENGTH);
  5707. }
  5708. _delay(7.33);
  5709. for(int i=0; i < NUM_PULSES; i++) {
  5710. WRITE(PHOTOGRAPH_PIN, HIGH);
  5711. _delay_ms(PULSE_LENGTH);
  5712. WRITE(PHOTOGRAPH_PIN, LOW);
  5713. _delay_ms(PULSE_LENGTH);
  5714. }
  5715. #endif
  5716. #endif //chdk end if
  5717. }
  5718. break;
  5719. #ifdef PREVENT_DANGEROUS_EXTRUDE
  5720. case 302: // allow cold extrudes, or set the minimum extrude temperature
  5721. {
  5722. float temp = .0;
  5723. if (code_seen('S')) temp=code_value();
  5724. set_extrude_min_temp(temp);
  5725. }
  5726. break;
  5727. #endif
  5728. case 303: // M303 PID autotune
  5729. {
  5730. float temp = 150.0;
  5731. int e=0;
  5732. int c=5;
  5733. if (code_seen('E')) e=code_value();
  5734. if (e<0)
  5735. temp=70;
  5736. if (code_seen('S')) temp=code_value();
  5737. if (code_seen('C')) c=code_value();
  5738. PID_autotune(temp, e, c);
  5739. }
  5740. break;
  5741. case 400: // M400 finish all moves
  5742. {
  5743. st_synchronize();
  5744. }
  5745. break;
  5746. case 403: //! M403 set filament type (material) for particular extruder and send this information to mmu
  5747. {
  5748. //! currently three different materials are needed (default, flex and PVA)
  5749. //! add storing this information for different load/unload profiles etc. in the future
  5750. //!firmware does not wait for "ok" from mmu
  5751. if (mmu_enabled)
  5752. {
  5753. uint8_t extruder = 255;
  5754. uint8_t filament = FILAMENT_UNDEFINED;
  5755. if(code_seen('E')) extruder = code_value();
  5756. if(code_seen('F')) filament = code_value();
  5757. mmu_set_filament_type(extruder, filament);
  5758. }
  5759. }
  5760. break;
  5761. case 500: // M500 Store settings in EEPROM
  5762. {
  5763. Config_StoreSettings();
  5764. }
  5765. break;
  5766. case 501: // M501 Read settings from EEPROM
  5767. {
  5768. Config_RetrieveSettings();
  5769. }
  5770. break;
  5771. case 502: // M502 Revert to default settings
  5772. {
  5773. Config_ResetDefault();
  5774. }
  5775. break;
  5776. case 503: // M503 print settings currently in memory
  5777. {
  5778. Config_PrintSettings();
  5779. }
  5780. break;
  5781. case 509: //M509 Force language selection
  5782. {
  5783. lang_reset();
  5784. SERIAL_ECHO_START;
  5785. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  5786. }
  5787. break;
  5788. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  5789. case 540:
  5790. {
  5791. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  5792. }
  5793. break;
  5794. #endif
  5795. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  5796. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  5797. {
  5798. float value;
  5799. if (code_seen('Z'))
  5800. {
  5801. value = code_value();
  5802. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  5803. {
  5804. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  5805. SERIAL_ECHO_START;
  5806. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  5807. SERIAL_PROTOCOLLN("");
  5808. }
  5809. else
  5810. {
  5811. SERIAL_ECHO_START;
  5812. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  5813. SERIAL_ECHORPGM(MSG_Z_MIN);
  5814. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  5815. SERIAL_ECHORPGM(MSG_Z_MAX);
  5816. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  5817. SERIAL_PROTOCOLLN("");
  5818. }
  5819. }
  5820. else
  5821. {
  5822. SERIAL_ECHO_START;
  5823. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  5824. SERIAL_ECHO(-cs.zprobe_zoffset);
  5825. SERIAL_PROTOCOLLN("");
  5826. }
  5827. break;
  5828. }
  5829. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  5830. #ifdef FILAMENTCHANGEENABLE
  5831. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  5832. {
  5833. st_synchronize();
  5834. float x_position = current_position[X_AXIS];
  5835. float y_position = current_position[Y_AXIS];
  5836. float z_shift = 0; // is it necessary to be a float?
  5837. float e_shift_init = 0;
  5838. float e_shift_late = 0;
  5839. bool automatic = false;
  5840. //Retract extruder
  5841. if(code_seen('E'))
  5842. {
  5843. e_shift_init = code_value();
  5844. }
  5845. else
  5846. {
  5847. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  5848. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  5849. #endif
  5850. }
  5851. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  5852. if (code_seen('L'))
  5853. {
  5854. e_shift_late = code_value();
  5855. }
  5856. else
  5857. {
  5858. #ifdef FILAMENTCHANGE_FINALRETRACT
  5859. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  5860. #endif
  5861. }
  5862. //Lift Z
  5863. if(code_seen('Z'))
  5864. {
  5865. z_shift = code_value();
  5866. }
  5867. else
  5868. {
  5869. z_shift = gcode_M600_filament_change_z_shift<uint8_t>();
  5870. }
  5871. //Move XY to side
  5872. if(code_seen('X'))
  5873. {
  5874. x_position = code_value();
  5875. }
  5876. else
  5877. {
  5878. #ifdef FILAMENTCHANGE_XPOS
  5879. x_position = FILAMENTCHANGE_XPOS;
  5880. #endif
  5881. }
  5882. if(code_seen('Y'))
  5883. {
  5884. y_position = code_value();
  5885. }
  5886. else
  5887. {
  5888. #ifdef FILAMENTCHANGE_YPOS
  5889. y_position = FILAMENTCHANGE_YPOS ;
  5890. #endif
  5891. }
  5892. if (mmu_enabled && code_seen("AUTO"))
  5893. automatic = true;
  5894. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  5895. }
  5896. break;
  5897. #endif //FILAMENTCHANGEENABLE
  5898. case 601: //! M601 - Pause print
  5899. {
  5900. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  5901. lcd_pause_print();
  5902. }
  5903. break;
  5904. case 602: { //! M602 - Resume print
  5905. lcd_resume_print();
  5906. }
  5907. break;
  5908. #ifdef PINDA_THERMISTOR
  5909. case 860: // M860 - Wait for PINDA thermistor to reach target temperature.
  5910. {
  5911. int set_target_pinda = 0;
  5912. if (code_seen('S')) {
  5913. set_target_pinda = code_value();
  5914. }
  5915. else {
  5916. break;
  5917. }
  5918. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  5919. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  5920. SERIAL_PROTOCOL(set_target_pinda);
  5921. SERIAL_PROTOCOLLN("");
  5922. codenum = _millis();
  5923. cancel_heatup = false;
  5924. bool is_pinda_cooling = false;
  5925. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  5926. is_pinda_cooling = true;
  5927. }
  5928. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  5929. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  5930. {
  5931. SERIAL_PROTOCOLPGM("P:");
  5932. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  5933. SERIAL_PROTOCOLPGM("/");
  5934. SERIAL_PROTOCOL(set_target_pinda);
  5935. SERIAL_PROTOCOLLN("");
  5936. codenum = _millis();
  5937. }
  5938. manage_heater();
  5939. manage_inactivity();
  5940. lcd_update(0);
  5941. }
  5942. LCD_MESSAGERPGM(MSG_OK);
  5943. break;
  5944. }
  5945. case 861: // M861 - Set/Read PINDA temperature compensation offsets
  5946. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  5947. uint8_t cal_status = calibration_status_pinda();
  5948. int16_t usteps = 0;
  5949. cal_status ? SERIAL_PROTOCOLLN("PINDA cal status: 1") : SERIAL_PROTOCOLLN("PINDA cal status: 0");
  5950. SERIAL_PROTOCOLLN("index, temp, ustep, um");
  5951. for (uint8_t i = 0; i < 6; i++)
  5952. {
  5953. if(i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i-1) * 2, &usteps);
  5954. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  5955. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  5956. SERIAL_PROTOCOLPGM(", ");
  5957. SERIAL_PROTOCOL(35 + (i * 5));
  5958. SERIAL_PROTOCOLPGM(", ");
  5959. SERIAL_PROTOCOL(usteps);
  5960. SERIAL_PROTOCOLPGM(", ");
  5961. SERIAL_PROTOCOL(mm * 1000);
  5962. SERIAL_PROTOCOLLN("");
  5963. }
  5964. }
  5965. else if (code_seen('!')) { // ! - Set factory default values
  5966. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  5967. int16_t z_shift = 8; //40C - 20um - 8usteps
  5968. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT, &z_shift);
  5969. z_shift = 24; //45C - 60um - 24usteps
  5970. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 2, &z_shift);
  5971. z_shift = 48; //50C - 120um - 48usteps
  5972. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 4, &z_shift);
  5973. z_shift = 80; //55C - 200um - 80usteps
  5974. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 6, &z_shift);
  5975. z_shift = 120; //60C - 300um - 120usteps
  5976. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 8, &z_shift);
  5977. SERIAL_PROTOCOLLN("factory restored");
  5978. }
  5979. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  5980. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  5981. int16_t z_shift = 0;
  5982. for (uint8_t i = 0; i < 5; i++) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  5983. SERIAL_PROTOCOLLN("zerorized");
  5984. }
  5985. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  5986. int16_t usteps = code_value();
  5987. if (code_seen('I')) {
  5988. uint8_t index = code_value();
  5989. if (index < 5) {
  5990. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + index * 2, &usteps);
  5991. SERIAL_PROTOCOLLN("OK");
  5992. SERIAL_PROTOCOLLN("index, temp, ustep, um");
  5993. for (uint8_t i = 0; i < 6; i++)
  5994. {
  5995. usteps = 0;
  5996. if (i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i - 1) * 2, &usteps);
  5997. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  5998. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  5999. SERIAL_PROTOCOLPGM(", ");
  6000. SERIAL_PROTOCOL(35 + (i * 5));
  6001. SERIAL_PROTOCOLPGM(", ");
  6002. SERIAL_PROTOCOL(usteps);
  6003. SERIAL_PROTOCOLPGM(", ");
  6004. SERIAL_PROTOCOL(mm * 1000);
  6005. SERIAL_PROTOCOLLN("");
  6006. }
  6007. }
  6008. }
  6009. }
  6010. else {
  6011. SERIAL_PROTOCOLPGM("no valid command");
  6012. }
  6013. break;
  6014. #endif //PINDA_THERMISTOR
  6015. #ifdef LIN_ADVANCE
  6016. case 900: // M900: Set LIN_ADVANCE options.
  6017. gcode_M900();
  6018. break;
  6019. #endif
  6020. case 907: // M907 Set digital trimpot motor current using axis codes.
  6021. {
  6022. #ifdef TMC2130
  6023. for (int i = 0; i < NUM_AXIS; i++)
  6024. if(code_seen(axis_codes[i]))
  6025. {
  6026. long cur_mA = code_value_long();
  6027. uint8_t val = tmc2130_cur2val(cur_mA);
  6028. tmc2130_set_current_h(i, val);
  6029. tmc2130_set_current_r(i, val);
  6030. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  6031. }
  6032. #else //TMC2130
  6033. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  6034. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  6035. if(code_seen('B')) st_current_set(4,code_value());
  6036. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  6037. #endif
  6038. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  6039. if(code_seen('X')) st_current_set(0, code_value());
  6040. #endif
  6041. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  6042. if(code_seen('Z')) st_current_set(1, code_value());
  6043. #endif
  6044. #ifdef MOTOR_CURRENT_PWM_E_PIN
  6045. if(code_seen('E')) st_current_set(2, code_value());
  6046. #endif
  6047. #endif //TMC2130
  6048. }
  6049. break;
  6050. case 908: // M908 Control digital trimpot directly.
  6051. {
  6052. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  6053. uint8_t channel,current;
  6054. if(code_seen('P')) channel=code_value();
  6055. if(code_seen('S')) current=code_value();
  6056. digitalPotWrite(channel, current);
  6057. #endif
  6058. }
  6059. break;
  6060. #ifdef TMC2130_SERVICE_CODES_M910_M918
  6061. case 910: //! M910 - TMC2130 init
  6062. {
  6063. tmc2130_init();
  6064. }
  6065. break;
  6066. case 911: //! M911 - Set TMC2130 holding currents
  6067. {
  6068. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  6069. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  6070. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  6071. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  6072. }
  6073. break;
  6074. case 912: //! M912 - Set TMC2130 running currents
  6075. {
  6076. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  6077. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  6078. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  6079. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  6080. }
  6081. break;
  6082. case 913: //! M913 - Print TMC2130 currents
  6083. {
  6084. tmc2130_print_currents();
  6085. }
  6086. break;
  6087. case 914: //! M914 - Set normal mode
  6088. {
  6089. tmc2130_mode = TMC2130_MODE_NORMAL;
  6090. update_mode_profile();
  6091. tmc2130_init();
  6092. }
  6093. break;
  6094. case 915: //! M915 - Set silent mode
  6095. {
  6096. tmc2130_mode = TMC2130_MODE_SILENT;
  6097. update_mode_profile();
  6098. tmc2130_init();
  6099. }
  6100. break;
  6101. case 916: //! M916 - Set sg_thrs
  6102. {
  6103. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  6104. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  6105. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  6106. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  6107. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  6108. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  6109. }
  6110. break;
  6111. case 917: //! M917 - Set TMC2130 pwm_ampl
  6112. {
  6113. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  6114. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  6115. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  6116. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  6117. }
  6118. break;
  6119. case 918: //! M918 - Set TMC2130 pwm_grad
  6120. {
  6121. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  6122. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  6123. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  6124. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  6125. }
  6126. break;
  6127. #endif //TMC2130_SERVICE_CODES_M910_M918
  6128. case 350: //! M350 - Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  6129. {
  6130. #ifdef TMC2130
  6131. if(code_seen('E'))
  6132. {
  6133. uint16_t res_new = code_value();
  6134. if ((res_new == 8) || (res_new == 16) || (res_new == 32) || (res_new == 64) || (res_new == 128))
  6135. {
  6136. st_synchronize();
  6137. uint8_t axis = E_AXIS;
  6138. uint16_t res = tmc2130_get_res(axis);
  6139. tmc2130_set_res(axis, res_new);
  6140. cs.axis_ustep_resolution[axis] = res_new;
  6141. if (res_new > res)
  6142. {
  6143. uint16_t fac = (res_new / res);
  6144. cs.axis_steps_per_unit[axis] *= fac;
  6145. position[E_AXIS] *= fac;
  6146. }
  6147. else
  6148. {
  6149. uint16_t fac = (res / res_new);
  6150. cs.axis_steps_per_unit[axis] /= fac;
  6151. position[E_AXIS] /= fac;
  6152. }
  6153. }
  6154. }
  6155. #else //TMC2130
  6156. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  6157. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  6158. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  6159. if(code_seen('B')) microstep_mode(4,code_value());
  6160. microstep_readings();
  6161. #endif
  6162. #endif //TMC2130
  6163. }
  6164. break;
  6165. case 351: //! M351 - Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  6166. {
  6167. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  6168. if(code_seen('S')) switch((int)code_value())
  6169. {
  6170. case 1:
  6171. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  6172. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  6173. break;
  6174. case 2:
  6175. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  6176. if(code_seen('B')) microstep_ms(4,-1,code_value());
  6177. break;
  6178. }
  6179. microstep_readings();
  6180. #endif
  6181. }
  6182. break;
  6183. case 701: //! M701 - load filament
  6184. {
  6185. if (mmu_enabled && code_seen('E'))
  6186. tmp_extruder = code_value();
  6187. gcode_M701();
  6188. }
  6189. break;
  6190. case 702: //! M702 [U C] -
  6191. {
  6192. #ifdef SNMM
  6193. if (code_seen('U'))
  6194. extr_unload_used(); //! if "U" unload all filaments which were used in current print
  6195. else if (code_seen('C'))
  6196. extr_unload(); //! if "C" unload just current filament
  6197. else
  6198. extr_unload_all(); //! otherwise unload all filaments
  6199. #else
  6200. if (code_seen('C')) {
  6201. if(mmu_enabled) extr_unload(); //! if "C" unload current filament; if mmu is not present no action is performed
  6202. }
  6203. else {
  6204. if(mmu_enabled) extr_unload(); //! unload current filament
  6205. else unload_filament();
  6206. }
  6207. #endif //SNMM
  6208. }
  6209. break;
  6210. case 999: // M999: Restart after being stopped
  6211. Stopped = false;
  6212. lcd_reset_alert_level();
  6213. gcode_LastN = Stopped_gcode_LastN;
  6214. FlushSerialRequestResend();
  6215. break;
  6216. default:
  6217. printf_P(PSTR("Unknown M code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  6218. }
  6219. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  6220. mcode_in_progress = 0;
  6221. }
  6222. }
  6223. // end if(code_seen('M')) (end of M codes)
  6224. //! T<extruder nr.> - select extruder in case of multi extruder printer
  6225. //! select filament in case of MMU_V2
  6226. //! if extruder is "?", open menu to let the user select extruder/filament
  6227. //!
  6228. //! For MMU_V2:
  6229. //! @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.
  6230. //! @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  6231. //! @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.
  6232. //! @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  6233. else if(code_seen('T'))
  6234. {
  6235. int index;
  6236. bool load_to_nozzle = false;
  6237. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  6238. *(strchr_pointer + index) = tolower(*(strchr_pointer + index));
  6239. if ((*(strchr_pointer + index) < '0' || *(strchr_pointer + index) > '4') && *(strchr_pointer + index) != '?' && *(strchr_pointer + index) != 'x' && *(strchr_pointer + index) != 'c') {
  6240. SERIAL_ECHOLNPGM("Invalid T code.");
  6241. }
  6242. else if (*(strchr_pointer + index) == 'x'){ //load to bondtech gears; if mmu is not present do nothing
  6243. if (mmu_enabled)
  6244. {
  6245. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_FILAMENT), _T(MSG_FILAMENT));
  6246. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  6247. {
  6248. printf_P(PSTR("Duplicate T-code ignored.\n"));
  6249. }
  6250. else
  6251. {
  6252. st_synchronize();
  6253. mmu_command(MmuCmd::T0 + tmp_extruder);
  6254. manage_response(true, true, MMU_TCODE_MOVE);
  6255. }
  6256. }
  6257. }
  6258. else if (*(strchr_pointer + index) == 'c') { //load to from bondtech gears to nozzle (nozzle should be preheated)
  6259. if (mmu_enabled)
  6260. {
  6261. st_synchronize();
  6262. mmu_continue_loading(is_usb_printing);
  6263. mmu_extruder = tmp_extruder; //filament change is finished
  6264. mmu_load_to_nozzle();
  6265. }
  6266. }
  6267. else {
  6268. if (*(strchr_pointer + index) == '?')
  6269. {
  6270. if(mmu_enabled)
  6271. {
  6272. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_FILAMENT), _T(MSG_FILAMENT));
  6273. load_to_nozzle = true;
  6274. } else
  6275. {
  6276. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_EXTRUDER), _T(MSG_EXTRUDER));
  6277. }
  6278. }
  6279. else {
  6280. tmp_extruder = code_value();
  6281. if (mmu_enabled && lcd_autoDepleteEnabled())
  6282. {
  6283. tmp_extruder = ad_getAlternative(tmp_extruder);
  6284. }
  6285. }
  6286. st_synchronize();
  6287. snmm_filaments_used |= (1 << tmp_extruder); //for stop print
  6288. if (mmu_enabled)
  6289. {
  6290. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  6291. {
  6292. printf_P(PSTR("Duplicate T-code ignored.\n"));
  6293. }
  6294. else
  6295. {
  6296. #if defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  6297. if (EEPROM_MMU_CUTTER_ENABLED_always == eeprom_read_byte((uint8_t*)EEPROM_MMU_CUTTER_ENABLED))
  6298. {
  6299. mmu_command(MmuCmd::K0 + tmp_extruder);
  6300. manage_response(true, true, MMU_UNLOAD_MOVE);
  6301. }
  6302. #endif //defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  6303. mmu_command(MmuCmd::T0 + tmp_extruder);
  6304. manage_response(true, true, MMU_TCODE_MOVE);
  6305. mmu_continue_loading(is_usb_printing);
  6306. mmu_extruder = tmp_extruder; //filament change is finished
  6307. if (load_to_nozzle)// for single material usage with mmu
  6308. {
  6309. mmu_load_to_nozzle();
  6310. }
  6311. }
  6312. }
  6313. else
  6314. {
  6315. #ifdef SNMM
  6316. #ifdef LIN_ADVANCE
  6317. if (mmu_extruder != tmp_extruder)
  6318. clear_current_adv_vars(); //Check if the selected extruder is not the active one and reset LIN_ADVANCE variables if so.
  6319. #endif
  6320. mmu_extruder = tmp_extruder;
  6321. _delay(100);
  6322. disable_e0();
  6323. disable_e1();
  6324. disable_e2();
  6325. pinMode(E_MUX0_PIN, OUTPUT);
  6326. pinMode(E_MUX1_PIN, OUTPUT);
  6327. _delay(100);
  6328. SERIAL_ECHO_START;
  6329. SERIAL_ECHO("T:");
  6330. SERIAL_ECHOLN((int)tmp_extruder);
  6331. switch (tmp_extruder) {
  6332. case 1:
  6333. WRITE(E_MUX0_PIN, HIGH);
  6334. WRITE(E_MUX1_PIN, LOW);
  6335. break;
  6336. case 2:
  6337. WRITE(E_MUX0_PIN, LOW);
  6338. WRITE(E_MUX1_PIN, HIGH);
  6339. break;
  6340. case 3:
  6341. WRITE(E_MUX0_PIN, HIGH);
  6342. WRITE(E_MUX1_PIN, HIGH);
  6343. break;
  6344. default:
  6345. WRITE(E_MUX0_PIN, LOW);
  6346. WRITE(E_MUX1_PIN, LOW);
  6347. break;
  6348. }
  6349. _delay(100);
  6350. #else //SNMM
  6351. if (tmp_extruder >= EXTRUDERS) {
  6352. SERIAL_ECHO_START;
  6353. SERIAL_ECHOPGM("T");
  6354. SERIAL_PROTOCOLLN((int)tmp_extruder);
  6355. SERIAL_ECHOLNRPGM(_n("Invalid extruder"));////MSG_INVALID_EXTRUDER
  6356. }
  6357. else {
  6358. #if EXTRUDERS > 1
  6359. boolean make_move = false;
  6360. #endif
  6361. if (code_seen('F')) {
  6362. #if EXTRUDERS > 1
  6363. make_move = true;
  6364. #endif
  6365. next_feedrate = code_value();
  6366. if (next_feedrate > 0.0) {
  6367. feedrate = next_feedrate;
  6368. }
  6369. }
  6370. #if EXTRUDERS > 1
  6371. if (tmp_extruder != active_extruder) {
  6372. // Save current position to return to after applying extruder offset
  6373. memcpy(destination, current_position, sizeof(destination));
  6374. // Offset extruder (only by XY)
  6375. int i;
  6376. for (i = 0; i < 2; i++) {
  6377. current_position[i] = current_position[i] -
  6378. extruder_offset[i][active_extruder] +
  6379. extruder_offset[i][tmp_extruder];
  6380. }
  6381. // Set the new active extruder and position
  6382. active_extruder = tmp_extruder;
  6383. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  6384. // Move to the old position if 'F' was in the parameters
  6385. if (make_move && Stopped == false) {
  6386. prepare_move();
  6387. }
  6388. }
  6389. #endif
  6390. SERIAL_ECHO_START;
  6391. SERIAL_ECHORPGM(_n("Active Extruder: "));////MSG_ACTIVE_EXTRUDER
  6392. SERIAL_PROTOCOLLN((int)active_extruder);
  6393. }
  6394. #endif //SNMM
  6395. }
  6396. }
  6397. } // end if(code_seen('T')) (end of T codes)
  6398. else if (code_seen('D')) // D codes (debug)
  6399. {
  6400. switch((int)code_value())
  6401. {
  6402. case -1: //! D-1 - Endless loop
  6403. dcode__1(); break;
  6404. #ifdef DEBUG_DCODES
  6405. case 0: //! D0 - Reset
  6406. dcode_0(); break;
  6407. case 1: //! D1 - Clear EEPROM
  6408. dcode_1(); break;
  6409. case 2: //! D2 - Read/Write RAM
  6410. dcode_2(); break;
  6411. #endif //DEBUG_DCODES
  6412. #ifdef DEBUG_DCODE3
  6413. case 3: //! D3 - Read/Write EEPROM
  6414. dcode_3(); break;
  6415. #endif //DEBUG_DCODE3
  6416. #ifdef DEBUG_DCODES
  6417. case 4: //! D4 - Read/Write PIN
  6418. dcode_4(); break;
  6419. #endif //DEBUG_DCODES
  6420. #ifdef DEBUG_DCODE5
  6421. case 5: // D5 - Read/Write FLASH
  6422. dcode_5(); break;
  6423. break;
  6424. #endif //DEBUG_DCODE5
  6425. #ifdef DEBUG_DCODES
  6426. case 6: // D6 - Read/Write external FLASH
  6427. dcode_6(); break;
  6428. case 7: //! D7 - Read/Write Bootloader
  6429. dcode_7(); break;
  6430. case 8: //! D8 - Read/Write PINDA
  6431. dcode_8(); break;
  6432. case 9: //! D9 - Read/Write ADC
  6433. dcode_9(); break;
  6434. case 10: //! D10 - XYZ calibration = OK
  6435. dcode_10(); break;
  6436. #endif //DEBUG_DCODES
  6437. #ifdef HEATBED_ANALYSIS
  6438. case 80:
  6439. {
  6440. float dimension_x = 40;
  6441. float dimension_y = 40;
  6442. int points_x = 40;
  6443. int points_y = 40;
  6444. float offset_x = 74;
  6445. float offset_y = 33;
  6446. if (code_seen('E')) dimension_x = code_value();
  6447. if (code_seen('F')) dimension_y = code_value();
  6448. if (code_seen('G')) {points_x = code_value(); }
  6449. if (code_seen('H')) {points_y = code_value(); }
  6450. if (code_seen('I')) {offset_x = code_value(); }
  6451. if (code_seen('J')) {offset_y = code_value(); }
  6452. printf_P(PSTR("DIM X: %f\n"), dimension_x);
  6453. printf_P(PSTR("DIM Y: %f\n"), dimension_y);
  6454. printf_P(PSTR("POINTS X: %d\n"), points_x);
  6455. printf_P(PSTR("POINTS Y: %d\n"), points_y);
  6456. printf_P(PSTR("OFFSET X: %f\n"), offset_x);
  6457. printf_P(PSTR("OFFSET Y: %f\n"), offset_y);
  6458. bed_check(dimension_x,dimension_y,points_x,points_y,offset_x,offset_y);
  6459. }break;
  6460. case 81:
  6461. {
  6462. float dimension_x = 40;
  6463. float dimension_y = 40;
  6464. int points_x = 40;
  6465. int points_y = 40;
  6466. float offset_x = 74;
  6467. float offset_y = 33;
  6468. if (code_seen('E')) dimension_x = code_value();
  6469. if (code_seen('F')) dimension_y = code_value();
  6470. if (code_seen("G")) { strchr_pointer+=1; points_x = code_value(); }
  6471. if (code_seen("H")) { strchr_pointer+=1; points_y = code_value(); }
  6472. if (code_seen("I")) { strchr_pointer+=1; offset_x = code_value(); }
  6473. if (code_seen("J")) { strchr_pointer+=1; offset_y = code_value(); }
  6474. bed_analysis(dimension_x,dimension_y,points_x,points_y,offset_x,offset_y);
  6475. } break;
  6476. #endif //HEATBED_ANALYSIS
  6477. #ifdef DEBUG_DCODES
  6478. case 106: //D106 print measured fan speed for different pwm values
  6479. {
  6480. for (int i = 255; i > 0; i = i - 5) {
  6481. fanSpeed = i;
  6482. //delay_keep_alive(2000);
  6483. for (int j = 0; j < 100; j++) {
  6484. delay_keep_alive(100);
  6485. }
  6486. printf_P(_N("%d: %d\n"), i, fan_speed[1]);
  6487. }
  6488. }break;
  6489. #ifdef TMC2130
  6490. case 2130: //! D2130 - TMC2130
  6491. dcode_2130(); break;
  6492. #endif //TMC2130
  6493. #if (defined (FILAMENT_SENSOR) && defined(PAT9125))
  6494. case 9125: //! D9125 - FILAMENT_SENSOR
  6495. dcode_9125(); break;
  6496. #endif //FILAMENT_SENSOR
  6497. #endif //DEBUG_DCODES
  6498. }
  6499. }
  6500. else
  6501. {
  6502. SERIAL_ECHO_START;
  6503. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6504. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6505. SERIAL_ECHOLNPGM("\"(2)");
  6506. }
  6507. KEEPALIVE_STATE(NOT_BUSY);
  6508. ClearToSend();
  6509. }
  6510. void FlushSerialRequestResend()
  6511. {
  6512. //char cmdbuffer[bufindr][100]="Resend:";
  6513. MYSERIAL.flush();
  6514. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  6515. }
  6516. // Confirm the execution of a command, if sent from a serial line.
  6517. // Execution of a command from a SD card will not be confirmed.
  6518. void ClearToSend()
  6519. {
  6520. previous_millis_cmd = _millis();
  6521. if ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR))
  6522. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  6523. }
  6524. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  6525. void update_currents() {
  6526. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  6527. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  6528. float tmp_motor[3];
  6529. //SERIAL_ECHOLNPGM("Currents updated: ");
  6530. if (destination[Z_AXIS] < Z_SILENT) {
  6531. //SERIAL_ECHOLNPGM("LOW");
  6532. for (uint8_t i = 0; i < 3; i++) {
  6533. st_current_set(i, current_low[i]);
  6534. /*MYSERIAL.print(int(i));
  6535. SERIAL_ECHOPGM(": ");
  6536. MYSERIAL.println(current_low[i]);*/
  6537. }
  6538. }
  6539. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  6540. //SERIAL_ECHOLNPGM("HIGH");
  6541. for (uint8_t i = 0; i < 3; i++) {
  6542. st_current_set(i, current_high[i]);
  6543. /*MYSERIAL.print(int(i));
  6544. SERIAL_ECHOPGM(": ");
  6545. MYSERIAL.println(current_high[i]);*/
  6546. }
  6547. }
  6548. else {
  6549. for (uint8_t i = 0; i < 3; i++) {
  6550. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  6551. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  6552. st_current_set(i, tmp_motor[i]);
  6553. /*MYSERIAL.print(int(i));
  6554. SERIAL_ECHOPGM(": ");
  6555. MYSERIAL.println(tmp_motor[i]);*/
  6556. }
  6557. }
  6558. }
  6559. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  6560. void get_coordinates()
  6561. {
  6562. bool seen[4]={false,false,false,false};
  6563. for(int8_t i=0; i < NUM_AXIS; i++) {
  6564. if(code_seen(axis_codes[i]))
  6565. {
  6566. bool relative = axis_relative_modes[i] || relative_mode;
  6567. destination[i] = (float)code_value();
  6568. if (i == E_AXIS) {
  6569. float emult = extruder_multiplier[active_extruder];
  6570. if (emult != 1.) {
  6571. if (! relative) {
  6572. destination[i] -= current_position[i];
  6573. relative = true;
  6574. }
  6575. destination[i] *= emult;
  6576. }
  6577. }
  6578. if (relative)
  6579. destination[i] += current_position[i];
  6580. seen[i]=true;
  6581. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  6582. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  6583. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  6584. }
  6585. else destination[i] = current_position[i]; //Are these else lines really needed?
  6586. }
  6587. if(code_seen('F')) {
  6588. next_feedrate = code_value();
  6589. #ifdef MAX_SILENT_FEEDRATE
  6590. if (tmc2130_mode == TMC2130_MODE_SILENT)
  6591. if (next_feedrate > MAX_SILENT_FEEDRATE) next_feedrate = MAX_SILENT_FEEDRATE;
  6592. #endif //MAX_SILENT_FEEDRATE
  6593. if(next_feedrate > 0.0) feedrate = next_feedrate;
  6594. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  6595. {
  6596. // float e_max_speed =
  6597. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  6598. }
  6599. }
  6600. }
  6601. void get_arc_coordinates()
  6602. {
  6603. #ifdef SF_ARC_FIX
  6604. bool relative_mode_backup = relative_mode;
  6605. relative_mode = true;
  6606. #endif
  6607. get_coordinates();
  6608. #ifdef SF_ARC_FIX
  6609. relative_mode=relative_mode_backup;
  6610. #endif
  6611. if(code_seen('I')) {
  6612. offset[0] = code_value();
  6613. }
  6614. else {
  6615. offset[0] = 0.0;
  6616. }
  6617. if(code_seen('J')) {
  6618. offset[1] = code_value();
  6619. }
  6620. else {
  6621. offset[1] = 0.0;
  6622. }
  6623. }
  6624. void clamp_to_software_endstops(float target[3])
  6625. {
  6626. #ifdef DEBUG_DISABLE_SWLIMITS
  6627. return;
  6628. #endif //DEBUG_DISABLE_SWLIMITS
  6629. world2machine_clamp(target[0], target[1]);
  6630. // Clamp the Z coordinate.
  6631. if (min_software_endstops) {
  6632. float negative_z_offset = 0;
  6633. #ifdef ENABLE_AUTO_BED_LEVELING
  6634. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  6635. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  6636. #endif
  6637. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  6638. }
  6639. if (max_software_endstops) {
  6640. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  6641. }
  6642. }
  6643. #ifdef MESH_BED_LEVELING
  6644. 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) {
  6645. float dx = x - current_position[X_AXIS];
  6646. float dy = y - current_position[Y_AXIS];
  6647. float dz = z - current_position[Z_AXIS];
  6648. int n_segments = 0;
  6649. if (mbl.active) {
  6650. float len = abs(dx) + abs(dy);
  6651. if (len > 0)
  6652. // Split to 3cm segments or shorter.
  6653. n_segments = int(ceil(len / 30.f));
  6654. }
  6655. if (n_segments > 1) {
  6656. float de = e - current_position[E_AXIS];
  6657. for (int i = 1; i < n_segments; ++ i) {
  6658. float t = float(i) / float(n_segments);
  6659. if (saved_printing || (mbl.active == false)) return;
  6660. plan_buffer_line(
  6661. current_position[X_AXIS] + t * dx,
  6662. current_position[Y_AXIS] + t * dy,
  6663. current_position[Z_AXIS] + t * dz,
  6664. current_position[E_AXIS] + t * de,
  6665. feed_rate, extruder);
  6666. }
  6667. }
  6668. // The rest of the path.
  6669. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  6670. current_position[X_AXIS] = x;
  6671. current_position[Y_AXIS] = y;
  6672. current_position[Z_AXIS] = z;
  6673. current_position[E_AXIS] = e;
  6674. }
  6675. #endif // MESH_BED_LEVELING
  6676. void prepare_move()
  6677. {
  6678. clamp_to_software_endstops(destination);
  6679. previous_millis_cmd = _millis();
  6680. // Do not use feedmultiply for E or Z only moves
  6681. if( (current_position[X_AXIS] == destination [X_AXIS]) && (current_position[Y_AXIS] == destination [Y_AXIS])) {
  6682. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  6683. }
  6684. else {
  6685. #ifdef MESH_BED_LEVELING
  6686. 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);
  6687. #else
  6688. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate*feedmultiply*(1./(60.f*100.f)), active_extruder);
  6689. #endif
  6690. }
  6691. for(int8_t i=0; i < NUM_AXIS; i++) {
  6692. current_position[i] = destination[i];
  6693. }
  6694. }
  6695. void prepare_arc_move(char isclockwise) {
  6696. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  6697. // Trace the arc
  6698. mc_arc(current_position, destination, offset, X_AXIS, Y_AXIS, Z_AXIS, feedrate*feedmultiply/60/100.0, r, isclockwise, active_extruder);
  6699. // As far as the parser is concerned, the position is now == target. In reality the
  6700. // motion control system might still be processing the action and the real tool position
  6701. // in any intermediate location.
  6702. for(int8_t i=0; i < NUM_AXIS; i++) {
  6703. current_position[i] = destination[i];
  6704. }
  6705. previous_millis_cmd = _millis();
  6706. }
  6707. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  6708. #if defined(FAN_PIN)
  6709. #if CONTROLLERFAN_PIN == FAN_PIN
  6710. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  6711. #endif
  6712. #endif
  6713. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  6714. unsigned long lastMotorCheck = 0;
  6715. void controllerFan()
  6716. {
  6717. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  6718. {
  6719. lastMotorCheck = _millis();
  6720. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  6721. #if EXTRUDERS > 2
  6722. || !READ(E2_ENABLE_PIN)
  6723. #endif
  6724. #if EXTRUDER > 1
  6725. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  6726. || !READ(X2_ENABLE_PIN)
  6727. #endif
  6728. || !READ(E1_ENABLE_PIN)
  6729. #endif
  6730. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  6731. {
  6732. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  6733. }
  6734. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  6735. {
  6736. digitalWrite(CONTROLLERFAN_PIN, 0);
  6737. analogWrite(CONTROLLERFAN_PIN, 0);
  6738. }
  6739. else
  6740. {
  6741. // allows digital or PWM fan output to be used (see M42 handling)
  6742. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  6743. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  6744. }
  6745. }
  6746. }
  6747. #endif
  6748. #ifdef TEMP_STAT_LEDS
  6749. static bool blue_led = false;
  6750. static bool red_led = false;
  6751. static uint32_t stat_update = 0;
  6752. void handle_status_leds(void) {
  6753. float max_temp = 0.0;
  6754. if(_millis() > stat_update) {
  6755. stat_update += 500; // Update every 0.5s
  6756. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  6757. max_temp = max(max_temp, degHotend(cur_extruder));
  6758. max_temp = max(max_temp, degTargetHotend(cur_extruder));
  6759. }
  6760. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  6761. max_temp = max(max_temp, degTargetBed());
  6762. max_temp = max(max_temp, degBed());
  6763. #endif
  6764. if((max_temp > 55.0) && (red_led == false)) {
  6765. digitalWrite(STAT_LED_RED, 1);
  6766. digitalWrite(STAT_LED_BLUE, 0);
  6767. red_led = true;
  6768. blue_led = false;
  6769. }
  6770. if((max_temp < 54.0) && (blue_led == false)) {
  6771. digitalWrite(STAT_LED_RED, 0);
  6772. digitalWrite(STAT_LED_BLUE, 1);
  6773. red_led = false;
  6774. blue_led = true;
  6775. }
  6776. }
  6777. }
  6778. #endif
  6779. #ifdef SAFETYTIMER
  6780. /**
  6781. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  6782. *
  6783. * Full screen blocking notification message is shown after heater turning off.
  6784. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  6785. * damage print.
  6786. *
  6787. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  6788. */
  6789. static void handleSafetyTimer()
  6790. {
  6791. #if (EXTRUDERS > 1)
  6792. #error Implemented only for one extruder.
  6793. #endif //(EXTRUDERS > 1)
  6794. if ((PRINTER_ACTIVE) || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  6795. {
  6796. safetyTimer.stop();
  6797. }
  6798. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  6799. {
  6800. safetyTimer.start();
  6801. }
  6802. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  6803. {
  6804. setTargetBed(0);
  6805. setAllTargetHotends(0);
  6806. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED
  6807. }
  6808. }
  6809. #endif //SAFETYTIMER
  6810. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  6811. {
  6812. bool bInhibitFlag;
  6813. #ifdef FILAMENT_SENSOR
  6814. if (mmu_enabled == false)
  6815. {
  6816. //-// if (mcode_in_progress != 600) //M600 not in progress
  6817. #ifdef PAT9125
  6818. bInhibitFlag=(menu_menu==lcd_menu_extruder_info); // Support::ExtruderInfo menu active
  6819. #endif // PAT9125
  6820. #ifdef IR_SENSOR
  6821. bInhibitFlag=(menu_menu==lcd_menu_show_sensors_state); // Support::SensorInfo menu active
  6822. #endif // IR_SENSOR
  6823. if ((mcode_in_progress != 600) && (eFilamentAction != FilamentAction::AutoLoad) && (!bInhibitFlag)) //M600 not in progress, preHeat @ autoLoad menu not active, Support::ExtruderInfo/SensorInfo menu not active
  6824. {
  6825. if (!moves_planned() && !IS_SD_PRINTING && !is_usb_printing && (lcd_commands_type != LcdCommands::Layer1Cal) && !wizard_active)
  6826. {
  6827. if (fsensor_check_autoload())
  6828. {
  6829. #ifdef PAT9125
  6830. fsensor_autoload_check_stop();
  6831. #endif //PAT9125
  6832. //-// if (degHotend0() > EXTRUDE_MINTEMP)
  6833. if(0)
  6834. {
  6835. if ((eSoundMode == e_SOUND_MODE_LOUD) || (eSoundMode == e_SOUND_MODE_ONCE))
  6836. _tone(BEEPER, 1000);
  6837. delay_keep_alive(50);
  6838. _noTone(BEEPER);
  6839. loading_flag = true;
  6840. enquecommand_front_P((PSTR("M701")));
  6841. }
  6842. else
  6843. {
  6844. /*
  6845. lcd_update_enable(false);
  6846. show_preheat_nozzle_warning();
  6847. lcd_update_enable(true);
  6848. */
  6849. eFilamentAction=FilamentAction::AutoLoad;
  6850. bFilamentFirstRun=false;
  6851. if(target_temperature[0]>=EXTRUDE_MINTEMP)
  6852. {
  6853. bFilamentPreheatState=true;
  6854. // mFilamentItem(target_temperature[0],target_temperature_bed);
  6855. menu_submenu(mFilamentItemForce);
  6856. }
  6857. else
  6858. {
  6859. menu_submenu(mFilamentMenu);
  6860. lcd_timeoutToStatus.start();
  6861. }
  6862. }
  6863. }
  6864. }
  6865. else
  6866. {
  6867. #ifdef PAT9125
  6868. fsensor_autoload_check_stop();
  6869. #endif //PAT9125
  6870. fsensor_update();
  6871. }
  6872. }
  6873. }
  6874. #endif //FILAMENT_SENSOR
  6875. #ifdef SAFETYTIMER
  6876. handleSafetyTimer();
  6877. #endif //SAFETYTIMER
  6878. #if defined(KILL_PIN) && KILL_PIN > -1
  6879. static int killCount = 0; // make the inactivity button a bit less responsive
  6880. const int KILL_DELAY = 10000;
  6881. #endif
  6882. if(buflen < (BUFSIZE-1)){
  6883. get_command();
  6884. }
  6885. if( (_millis() - previous_millis_cmd) > max_inactive_time )
  6886. if(max_inactive_time)
  6887. kill(_n(""), 4);
  6888. if(stepper_inactive_time) {
  6889. if( (_millis() - previous_millis_cmd) > stepper_inactive_time )
  6890. {
  6891. if(blocks_queued() == false && ignore_stepper_queue == false) {
  6892. disable_x();
  6893. disable_y();
  6894. disable_z();
  6895. disable_e0();
  6896. disable_e1();
  6897. disable_e2();
  6898. }
  6899. }
  6900. }
  6901. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  6902. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  6903. {
  6904. chdkActive = false;
  6905. WRITE(CHDK, LOW);
  6906. }
  6907. #endif
  6908. #if defined(KILL_PIN) && KILL_PIN > -1
  6909. // Check if the kill button was pressed and wait just in case it was an accidental
  6910. // key kill key press
  6911. // -------------------------------------------------------------------------------
  6912. if( 0 == READ(KILL_PIN) )
  6913. {
  6914. killCount++;
  6915. }
  6916. else if (killCount > 0)
  6917. {
  6918. killCount--;
  6919. }
  6920. // Exceeded threshold and we can confirm that it was not accidental
  6921. // KILL the machine
  6922. // ----------------------------------------------------------------
  6923. if ( killCount >= KILL_DELAY)
  6924. {
  6925. kill("", 5);
  6926. }
  6927. #endif
  6928. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  6929. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  6930. #endif
  6931. #ifdef EXTRUDER_RUNOUT_PREVENT
  6932. if( (_millis() - previous_millis_cmd) > EXTRUDER_RUNOUT_SECONDS*1000 )
  6933. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  6934. {
  6935. bool oldstatus=READ(E0_ENABLE_PIN);
  6936. enable_e0();
  6937. float oldepos=current_position[E_AXIS];
  6938. float oldedes=destination[E_AXIS];
  6939. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  6940. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  6941. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  6942. current_position[E_AXIS]=oldepos;
  6943. destination[E_AXIS]=oldedes;
  6944. plan_set_e_position(oldepos);
  6945. previous_millis_cmd=_millis();
  6946. st_synchronize();
  6947. WRITE(E0_ENABLE_PIN,oldstatus);
  6948. }
  6949. #endif
  6950. #ifdef TEMP_STAT_LEDS
  6951. handle_status_leds();
  6952. #endif
  6953. check_axes_activity();
  6954. mmu_loop();
  6955. }
  6956. void kill(const char *full_screen_message, unsigned char id)
  6957. {
  6958. printf_P(_N("KILL: %d\n"), id);
  6959. //return;
  6960. cli(); // Stop interrupts
  6961. disable_heater();
  6962. disable_x();
  6963. // SERIAL_ECHOLNPGM("kill - disable Y");
  6964. disable_y();
  6965. disable_z();
  6966. disable_e0();
  6967. disable_e1();
  6968. disable_e2();
  6969. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  6970. pinMode(PS_ON_PIN,INPUT);
  6971. #endif
  6972. SERIAL_ERROR_START;
  6973. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  6974. if (full_screen_message != NULL) {
  6975. SERIAL_ERRORLNRPGM(full_screen_message);
  6976. lcd_display_message_fullscreen_P(full_screen_message);
  6977. } else {
  6978. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  6979. }
  6980. // FMC small patch to update the LCD before ending
  6981. sei(); // enable interrupts
  6982. for ( int i=5; i--; lcd_update(0))
  6983. {
  6984. _delay(200);
  6985. }
  6986. cli(); // disable interrupts
  6987. suicide();
  6988. while(1)
  6989. {
  6990. #ifdef WATCHDOG
  6991. wdt_reset();
  6992. #endif //WATCHDOG
  6993. /* Intentionally left empty */
  6994. } // Wait for reset
  6995. }
  6996. void Stop()
  6997. {
  6998. disable_heater();
  6999. if(Stopped == false) {
  7000. Stopped = true;
  7001. lcd_print_stop();
  7002. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  7003. SERIAL_ERROR_START;
  7004. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  7005. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  7006. }
  7007. }
  7008. bool IsStopped() { return Stopped; };
  7009. #ifdef FAST_PWM_FAN
  7010. void setPwmFrequency(uint8_t pin, int val)
  7011. {
  7012. val &= 0x07;
  7013. switch(digitalPinToTimer(pin))
  7014. {
  7015. #if defined(TCCR0A)
  7016. case TIMER0A:
  7017. case TIMER0B:
  7018. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  7019. // TCCR0B |= val;
  7020. break;
  7021. #endif
  7022. #if defined(TCCR1A)
  7023. case TIMER1A:
  7024. case TIMER1B:
  7025. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  7026. // TCCR1B |= val;
  7027. break;
  7028. #endif
  7029. #if defined(TCCR2)
  7030. case TIMER2:
  7031. case TIMER2:
  7032. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  7033. TCCR2 |= val;
  7034. break;
  7035. #endif
  7036. #if defined(TCCR2A)
  7037. case TIMER2A:
  7038. case TIMER2B:
  7039. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  7040. TCCR2B |= val;
  7041. break;
  7042. #endif
  7043. #if defined(TCCR3A)
  7044. case TIMER3A:
  7045. case TIMER3B:
  7046. case TIMER3C:
  7047. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  7048. TCCR3B |= val;
  7049. break;
  7050. #endif
  7051. #if defined(TCCR4A)
  7052. case TIMER4A:
  7053. case TIMER4B:
  7054. case TIMER4C:
  7055. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  7056. TCCR4B |= val;
  7057. break;
  7058. #endif
  7059. #if defined(TCCR5A)
  7060. case TIMER5A:
  7061. case TIMER5B:
  7062. case TIMER5C:
  7063. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  7064. TCCR5B |= val;
  7065. break;
  7066. #endif
  7067. }
  7068. }
  7069. #endif //FAST_PWM_FAN
  7070. //! @brief Get and validate extruder number
  7071. //!
  7072. //! If it is not specified, active_extruder is returned in parameter extruder.
  7073. //! @param [in] code M code number
  7074. //! @param [out] extruder
  7075. //! @return error
  7076. //! @retval true Invalid extruder specified in T code
  7077. //! @retval false Valid extruder specified in T code, or not specifiead
  7078. bool setTargetedHotend(int code, uint8_t &extruder)
  7079. {
  7080. extruder = active_extruder;
  7081. if(code_seen('T')) {
  7082. extruder = code_value();
  7083. if(extruder >= EXTRUDERS) {
  7084. SERIAL_ECHO_START;
  7085. switch(code){
  7086. case 104:
  7087. SERIAL_ECHORPGM(_n("M104 Invalid extruder "));////MSG_M104_INVALID_EXTRUDER
  7088. break;
  7089. case 105:
  7090. SERIAL_ECHO(_n("M105 Invalid extruder "));////MSG_M105_INVALID_EXTRUDER
  7091. break;
  7092. case 109:
  7093. SERIAL_ECHO(_n("M109 Invalid extruder "));////MSG_M109_INVALID_EXTRUDER
  7094. break;
  7095. case 218:
  7096. SERIAL_ECHO(_n("M218 Invalid extruder "));////MSG_M218_INVALID_EXTRUDER
  7097. break;
  7098. case 221:
  7099. SERIAL_ECHO(_n("M221 Invalid extruder "));////MSG_M221_INVALID_EXTRUDER
  7100. break;
  7101. }
  7102. SERIAL_PROTOCOLLN((int)extruder);
  7103. return true;
  7104. }
  7105. }
  7106. return false;
  7107. }
  7108. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  7109. {
  7110. 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)
  7111. {
  7112. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  7113. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  7114. }
  7115. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  7116. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  7117. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  7118. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  7119. total_filament_used = 0;
  7120. }
  7121. float calculate_extruder_multiplier(float diameter) {
  7122. float out = 1.f;
  7123. if (cs.volumetric_enabled && diameter > 0.f) {
  7124. float area = M_PI * diameter * diameter * 0.25;
  7125. out = 1.f / area;
  7126. }
  7127. if (extrudemultiply != 100)
  7128. out *= float(extrudemultiply) * 0.01f;
  7129. return out;
  7130. }
  7131. void calculate_extruder_multipliers() {
  7132. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  7133. #if EXTRUDERS > 1
  7134. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  7135. #if EXTRUDERS > 2
  7136. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  7137. #endif
  7138. #endif
  7139. }
  7140. void delay_keep_alive(unsigned int ms)
  7141. {
  7142. for (;;) {
  7143. manage_heater();
  7144. // Manage inactivity, but don't disable steppers on timeout.
  7145. manage_inactivity(true);
  7146. lcd_update(0);
  7147. if (ms == 0)
  7148. break;
  7149. else if (ms >= 50) {
  7150. _delay(50);
  7151. ms -= 50;
  7152. } else {
  7153. _delay(ms);
  7154. ms = 0;
  7155. }
  7156. }
  7157. }
  7158. static void wait_for_heater(long codenum, uint8_t extruder) {
  7159. #ifdef TEMP_RESIDENCY_TIME
  7160. long residencyStart;
  7161. residencyStart = -1;
  7162. /* continue to loop until we have reached the target temp
  7163. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  7164. while ((!cancel_heatup) && ((residencyStart == -1) ||
  7165. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  7166. #else
  7167. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  7168. #endif //TEMP_RESIDENCY_TIME
  7169. if ((_millis() - codenum) > 1000UL)
  7170. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  7171. if (!farm_mode) {
  7172. SERIAL_PROTOCOLPGM("T:");
  7173. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  7174. SERIAL_PROTOCOLPGM(" E:");
  7175. SERIAL_PROTOCOL((int)extruder);
  7176. #ifdef TEMP_RESIDENCY_TIME
  7177. SERIAL_PROTOCOLPGM(" W:");
  7178. if (residencyStart > -1)
  7179. {
  7180. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  7181. SERIAL_PROTOCOLLN(codenum);
  7182. }
  7183. else
  7184. {
  7185. SERIAL_PROTOCOLLN("?");
  7186. }
  7187. }
  7188. #else
  7189. SERIAL_PROTOCOLLN("");
  7190. #endif
  7191. codenum = _millis();
  7192. }
  7193. manage_heater();
  7194. manage_inactivity(true); //do not disable steppers
  7195. lcd_update(0);
  7196. #ifdef TEMP_RESIDENCY_TIME
  7197. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  7198. or when current temp falls outside the hysteresis after target temp was reached */
  7199. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  7200. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  7201. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  7202. {
  7203. residencyStart = _millis();
  7204. }
  7205. #endif //TEMP_RESIDENCY_TIME
  7206. }
  7207. }
  7208. void check_babystep()
  7209. {
  7210. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  7211. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  7212. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  7213. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  7214. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  7215. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  7216. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  7217. babystep_z);
  7218. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  7219. lcd_update_enable(true);
  7220. }
  7221. }
  7222. #ifdef HEATBED_ANALYSIS
  7223. void d_setup()
  7224. {
  7225. pinMode(D_DATACLOCK, INPUT_PULLUP);
  7226. pinMode(D_DATA, INPUT_PULLUP);
  7227. pinMode(D_REQUIRE, OUTPUT);
  7228. digitalWrite(D_REQUIRE, HIGH);
  7229. }
  7230. float d_ReadData()
  7231. {
  7232. int digit[13];
  7233. String mergeOutput;
  7234. float output;
  7235. digitalWrite(D_REQUIRE, HIGH);
  7236. for (int i = 0; i<13; i++)
  7237. {
  7238. for (int j = 0; j < 4; j++)
  7239. {
  7240. while (digitalRead(D_DATACLOCK) == LOW) {}
  7241. while (digitalRead(D_DATACLOCK) == HIGH) {}
  7242. bitWrite(digit[i], j, digitalRead(D_DATA));
  7243. }
  7244. }
  7245. digitalWrite(D_REQUIRE, LOW);
  7246. mergeOutput = "";
  7247. output = 0;
  7248. for (int r = 5; r <= 10; r++) //Merge digits
  7249. {
  7250. mergeOutput += digit[r];
  7251. }
  7252. output = mergeOutput.toFloat();
  7253. if (digit[4] == 8) //Handle sign
  7254. {
  7255. output *= -1;
  7256. }
  7257. for (int i = digit[11]; i > 0; i--) //Handle floating point
  7258. {
  7259. output /= 10;
  7260. }
  7261. return output;
  7262. }
  7263. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  7264. int t1 = 0;
  7265. int t_delay = 0;
  7266. int digit[13];
  7267. int m;
  7268. char str[3];
  7269. //String mergeOutput;
  7270. char mergeOutput[15];
  7271. float output;
  7272. int mesh_point = 0; //index number of calibration point
  7273. 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
  7274. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  7275. float mesh_home_z_search = 4;
  7276. float measure_z_height = 0.2f;
  7277. float row[x_points_num];
  7278. int ix = 0;
  7279. int iy = 0;
  7280. const char* filename_wldsd = "mesh.txt";
  7281. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  7282. char numb_wldsd[8]; // (" -A.BCD" + null)
  7283. #ifdef MICROMETER_LOGGING
  7284. d_setup();
  7285. #endif //MICROMETER_LOGGING
  7286. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  7287. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  7288. unsigned int custom_message_type_old = custom_message_type;
  7289. unsigned int custom_message_state_old = custom_message_state;
  7290. custom_message_type = CustomMsg::MeshBedLeveling;
  7291. custom_message_state = (x_points_num * y_points_num) + 10;
  7292. lcd_update(1);
  7293. //mbl.reset();
  7294. babystep_undo();
  7295. card.openFile(filename_wldsd, false);
  7296. /*destination[Z_AXIS] = mesh_home_z_search;
  7297. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  7298. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  7299. for(int8_t i=0; i < NUM_AXIS; i++) {
  7300. current_position[i] = destination[i];
  7301. }
  7302. st_synchronize();
  7303. */
  7304. destination[Z_AXIS] = measure_z_height;
  7305. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  7306. for(int8_t i=0; i < NUM_AXIS; i++) {
  7307. current_position[i] = destination[i];
  7308. }
  7309. st_synchronize();
  7310. /*int l_feedmultiply = */setup_for_endstop_move(false);
  7311. SERIAL_PROTOCOLPGM("Num X,Y: ");
  7312. SERIAL_PROTOCOL(x_points_num);
  7313. SERIAL_PROTOCOLPGM(",");
  7314. SERIAL_PROTOCOL(y_points_num);
  7315. SERIAL_PROTOCOLPGM("\nZ search height: ");
  7316. SERIAL_PROTOCOL(mesh_home_z_search);
  7317. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  7318. SERIAL_PROTOCOL(x_dimension);
  7319. SERIAL_PROTOCOLPGM(",");
  7320. SERIAL_PROTOCOL(y_dimension);
  7321. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  7322. while (mesh_point != x_points_num * y_points_num) {
  7323. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  7324. iy = mesh_point / x_points_num;
  7325. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  7326. float z0 = 0.f;
  7327. /*destination[Z_AXIS] = mesh_home_z_search;
  7328. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  7329. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  7330. for(int8_t i=0; i < NUM_AXIS; i++) {
  7331. current_position[i] = destination[i];
  7332. }
  7333. st_synchronize();*/
  7334. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  7335. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  7336. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  7337. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  7338. mesh_plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], XY_AXIS_FEEDRATE/6, active_extruder);
  7339. for(int8_t i=0; i < NUM_AXIS; i++) {
  7340. current_position[i] = destination[i];
  7341. }
  7342. st_synchronize();
  7343. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  7344. delay_keep_alive(1000);
  7345. #ifdef MICROMETER_LOGGING
  7346. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  7347. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  7348. //strcat(data_wldsd, numb_wldsd);
  7349. //MYSERIAL.println(data_wldsd);
  7350. //delay(1000);
  7351. //delay(3000);
  7352. //t1 = millis();
  7353. //while (digitalRead(D_DATACLOCK) == LOW) {}
  7354. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  7355. memset(digit, 0, sizeof(digit));
  7356. //cli();
  7357. digitalWrite(D_REQUIRE, LOW);
  7358. for (int i = 0; i<13; i++)
  7359. {
  7360. //t1 = millis();
  7361. for (int j = 0; j < 4; j++)
  7362. {
  7363. while (digitalRead(D_DATACLOCK) == LOW) {}
  7364. while (digitalRead(D_DATACLOCK) == HIGH) {}
  7365. //printf_P(PSTR("Done %d\n"), j);
  7366. bitWrite(digit[i], j, digitalRead(D_DATA));
  7367. }
  7368. //t_delay = (millis() - t1);
  7369. //SERIAL_PROTOCOLPGM(" ");
  7370. //SERIAL_PROTOCOL_F(t_delay, 5);
  7371. //SERIAL_PROTOCOLPGM(" ");
  7372. }
  7373. //sei();
  7374. digitalWrite(D_REQUIRE, HIGH);
  7375. mergeOutput[0] = '\0';
  7376. output = 0;
  7377. for (int r = 5; r <= 10; r++) //Merge digits
  7378. {
  7379. sprintf(str, "%d", digit[r]);
  7380. strcat(mergeOutput, str);
  7381. }
  7382. output = atof(mergeOutput);
  7383. if (digit[4] == 8) //Handle sign
  7384. {
  7385. output *= -1;
  7386. }
  7387. for (int i = digit[11]; i > 0; i--) //Handle floating point
  7388. {
  7389. output *= 0.1;
  7390. }
  7391. //output = d_ReadData();
  7392. //row[ix] = current_position[Z_AXIS];
  7393. //row[ix] = d_ReadData();
  7394. row[ix] = output;
  7395. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  7396. memset(data_wldsd, 0, sizeof(data_wldsd));
  7397. for (int i = 0; i < x_points_num; i++) {
  7398. SERIAL_PROTOCOLPGM(" ");
  7399. SERIAL_PROTOCOL_F(row[i], 5);
  7400. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  7401. dtostrf(row[i], 7, 3, numb_wldsd);
  7402. strcat(data_wldsd, numb_wldsd);
  7403. }
  7404. card.write_command(data_wldsd);
  7405. SERIAL_PROTOCOLPGM("\n");
  7406. }
  7407. custom_message_state--;
  7408. mesh_point++;
  7409. lcd_update(1);
  7410. }
  7411. #endif //MICROMETER_LOGGING
  7412. card.closefile();
  7413. //clean_up_after_endstop_move(l_feedmultiply);
  7414. }
  7415. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  7416. int t1 = 0;
  7417. int t_delay = 0;
  7418. int digit[13];
  7419. int m;
  7420. char str[3];
  7421. //String mergeOutput;
  7422. char mergeOutput[15];
  7423. float output;
  7424. int mesh_point = 0; //index number of calibration point
  7425. 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
  7426. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  7427. float mesh_home_z_search = 4;
  7428. float row[x_points_num];
  7429. int ix = 0;
  7430. int iy = 0;
  7431. const char* filename_wldsd = "wldsd.txt";
  7432. char data_wldsd[70];
  7433. char numb_wldsd[10];
  7434. d_setup();
  7435. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  7436. // We don't know where we are! HOME!
  7437. // Push the commands to the front of the message queue in the reverse order!
  7438. // There shall be always enough space reserved for these commands.
  7439. repeatcommand_front(); // repeat G80 with all its parameters
  7440. enquecommand_front_P((PSTR("G28 W0")));
  7441. enquecommand_front_P((PSTR("G1 Z5")));
  7442. return;
  7443. }
  7444. unsigned int custom_message_type_old = custom_message_type;
  7445. unsigned int custom_message_state_old = custom_message_state;
  7446. custom_message_type = CustomMsg::MeshBedLeveling;
  7447. custom_message_state = (x_points_num * y_points_num) + 10;
  7448. lcd_update(1);
  7449. mbl.reset();
  7450. babystep_undo();
  7451. card.openFile(filename_wldsd, false);
  7452. current_position[Z_AXIS] = mesh_home_z_search;
  7453. 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);
  7454. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  7455. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  7456. int l_feedmultiply = setup_for_endstop_move(false);
  7457. SERIAL_PROTOCOLPGM("Num X,Y: ");
  7458. SERIAL_PROTOCOL(x_points_num);
  7459. SERIAL_PROTOCOLPGM(",");
  7460. SERIAL_PROTOCOL(y_points_num);
  7461. SERIAL_PROTOCOLPGM("\nZ search height: ");
  7462. SERIAL_PROTOCOL(mesh_home_z_search);
  7463. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  7464. SERIAL_PROTOCOL(x_dimension);
  7465. SERIAL_PROTOCOLPGM(",");
  7466. SERIAL_PROTOCOL(y_dimension);
  7467. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  7468. while (mesh_point != x_points_num * y_points_num) {
  7469. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  7470. iy = mesh_point / x_points_num;
  7471. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  7472. float z0 = 0.f;
  7473. current_position[Z_AXIS] = mesh_home_z_search;
  7474. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  7475. st_synchronize();
  7476. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  7477. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  7478. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], XY_AXIS_FEEDRATE, active_extruder);
  7479. st_synchronize();
  7480. 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
  7481. break;
  7482. card.closefile();
  7483. }
  7484. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  7485. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  7486. //strcat(data_wldsd, numb_wldsd);
  7487. //MYSERIAL.println(data_wldsd);
  7488. //_delay(1000);
  7489. //_delay(3000);
  7490. //t1 = _millis();
  7491. //while (digitalRead(D_DATACLOCK) == LOW) {}
  7492. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  7493. memset(digit, 0, sizeof(digit));
  7494. //cli();
  7495. digitalWrite(D_REQUIRE, LOW);
  7496. for (int i = 0; i<13; i++)
  7497. {
  7498. //t1 = _millis();
  7499. for (int j = 0; j < 4; j++)
  7500. {
  7501. while (digitalRead(D_DATACLOCK) == LOW) {}
  7502. while (digitalRead(D_DATACLOCK) == HIGH) {}
  7503. bitWrite(digit[i], j, digitalRead(D_DATA));
  7504. }
  7505. //t_delay = (_millis() - t1);
  7506. //SERIAL_PROTOCOLPGM(" ");
  7507. //SERIAL_PROTOCOL_F(t_delay, 5);
  7508. //SERIAL_PROTOCOLPGM(" ");
  7509. }
  7510. //sei();
  7511. digitalWrite(D_REQUIRE, HIGH);
  7512. mergeOutput[0] = '\0';
  7513. output = 0;
  7514. for (int r = 5; r <= 10; r++) //Merge digits
  7515. {
  7516. sprintf(str, "%d", digit[r]);
  7517. strcat(mergeOutput, str);
  7518. }
  7519. output = atof(mergeOutput);
  7520. if (digit[4] == 8) //Handle sign
  7521. {
  7522. output *= -1;
  7523. }
  7524. for (int i = digit[11]; i > 0; i--) //Handle floating point
  7525. {
  7526. output *= 0.1;
  7527. }
  7528. //output = d_ReadData();
  7529. //row[ix] = current_position[Z_AXIS];
  7530. memset(data_wldsd, 0, sizeof(data_wldsd));
  7531. for (int i = 0; i <3; i++) {
  7532. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  7533. dtostrf(current_position[i], 8, 5, numb_wldsd);
  7534. strcat(data_wldsd, numb_wldsd);
  7535. strcat(data_wldsd, ";");
  7536. }
  7537. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  7538. dtostrf(output, 8, 5, numb_wldsd);
  7539. strcat(data_wldsd, numb_wldsd);
  7540. //strcat(data_wldsd, ";");
  7541. card.write_command(data_wldsd);
  7542. //row[ix] = d_ReadData();
  7543. row[ix] = output; // current_position[Z_AXIS];
  7544. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  7545. for (int i = 0; i < x_points_num; i++) {
  7546. SERIAL_PROTOCOLPGM(" ");
  7547. SERIAL_PROTOCOL_F(row[i], 5);
  7548. }
  7549. SERIAL_PROTOCOLPGM("\n");
  7550. }
  7551. custom_message_state--;
  7552. mesh_point++;
  7553. lcd_update(1);
  7554. }
  7555. card.closefile();
  7556. clean_up_after_endstop_move(l_feedmultiply);
  7557. }
  7558. #endif //HEATBED_ANALYSIS
  7559. void temp_compensation_start() {
  7560. custom_message_type = CustomMsg::TempCompPreheat;
  7561. custom_message_state = PINDA_HEAT_T + 1;
  7562. lcd_update(2);
  7563. if (degHotend(active_extruder) > EXTRUDE_MINTEMP) {
  7564. current_position[E_AXIS] -= default_retraction;
  7565. }
  7566. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  7567. current_position[X_AXIS] = PINDA_PREHEAT_X;
  7568. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  7569. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  7570. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  7571. st_synchronize();
  7572. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  7573. for (int i = 0; i < PINDA_HEAT_T; i++) {
  7574. delay_keep_alive(1000);
  7575. custom_message_state = PINDA_HEAT_T - i;
  7576. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  7577. else lcd_update(1);
  7578. }
  7579. custom_message_type = CustomMsg::Status;
  7580. custom_message_state = 0;
  7581. }
  7582. void temp_compensation_apply() {
  7583. int i_add;
  7584. int z_shift = 0;
  7585. float z_shift_mm;
  7586. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  7587. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  7588. i_add = (target_temperature_bed - 60) / 10;
  7589. EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + i_add * 2, &z_shift);
  7590. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  7591. }else {
  7592. //interpolation
  7593. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  7594. }
  7595. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  7596. 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);
  7597. st_synchronize();
  7598. plan_set_z_position(current_position[Z_AXIS]);
  7599. }
  7600. else {
  7601. //we have no temp compensation data
  7602. }
  7603. }
  7604. float temp_comp_interpolation(float inp_temperature) {
  7605. //cubic spline interpolation
  7606. int n, i, j;
  7607. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  7608. int shift[10];
  7609. int temp_C[10];
  7610. n = 6; //number of measured points
  7611. shift[0] = 0;
  7612. for (i = 0; i < n; i++) {
  7613. if (i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i-1) * 2, &shift[i]); //read shift in steps from EEPROM
  7614. temp_C[i] = 50 + i * 10; //temperature in C
  7615. #ifdef PINDA_THERMISTOR
  7616. temp_C[i] = 35 + i * 5; //temperature in C
  7617. #else
  7618. temp_C[i] = 50 + i * 10; //temperature in C
  7619. #endif
  7620. x[i] = (float)temp_C[i];
  7621. f[i] = (float)shift[i];
  7622. }
  7623. if (inp_temperature < x[0]) return 0;
  7624. for (i = n - 1; i>0; i--) {
  7625. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  7626. h[i - 1] = x[i] - x[i - 1];
  7627. }
  7628. //*********** formation of h, s , f matrix **************
  7629. for (i = 1; i<n - 1; i++) {
  7630. m[i][i] = 2 * (h[i - 1] + h[i]);
  7631. if (i != 1) {
  7632. m[i][i - 1] = h[i - 1];
  7633. m[i - 1][i] = h[i - 1];
  7634. }
  7635. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  7636. }
  7637. //*********** forward elimination **************
  7638. for (i = 1; i<n - 2; i++) {
  7639. temp = (m[i + 1][i] / m[i][i]);
  7640. for (j = 1; j <= n - 1; j++)
  7641. m[i + 1][j] -= temp*m[i][j];
  7642. }
  7643. //*********** backward substitution *********
  7644. for (i = n - 2; i>0; i--) {
  7645. sum = 0;
  7646. for (j = i; j <= n - 2; j++)
  7647. sum += m[i][j] * s[j];
  7648. s[i] = (m[i][n - 1] - sum) / m[i][i];
  7649. }
  7650. for (i = 0; i<n - 1; i++)
  7651. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  7652. a = (s[i + 1] - s[i]) / (6 * h[i]);
  7653. b = s[i] / 2;
  7654. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  7655. d = f[i];
  7656. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  7657. }
  7658. return sum;
  7659. }
  7660. #ifdef PINDA_THERMISTOR
  7661. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  7662. {
  7663. if (!temp_cal_active) return 0;
  7664. if (!calibration_status_pinda()) return 0;
  7665. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  7666. }
  7667. #endif //PINDA_THERMISTOR
  7668. void long_pause() //long pause print
  7669. {
  7670. st_synchronize();
  7671. start_pause_print = _millis();
  7672. //retract
  7673. current_position[E_AXIS] -= default_retraction;
  7674. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  7675. //lift z
  7676. current_position[Z_AXIS] += Z_PAUSE_LIFT;
  7677. if (current_position[Z_AXIS] > Z_MAX_POS) current_position[Z_AXIS] = Z_MAX_POS;
  7678. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 15, active_extruder);
  7679. //Move XY to side
  7680. current_position[X_AXIS] = X_PAUSE_POS;
  7681. current_position[Y_AXIS] = Y_PAUSE_POS;
  7682. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 50, active_extruder);
  7683. // Turn off the print fan
  7684. fanSpeed = 0;
  7685. st_synchronize();
  7686. }
  7687. void serialecho_temperatures() {
  7688. float tt = degHotend(active_extruder);
  7689. SERIAL_PROTOCOLPGM("T:");
  7690. SERIAL_PROTOCOL(tt);
  7691. SERIAL_PROTOCOLPGM(" E:");
  7692. SERIAL_PROTOCOL((int)active_extruder);
  7693. SERIAL_PROTOCOLPGM(" B:");
  7694. SERIAL_PROTOCOL_F(degBed(), 1);
  7695. SERIAL_PROTOCOLLN("");
  7696. }
  7697. extern uint32_t sdpos_atomic;
  7698. #ifdef UVLO_SUPPORT
  7699. void uvlo_()
  7700. {
  7701. unsigned long time_start = _millis();
  7702. bool sd_print = card.sdprinting;
  7703. // Conserve power as soon as possible.
  7704. disable_x();
  7705. disable_y();
  7706. #ifdef TMC2130
  7707. tmc2130_set_current_h(Z_AXIS, 20);
  7708. tmc2130_set_current_r(Z_AXIS, 20);
  7709. tmc2130_set_current_h(E_AXIS, 20);
  7710. tmc2130_set_current_r(E_AXIS, 20);
  7711. #endif //TMC2130
  7712. // Indicate that the interrupt has been triggered.
  7713. // SERIAL_ECHOLNPGM("UVLO");
  7714. // Read out the current Z motor microstep counter. This will be later used
  7715. // for reaching the zero full step before powering off.
  7716. uint16_t z_microsteps = 0;
  7717. #ifdef TMC2130
  7718. z_microsteps = tmc2130_rd_MSCNT(Z_TMC2130_CS);
  7719. #endif //TMC2130
  7720. // Calculate the file position, from which to resume this print.
  7721. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  7722. {
  7723. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  7724. sd_position -= sdlen_planner;
  7725. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  7726. sd_position -= sdlen_cmdqueue;
  7727. if (sd_position < 0) sd_position = 0;
  7728. }
  7729. // Backup the feedrate in mm/min.
  7730. int feedrate_bckp = blocks_queued() ? (block_buffer[block_buffer_tail].nominal_speed * 60.f) : feedrate;
  7731. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  7732. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  7733. // are in action.
  7734. planner_abort_hard();
  7735. // Store the current extruder position.
  7736. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), st_get_position_mm(E_AXIS));
  7737. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, axis_relative_modes[3]?0:1);
  7738. // Clean the input command queue.
  7739. cmdqueue_reset();
  7740. card.sdprinting = false;
  7741. // card.closefile();
  7742. // Enable stepper driver interrupt to move Z axis.
  7743. // This should be fine as the planner and command queues are empty and the SD card printing is disabled.
  7744. //FIXME one may want to disable serial lines at this point of time to avoid interfering with the command queue,
  7745. // though it should not happen that the command queue is touched as the plan_buffer_line always succeed without blocking.
  7746. sei();
  7747. plan_buffer_line(
  7748. current_position[X_AXIS],
  7749. current_position[Y_AXIS],
  7750. current_position[Z_AXIS],
  7751. current_position[E_AXIS] - default_retraction,
  7752. 95, active_extruder);
  7753. st_synchronize();
  7754. disable_e0();
  7755. plan_buffer_line(
  7756. current_position[X_AXIS],
  7757. current_position[Y_AXIS],
  7758. current_position[Z_AXIS] + UVLO_Z_AXIS_SHIFT + float((1024 - z_microsteps + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS],
  7759. current_position[E_AXIS] - default_retraction,
  7760. 40, active_extruder);
  7761. st_synchronize();
  7762. disable_e0();
  7763. plan_buffer_line(
  7764. current_position[X_AXIS],
  7765. current_position[Y_AXIS],
  7766. current_position[Z_AXIS] + UVLO_Z_AXIS_SHIFT + float((1024 - z_microsteps + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS],
  7767. current_position[E_AXIS] - default_retraction,
  7768. 40, active_extruder);
  7769. st_synchronize();
  7770. disable_e0();
  7771. disable_z();
  7772. // Move Z up to the next 0th full step.
  7773. // Write the file position.
  7774. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  7775. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  7776. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  7777. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  7778. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  7779. // Scale the z value to 1u resolution.
  7780. int16_t v = mbl.active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  7781. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  7782. }
  7783. // Read out the current Z motor microstep counter. This will be later used
  7784. // for reaching the zero full step before powering off.
  7785. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  7786. // Store the current position.
  7787. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  7788. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  7789. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z , current_position[Z_AXIS]);
  7790. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  7791. EEPROM_save_B(EEPROM_UVLO_FEEDRATE, &feedrate_bckp);
  7792. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_HOTEND, target_temperature[active_extruder]);
  7793. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, target_temperature_bed);
  7794. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  7795. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  7796. #if EXTRUDERS > 1
  7797. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  7798. #if EXTRUDERS > 2
  7799. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  7800. #endif
  7801. #endif
  7802. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  7803. // Finaly store the "power outage" flag.
  7804. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  7805. st_synchronize();
  7806. printf_P(_N("stps%d\n"), tmc2130_rd_MSCNT(Z_AXIS));
  7807. disable_z();
  7808. // Increment power failure counter
  7809. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  7810. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  7811. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  7812. #if 0
  7813. // Move the print head to the side of the print until all the power stored in the power supply capacitors is depleted.
  7814. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  7815. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 500, active_extruder);
  7816. st_synchronize();
  7817. #endif
  7818. wdt_enable(WDTO_500MS);
  7819. WRITE(BEEPER,HIGH);
  7820. while(1)
  7821. ;
  7822. }
  7823. void uvlo_tiny()
  7824. {
  7825. uint16_t z_microsteps=0;
  7826. // Conserve power as soon as possible.
  7827. disable_x();
  7828. disable_y();
  7829. disable_e0();
  7830. #ifdef TMC2130
  7831. tmc2130_set_current_h(Z_AXIS, 20);
  7832. tmc2130_set_current_r(Z_AXIS, 20);
  7833. #endif //TMC2130
  7834. // Read out the current Z motor microstep counter
  7835. #ifdef TMC2130
  7836. z_microsteps=tmc2130_rd_MSCNT(Z_TMC2130_CS);
  7837. #endif //TMC2130
  7838. planner_abort_hard();
  7839. disable_z();
  7840. //save current position only in case, where the printer is moving on Z axis, which is only when EEPROM_UVLO is 1
  7841. //EEPROM_UVLO is 1 after normal uvlo or after recover_print(), when the extruder is moving on Z axis after rehome
  7842. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)!=2){
  7843. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  7844. eeprom_update_word((uint16_t*)(EEPROM_UVLO_TINY_Z_MICROSTEPS),z_microsteps);
  7845. }
  7846. //after multiple power panics current Z axis is unknow
  7847. //in this case we set EEPROM_UVLO_TINY_CURRENT_POSITION_Z to last know position which is EEPROM_UVLO_CURRENT_POSITION_Z
  7848. if(eeprom_read_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z) < 0.001f){
  7849. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), eeprom_read_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z));
  7850. eeprom_update_word((uint16_t*)(EEPROM_UVLO_TINY_Z_MICROSTEPS), eeprom_read_word((uint16_t*)EEPROM_UVLO_Z_MICROSTEPS));
  7851. }
  7852. // Finaly store the "power outage" flag.
  7853. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  7854. // Increment power failure counter
  7855. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  7856. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  7857. wdt_enable(WDTO_500MS);
  7858. WRITE(BEEPER,HIGH);
  7859. while(1)
  7860. ;
  7861. }
  7862. #endif //UVLO_SUPPORT
  7863. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  7864. void setup_fan_interrupt() {
  7865. //INT7
  7866. DDRE &= ~(1 << 7); //input pin
  7867. PORTE &= ~(1 << 7); //no internal pull-up
  7868. //start with sensing rising edge
  7869. EICRB &= ~(1 << 6);
  7870. EICRB |= (1 << 7);
  7871. //enable INT7 interrupt
  7872. EIMSK |= (1 << 7);
  7873. }
  7874. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  7875. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  7876. ISR(INT7_vect) {
  7877. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  7878. #ifdef FAN_SOFT_PWM
  7879. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  7880. #else //FAN_SOFT_PWM
  7881. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  7882. #endif //FAN_SOFT_PWM
  7883. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  7884. t_fan_rising_edge = millis_nc();
  7885. }
  7886. else { //interrupt was triggered by falling edge
  7887. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  7888. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  7889. }
  7890. }
  7891. EICRB ^= (1 << 6); //change edge
  7892. }
  7893. #endif
  7894. #ifdef UVLO_SUPPORT
  7895. void setup_uvlo_interrupt() {
  7896. DDRE &= ~(1 << 4); //input pin
  7897. PORTE &= ~(1 << 4); //no internal pull-up
  7898. //sensing falling edge
  7899. EICRB |= (1 << 0);
  7900. EICRB &= ~(1 << 1);
  7901. //enable INT4 interrupt
  7902. EIMSK |= (1 << 4);
  7903. }
  7904. ISR(INT4_vect) {
  7905. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  7906. SERIAL_ECHOLNPGM("INT4");
  7907. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  7908. //Don't change || to && because in some case the printer can be moving although IS_SD_PRINTING is zero
  7909. if((IS_SD_PRINTING ) || (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  7910. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  7911. }
  7912. void recover_print(uint8_t automatic) {
  7913. char cmd[30];
  7914. lcd_update_enable(true);
  7915. lcd_update(2);
  7916. lcd_setstatuspgm(_i("Recovering print "));////MSG_RECOVERING_PRINT c=20 r=1
  7917. bool bTiny=(eeprom_read_byte((uint8_t*)EEPROM_UVLO)==2);
  7918. recover_machine_state_after_power_panic(bTiny); //recover position, temperatures and extrude_multipliers
  7919. // Lift the print head, so one may remove the excess priming material.
  7920. if(!bTiny&&(current_position[Z_AXIS]<25))
  7921. enquecommand_P(PSTR("G1 Z25 F800"));
  7922. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine transformation status.
  7923. enquecommand_P(PSTR("G28 X Y"));
  7924. // Set the target bed and nozzle temperatures and wait.
  7925. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  7926. enquecommand(cmd);
  7927. sprintf_P(cmd, PSTR("M190 S%d"), target_temperature_bed);
  7928. enquecommand(cmd);
  7929. enquecommand_P(PSTR("M83")); //E axis relative mode
  7930. //enquecommand_P(PSTR("G1 E5 F120")); //Extrude some filament to stabilize pessure
  7931. // If not automatically recoreverd (long power loss), extrude extra filament to stabilize
  7932. if(automatic == 0){
  7933. enquecommand_P(PSTR("G1 E5 F120")); //Extrude some filament to stabilize pessure
  7934. }
  7935. enquecommand_P(PSTR("G1 E" STRINGIFY(-default_retraction)" F480"));
  7936. 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]);
  7937. // Restart the print.
  7938. restore_print_from_eeprom();
  7939. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  7940. }
  7941. void recover_machine_state_after_power_panic(bool bTiny)
  7942. {
  7943. char cmd[30];
  7944. // 1) Recover the logical cordinates at the time of the power panic.
  7945. // The logical XY coordinates are needed to recover the machine Z coordinate corrected by the mesh bed leveling.
  7946. current_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  7947. current_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  7948. // 2) Restore the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  7949. mbl.active = false;
  7950. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  7951. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  7952. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  7953. // Scale the z value to 10u resolution.
  7954. int16_t v;
  7955. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  7956. if (v != 0)
  7957. mbl.active = true;
  7958. mbl.z_values[iy][ix] = float(v) * 0.001f;
  7959. }
  7960. // Recover the logical coordinate of the Z axis at the time of the power panic.
  7961. // The current position after power panic is moved to the next closest 0th full step.
  7962. if(bTiny){
  7963. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z))
  7964. + float((1024 - eeprom_read_word((uint16_t*)(EEPROM_UVLO_TINY_Z_MICROSTEPS))
  7965. + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS];
  7966. //after multiple power panics the print is slightly in the air so get it little bit down.
  7967. //Not exactly sure why is this happening, but it has something to do with bed leveling and world2machine coordinates
  7968. current_position[Z_AXIS] -= 0.4*mbl.get_z(current_position[X_AXIS], current_position[Y_AXIS]);
  7969. }
  7970. else{
  7971. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)) +
  7972. UVLO_Z_AXIS_SHIFT + float((1024 - eeprom_read_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS))
  7973. + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS];
  7974. }
  7975. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS)) {
  7976. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  7977. sprintf_P(cmd, PSTR("G92 E"));
  7978. dtostrf(current_position[E_AXIS], 6, 3, cmd + strlen(cmd));
  7979. enquecommand(cmd);
  7980. }
  7981. memcpy(destination, current_position, sizeof(destination));
  7982. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  7983. print_world_coordinates();
  7984. // 3) Initialize the logical to physical coordinate system transformation.
  7985. world2machine_initialize();
  7986. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  7987. // print_mesh_bed_leveling_table();
  7988. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  7989. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  7990. babystep_load();
  7991. // 5) Set the physical positions from the logical positions using the world2machine transformation and the active bed leveling.
  7992. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  7993. // 6) Power up the motors, mark their positions as known.
  7994. //FIXME Verfiy, whether the X and Y axes should be powered up here, as they will later be re-homed anyway.
  7995. axis_known_position[X_AXIS] = true; enable_x();
  7996. axis_known_position[Y_AXIS] = true; enable_y();
  7997. axis_known_position[Z_AXIS] = true; enable_z();
  7998. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  7999. print_physical_coordinates();
  8000. // 7) Recover the target temperatures.
  8001. target_temperature[active_extruder] = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_HOTEND);
  8002. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  8003. // 8) Recover extruder multipilers
  8004. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  8005. #if EXTRUDERS > 1
  8006. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  8007. #if EXTRUDERS > 2
  8008. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  8009. #endif
  8010. #endif
  8011. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  8012. }
  8013. void restore_print_from_eeprom() {
  8014. int feedrate_rec;
  8015. uint8_t fan_speed_rec;
  8016. char cmd[30];
  8017. char filename[13];
  8018. uint8_t depth = 0;
  8019. char dir_name[9];
  8020. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  8021. EEPROM_read_B(EEPROM_UVLO_FEEDRATE, &feedrate_rec);
  8022. SERIAL_ECHOPGM("Feedrate:");
  8023. MYSERIAL.println(feedrate_rec);
  8024. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  8025. MYSERIAL.println(int(depth));
  8026. for (int i = 0; i < depth; i++) {
  8027. for (int j = 0; j < 8; j++) {
  8028. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  8029. }
  8030. dir_name[8] = '\0';
  8031. MYSERIAL.println(dir_name);
  8032. strcpy(dir_names[i], dir_name);
  8033. card.chdir(dir_name);
  8034. }
  8035. for (int i = 0; i < 8; i++) {
  8036. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  8037. }
  8038. filename[8] = '\0';
  8039. MYSERIAL.print(filename);
  8040. strcat_P(filename, PSTR(".gco"));
  8041. sprintf_P(cmd, PSTR("M23 %s"), filename);
  8042. enquecommand(cmd);
  8043. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  8044. SERIAL_ECHOPGM("Position read from eeprom:");
  8045. MYSERIAL.println(position);
  8046. // E axis relative mode.
  8047. enquecommand_P(PSTR("M83"));
  8048. // Move to the XY print position in logical coordinates, where the print has been killed.
  8049. strcpy_P(cmd, PSTR("G1 X")); strcat(cmd, ftostr32(eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0))));
  8050. strcat_P(cmd, PSTR(" Y")); strcat(cmd, ftostr32(eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4))));
  8051. strcat_P(cmd, PSTR(" F2000"));
  8052. enquecommand(cmd);
  8053. //moving on Z axis ahead, set EEPROM_UVLO to 1, so normal uvlo can fire
  8054. eeprom_update_byte((uint8_t*)EEPROM_UVLO,1);
  8055. // Move the Z axis down to the print, in logical coordinates.
  8056. strcpy_P(cmd, PSTR("G1 Z")); strcat(cmd, ftostr32(eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z))));
  8057. enquecommand(cmd);
  8058. // Unretract.
  8059. enquecommand_P(PSTR("G1 E" STRINGIFY(2*default_retraction)" F480"));
  8060. // Set the feedrate saved at the power panic.
  8061. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  8062. enquecommand(cmd);
  8063. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  8064. {
  8065. enquecommand_P(PSTR("M82")); //E axis abslute mode
  8066. }
  8067. // Set the fan speed saved at the power panic.
  8068. strcpy_P(cmd, PSTR("M106 S"));
  8069. strcat(cmd, itostr3(int(fan_speed_rec)));
  8070. enquecommand(cmd);
  8071. // Set a position in the file.
  8072. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  8073. enquecommand(cmd);
  8074. enquecommand_P(PSTR("G4 S0"));
  8075. enquecommand_P(PSTR("PRUSA uvlo"));
  8076. }
  8077. #endif //UVLO_SUPPORT
  8078. //! @brief Immediately stop print moves
  8079. //!
  8080. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  8081. //! If printing from sd card, position in file is saved.
  8082. //! If printing from USB, line number is saved.
  8083. //!
  8084. //! @param z_move
  8085. //! @param e_move
  8086. void stop_and_save_print_to_ram(float z_move, float e_move)
  8087. {
  8088. if (saved_printing) return;
  8089. #if 0
  8090. unsigned char nplanner_blocks;
  8091. #endif
  8092. unsigned char nlines;
  8093. uint16_t sdlen_planner;
  8094. uint16_t sdlen_cmdqueue;
  8095. cli();
  8096. if (card.sdprinting) {
  8097. #if 0
  8098. nplanner_blocks = number_of_blocks();
  8099. #endif
  8100. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  8101. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  8102. saved_sdpos -= sdlen_planner;
  8103. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  8104. saved_sdpos -= sdlen_cmdqueue;
  8105. saved_printing_type = PRINTING_TYPE_SD;
  8106. }
  8107. else if (is_usb_printing) { //reuse saved_sdpos for storing line number
  8108. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  8109. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  8110. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  8111. saved_sdpos -= nlines;
  8112. saved_sdpos -= buflen; //number of blocks in cmd buffer
  8113. saved_printing_type = PRINTING_TYPE_USB;
  8114. }
  8115. else {
  8116. saved_printing_type = PRINTING_TYPE_NONE;
  8117. //not sd printing nor usb printing
  8118. }
  8119. #if 0
  8120. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  8121. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  8122. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  8123. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  8124. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  8125. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  8126. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  8127. {
  8128. card.setIndex(saved_sdpos);
  8129. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  8130. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  8131. MYSERIAL.print(char(card.get()));
  8132. SERIAL_ECHOLNPGM("Content of command buffer: ");
  8133. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  8134. MYSERIAL.print(char(card.get()));
  8135. SERIAL_ECHOLNPGM("End of command buffer");
  8136. }
  8137. {
  8138. // Print the content of the planner buffer, line by line:
  8139. card.setIndex(saved_sdpos);
  8140. int8_t iline = 0;
  8141. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  8142. SERIAL_ECHOPGM("Planner line (from file): ");
  8143. MYSERIAL.print(int(iline), DEC);
  8144. SERIAL_ECHOPGM(", length: ");
  8145. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  8146. SERIAL_ECHOPGM(", steps: (");
  8147. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  8148. SERIAL_ECHOPGM(",");
  8149. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  8150. SERIAL_ECHOPGM(",");
  8151. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  8152. SERIAL_ECHOPGM(",");
  8153. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  8154. SERIAL_ECHOPGM("), events: ");
  8155. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  8156. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  8157. MYSERIAL.print(char(card.get()));
  8158. }
  8159. }
  8160. {
  8161. // Print the content of the command buffer, line by line:
  8162. int8_t iline = 0;
  8163. union {
  8164. struct {
  8165. char lo;
  8166. char hi;
  8167. } lohi;
  8168. uint16_t value;
  8169. } sdlen_single;
  8170. int _bufindr = bufindr;
  8171. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  8172. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  8173. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  8174. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  8175. }
  8176. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  8177. MYSERIAL.print(int(iline), DEC);
  8178. SERIAL_ECHOPGM(", type: ");
  8179. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  8180. SERIAL_ECHOPGM(", len: ");
  8181. MYSERIAL.println(sdlen_single.value, DEC);
  8182. // Print the content of the buffer line.
  8183. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  8184. SERIAL_ECHOPGM("Buffer line (from file): ");
  8185. MYSERIAL.println(int(iline), DEC);
  8186. for (; sdlen_single.value > 0; -- sdlen_single.value)
  8187. MYSERIAL.print(char(card.get()));
  8188. if (-- _buflen == 0)
  8189. break;
  8190. // First skip the current command ID and iterate up to the end of the string.
  8191. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  8192. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  8193. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  8194. // If the end of the buffer was empty,
  8195. if (_bufindr == sizeof(cmdbuffer)) {
  8196. // skip to the start and find the nonzero command.
  8197. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  8198. }
  8199. }
  8200. }
  8201. #endif
  8202. #if 0
  8203. saved_feedrate2 = feedrate; //save feedrate
  8204. #else
  8205. // Try to deduce the feedrate from the first block of the planner.
  8206. // Speed is in mm/min.
  8207. saved_feedrate2 = blocks_queued() ? (block_buffer[block_buffer_tail].nominal_speed * 60.f) : feedrate;
  8208. #endif
  8209. planner_abort_hard(); //abort printing
  8210. memcpy(saved_pos, current_position, sizeof(saved_pos));
  8211. saved_active_extruder = active_extruder; //save active_extruder
  8212. saved_extruder_temperature = degTargetHotend(active_extruder);
  8213. saved_extruder_under_pressure = extruder_under_pressure; //extruder under pressure flag - currently unused
  8214. saved_extruder_relative_mode = axis_relative_modes[E_AXIS];
  8215. saved_fanSpeed = fanSpeed;
  8216. cmdqueue_reset(); //empty cmdqueue
  8217. card.sdprinting = false;
  8218. // card.closefile();
  8219. saved_printing = true;
  8220. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  8221. st_reset_timer();
  8222. sei();
  8223. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  8224. #if 1
  8225. // Rather than calling plan_buffer_line directly, push the move into the command queue,
  8226. char buf[48];
  8227. // First unretract (relative extrusion)
  8228. if(!saved_extruder_relative_mode){
  8229. enquecommand(PSTR("M83"), true);
  8230. }
  8231. //retract 45mm/s
  8232. // A single sprintf may not be faster, but is definitely 20B shorter
  8233. // than a sequence of commands building the string piece by piece
  8234. // A snprintf would have been a safer call, but since it is not used
  8235. // in the whole program, its implementation would bring more bytes to the total size
  8236. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  8237. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  8238. enquecommand(buf, false);
  8239. // Then lift Z axis
  8240. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  8241. // At this point the command queue is empty.
  8242. enquecommand(buf, false);
  8243. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  8244. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  8245. repeatcommand_front();
  8246. #else
  8247. 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);
  8248. st_synchronize(); //wait moving
  8249. memcpy(current_position, saved_pos, sizeof(saved_pos));
  8250. memcpy(destination, current_position, sizeof(destination));
  8251. #endif
  8252. }
  8253. }
  8254. //! @brief Restore print from ram
  8255. //!
  8256. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking,
  8257. //! waits for extruder temperature restore, then restores position and continues
  8258. //! print moves.
  8259. //! Internaly lcd_update() is called by wait_for_heater().
  8260. //!
  8261. //! @param e_move
  8262. void restore_print_from_ram_and_continue(float e_move)
  8263. {
  8264. if (!saved_printing) return;
  8265. #ifdef FANCHECK
  8266. // Do not allow resume printing if fans are still not ok
  8267. if( fan_check_error != EFCE_OK )return;
  8268. #endif
  8269. // for (int axis = X_AXIS; axis <= E_AXIS; axis++)
  8270. // current_position[axis] = st_get_position_mm(axis);
  8271. active_extruder = saved_active_extruder; //restore active_extruder
  8272. if (saved_extruder_temperature) {
  8273. setTargetHotendSafe(saved_extruder_temperature, saved_active_extruder);
  8274. heating_status = 1;
  8275. wait_for_heater(_millis(), saved_active_extruder);
  8276. heating_status = 2;
  8277. }
  8278. feedrate = saved_feedrate2; //restore feedrate
  8279. axis_relative_modes[E_AXIS] = saved_extruder_relative_mode;
  8280. fanSpeed = saved_fanSpeed;
  8281. float e = saved_pos[E_AXIS] - e_move;
  8282. plan_set_e_position(e);
  8283. //first move print head in XY to the saved position:
  8284. 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);
  8285. st_synchronize();
  8286. //then move Z
  8287. 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);
  8288. st_synchronize();
  8289. //and finaly unretract (35mm/s)
  8290. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], 35, active_extruder);
  8291. st_synchronize();
  8292. memcpy(current_position, saved_pos, sizeof(saved_pos));
  8293. memcpy(destination, current_position, sizeof(destination));
  8294. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  8295. card.setIndex(saved_sdpos);
  8296. sdpos_atomic = saved_sdpos;
  8297. card.sdprinting = true;
  8298. printf_P(PSTR("ok\n")); //dummy response because of octoprint is waiting for this
  8299. }
  8300. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  8301. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  8302. serial_count = 0;
  8303. FlushSerialRequestResend();
  8304. }
  8305. else {
  8306. //not sd printing nor usb printing
  8307. }
  8308. lcd_setstatuspgm(_T(WELCOME_MSG));
  8309. saved_printing = false;
  8310. }
  8311. void print_world_coordinates()
  8312. {
  8313. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  8314. }
  8315. void print_physical_coordinates()
  8316. {
  8317. 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));
  8318. }
  8319. void print_mesh_bed_leveling_table()
  8320. {
  8321. SERIAL_ECHOPGM("mesh bed leveling: ");
  8322. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  8323. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  8324. MYSERIAL.print(mbl.z_values[y][x], 3);
  8325. SERIAL_ECHOPGM(" ");
  8326. }
  8327. SERIAL_ECHOLNPGM("");
  8328. }
  8329. uint16_t print_time_remaining() {
  8330. uint16_t print_t = PRINT_TIME_REMAINING_INIT;
  8331. #ifdef TMC2130
  8332. if (SilentModeMenu == SILENT_MODE_OFF) print_t = print_time_remaining_normal;
  8333. else print_t = print_time_remaining_silent;
  8334. #else
  8335. print_t = print_time_remaining_normal;
  8336. #endif //TMC2130
  8337. if ((print_t != PRINT_TIME_REMAINING_INIT) && (feedmultiply != 0)) print_t = 100ul * print_t / feedmultiply;
  8338. return print_t;
  8339. }
  8340. uint8_t calc_percent_done()
  8341. {
  8342. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  8343. uint8_t percent_done = 0;
  8344. #ifdef TMC2130
  8345. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100) {
  8346. percent_done = print_percent_done_normal;
  8347. }
  8348. else if (print_percent_done_silent <= 100) {
  8349. percent_done = print_percent_done_silent;
  8350. }
  8351. #else
  8352. if (print_percent_done_normal <= 100) {
  8353. percent_done = print_percent_done_normal;
  8354. }
  8355. #endif //TMC2130
  8356. else {
  8357. percent_done = card.percentDone();
  8358. }
  8359. return percent_done;
  8360. }
  8361. static void print_time_remaining_init()
  8362. {
  8363. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  8364. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  8365. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  8366. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  8367. }
  8368. void load_filament_final_feed()
  8369. {
  8370. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  8371. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_EFEED_FINAL, active_extruder);
  8372. }
  8373. //! @brief Wait for user to check the state
  8374. //! @par nozzle_temp nozzle temperature to load filament
  8375. void M600_check_state(float nozzle_temp)
  8376. {
  8377. lcd_change_fil_state = 0;
  8378. while (lcd_change_fil_state != 1)
  8379. {
  8380. lcd_change_fil_state = 0;
  8381. KEEPALIVE_STATE(PAUSED_FOR_USER);
  8382. lcd_alright();
  8383. KEEPALIVE_STATE(IN_HANDLER);
  8384. switch(lcd_change_fil_state)
  8385. {
  8386. // Filament failed to load so load it again
  8387. case 2:
  8388. if (mmu_enabled)
  8389. mmu_M600_load_filament(false, nozzle_temp); //nonautomatic load; change to "wrong filament loaded" option?
  8390. else
  8391. M600_load_filament_movements();
  8392. break;
  8393. // Filament loaded properly but color is not clear
  8394. case 3:
  8395. st_synchronize();
  8396. load_filament_final_feed();
  8397. lcd_loading_color();
  8398. st_synchronize();
  8399. break;
  8400. // Everything good
  8401. default:
  8402. lcd_change_success();
  8403. break;
  8404. }
  8405. }
  8406. }
  8407. //! @brief Wait for user action
  8408. //!
  8409. //! Beep, manage nozzle heater and wait for user to start unload filament
  8410. //! If times out, active extruder temperature is set to 0.
  8411. //!
  8412. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  8413. void M600_wait_for_user(float HotendTempBckp) {
  8414. KEEPALIVE_STATE(PAUSED_FOR_USER);
  8415. int counterBeep = 0;
  8416. unsigned long waiting_start_time = _millis();
  8417. uint8_t wait_for_user_state = 0;
  8418. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  8419. bool bFirst=true;
  8420. while (!(wait_for_user_state == 0 && lcd_clicked())){
  8421. manage_heater();
  8422. manage_inactivity(true);
  8423. #if BEEPER > 0
  8424. if (counterBeep == 500) {
  8425. counterBeep = 0;
  8426. }
  8427. SET_OUTPUT(BEEPER);
  8428. if (counterBeep == 0) {
  8429. if((eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  8430. {
  8431. bFirst=false;
  8432. WRITE(BEEPER, HIGH);
  8433. }
  8434. }
  8435. if (counterBeep == 20) {
  8436. WRITE(BEEPER, LOW);
  8437. }
  8438. counterBeep++;
  8439. #endif //BEEPER > 0
  8440. switch (wait_for_user_state) {
  8441. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  8442. delay_keep_alive(4);
  8443. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  8444. lcd_display_message_fullscreen_P(_i("Press knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  8445. wait_for_user_state = 1;
  8446. setAllTargetHotends(0);
  8447. st_synchronize();
  8448. disable_e0();
  8449. disable_e1();
  8450. disable_e2();
  8451. }
  8452. break;
  8453. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  8454. delay_keep_alive(4);
  8455. if (lcd_clicked()) {
  8456. setTargetHotend(HotendTempBckp, active_extruder);
  8457. lcd_wait_for_heater();
  8458. wait_for_user_state = 2;
  8459. }
  8460. break;
  8461. case 2: //waiting for nozzle to reach target temperature
  8462. if (abs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  8463. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  8464. waiting_start_time = _millis();
  8465. wait_for_user_state = 0;
  8466. }
  8467. else {
  8468. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  8469. lcd_set_cursor(1, 4);
  8470. lcd_print(ftostr3(degHotend(active_extruder)));
  8471. }
  8472. break;
  8473. }
  8474. }
  8475. WRITE(BEEPER, LOW);
  8476. }
  8477. void M600_load_filament_movements()
  8478. {
  8479. #ifdef SNMM
  8480. display_loading();
  8481. do
  8482. {
  8483. current_position[E_AXIS] += 0.002;
  8484. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 500, active_extruder);
  8485. delay_keep_alive(2);
  8486. }
  8487. while (!lcd_clicked());
  8488. st_synchronize();
  8489. current_position[E_AXIS] += bowden_length[mmu_extruder];
  8490. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000, active_extruder);
  8491. current_position[E_AXIS] += FIL_LOAD_LENGTH - 60;
  8492. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 1400, active_extruder);
  8493. current_position[E_AXIS] += 40;
  8494. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  8495. current_position[E_AXIS] += 10;
  8496. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 50, active_extruder);
  8497. #else
  8498. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  8499. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_EFEED_FIRST, active_extruder);
  8500. #endif
  8501. load_filament_final_feed();
  8502. lcd_loading_filament();
  8503. st_synchronize();
  8504. }
  8505. void M600_load_filament() {
  8506. //load filament for single material and SNMM
  8507. lcd_wait_interact();
  8508. //load_filament_time = _millis();
  8509. KEEPALIVE_STATE(PAUSED_FOR_USER);
  8510. #ifdef PAT9125
  8511. fsensor_autoload_check_start();
  8512. #endif //PAT9125
  8513. while(!lcd_clicked())
  8514. {
  8515. manage_heater();
  8516. manage_inactivity(true);
  8517. #ifdef FILAMENT_SENSOR
  8518. if (fsensor_check_autoload())
  8519. {
  8520. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  8521. _tone(BEEPER, 1000);
  8522. delay_keep_alive(50);
  8523. _noTone(BEEPER);
  8524. break;
  8525. }
  8526. #endif //FILAMENT_SENSOR
  8527. }
  8528. #ifdef PAT9125
  8529. fsensor_autoload_check_stop();
  8530. #endif //PAT9125
  8531. KEEPALIVE_STATE(IN_HANDLER);
  8532. #ifdef FSENSOR_QUALITY
  8533. fsensor_oq_meassure_start(70);
  8534. #endif //FSENSOR_QUALITY
  8535. M600_load_filament_movements();
  8536. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  8537. _tone(BEEPER, 500);
  8538. delay_keep_alive(50);
  8539. _noTone(BEEPER);
  8540. #ifdef FSENSOR_QUALITY
  8541. fsensor_oq_meassure_stop();
  8542. if (!fsensor_oq_result())
  8543. {
  8544. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Fil. sensor response is poor, disable it?"), false, true);
  8545. lcd_update_enable(true);
  8546. lcd_update(2);
  8547. if (disable)
  8548. fsensor_disable();
  8549. }
  8550. #endif //FSENSOR_QUALITY
  8551. lcd_update_enable(false);
  8552. }
  8553. //! @brief Wait for click
  8554. //!
  8555. //! Set
  8556. void marlin_wait_for_click()
  8557. {
  8558. int8_t busy_state_backup = busy_state;
  8559. KEEPALIVE_STATE(PAUSED_FOR_USER);
  8560. lcd_consume_click();
  8561. while(!lcd_clicked())
  8562. {
  8563. manage_heater();
  8564. manage_inactivity(true);
  8565. lcd_update(0);
  8566. }
  8567. KEEPALIVE_STATE(busy_state_backup);
  8568. }
  8569. #define FIL_LOAD_LENGTH 60