Marlin_main.cpp 352 KB

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