Marlin_main.cpp 397 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921
  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. #include "config.h"
  48. #include "macros.h"
  49. #ifdef ENABLE_AUTO_BED_LEVELING
  50. #include "vector_3.h"
  51. #ifdef AUTO_BED_LEVELING_GRID
  52. #include "qr_solve.h"
  53. #endif
  54. #endif // ENABLE_AUTO_BED_LEVELING
  55. #ifdef MESH_BED_LEVELING
  56. #include "mesh_bed_leveling.h"
  57. #include "mesh_bed_calibration.h"
  58. #endif
  59. #include "printers.h"
  60. #include "menu.h"
  61. #include "ultralcd.h"
  62. #include "conv2str.h"
  63. #include "backlight.h"
  64. #include "planner.h"
  65. #include "stepper.h"
  66. #include "temperature.h"
  67. #include "motion_control.h"
  68. #include "cardreader.h"
  69. #include "ConfigurationStore.h"
  70. #include "language.h"
  71. #include "pins_arduino.h"
  72. #include "math.h"
  73. #include "util.h"
  74. #include "Timer.h"
  75. #include <avr/wdt.h>
  76. #include <avr/pgmspace.h>
  77. #include "Dcodes.h"
  78. #include "AutoDeplete.h"
  79. #ifndef LA_NOCOMPAT
  80. #include "la10compat.h"
  81. #endif
  82. #include "spi.h"
  83. #ifdef FILAMENT_SENSOR
  84. #include "fsensor.h"
  85. #ifdef IR_SENSOR
  86. #include "pat9125.h" // for pat9125_probe
  87. #endif
  88. #endif //FILAMENT_SENSOR
  89. #ifdef TMC2130
  90. #include "tmc2130.h"
  91. #endif //TMC2130
  92. #ifdef XFLASH
  93. #include "xflash.h"
  94. #include "optiboot_xflash.h"
  95. #endif //XFLASH
  96. #include "xflash_dump.h"
  97. #ifdef BLINKM
  98. #include "BlinkM.h"
  99. #include "Wire.h"
  100. #endif
  101. #ifdef ULTRALCD
  102. #include "ultralcd.h"
  103. #endif
  104. #if NUM_SERVOS > 0
  105. #include "Servo.h"
  106. #endif
  107. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  108. #include <SPI.h>
  109. #endif
  110. #include "mmu.h"
  111. #define VERSION_STRING "1.0.2"
  112. #include "ultralcd.h"
  113. #include "sound.h"
  114. #include "cmdqueue.h"
  115. //Macro for print fan speed
  116. #define FAN_PULSE_WIDTH_LIMIT ((fanSpeed > 100) ? 3 : 4) //time in ms
  117. //filament types
  118. #define FILAMENT_DEFAULT 0
  119. #define FILAMENT_FLEX 1
  120. #define FILAMENT_PVA 2
  121. #define FILAMENT_UNDEFINED 255
  122. //Stepper Movement Variables
  123. //===========================================================================
  124. //=============================imported variables============================
  125. //===========================================================================
  126. //===========================================================================
  127. //=============================public variables=============================
  128. //===========================================================================
  129. #ifdef SDSUPPORT
  130. CardReader card;
  131. #endif
  132. unsigned long PingTime = _millis();
  133. uint8_t mbl_z_probe_nr = 3; //numer of Z measurements for each point in mesh bed leveling calibration
  134. //used for PINDA temp calibration and pause print
  135. #define DEFAULT_RETRACTION 1
  136. #define DEFAULT_RETRACTION_MM 4 //MM
  137. float default_retraction = DEFAULT_RETRACTION;
  138. float homing_feedrate[] = HOMING_FEEDRATE;
  139. //Although this flag and many others like this could be represented with a struct/bitfield for each axis (more readable and efficient code), the implementation
  140. //would not be standard across all platforms. That being said, the code will continue to use bitmasks for independent axis.
  141. //Moreover, according to C/C++ standard, the ordering of bits is platform/compiler dependent and the compiler is allowed to align the bits arbitrarily,
  142. //thus bit operations like shifting and masking may stop working and will be very hard to fix.
  143. uint8_t axis_relative_modes = 0;
  144. int feedmultiply=100; //100->1 200->2
  145. int extrudemultiply=100; //100->1 200->2
  146. int extruder_multiply[EXTRUDERS] = {100
  147. #if EXTRUDERS > 1
  148. , 100
  149. #if EXTRUDERS > 2
  150. , 100
  151. #endif
  152. #endif
  153. };
  154. bool homing_flag = false;
  155. int8_t lcd_change_fil_state = 0;
  156. unsigned long pause_time = 0;
  157. unsigned long start_pause_print = _millis();
  158. unsigned long t_fan_rising_edge = _millis();
  159. LongTimer safetyTimer;
  160. static LongTimer crashDetTimer;
  161. //unsigned long load_filament_time;
  162. bool mesh_bed_leveling_flag = false;
  163. #ifdef PRUSA_M28
  164. bool prusa_sd_card_upload = false;
  165. #endif
  166. uint8_t status_number = 0;
  167. unsigned long total_filament_used;
  168. HeatingStatus heating_status;
  169. uint8_t heating_status_counter;
  170. bool loading_flag = false;
  171. #define XY_NO_RESTORE_FLAG (mesh_bed_leveling_flag || homing_flag)
  172. bool fan_state[2];
  173. int fan_edge_counter[2];
  174. int fan_speed[2];
  175. float extruder_multiplier[EXTRUDERS] = {1.0
  176. #if EXTRUDERS > 1
  177. , 1.0
  178. #if EXTRUDERS > 2
  179. , 1.0
  180. #endif
  181. #endif
  182. };
  183. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  184. //shortcuts for more readable code
  185. #define _x current_position[X_AXIS]
  186. #define _y current_position[Y_AXIS]
  187. #define _z current_position[Z_AXIS]
  188. #define _e current_position[E_AXIS]
  189. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  190. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  191. bool axis_known_position[3] = {false, false, false};
  192. // Extruder offset
  193. #if EXTRUDERS > 1
  194. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  195. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  196. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  197. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  198. #endif
  199. };
  200. #endif
  201. uint8_t active_extruder = 0;
  202. int fanSpeed=0;
  203. uint8_t newFanSpeed = 0;
  204. #ifdef FWRETRACT
  205. bool retracted[EXTRUDERS]={false
  206. #if EXTRUDERS > 1
  207. , false
  208. #if EXTRUDERS > 2
  209. , false
  210. #endif
  211. #endif
  212. };
  213. bool retracted_swap[EXTRUDERS]={false
  214. #if EXTRUDERS > 1
  215. , false
  216. #if EXTRUDERS > 2
  217. , false
  218. #endif
  219. #endif
  220. };
  221. float retract_length_swap = RETRACT_LENGTH_SWAP;
  222. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  223. #endif
  224. #ifdef PS_DEFAULT_OFF
  225. bool powersupply = false;
  226. #else
  227. bool powersupply = true;
  228. #endif
  229. bool cancel_heatup = false;
  230. int8_t busy_state = NOT_BUSY;
  231. static long prev_busy_signal_ms = -1;
  232. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  233. const char errormagic[] PROGMEM = "Error:";
  234. const char echomagic[] PROGMEM = "echo:";
  235. const char G28W0[] PROGMEM = "G28 W0";
  236. bool no_response = false;
  237. uint8_t important_status;
  238. uint8_t saved_filament_type;
  239. // Define some coordinates outside the clamp limits (making them invalid past the parsing stage) so
  240. // that they can be used later for various logical checks
  241. #define X_COORD_INVALID (X_MIN_POS-1)
  242. #define Y_COORD_INVALID (Y_MIN_POS-1)
  243. #define SAVED_TARGET_UNSET X_COORD_INVALID
  244. float saved_target[NUM_AXIS] = {SAVED_TARGET_UNSET, 0, 0, 0};
  245. // save/restore printing in case that mmu was not responding
  246. bool mmu_print_saved = false;
  247. // storing estimated time to end of print counted by slicer
  248. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  249. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  250. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  251. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  252. uint16_t print_time_to_change_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  253. uint16_t print_time_to_change_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  254. uint32_t IP_address = 0;
  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. const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS; // Sensitive pin list for M42
  270. //static float tt = 0;
  271. //static float bt = 0;
  272. //Inactivity shutdown variables
  273. static LongTimer previous_millis_cmd;
  274. unsigned long max_inactive_time = 0;
  275. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  276. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  277. unsigned long starttime=0;
  278. unsigned long stoptime=0;
  279. ShortTimer usb_timer;
  280. bool Stopped=false;
  281. #if NUM_SERVOS > 0
  282. Servo servos[NUM_SERVOS];
  283. #endif
  284. bool target_direction;
  285. //Insert variables if CHDK is defined
  286. #ifdef CHDK
  287. unsigned long chdkHigh = 0;
  288. bool chdkActive = false;
  289. #endif
  290. //! @name RAM save/restore printing
  291. //! @{
  292. bool saved_printing = false; //!< Print is paused and saved in RAM
  293. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  294. uint8_t saved_printing_type = PRINTING_TYPE_SD;
  295. static float saved_pos[4] = { X_COORD_INVALID, 0, 0, 0 };
  296. static uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
  297. static int saved_feedmultiply2 = 0;
  298. static uint8_t saved_active_extruder = 0;
  299. static float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  300. static bool saved_extruder_relative_mode = false;
  301. static int saved_fanSpeed = 0; //!< Print fan speed
  302. //! @}
  303. static int saved_feedmultiply_mm = 100;
  304. class AutoReportFeatures {
  305. union {
  306. struct {
  307. uint8_t temp : 1; //Temperature flag
  308. uint8_t fans : 1; //Fans flag
  309. uint8_t pos: 1; //Position flag
  310. uint8_t ar4 : 1; //Unused
  311. uint8_t ar5 : 1; //Unused
  312. uint8_t ar6 : 1; //Unused
  313. uint8_t ar7 : 1; //Unused
  314. } __attribute__((packed)) bits;
  315. uint8_t byte;
  316. } arFunctionsActive;
  317. uint8_t auto_report_period;
  318. public:
  319. LongTimer auto_report_timer;
  320. AutoReportFeatures():auto_report_period(0){
  321. #if defined(AUTO_REPORT)
  322. arFunctionsActive.byte = 0xff;
  323. #else
  324. arFunctionsActive.byte = 0;
  325. #endif //AUTO_REPORT
  326. }
  327. inline bool Temp()const { return arFunctionsActive.bits.temp != 0; }
  328. inline void SetTemp(uint8_t v){ arFunctionsActive.bits.temp = v; }
  329. inline bool Fans()const { return arFunctionsActive.bits.fans != 0; }
  330. inline void SetFans(uint8_t v){ arFunctionsActive.bits.fans = v; }
  331. inline bool Pos()const { return arFunctionsActive.bits.pos != 0; }
  332. inline void SetPos(uint8_t v){ arFunctionsActive.bits.pos = v; }
  333. inline void SetMask(uint8_t mask){ arFunctionsActive.byte = mask; }
  334. /// sets the autoreporting timer's period
  335. /// setting it to zero stops the timer
  336. void SetPeriod(uint8_t p){
  337. auto_report_period = p;
  338. if (auto_report_period != 0){
  339. auto_report_timer.start();
  340. } else{
  341. auto_report_timer.stop();
  342. }
  343. }
  344. inline void TimerStart() { auto_report_timer.start(); }
  345. inline bool TimerRunning()const { return auto_report_timer.running(); }
  346. inline bool TimerExpired() { return auto_report_timer.expired(auto_report_period * 1000ul); }
  347. };
  348. AutoReportFeatures autoReportFeatures;
  349. //===========================================================================
  350. //=============================Routines======================================
  351. //===========================================================================
  352. static void get_arc_coordinates();
  353. static bool setTargetedHotend(int code, uint8_t &extruder);
  354. static void print_time_remaining_init();
  355. static void wait_for_heater(long codenum, uint8_t extruder);
  356. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
  357. static void gcode_M105(uint8_t extruder);
  358. #ifndef PINDA_THERMISTOR
  359. static void temp_compensation_start();
  360. static void temp_compensation_apply();
  361. #endif
  362. #ifdef PRUSA_SN_SUPPORT
  363. static uint8_t get_PRUSA_SN(char* SN);
  364. #endif //PRUSA_SN_SUPPORT
  365. uint16_t gcode_in_progress = 0;
  366. uint16_t mcode_in_progress = 0;
  367. void serial_echopair_P(const char *s_P, float v)
  368. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  369. void serial_echopair_P(const char *s_P, double v)
  370. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  371. void serial_echopair_P(const char *s_P, unsigned long v)
  372. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  373. void serialprintPGM(const char *str) {
  374. while(uint8_t ch = pgm_read_byte(str)) {
  375. MYSERIAL.write((char)ch);
  376. ++str;
  377. }
  378. }
  379. void serialprintlnPGM(const char *str) {
  380. serialprintPGM(str);
  381. MYSERIAL.println();
  382. }
  383. #ifdef SDSUPPORT
  384. #include "SdFatUtil.h"
  385. int freeMemory() { return SdFatUtil::FreeRam(); }
  386. #else
  387. extern "C" {
  388. extern unsigned int __bss_end;
  389. extern unsigned int __heap_start;
  390. extern void *__brkval;
  391. int freeMemory() {
  392. int free_memory;
  393. if ((int)__brkval == 0)
  394. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  395. else
  396. free_memory = ((int)&free_memory) - ((int)__brkval);
  397. return free_memory;
  398. }
  399. }
  400. #endif //!SDSUPPORT
  401. void setup_killpin()
  402. {
  403. #if defined(KILL_PIN) && KILL_PIN > -1
  404. SET_INPUT(KILL_PIN);
  405. WRITE(KILL_PIN,HIGH);
  406. #endif
  407. }
  408. // Set home pin
  409. void setup_homepin(void)
  410. {
  411. #if defined(HOME_PIN) && HOME_PIN > -1
  412. SET_INPUT(HOME_PIN);
  413. WRITE(HOME_PIN,HIGH);
  414. #endif
  415. }
  416. void setup_photpin()
  417. {
  418. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  419. SET_OUTPUT(PHOTOGRAPH_PIN);
  420. WRITE(PHOTOGRAPH_PIN, LOW);
  421. #endif
  422. }
  423. void setup_powerhold()
  424. {
  425. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  426. SET_OUTPUT(SUICIDE_PIN);
  427. WRITE(SUICIDE_PIN, HIGH);
  428. #endif
  429. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  430. SET_OUTPUT(PS_ON_PIN);
  431. #if defined(PS_DEFAULT_OFF)
  432. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  433. #else
  434. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  435. #endif
  436. #endif
  437. }
  438. void suicide()
  439. {
  440. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  441. SET_OUTPUT(SUICIDE_PIN);
  442. WRITE(SUICIDE_PIN, LOW);
  443. #endif
  444. }
  445. void servo_init()
  446. {
  447. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  448. servos[0].attach(SERVO0_PIN);
  449. #endif
  450. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  451. servos[1].attach(SERVO1_PIN);
  452. #endif
  453. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  454. servos[2].attach(SERVO2_PIN);
  455. #endif
  456. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  457. servos[3].attach(SERVO3_PIN);
  458. #endif
  459. #if (NUM_SERVOS >= 5)
  460. #error "TODO: enter initalisation code for more servos"
  461. #endif
  462. }
  463. bool fans_check_enabled = true;
  464. #ifdef TMC2130
  465. void crashdet_stop_and_save_print()
  466. {
  467. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  468. }
  469. void crashdet_restore_print_and_continue()
  470. {
  471. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  472. // babystep_apply();
  473. }
  474. void crashdet_fmt_error(char* buf, uint8_t mask)
  475. {
  476. if(mask & X_AXIS_MASK) *buf++ = axis_codes[X_AXIS];
  477. if(mask & Y_AXIS_MASK) *buf++ = axis_codes[Y_AXIS];
  478. *buf++ = ' ';
  479. strcpy_P(buf, _T(MSG_CRASH_DETECTED));
  480. }
  481. void crashdet_detected(uint8_t mask)
  482. {
  483. st_synchronize();
  484. static uint8_t crashDet_counter = 0;
  485. static uint8_t crashDet_axes = 0;
  486. bool automatic_recovery_after_crash = true;
  487. char msg[LCD_WIDTH+1] = "";
  488. if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)) {
  489. crashDet_counter = 0;
  490. }
  491. if(++crashDet_counter >= CRASHDET_COUNTER_MAX) {
  492. automatic_recovery_after_crash = false;
  493. }
  494. crashDetTimer.start();
  495. crashDet_axes |= mask;
  496. lcd_update_enable(true);
  497. lcd_clear();
  498. lcd_update(2);
  499. if (mask & X_AXIS_MASK)
  500. {
  501. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_X, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_X) + 1);
  502. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT) + 1);
  503. }
  504. if (mask & Y_AXIS_MASK)
  505. {
  506. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_Y, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_Y) + 1);
  507. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT) + 1);
  508. }
  509. lcd_update_enable(true);
  510. lcd_update(2);
  511. // prepare the status message with the _current_ axes status
  512. crashdet_fmt_error(msg, mask);
  513. lcd_setstatus(msg);
  514. gcode_G28(true, true, false); //home X and Y
  515. st_synchronize();
  516. if (automatic_recovery_after_crash) {
  517. enquecommand_P(PSTR("CRASH_RECOVER"));
  518. }else{
  519. setTargetHotend(0, active_extruder);
  520. // notify the user of *all* the axes previously affected, not just the last one
  521. lcd_update_enable(false);
  522. lcd_clear();
  523. crashdet_fmt_error(msg, crashDet_axes);
  524. crashDet_axes = 0;
  525. lcd_print(msg);
  526. // ask whether to resume printing
  527. lcd_set_cursor(0, 1);
  528. lcd_puts_P(_T(MSG_RESUME_PRINT));
  529. lcd_putc('?');
  530. bool yesno = lcd_show_yes_no_and_wait(false);
  531. lcd_update_enable(true);
  532. if (yesno)
  533. {
  534. enquecommand_P(PSTR("CRASH_RECOVER"));
  535. }
  536. else
  537. {
  538. enquecommand_P(PSTR("CRASH_CANCEL"));
  539. }
  540. }
  541. }
  542. void crashdet_recover()
  543. {
  544. crashdet_restore_print_and_continue();
  545. if (lcd_crash_detect_enabled()) tmc2130_sg_stop_on_crash = true;
  546. }
  547. void crashdet_cancel()
  548. {
  549. saved_printing = false;
  550. tmc2130_sg_stop_on_crash = true;
  551. if (saved_printing_type == PRINTING_TYPE_SD) {
  552. lcd_print_stop();
  553. }else if(saved_printing_type == PRINTING_TYPE_USB){
  554. SERIAL_ECHOLNRPGM(MSG_OCTOPRINT_CANCEL); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  555. cmdqueue_reset();
  556. }
  557. }
  558. #endif //TMC2130
  559. void failstats_reset_print()
  560. {
  561. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  562. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  563. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  564. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  565. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  566. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  567. #if defined(FILAMENT_SENSOR) && defined(PAT9125)
  568. fsensor_softfail = 0;
  569. #endif
  570. }
  571. void softReset()
  572. {
  573. cli();
  574. wdt_enable(WDTO_15MS);
  575. while(1);
  576. }
  577. #ifdef MESH_BED_LEVELING
  578. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  579. #endif
  580. static void factory_reset_stats(){
  581. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  582. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  583. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  584. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  585. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  586. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  587. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  588. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  589. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  590. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  591. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  592. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  593. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  594. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  595. }
  596. // Factory reset function
  597. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  598. // Level input parameter sets depth of reset
  599. static void factory_reset(char level)
  600. {
  601. lcd_clear();
  602. Sound_MakeCustom(100,0,false);
  603. switch (level) {
  604. case 0: // Level 0: Language reset
  605. lang_reset();
  606. break;
  607. case 1: //Level 1: Reset statistics
  608. factory_reset_stats();
  609. lcd_menu_statistics();
  610. break;
  611. case 2: // Level 2: Prepare for shipping
  612. factory_reset_stats();
  613. // FALLTHRU
  614. case 3: // Level 3: Preparation after being serviced
  615. // Force language selection at the next boot up.
  616. lang_reset();
  617. // Force the "Follow calibration flow" message at the next boot up.
  618. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  619. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 2); //run wizard
  620. farm_mode = false;
  621. eeprom_update_byte((uint8_t*)EEPROM_FARM_MODE, farm_mode);
  622. #ifdef FILAMENT_SENSOR
  623. fsensor_enable();
  624. fsensor_autoload_set(true);
  625. #endif //FILAMENT_SENSOR
  626. break;
  627. case 4:
  628. menu_progressbar_init(EEPROM_TOP, PSTR("ERASING all data"));
  629. // Erase EEPROM
  630. for (uint16_t i = 0; i < EEPROM_TOP; i++) {
  631. eeprom_update_byte((uint8_t*)i, 0xFF);
  632. menu_progressbar_update(i);
  633. }
  634. menu_progressbar_finish();
  635. softReset();
  636. break;
  637. default:
  638. break;
  639. }
  640. }
  641. extern "C" {
  642. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  643. }
  644. int uart_putchar(char c, FILE *)
  645. {
  646. MYSERIAL.write(c);
  647. return 0;
  648. }
  649. void lcd_splash()
  650. {
  651. lcd_clear(); // clears display and homes screen
  652. lcd_puts_P(PSTR("\n Original Prusa i3\n Prusa Research"));
  653. }
  654. void factory_reset()
  655. {
  656. KEEPALIVE_STATE(PAUSED_FOR_USER);
  657. if (!READ(BTN_ENC))
  658. {
  659. _delay_ms(1000);
  660. if (!READ(BTN_ENC))
  661. {
  662. lcd_clear();
  663. lcd_puts_P(PSTR("Factory RESET"));
  664. SET_OUTPUT(BEEPER);
  665. if(eSoundMode!=e_SOUND_MODE_SILENT)
  666. WRITE(BEEPER, HIGH);
  667. while (!READ(BTN_ENC));
  668. WRITE(BEEPER, LOW);
  669. _delay_ms(2000);
  670. char level = reset_menu();
  671. factory_reset(level);
  672. switch (level) {
  673. case 0:
  674. case 1:
  675. case 2:
  676. case 3:
  677. case 4: _delay_ms(0); break;
  678. }
  679. }
  680. }
  681. KEEPALIVE_STATE(IN_HANDLER);
  682. }
  683. void show_fw_version_warnings() {
  684. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  685. switch (FW_DEV_VERSION) {
  686. 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
  687. 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
  688. case(FW_VERSION_DEVEL):
  689. case(FW_VERSION_DEBUG):
  690. lcd_update_enable(false);
  691. lcd_clear();
  692. #if FW_DEV_VERSION == FW_VERSION_DEVEL
  693. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  694. #else
  695. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  696. #endif
  697. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  698. lcd_puts_at_P(0, 2, PSTR("ver ")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  699. lcd_puts_at_P(0, 3, PSTR(FW_REPOSITORY));
  700. lcd_wait_for_click();
  701. break;
  702. // 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
  703. }
  704. lcd_update_enable(true);
  705. }
  706. //! @brief try to check if firmware is on right type of printer
  707. static void check_if_fw_is_on_right_printer(){
  708. #ifdef FILAMENT_SENSOR
  709. if((PRINTER_TYPE == PRINTER_MK3) || (PRINTER_TYPE == PRINTER_MK3S)){
  710. #ifdef IR_SENSOR
  711. if (pat9125_probe()){
  712. lcd_show_fullscreen_message_and_wait_P(_i("MK3S firmware detected on MK3 printer"));}////MSG_MK3S_FIRMWARE_ON_MK3 c=20 r=4
  713. #endif //IR_SENSOR
  714. #ifdef PAT9125
  715. //will return 1 only if IR can detect filament in bondtech extruder so this may fail even when we have IR sensor
  716. const uint8_t ir_detected = !READ(IR_SENSOR_PIN);
  717. if (ir_detected){
  718. lcd_show_fullscreen_message_and_wait_P(_i("MK3 firmware detected on MK3S printer"));}////MSG_MK3_FIRMWARE_ON_MK3S c=20 r=4
  719. #endif //PAT9125
  720. }
  721. #endif //FILAMENT_SENSOR
  722. }
  723. uint8_t check_printer_version()
  724. {
  725. uint8_t version_changed = 0;
  726. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  727. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  728. if (printer_type != PRINTER_TYPE) {
  729. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  730. else version_changed |= 0b10;
  731. }
  732. if (motherboard != MOTHERBOARD) {
  733. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  734. else version_changed |= 0b01;
  735. }
  736. return version_changed;
  737. }
  738. #ifdef BOOTAPP
  739. #include "bootapp.h" //bootloader support
  740. #endif //BOOTAPP
  741. #if (LANG_MODE != 0) //secondary language support
  742. #ifdef XFLASH
  743. // language update from external flash
  744. #define LANGBOOT_BLOCKSIZE 0x1000u
  745. #define LANGBOOT_RAMBUFFER 0x0800
  746. void update_sec_lang_from_external_flash()
  747. {
  748. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  749. {
  750. uint8_t lang = boot_reserved >> 3;
  751. uint8_t state = boot_reserved & 0x07;
  752. lang_table_header_t header;
  753. uint32_t src_addr;
  754. if (lang_get_header(lang, &header, &src_addr))
  755. {
  756. lcd_puts_at_P(1,3,PSTR("Language update."));
  757. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  758. _delay(100);
  759. boot_reserved = (boot_reserved & 0xF8) | ((state + 1) & 0x07);
  760. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  761. {
  762. cli();
  763. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  764. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  765. xflash_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  766. if (state == 0)
  767. {
  768. //TODO - check header integrity
  769. }
  770. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  771. }
  772. else
  773. {
  774. //TODO - check sec lang data integrity
  775. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  776. }
  777. }
  778. }
  779. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  780. }
  781. #ifdef DEBUG_XFLASH
  782. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  783. {
  784. lang_table_header_t header;
  785. uint8_t count = 0;
  786. uint32_t addr = 0x00000;
  787. while (1)
  788. {
  789. printf_P(_n("LANGTABLE%d:"), count);
  790. xflash_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  791. if (header.magic != LANG_MAGIC)
  792. {
  793. puts_P(_n("NG!"));
  794. break;
  795. }
  796. puts_P(_n("OK"));
  797. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  798. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  799. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  800. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  801. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  802. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  803. addr += header.size;
  804. codes[count] = header.code;
  805. count ++;
  806. }
  807. return count;
  808. }
  809. void list_sec_lang_from_external_flash()
  810. {
  811. uint16_t codes[8];
  812. uint8_t count = lang_xflash_enum_codes(codes);
  813. printf_P(_n("XFlash lang count = %hhd\n"), count);
  814. }
  815. #endif //DEBUG_XFLASH
  816. #endif //XFLASH
  817. #endif //(LANG_MODE != 0)
  818. static void fw_crash_init()
  819. {
  820. #ifdef XFLASH_DUMP
  821. dump_crash_reason crash_reason;
  822. if(xfdump_check_state(&crash_reason))
  823. {
  824. // always signal to the host that a dump is available for retrieval
  825. puts_P(_N("// action:dump_available"));
  826. #ifdef EMERGENCY_DUMP
  827. if(crash_reason != dump_crash_reason::manual &&
  828. eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG) != 0xFF)
  829. {
  830. lcd_show_fullscreen_message_and_wait_P(
  831. _n("FW crash detected! "
  832. "You can continue printing. "
  833. "Debug data available for analysis. "
  834. "Contact support to submit details."));
  835. }
  836. #endif
  837. }
  838. #else //XFLASH_DUMP
  839. dump_crash_reason crash_reason = (dump_crash_reason)eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG);
  840. if(crash_reason != dump_crash_reason::manual && (uint8_t)crash_reason != 0xFF)
  841. {
  842. lcd_beeper_quick_feedback();
  843. lcd_clear();
  844. lcd_puts_P(_n("FIRMWARE CRASH!\nCrash reason:\n"));
  845. switch(crash_reason)
  846. {
  847. case dump_crash_reason::stack_error:
  848. lcd_puts_P(_n("Static memory has\nbeen overwritten"));
  849. break;
  850. case dump_crash_reason::watchdog:
  851. lcd_puts_P(_n("Watchdog timeout"));
  852. break;
  853. case dump_crash_reason::bad_isr:
  854. lcd_puts_P(_n("Bad interrupt"));
  855. break;
  856. default:
  857. lcd_print((uint8_t)crash_reason);
  858. break;
  859. }
  860. lcd_wait_for_click();
  861. }
  862. #endif //XFLASH_DUMP
  863. // prevent crash prompts to reappear once acknowledged
  864. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, 0xFF);
  865. }
  866. static void xflash_err_msg()
  867. {
  868. puts_P(_n("XFLASH not responding."));
  869. lcd_show_fullscreen_message_and_wait_P(_n("External SPI flash\nXFLASH is not res-\nponding. Language\nswitch unavailable."));
  870. }
  871. // "Setup" function is called by the Arduino framework on startup.
  872. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  873. // are initialized by the main() routine provided by the Arduino framework.
  874. void setup()
  875. {
  876. timer2_init(); // enables functional millis
  877. mmu_init();
  878. ultralcd_init();
  879. spi_init();
  880. lcd_splash();
  881. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  882. selectedSerialPort = eeprom_read_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE);
  883. if (selectedSerialPort == 0xFF) selectedSerialPort = 0;
  884. eeprom_update_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE, selectedSerialPort);
  885. MYSERIAL.begin(BAUDRATE);
  886. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  887. stdout = uartout;
  888. #ifdef XFLASH
  889. bool xflash_success = xflash_init();
  890. uint8_t optiboot_status = 1;
  891. if (xflash_success)
  892. {
  893. optiboot_status = optiboot_xflash_enter();
  894. #if (LANG_MODE != 0) //secondary language support
  895. update_sec_lang_from_external_flash();
  896. #endif //(LANG_MODE != 0)
  897. }
  898. #else
  899. const bool xflash_success = true;
  900. #endif //XFLASH
  901. setup_killpin();
  902. setup_powerhold();
  903. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  904. if (farm_mode == 0xFF) {
  905. 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
  906. eeprom_update_byte((uint8_t*)EEPROM_FARM_MODE, farm_mode);
  907. } else if (farm_mode) {
  908. no_response = true; //we need confirmation by recieving PRUSA thx
  909. important_status = 8;
  910. prusa_statistics(8);
  911. #ifdef HAS_SECOND_SERIAL_PORT
  912. selectedSerialPort = 1;
  913. #endif //HAS_SECOND_SERIAL_PORT
  914. MYSERIAL.begin(BAUDRATE);
  915. #ifdef FILAMENT_SENSOR
  916. //disabled filament autoload (PFW360)
  917. fsensor_autoload_set(false);
  918. #endif //FILAMENT_SENSOR
  919. // ~ FanCheck -> on
  920. eeprom_update_byte((uint8_t*)EEPROM_FAN_CHECK_ENABLED, true);
  921. }
  922. #ifdef TMC2130
  923. if( FarmOrUserECool() ){
  924. //increased extruder current (PFW363)
  925. tmc2130_current_h[E_AXIS] = TMC2130_CURRENTS_FARM;
  926. tmc2130_current_r[E_AXIS] = TMC2130_CURRENTS_FARM;
  927. }
  928. #endif //TMC2130
  929. #ifdef PRUSA_SN_SUPPORT
  930. //Check for valid SN in EEPROM. Try to retrieve it in case it's invalid.
  931. //SN is valid only if it is NULL terminated and starts with "CZPX".
  932. {
  933. char SN[20];
  934. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  935. if (SN[19] || strncmp_P(SN, PSTR("CZPX"), 4))
  936. {
  937. if (!get_PRUSA_SN(SN))
  938. {
  939. eeprom_update_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  940. puts_P(PSTR("SN updated"));
  941. }
  942. else
  943. puts_P(PSTR("SN update failed"));
  944. }
  945. }
  946. #endif //PRUSA_SN_SUPPORT
  947. #ifndef XFLASH
  948. SERIAL_PROTOCOLLNPGM("start");
  949. #else
  950. if ((optiboot_status != 0) || (selectedSerialPort != 0))
  951. SERIAL_PROTOCOLLNPGM("start");
  952. #endif
  953. SERIAL_ECHO_START;
  954. puts_P(PSTR(" " FW_VERSION_FULL));
  955. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  956. #ifdef DEBUG_SEC_LANG
  957. lang_table_header_t header;
  958. uint32_t src_addr = 0x00000;
  959. if (lang_get_header(1, &header, &src_addr))
  960. {
  961. printf_P(
  962. _n(
  963. " _src_addr = 0x%08lx\n"
  964. " _lt_magic = 0x%08lx %S\n"
  965. " _lt_size = 0x%04x (%d)\n"
  966. " _lt_count = 0x%04x (%d)\n"
  967. " _lt_chsum = 0x%04x\n"
  968. " _lt_code = 0x%04x (%c%c)\n"
  969. " _lt_resv1 = 0x%08lx\n"
  970. ),
  971. src_addr,
  972. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  973. header.size, header.size,
  974. header.count, header.count,
  975. header.checksum,
  976. header.code, header.code >> 8, header.code & 0xff,
  977. header.signature
  978. );
  979. #if 0
  980. xflash_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  981. for (uint16_t i = 0; i < 1024; i++)
  982. {
  983. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  984. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  985. if ((i % 16) == 15) putchar('\n');
  986. }
  987. #endif
  988. uint16_t sum = 0;
  989. for (uint16_t i = 0; i < header.size; i++)
  990. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  991. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  992. sum -= header.checksum; //subtract checksum
  993. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  994. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  995. if (sum == header.checksum)
  996. puts_P(_n("Checksum OK"));
  997. else
  998. puts_P(_n("Checksum NG"));
  999. }
  1000. else
  1001. puts_P(_n("lang_get_header failed!"));
  1002. #if 0
  1003. for (uint16_t i = 0; i < 1024*10; i++)
  1004. {
  1005. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  1006. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  1007. if ((i % 16) == 15) putchar('\n');
  1008. }
  1009. #endif
  1010. #if 0
  1011. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  1012. for (int i = 0; i < 4096; ++i) {
  1013. int b = eeprom_read_byte((unsigned char*)i);
  1014. if (b != 255) {
  1015. SERIAL_ECHO(i);
  1016. SERIAL_ECHO(":");
  1017. SERIAL_ECHO(b);
  1018. SERIAL_ECHOLN("");
  1019. }
  1020. }
  1021. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  1022. #endif
  1023. #endif //DEBUG_SEC_LANG
  1024. // Check startup - does nothing if bootloader sets MCUSR to 0
  1025. byte mcu = MCUSR;
  1026. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  1027. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  1028. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  1029. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  1030. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  1031. if (mcu & 1) puts_P(MSG_POWERUP);
  1032. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  1033. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  1034. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  1035. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  1036. MCUSR = 0;
  1037. //SERIAL_ECHORPGM(MSG_MARLIN);
  1038. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  1039. #ifdef STRING_VERSION_CONFIG_H
  1040. #ifdef STRING_CONFIG_H_AUTHOR
  1041. SERIAL_ECHO_START;
  1042. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  1043. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  1044. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  1045. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  1046. SERIAL_ECHOPGM("Compiled: ");
  1047. SERIAL_ECHOLNPGM(__DATE__);
  1048. #endif
  1049. #endif
  1050. SERIAL_ECHO_START;
  1051. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1052. SERIAL_ECHO(freeMemory());
  1053. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1054. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1055. //lcd_update_enable(false); // why do we need this?? - andre
  1056. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1057. bool previous_settings_retrieved = false;
  1058. uint8_t hw_changed = check_printer_version();
  1059. 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
  1060. previous_settings_retrieved = Config_RetrieveSettings();
  1061. }
  1062. else { //printer version was changed so use default settings
  1063. Config_ResetDefault();
  1064. }
  1065. SdFatUtil::set_stack_guard(); //writes magic number at the end of static variables to protect against overwriting static memory by stack
  1066. tp_init(); // Initialize temperature loop
  1067. #ifdef EXTRUDER_ALTFAN_DETECT
  1068. SERIAL_ECHORPGM(_n("Extruder fan type: "));
  1069. if (extruder_altfan_detect())
  1070. SERIAL_ECHOLNRPGM(PSTR("ALTFAN"));
  1071. else
  1072. SERIAL_ECHOLNRPGM(PSTR("NOCTUA"));
  1073. #endif //EXTRUDER_ALTFAN_DETECT
  1074. plan_init(); // Initialize planner;
  1075. factory_reset();
  1076. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  1077. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff)
  1078. {
  1079. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  1080. // where all the EEPROM entries are set to 0x0ff.
  1081. // Once a firmware boots up, it forces at least a language selection, which changes
  1082. // EEPROM_LANG to number lower than 0x0ff.
  1083. // 1) Set a high power mode.
  1084. eeprom_update_byte((uint8_t*)EEPROM_SILENT, SILENT_MODE_OFF);
  1085. #ifdef TMC2130
  1086. tmc2130_mode = TMC2130_MODE_NORMAL;
  1087. #endif //TMC2130
  1088. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  1089. }
  1090. lcd_encoder_diff=0;
  1091. #ifdef TMC2130
  1092. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1093. if (silentMode == 0xff) silentMode = 0;
  1094. tmc2130_mode = TMC2130_MODE_NORMAL;
  1095. if (lcd_crash_detect_enabled() && !farm_mode)
  1096. {
  1097. lcd_crash_detect_enable();
  1098. puts_P(_N("CrashDetect ENABLED!"));
  1099. }
  1100. else
  1101. {
  1102. lcd_crash_detect_disable();
  1103. puts_P(_N("CrashDetect DISABLED"));
  1104. }
  1105. #ifdef TMC2130_LINEARITY_CORRECTION
  1106. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1107. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1108. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1109. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1110. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1111. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1112. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1113. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1114. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1115. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1116. #endif //TMC2130_LINEARITY_CORRECTION
  1117. #ifdef TMC2130_VARIABLE_RESOLUTION
  1118. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1119. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1120. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1121. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1122. #else //TMC2130_VARIABLE_RESOLUTION
  1123. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1124. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1125. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1126. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1127. #endif //TMC2130_VARIABLE_RESOLUTION
  1128. #endif //TMC2130
  1129. st_init(); // Initialize stepper, this enables interrupts!
  1130. #ifdef TMC2130
  1131. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1132. update_mode_profile();
  1133. tmc2130_init(TMCInitParams(false, FarmOrUserECool() ));
  1134. #endif //TMC2130
  1135. #ifdef PSU_Delta
  1136. init_force_z(); // ! important for correct Z-axis initialization
  1137. #endif // PSU_Delta
  1138. setup_photpin();
  1139. servo_init();
  1140. // Reset the machine correction matrix.
  1141. // It does not make sense to load the correction matrix until the machine is homed.
  1142. world2machine_reset();
  1143. // Initialize current_position accounting for software endstops to
  1144. // avoid unexpected initial shifts on the first move
  1145. clamp_to_software_endstops(current_position);
  1146. plan_set_position_curposXYZE();
  1147. // Show the xflash error message now that serial, lcd and encoder are available
  1148. if (!xflash_success)
  1149. xflash_err_msg();
  1150. #ifdef FILAMENT_SENSOR
  1151. fsensor_init();
  1152. #endif //FILAMENT_SENSOR
  1153. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1154. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1155. #endif
  1156. setup_homepin();
  1157. #if defined(Z_AXIS_ALWAYS_ON)
  1158. enable_z();
  1159. #endif
  1160. if (farm_mode) {
  1161. // The farm monitoring SW may accidentally expect
  1162. // 2 messages of "printer started" to consider a printer working.
  1163. prusa_statistics(8);
  1164. }
  1165. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1166. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1167. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1168. // but this times out if a blocking dialog is shown in setup().
  1169. card.initsd();
  1170. #ifdef DEBUG_SD_SPEED_TEST
  1171. if (card.cardOK)
  1172. {
  1173. uint8_t* buff = (uint8_t*)block_buffer;
  1174. uint32_t block = 0;
  1175. uint32_t sumr = 0;
  1176. uint32_t sumw = 0;
  1177. for (int i = 0; i < 1024; i++)
  1178. {
  1179. uint32_t u = _micros();
  1180. bool res = card.card.readBlock(i, buff);
  1181. u = _micros() - u;
  1182. if (res)
  1183. {
  1184. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1185. sumr += u;
  1186. u = _micros();
  1187. res = card.card.writeBlock(i, buff);
  1188. u = _micros() - u;
  1189. if (res)
  1190. {
  1191. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1192. sumw += u;
  1193. }
  1194. else
  1195. {
  1196. printf_P(PSTR("writeBlock %4d error\n"), i);
  1197. break;
  1198. }
  1199. }
  1200. else
  1201. {
  1202. printf_P(PSTR("readBlock %4d error\n"), i);
  1203. break;
  1204. }
  1205. }
  1206. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1207. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1208. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1209. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1210. }
  1211. else
  1212. printf_P(PSTR("Card NG!\n"));
  1213. #endif //DEBUG_SD_SPEED_TEST
  1214. eeprom_init();
  1215. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1216. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1217. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1218. #if (LANG_MODE != 0) //secondary language support
  1219. #ifdef DEBUG_XFLASH
  1220. XFLASH_SPI_ENTER();
  1221. uint8_t uid[8]; // 64bit unique id
  1222. xflash_rd_uid(uid);
  1223. puts_P(_n("XFLASH UID="));
  1224. for (uint8_t i = 0; i < 8; i ++)
  1225. printf_P(PSTR("%02x"), uid[i]);
  1226. putchar('\n');
  1227. list_sec_lang_from_external_flash();
  1228. #endif //DEBUG_XFLASH
  1229. // lang_reset();
  1230. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1231. lcd_language();
  1232. #ifdef DEBUG_SEC_LANG
  1233. uint16_t sec_lang_code = lang_get_code(1);
  1234. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1235. 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);
  1236. lang_print_sec_lang(uartout);
  1237. #endif //DEBUG_SEC_LANG
  1238. #endif //(LANG_MODE != 0)
  1239. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  1240. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1241. }
  1242. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1243. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1244. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1245. int16_t z_shift = 0;
  1246. for (uint8_t i = 0; i < 5; i++) {
  1247. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  1248. }
  1249. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1250. }
  1251. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 255) {
  1252. eeprom_write_byte((uint8_t*)EEPROM_UVLO, 0);
  1253. }
  1254. if (eeprom_read_byte((uint8_t*)EEPROM_SD_SORT) == 255) {
  1255. eeprom_write_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1256. }
  1257. //mbl_mode_init();
  1258. mbl_settings_init();
  1259. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1260. if (SilentModeMenu_MMU == 255) {
  1261. SilentModeMenu_MMU = 1;
  1262. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1263. }
  1264. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1265. setup_fan_interrupt();
  1266. #endif //DEBUG_DISABLE_FANCHECK
  1267. #ifdef PAT9125
  1268. fsensor_setup_interrupt();
  1269. #endif //PAT9125
  1270. #ifndef DEBUG_DISABLE_STARTMSGS
  1271. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1272. if (!farm_mode) {
  1273. check_if_fw_is_on_right_printer();
  1274. show_fw_version_warnings();
  1275. }
  1276. switch (hw_changed) {
  1277. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1278. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1279. case(0b01):
  1280. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1281. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1282. break;
  1283. case(0b10):
  1284. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1285. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1286. break;
  1287. case(0b11):
  1288. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1289. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1290. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1291. break;
  1292. default: break; //no change, show no message
  1293. }
  1294. if (!previous_settings_retrieved) {
  1295. 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=6
  1296. Config_StoreSettings();
  1297. }
  1298. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) >= 1) {
  1299. lcd_wizard(WizState::Run);
  1300. }
  1301. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1302. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1303. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1304. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1305. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1306. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  1307. // Show the message.
  1308. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1309. }
  1310. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1311. // Show the message.
  1312. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1313. lcd_update_enable(true);
  1314. }
  1315. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == false) {
  1316. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1317. lcd_update_enable(true);
  1318. }
  1319. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1320. // Show the message.
  1321. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1322. }
  1323. }
  1324. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1325. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1326. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1327. update_current_firmware_version_to_eeprom();
  1328. lcd_selftest();
  1329. }
  1330. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1331. KEEPALIVE_STATE(IN_PROCESS);
  1332. #endif //DEBUG_DISABLE_STARTMSGS
  1333. lcd_update_enable(true);
  1334. lcd_clear();
  1335. lcd_update(2);
  1336. // Store the currently running firmware into an eeprom,
  1337. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1338. update_current_firmware_version_to_eeprom();
  1339. #ifdef TMC2130
  1340. tmc2130_home_origin[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN);
  1341. tmc2130_home_bsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS);
  1342. tmc2130_home_fsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS);
  1343. if (tmc2130_home_origin[X_AXIS] == 0xff) tmc2130_home_origin[X_AXIS] = 0;
  1344. if (tmc2130_home_bsteps[X_AXIS] == 0xff) tmc2130_home_bsteps[X_AXIS] = 48;
  1345. if (tmc2130_home_fsteps[X_AXIS] == 0xff) tmc2130_home_fsteps[X_AXIS] = 48;
  1346. tmc2130_home_origin[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN);
  1347. tmc2130_home_bsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS);
  1348. tmc2130_home_fsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS);
  1349. if (tmc2130_home_origin[Y_AXIS] == 0xff) tmc2130_home_origin[Y_AXIS] = 0;
  1350. if (tmc2130_home_bsteps[Y_AXIS] == 0xff) tmc2130_home_bsteps[Y_AXIS] = 48;
  1351. if (tmc2130_home_fsteps[Y_AXIS] == 0xff) tmc2130_home_fsteps[Y_AXIS] = 48;
  1352. tmc2130_home_enabled = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED);
  1353. if (tmc2130_home_enabled == 0xff) tmc2130_home_enabled = 0;
  1354. #endif //TMC2130
  1355. // report crash failures
  1356. fw_crash_init();
  1357. #ifdef UVLO_SUPPORT
  1358. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1359. /*
  1360. if (lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1361. else {
  1362. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1363. lcd_update_enable(true);
  1364. lcd_update(2);
  1365. lcd_setstatuspgm(MSG_WELCOME);
  1366. }
  1367. */
  1368. manage_heater(); // Update temperatures
  1369. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1370. 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));
  1371. #endif
  1372. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1373. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1374. puts_P(_N("Automatic recovery!"));
  1375. #endif
  1376. recover_print(1);
  1377. }
  1378. else{
  1379. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1380. puts_P(_N("Normal recovery!"));
  1381. #endif
  1382. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) ) recover_print(0);
  1383. else {
  1384. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1385. lcd_update_enable(true);
  1386. lcd_update(2);
  1387. lcd_setstatuspgm(MSG_WELCOME);
  1388. }
  1389. }
  1390. }
  1391. // Only arm the uvlo interrupt _after_ a recovering print has been initialized and
  1392. // the entire state machine initialized.
  1393. setup_uvlo_interrupt();
  1394. #endif //UVLO_SUPPORT
  1395. fCheckModeInit();
  1396. fSetMmuMode(mmu_enabled);
  1397. KEEPALIVE_STATE(NOT_BUSY);
  1398. #ifdef WATCHDOG
  1399. wdt_enable(WDTO_4S);
  1400. #ifdef EMERGENCY_HANDLERS
  1401. WDTCSR |= (1 << WDIE);
  1402. #endif //EMERGENCY_HANDLERS
  1403. #endif //WATCHDOG
  1404. }
  1405. static inline void crash_and_burn(dump_crash_reason reason)
  1406. {
  1407. WRITE(BEEPER, HIGH);
  1408. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, (uint8_t)reason);
  1409. #ifdef EMERGENCY_DUMP
  1410. xfdump_full_dump_and_reset(reason);
  1411. #elif defined(EMERGENCY_SERIAL_DUMP)
  1412. if(emergency_serial_dump)
  1413. serial_dump_and_reset(reason);
  1414. #endif
  1415. softReset();
  1416. }
  1417. #ifdef EMERGENCY_HANDLERS
  1418. #ifdef WATCHDOG
  1419. ISR(WDT_vect)
  1420. {
  1421. crash_and_burn(dump_crash_reason::watchdog);
  1422. }
  1423. #endif
  1424. ISR(BADISR_vect)
  1425. {
  1426. crash_and_burn(dump_crash_reason::bad_isr);
  1427. }
  1428. #endif //EMERGENCY_HANDLERS
  1429. void stack_error() {
  1430. crash_and_burn(dump_crash_reason::stack_error);
  1431. }
  1432. void pullup_error(bool fromTempISR) {
  1433. crash_and_burn(fromTempISR ? dump_crash_reason::bad_pullup_temp_isr : dump_crash_reason::bad_pullup_step_isr);
  1434. }
  1435. #ifdef PRUSA_M28
  1436. void trace();
  1437. #define CHUNK_SIZE 64 // bytes
  1438. #define SAFETY_MARGIN 1
  1439. char chunk[CHUNK_SIZE+SAFETY_MARGIN];
  1440. void serial_read_stream() {
  1441. setAllTargetHotends(0);
  1442. setTargetBed(0);
  1443. lcd_clear();
  1444. lcd_puts_P(PSTR(" Upload in progress"));
  1445. // first wait for how many bytes we will receive
  1446. uint32_t bytesToReceive;
  1447. // receive the four bytes
  1448. char bytesToReceiveBuffer[4];
  1449. for (int i=0; i<4; i++) {
  1450. int data;
  1451. while ((data = MYSERIAL.read()) == -1) {};
  1452. bytesToReceiveBuffer[i] = data;
  1453. }
  1454. // make it a uint32
  1455. memcpy(&bytesToReceive, &bytesToReceiveBuffer, 4);
  1456. // we're ready, notify the sender
  1457. MYSERIAL.write('+');
  1458. // lock in the routine
  1459. uint32_t receivedBytes = 0;
  1460. while (prusa_sd_card_upload) {
  1461. int i;
  1462. for (i=0; i<CHUNK_SIZE; i++) {
  1463. int data;
  1464. // check if we're not done
  1465. if (receivedBytes == bytesToReceive) {
  1466. break;
  1467. }
  1468. // read the next byte
  1469. while ((data = MYSERIAL.read()) == -1) {};
  1470. receivedBytes++;
  1471. // save it to the chunk
  1472. chunk[i] = data;
  1473. }
  1474. // write the chunk to SD
  1475. card.write_command_no_newline(&chunk[0]);
  1476. // notify the sender we're ready for more data
  1477. MYSERIAL.write('+');
  1478. // for safety
  1479. manage_heater();
  1480. // check if we're done
  1481. if(receivedBytes == bytesToReceive) {
  1482. trace(); // beep
  1483. card.closefile();
  1484. prusa_sd_card_upload = false;
  1485. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1486. }
  1487. }
  1488. }
  1489. #endif //PRUSA_M28
  1490. /**
  1491. * Output autoreport values according to features requested in M155
  1492. */
  1493. #if defined(AUTO_REPORT)
  1494. static void host_autoreport()
  1495. {
  1496. if (autoReportFeatures.TimerExpired())
  1497. {
  1498. if(autoReportFeatures.Temp()){
  1499. gcode_M105(active_extruder);
  1500. }
  1501. if(autoReportFeatures.Pos()){
  1502. gcode_M114();
  1503. }
  1504. #if defined(AUTO_REPORT) && (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  1505. if(autoReportFeatures.Fans()){
  1506. gcode_M123();
  1507. }
  1508. #endif //AUTO_REPORT and (FANCHECK and TACH_0 or TACH_1)
  1509. autoReportFeatures.TimerStart();
  1510. }
  1511. }
  1512. #endif //AUTO_REPORT
  1513. /**
  1514. * Output a "busy" message at regular intervals
  1515. * while the machine is not accepting commands.
  1516. */
  1517. void host_keepalive() {
  1518. #ifndef HOST_KEEPALIVE_FEATURE
  1519. return;
  1520. #endif //HOST_KEEPALIVE_FEATURE
  1521. if (farm_mode) return;
  1522. long ms = _millis();
  1523. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1524. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1525. switch (busy_state) {
  1526. case IN_HANDLER:
  1527. case IN_PROCESS:
  1528. SERIAL_ECHO_START;
  1529. SERIAL_ECHOLNPGM("busy: processing");
  1530. break;
  1531. case PAUSED_FOR_USER:
  1532. SERIAL_ECHO_START;
  1533. SERIAL_ECHOLNPGM("busy: paused for user");
  1534. break;
  1535. case PAUSED_FOR_INPUT:
  1536. SERIAL_ECHO_START;
  1537. SERIAL_ECHOLNPGM("busy: paused for input");
  1538. break;
  1539. default:
  1540. break;
  1541. }
  1542. }
  1543. prev_busy_signal_ms = ms;
  1544. }
  1545. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1546. // Before loop(), the setup() function is called by the main() routine.
  1547. void loop()
  1548. {
  1549. KEEPALIVE_STATE(NOT_BUSY);
  1550. if (isPrintPaused && saved_printing_type == PRINTING_TYPE_USB) { //keep believing that usb is being printed. Prevents accessing dangerous menus while pausing.
  1551. usb_timer.start();
  1552. }
  1553. else if (usb_timer.expired(10000)) { //just need to check if it expired. Nothing else is needed to be done.
  1554. ;
  1555. }
  1556. #ifdef FANCHECK
  1557. if (fan_check_error && isPrintPaused && !IS_SD_PRINTING) {
  1558. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1559. 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.
  1560. }
  1561. #endif
  1562. #ifdef PRUSA_M28
  1563. if (prusa_sd_card_upload)
  1564. {
  1565. //we read byte-by byte
  1566. serial_read_stream();
  1567. }
  1568. else
  1569. #endif
  1570. {
  1571. get_command();
  1572. #ifdef SDSUPPORT
  1573. card.checkautostart(false);
  1574. #endif
  1575. if(buflen)
  1576. {
  1577. cmdbuffer_front_already_processed = false;
  1578. #ifdef SDSUPPORT
  1579. if(card.saving)
  1580. {
  1581. // Saving a G-code file onto an SD-card is in progress.
  1582. // Saving starts with M28, saving until M29 is seen.
  1583. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1584. card.write_command(CMDBUFFER_CURRENT_STRING);
  1585. if(card.logging)
  1586. process_commands();
  1587. else
  1588. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1589. } else {
  1590. card.closefile();
  1591. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1592. }
  1593. } else {
  1594. process_commands();
  1595. }
  1596. #else
  1597. process_commands();
  1598. #endif //SDSUPPORT
  1599. if (! cmdbuffer_front_already_processed && buflen)
  1600. {
  1601. // ptr points to the start of the block currently being processed.
  1602. // The first character in the block is the block type.
  1603. char *ptr = cmdbuffer + bufindr;
  1604. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1605. // To support power panic, move the lenght of the command on the SD card to a planner buffer.
  1606. union {
  1607. struct {
  1608. char lo;
  1609. char hi;
  1610. } lohi;
  1611. uint16_t value;
  1612. } sdlen;
  1613. sdlen.value = 0;
  1614. {
  1615. // This block locks the interrupts globally for 3.25 us,
  1616. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1617. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1618. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1619. cli();
  1620. // Reset the command to something, which will be ignored by the power panic routine,
  1621. // so this buffer length will not be counted twice.
  1622. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1623. // Extract the current buffer length.
  1624. sdlen.lohi.lo = *ptr ++;
  1625. sdlen.lohi.hi = *ptr;
  1626. // and pass it to the planner queue.
  1627. planner_add_sd_length(sdlen.value);
  1628. sei();
  1629. }
  1630. }
  1631. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1632. cli();
  1633. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1634. // and one for each command to previous block in the planner queue.
  1635. planner_add_sd_length(1);
  1636. sei();
  1637. }
  1638. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1639. // this block's SD card length will not be counted twice as its command type has been replaced
  1640. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1641. cmdqueue_pop_front();
  1642. }
  1643. host_keepalive();
  1644. }
  1645. }
  1646. //check heater every n milliseconds
  1647. manage_heater();
  1648. isPrintPaused ? manage_inactivity(true) : manage_inactivity(false);
  1649. checkHitEndstops();
  1650. lcd_update(0);
  1651. #ifdef TMC2130
  1652. tmc2130_check_overtemp();
  1653. if (tmc2130_sg_crash)
  1654. {
  1655. uint8_t crash = tmc2130_sg_crash;
  1656. tmc2130_sg_crash = 0;
  1657. // crashdet_stop_and_save_print();
  1658. switch (crash)
  1659. {
  1660. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1661. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1662. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1663. }
  1664. }
  1665. #endif //TMC2130
  1666. mmu_loop();
  1667. }
  1668. #define DEFINE_PGM_READ_ANY(type, reader) \
  1669. static inline type pgm_read_any(const type *p) \
  1670. { return pgm_read_##reader##_near(p); }
  1671. DEFINE_PGM_READ_ANY(float, float);
  1672. DEFINE_PGM_READ_ANY(signed char, byte);
  1673. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1674. static const PROGMEM type array##_P[3] = \
  1675. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1676. static inline type array(uint8_t axis) \
  1677. { return pgm_read_any(&array##_P[axis]); } \
  1678. type array##_ext(uint8_t axis) \
  1679. { return pgm_read_any(&array##_P[axis]); }
  1680. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1681. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1682. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1683. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1684. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1685. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1686. static void axis_is_at_home(uint8_t axis) {
  1687. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1688. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1689. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1690. }
  1691. //! @return original feedmultiply
  1692. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1693. saved_feedrate = feedrate;
  1694. int l_feedmultiply = feedmultiply;
  1695. feedmultiply = 100;
  1696. previous_millis_cmd.start();
  1697. enable_endstops(enable_endstops_now);
  1698. return l_feedmultiply;
  1699. }
  1700. //! @param original_feedmultiply feedmultiply to restore
  1701. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1702. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1703. enable_endstops(false);
  1704. #endif
  1705. feedrate = saved_feedrate;
  1706. feedmultiply = original_feedmultiply;
  1707. previous_millis_cmd.start();
  1708. }
  1709. #ifdef ENABLE_AUTO_BED_LEVELING
  1710. #ifdef AUTO_BED_LEVELING_GRID
  1711. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1712. {
  1713. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1714. planeNormal.debug("planeNormal");
  1715. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1716. //bedLevel.debug("bedLevel");
  1717. //plan_bed_level_matrix.debug("bed level before");
  1718. //vector_3 uncorrected_position = plan_get_position_mm();
  1719. //uncorrected_position.debug("position before");
  1720. vector_3 corrected_position = plan_get_position();
  1721. // corrected_position.debug("position after");
  1722. current_position[X_AXIS] = corrected_position.x;
  1723. current_position[Y_AXIS] = corrected_position.y;
  1724. current_position[Z_AXIS] = corrected_position.z;
  1725. // put the bed at 0 so we don't go below it.
  1726. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1727. plan_set_position_curposXYZE();
  1728. }
  1729. #else // not AUTO_BED_LEVELING_GRID
  1730. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1731. plan_bed_level_matrix.set_to_identity();
  1732. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1733. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1734. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1735. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1736. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1737. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1738. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1739. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1740. vector_3 corrected_position = plan_get_position();
  1741. current_position[X_AXIS] = corrected_position.x;
  1742. current_position[Y_AXIS] = corrected_position.y;
  1743. current_position[Z_AXIS] = corrected_position.z;
  1744. // put the bed at 0 so we don't go below it.
  1745. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1746. plan_set_position_curposXYZE();
  1747. }
  1748. #endif // AUTO_BED_LEVELING_GRID
  1749. static void run_z_probe() {
  1750. plan_bed_level_matrix.set_to_identity();
  1751. feedrate = homing_feedrate[Z_AXIS];
  1752. // move down until you find the bed
  1753. float zPosition = -10;
  1754. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1755. st_synchronize();
  1756. // we have to let the planner know where we are right now as it is not where we said to go.
  1757. zPosition = st_get_position_mm(Z_AXIS);
  1758. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1759. // move up the retract distance
  1760. zPosition += home_retract_mm(Z_AXIS);
  1761. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1762. st_synchronize();
  1763. // move back down slowly to find bed
  1764. feedrate = homing_feedrate[Z_AXIS]/4;
  1765. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1766. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1767. st_synchronize();
  1768. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1769. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1770. plan_set_position_curposXYZE();
  1771. }
  1772. static void do_blocking_move_to(float x, float y, float z) {
  1773. float oldFeedRate = feedrate;
  1774. feedrate = homing_feedrate[Z_AXIS];
  1775. current_position[Z_AXIS] = z;
  1776. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1777. st_synchronize();
  1778. feedrate = XY_TRAVEL_SPEED;
  1779. current_position[X_AXIS] = x;
  1780. current_position[Y_AXIS] = y;
  1781. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1782. st_synchronize();
  1783. feedrate = oldFeedRate;
  1784. }
  1785. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1786. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1787. }
  1788. /// Probe bed height at position (x,y), returns the measured z value
  1789. static float probe_pt(float x, float y, float z_before) {
  1790. // move to right place
  1791. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1792. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1793. run_z_probe();
  1794. float measured_z = current_position[Z_AXIS];
  1795. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1796. SERIAL_PROTOCOLPGM(" x: ");
  1797. SERIAL_PROTOCOL(x);
  1798. SERIAL_PROTOCOLPGM(" y: ");
  1799. SERIAL_PROTOCOL(y);
  1800. SERIAL_PROTOCOLPGM(" z: ");
  1801. SERIAL_PROTOCOL(measured_z);
  1802. SERIAL_PROTOCOLPGM("\n");
  1803. return measured_z;
  1804. }
  1805. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1806. #ifdef LIN_ADVANCE
  1807. /**
  1808. * M900: Set and/or Get advance K factor
  1809. *
  1810. * K<factor> Set advance K factor
  1811. */
  1812. inline void gcode_M900() {
  1813. float newK = code_seen('K') ? code_value_float() : -2;
  1814. #ifdef LA_NOCOMPAT
  1815. if (newK >= 0 && newK < LA_K_MAX)
  1816. extruder_advance_K = newK;
  1817. else
  1818. SERIAL_ECHOLNPGM("K out of allowed range!");
  1819. #else
  1820. if (newK == 0)
  1821. {
  1822. extruder_advance_K = 0;
  1823. la10c_reset();
  1824. }
  1825. else
  1826. {
  1827. newK = la10c_value(newK);
  1828. if (newK < 0)
  1829. SERIAL_ECHOLNPGM("K out of allowed range!");
  1830. else
  1831. extruder_advance_K = newK;
  1832. }
  1833. #endif
  1834. SERIAL_ECHO_START;
  1835. SERIAL_ECHOPGM("Advance K=");
  1836. SERIAL_ECHOLN(extruder_advance_K);
  1837. }
  1838. #endif // LIN_ADVANCE
  1839. bool check_commands() {
  1840. bool end_command_found = false;
  1841. while (buflen)
  1842. {
  1843. if ((code_seen_P(PSTR("M84"))) || (code_seen_P(PSTR("M 84")))) end_command_found = true;
  1844. if (!cmdbuffer_front_already_processed)
  1845. cmdqueue_pop_front();
  1846. cmdbuffer_front_already_processed = false;
  1847. }
  1848. return end_command_found;
  1849. }
  1850. // raise_z_above: slowly raise Z to the requested height
  1851. //
  1852. // contrarily to a simple move, this function will carefully plan a move
  1853. // when the current Z position is unknown. In such cases, stallguard is
  1854. // enabled and will prevent prolonged pushing against the Z tops
  1855. void raise_z_above(float target, bool plan)
  1856. {
  1857. if (current_position[Z_AXIS] >= target)
  1858. return;
  1859. // Z needs raising
  1860. current_position[Z_AXIS] = target;
  1861. #if defined(Z_MIN_PIN) && (Z_MIN_PIN > -1) && !defined(DEBUG_DISABLE_ZMINLIMIT)
  1862. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1863. #else
  1864. bool z_min_endstop = false;
  1865. #endif
  1866. if (axis_known_position[Z_AXIS] || z_min_endstop)
  1867. {
  1868. // current position is known or very low, it's safe to raise Z
  1869. if(plan) plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1870. return;
  1871. }
  1872. // ensure Z is powered in normal mode to overcome initial load
  1873. enable_z();
  1874. st_synchronize();
  1875. // rely on crashguard to limit damage
  1876. bool z_endstop_enabled = enable_z_endstop(true);
  1877. #ifdef TMC2130
  1878. tmc2130_home_enter(Z_AXIS_MASK);
  1879. #endif //TMC2130
  1880. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  1881. st_synchronize();
  1882. #ifdef TMC2130
  1883. if (endstop_z_hit_on_purpose())
  1884. {
  1885. // not necessarily exact, but will avoid further vertical moves
  1886. current_position[Z_AXIS] = max_pos[Z_AXIS];
  1887. plan_set_position_curposXYZE();
  1888. }
  1889. tmc2130_home_exit();
  1890. #endif //TMC2130
  1891. enable_z_endstop(z_endstop_enabled);
  1892. }
  1893. #ifdef TMC2130
  1894. bool calibrate_z_auto()
  1895. {
  1896. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1897. lcd_clear();
  1898. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1899. bool endstops_enabled = enable_endstops(true);
  1900. int axis_up_dir = -home_dir(Z_AXIS);
  1901. tmc2130_home_enter(Z_AXIS_MASK);
  1902. current_position[Z_AXIS] = 0;
  1903. plan_set_position_curposXYZE();
  1904. set_destination_to_current();
  1905. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1906. feedrate = homing_feedrate[Z_AXIS];
  1907. plan_buffer_line_destinationXYZE(feedrate / 60);
  1908. st_synchronize();
  1909. // current_position[axis] = 0;
  1910. // plan_set_position_curposXYZE();
  1911. tmc2130_home_exit();
  1912. enable_endstops(false);
  1913. current_position[Z_AXIS] = 0;
  1914. plan_set_position_curposXYZE();
  1915. set_destination_to_current();
  1916. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1917. feedrate = homing_feedrate[Z_AXIS] / 2;
  1918. plan_buffer_line_destinationXYZE(feedrate / 60);
  1919. st_synchronize();
  1920. enable_endstops(endstops_enabled);
  1921. if (PRINTER_TYPE == PRINTER_MK3) {
  1922. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1923. }
  1924. else {
  1925. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1926. }
  1927. plan_set_position_curposXYZE();
  1928. return true;
  1929. }
  1930. #endif //TMC2130
  1931. #ifdef TMC2130
  1932. static void check_Z_crash(void)
  1933. {
  1934. if (READ(Z_TMC2130_DIAG) != 0) { //Z crash
  1935. FORCE_HIGH_POWER_END;
  1936. current_position[Z_AXIS] = 0;
  1937. plan_set_position_curposXYZE();
  1938. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  1939. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1940. st_synchronize();
  1941. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1942. }
  1943. }
  1944. #endif //TMC2130
  1945. #ifdef TMC2130
  1946. void homeaxis(uint8_t axis, uint8_t cnt, uint8_t* pstep)
  1947. #else
  1948. void homeaxis(uint8_t axis, uint8_t cnt)
  1949. #endif //TMC2130
  1950. {
  1951. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1952. #define HOMEAXIS_DO(LETTER) \
  1953. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1954. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1955. {
  1956. int axis_home_dir = home_dir(axis);
  1957. feedrate = homing_feedrate[axis];
  1958. #ifdef TMC2130
  1959. tmc2130_home_enter(X_AXIS_MASK << axis);
  1960. #endif //TMC2130
  1961. // Move away a bit, so that the print head does not touch the end position,
  1962. // and the following movement to endstop has a chance to achieve the required velocity
  1963. // for the stall guard to work.
  1964. current_position[axis] = 0;
  1965. plan_set_position_curposXYZE();
  1966. set_destination_to_current();
  1967. // destination[axis] = 11.f;
  1968. destination[axis] = -3.f * axis_home_dir;
  1969. plan_buffer_line_destinationXYZE(feedrate/60);
  1970. st_synchronize();
  1971. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1972. endstops_hit_on_purpose();
  1973. enable_endstops(false);
  1974. current_position[axis] = 0;
  1975. plan_set_position_curposXYZE();
  1976. destination[axis] = 1. * axis_home_dir;
  1977. plan_buffer_line_destinationXYZE(feedrate/60);
  1978. st_synchronize();
  1979. // Now continue to move up to the left end stop with the collision detection enabled.
  1980. enable_endstops(true);
  1981. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1982. plan_buffer_line_destinationXYZE(feedrate/60);
  1983. st_synchronize();
  1984. for (uint8_t i = 0; i < cnt; i++)
  1985. {
  1986. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1987. endstops_hit_on_purpose();
  1988. enable_endstops(false);
  1989. current_position[axis] = 0;
  1990. plan_set_position_curposXYZE();
  1991. destination[axis] = -10.f * axis_home_dir;
  1992. plan_buffer_line_destinationXYZE(feedrate/60);
  1993. st_synchronize();
  1994. endstops_hit_on_purpose();
  1995. // Now move left up to the collision, this time with a repeatable velocity.
  1996. enable_endstops(true);
  1997. destination[axis] = 11.f * axis_home_dir;
  1998. #ifdef TMC2130
  1999. feedrate = homing_feedrate[axis];
  2000. #else //TMC2130
  2001. feedrate = homing_feedrate[axis] / 2;
  2002. #endif //TMC2130
  2003. plan_buffer_line_destinationXYZE(feedrate/60);
  2004. st_synchronize();
  2005. #ifdef TMC2130
  2006. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  2007. if (pstep) pstep[i] = mscnt >> 4;
  2008. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  2009. #endif //TMC2130
  2010. }
  2011. endstops_hit_on_purpose();
  2012. enable_endstops(false);
  2013. #ifdef TMC2130
  2014. uint8_t orig = tmc2130_home_origin[axis];
  2015. uint8_t back = tmc2130_home_bsteps[axis];
  2016. if (tmc2130_home_enabled && (orig <= 63))
  2017. {
  2018. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  2019. if (back > 0)
  2020. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  2021. }
  2022. else
  2023. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  2024. tmc2130_home_exit();
  2025. #endif //TMC2130
  2026. axis_is_at_home(axis);
  2027. axis_known_position[axis] = true;
  2028. // Move from minimum
  2029. #ifdef TMC2130
  2030. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  2031. #else //TMC2130
  2032. float dist = - axis_home_dir * 0.01f * 64;
  2033. #endif //TMC2130
  2034. current_position[axis] -= dist;
  2035. plan_set_position_curposXYZE();
  2036. current_position[axis] += dist;
  2037. destination[axis] = current_position[axis];
  2038. plan_buffer_line_destinationXYZE(0.5f*feedrate/60);
  2039. st_synchronize();
  2040. feedrate = 0.0;
  2041. }
  2042. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  2043. {
  2044. #ifdef TMC2130
  2045. FORCE_HIGH_POWER_START;
  2046. #endif
  2047. int axis_home_dir = home_dir(axis);
  2048. current_position[axis] = 0;
  2049. plan_set_position_curposXYZE();
  2050. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  2051. feedrate = homing_feedrate[axis];
  2052. plan_buffer_line_destinationXYZE(feedrate/60);
  2053. st_synchronize();
  2054. #ifdef TMC2130
  2055. check_Z_crash();
  2056. #endif //TMC2130
  2057. current_position[axis] = 0;
  2058. plan_set_position_curposXYZE();
  2059. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  2060. plan_buffer_line_destinationXYZE(feedrate/60);
  2061. st_synchronize();
  2062. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  2063. feedrate = homing_feedrate[axis]/2 ;
  2064. plan_buffer_line_destinationXYZE(feedrate/60);
  2065. st_synchronize();
  2066. #ifdef TMC2130
  2067. check_Z_crash();
  2068. #endif //TMC2130
  2069. axis_is_at_home(axis);
  2070. destination[axis] = current_position[axis];
  2071. feedrate = 0.0;
  2072. endstops_hit_on_purpose();
  2073. axis_known_position[axis] = true;
  2074. #ifdef TMC2130
  2075. FORCE_HIGH_POWER_END;
  2076. #endif
  2077. }
  2078. enable_endstops(endstops_enabled);
  2079. }
  2080. /**/
  2081. void home_xy()
  2082. {
  2083. set_destination_to_current();
  2084. homeaxis(X_AXIS);
  2085. homeaxis(Y_AXIS);
  2086. plan_set_position_curposXYZE();
  2087. endstops_hit_on_purpose();
  2088. }
  2089. void refresh_cmd_timeout(void)
  2090. {
  2091. previous_millis_cmd.start();
  2092. }
  2093. #ifdef FWRETRACT
  2094. void retract(bool retracting, bool swapretract = false) {
  2095. // Perform FW retraction, just if needed, but behave as if the move has never took place in
  2096. // order to keep E/Z coordinates unchanged. This is done by manipulating the internal planner
  2097. // position, which requires a sync
  2098. if(retracting && !retracted[active_extruder]) {
  2099. st_synchronize();
  2100. set_destination_to_current();
  2101. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  2102. plan_set_e_position(current_position[E_AXIS]);
  2103. float oldFeedrate = feedrate;
  2104. feedrate=cs.retract_feedrate*60;
  2105. retracted[active_extruder]=true;
  2106. prepare_move();
  2107. if(cs.retract_zlift) {
  2108. st_synchronize();
  2109. current_position[Z_AXIS]-=cs.retract_zlift;
  2110. plan_set_position_curposXYZE();
  2111. prepare_move();
  2112. }
  2113. feedrate = oldFeedrate;
  2114. } else if(!retracting && retracted[active_extruder]) {
  2115. st_synchronize();
  2116. set_destination_to_current();
  2117. float oldFeedrate = feedrate;
  2118. feedrate=cs.retract_recover_feedrate*60;
  2119. if(cs.retract_zlift) {
  2120. current_position[Z_AXIS]+=cs.retract_zlift;
  2121. plan_set_position_curposXYZE();
  2122. prepare_move();
  2123. st_synchronize();
  2124. }
  2125. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  2126. plan_set_e_position(current_position[E_AXIS]);
  2127. retracted[active_extruder]=false;
  2128. prepare_move();
  2129. feedrate = oldFeedrate;
  2130. }
  2131. } //retract
  2132. #endif //FWRETRACT
  2133. #ifdef PRUSA_M28
  2134. void trace() {
  2135. Sound_MakeCustom(25,440,true);
  2136. }
  2137. #endif
  2138. /*
  2139. void ramming() {
  2140. // float tmp[4] = DEFAULT_MAX_FEEDRATE;
  2141. if (current_temperature[0] < 230) {
  2142. //PLA
  2143. max_feedrate[E_AXIS] = 50;
  2144. //current_position[E_AXIS] -= 8;
  2145. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2146. //current_position[E_AXIS] += 8;
  2147. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2148. current_position[E_AXIS] += 5.4;
  2149. plan_buffer_line_curposXYZE(2800 / 60, active_extruder);
  2150. current_position[E_AXIS] += 3.2;
  2151. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  2152. current_position[E_AXIS] += 3;
  2153. plan_buffer_line_curposXYZE(3400 / 60, active_extruder);
  2154. st_synchronize();
  2155. max_feedrate[E_AXIS] = 80;
  2156. current_position[E_AXIS] -= 82;
  2157. plan_buffer_line_curposXYZE(9500 / 60, active_extruder);
  2158. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  2159. current_position[E_AXIS] -= 20;
  2160. plan_buffer_line_curposXYZE(1200 / 60, active_extruder);
  2161. current_position[E_AXIS] += 5;
  2162. plan_buffer_line_curposXYZE(400 / 60, active_extruder);
  2163. current_position[E_AXIS] += 5;
  2164. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2165. current_position[E_AXIS] -= 10;
  2166. st_synchronize();
  2167. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2168. current_position[E_AXIS] += 10;
  2169. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2170. current_position[E_AXIS] -= 10;
  2171. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2172. current_position[E_AXIS] += 10;
  2173. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2174. current_position[E_AXIS] -= 10;
  2175. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2176. st_synchronize();
  2177. }
  2178. else {
  2179. //ABS
  2180. max_feedrate[E_AXIS] = 50;
  2181. //current_position[E_AXIS] -= 8;
  2182. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2183. //current_position[E_AXIS] += 8;
  2184. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2185. current_position[E_AXIS] += 3.1;
  2186. plan_buffer_line_curposXYZE(2000 / 60, active_extruder);
  2187. current_position[E_AXIS] += 3.1;
  2188. plan_buffer_line_curposXYZE(2500 / 60, active_extruder);
  2189. current_position[E_AXIS] += 4;
  2190. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  2191. st_synchronize();
  2192. //current_position[X_AXIS] += 23; //delay
  2193. //plan_buffer_line_curposXYZE(600/60, active_extruder); //delay
  2194. //current_position[X_AXIS] -= 23; //delay
  2195. //plan_buffer_line_curposXYZE(600/60, active_extruder); //delay
  2196. _delay(4700);
  2197. max_feedrate[E_AXIS] = 80;
  2198. current_position[E_AXIS] -= 92;
  2199. plan_buffer_line_curposXYZE(9900 / 60, active_extruder);
  2200. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  2201. current_position[E_AXIS] -= 5;
  2202. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2203. current_position[E_AXIS] += 5;
  2204. plan_buffer_line_curposXYZE(400 / 60, active_extruder);
  2205. current_position[E_AXIS] -= 5;
  2206. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2207. st_synchronize();
  2208. current_position[E_AXIS] += 5;
  2209. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2210. current_position[E_AXIS] -= 5;
  2211. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2212. current_position[E_AXIS] += 5;
  2213. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2214. current_position[E_AXIS] -= 5;
  2215. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2216. st_synchronize();
  2217. }
  2218. }
  2219. */
  2220. #ifdef TMC2130
  2221. void force_high_power_mode(bool start_high_power_section) {
  2222. #ifdef PSU_Delta
  2223. if (start_high_power_section == true) enable_force_z();
  2224. #endif //PSU_Delta
  2225. uint8_t silent;
  2226. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2227. if (silent == 1) {
  2228. //we are in silent mode, set to normal mode to enable crash detection
  2229. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2230. st_synchronize();
  2231. cli();
  2232. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2233. update_mode_profile();
  2234. tmc2130_init(TMCInitParams(FarmOrUserECool()));
  2235. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2236. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2237. st_reset_timer();
  2238. sei();
  2239. }
  2240. }
  2241. #endif //TMC2130
  2242. void gcode_M105(uint8_t extruder)
  2243. {
  2244. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  2245. SERIAL_PROTOCOLPGM("T:");
  2246. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  2247. SERIAL_PROTOCOLPGM(" /");
  2248. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  2249. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2250. SERIAL_PROTOCOLPGM(" B:");
  2251. SERIAL_PROTOCOL_F(degBed(),1);
  2252. SERIAL_PROTOCOLPGM(" /");
  2253. SERIAL_PROTOCOL_F(degTargetBed(),1);
  2254. #endif //TEMP_BED_PIN
  2255. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2256. SERIAL_PROTOCOLPGM(" T");
  2257. SERIAL_PROTOCOL(cur_extruder);
  2258. SERIAL_PROTOCOL(':');
  2259. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2260. SERIAL_PROTOCOLPGM(" /");
  2261. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  2262. }
  2263. #else
  2264. SERIAL_ERROR_START;
  2265. SERIAL_ERRORLNRPGM(_i("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  2266. #endif
  2267. SERIAL_PROTOCOLPGM(" @:");
  2268. #ifdef EXTRUDER_WATTS
  2269. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  2270. SERIAL_PROTOCOLPGM("W");
  2271. #else
  2272. SERIAL_PROTOCOL(getHeaterPower(extruder));
  2273. #endif
  2274. SERIAL_PROTOCOLPGM(" B@:");
  2275. #ifdef BED_WATTS
  2276. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  2277. SERIAL_PROTOCOLPGM("W");
  2278. #else
  2279. SERIAL_PROTOCOL(getHeaterPower(-1));
  2280. #endif
  2281. #ifdef PINDA_THERMISTOR
  2282. SERIAL_PROTOCOLPGM(" P:");
  2283. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  2284. #endif //PINDA_THERMISTOR
  2285. #ifdef AMBIENT_THERMISTOR
  2286. SERIAL_PROTOCOLPGM(" A:");
  2287. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  2288. #endif //AMBIENT_THERMISTOR
  2289. #ifdef SHOW_TEMP_ADC_VALUES
  2290. {
  2291. float raw = 0.0;
  2292. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2293. SERIAL_PROTOCOLPGM(" ADC B:");
  2294. SERIAL_PROTOCOL_F(degBed(),1);
  2295. SERIAL_PROTOCOLPGM("C->");
  2296. raw = rawBedTemp();
  2297. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2298. SERIAL_PROTOCOLPGM(" Rb->");
  2299. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2300. SERIAL_PROTOCOLPGM(" Rxb->");
  2301. SERIAL_PROTOCOL_F(raw, 5);
  2302. #endif
  2303. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2304. SERIAL_PROTOCOLPGM(" T");
  2305. SERIAL_PROTOCOL(cur_extruder);
  2306. SERIAL_PROTOCOLPGM(":");
  2307. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2308. SERIAL_PROTOCOLPGM("C->");
  2309. raw = rawHotendTemp(cur_extruder);
  2310. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2311. SERIAL_PROTOCOLPGM(" Rt");
  2312. SERIAL_PROTOCOL(cur_extruder);
  2313. SERIAL_PROTOCOLPGM("->");
  2314. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2315. SERIAL_PROTOCOLPGM(" Rx");
  2316. SERIAL_PROTOCOL(cur_extruder);
  2317. SERIAL_PROTOCOLPGM("->");
  2318. SERIAL_PROTOCOL_F(raw, 5);
  2319. }
  2320. }
  2321. #endif
  2322. SERIAL_PROTOCOLLN();
  2323. }
  2324. #ifdef TMC2130
  2325. 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)
  2326. #else
  2327. 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)
  2328. #endif //TMC2130
  2329. {
  2330. // Flag for the display update routine and to disable the print cancelation during homing.
  2331. st_synchronize();
  2332. homing_flag = true;
  2333. #if 0
  2334. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2335. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2336. #endif
  2337. // Which axes should be homed?
  2338. bool home_x = home_x_axis;
  2339. bool home_y = home_y_axis;
  2340. bool home_z = home_z_axis;
  2341. // Either all X,Y,Z codes are present, or none of them.
  2342. bool home_all_axes = home_x == home_y && home_x == home_z;
  2343. if (home_all_axes)
  2344. // No X/Y/Z code provided means to home all axes.
  2345. home_x = home_y = home_z = true;
  2346. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2347. if (home_all_axes) {
  2348. raise_z_above(MESH_HOME_Z_SEARCH);
  2349. st_synchronize();
  2350. }
  2351. #ifdef ENABLE_AUTO_BED_LEVELING
  2352. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2353. #endif //ENABLE_AUTO_BED_LEVELING
  2354. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2355. // the planner will not perform any adjustments in the XY plane.
  2356. // Wait for the motors to stop and update the current position with the absolute values.
  2357. world2machine_revert_to_uncorrected();
  2358. // For mesh bed leveling deactivate the matrix temporarily.
  2359. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2360. // in a single axis only.
  2361. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2362. #ifdef MESH_BED_LEVELING
  2363. uint8_t mbl_was_active = mbl.active;
  2364. mbl.active = 0;
  2365. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2366. #endif
  2367. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2368. if (home_z)
  2369. babystep_undo();
  2370. int l_feedmultiply = setup_for_endstop_move();
  2371. set_destination_to_current();
  2372. feedrate = 0.0;
  2373. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2374. if(home_z)
  2375. homeaxis(Z_AXIS);
  2376. #endif
  2377. #ifdef QUICK_HOME
  2378. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2379. if(home_x && home_y) //first diagonal move
  2380. {
  2381. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2382. uint8_t x_axis_home_dir = home_dir(X_AXIS);
  2383. plan_set_position_curposXYZE();
  2384. 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);
  2385. feedrate = homing_feedrate[X_AXIS];
  2386. if(homing_feedrate[Y_AXIS]<feedrate)
  2387. feedrate = homing_feedrate[Y_AXIS];
  2388. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2389. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2390. } else {
  2391. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2392. }
  2393. plan_buffer_line_destinationXYZE(feedrate/60);
  2394. st_synchronize();
  2395. axis_is_at_home(X_AXIS);
  2396. axis_is_at_home(Y_AXIS);
  2397. plan_set_position_curposXYZE();
  2398. destination[X_AXIS] = current_position[X_AXIS];
  2399. destination[Y_AXIS] = current_position[Y_AXIS];
  2400. plan_buffer_line_destinationXYZE(feedrate/60);
  2401. feedrate = 0.0;
  2402. st_synchronize();
  2403. endstops_hit_on_purpose();
  2404. current_position[X_AXIS] = destination[X_AXIS];
  2405. current_position[Y_AXIS] = destination[Y_AXIS];
  2406. current_position[Z_AXIS] = destination[Z_AXIS];
  2407. }
  2408. #endif /* QUICK_HOME */
  2409. #ifdef TMC2130
  2410. if(home_x)
  2411. {
  2412. if (!calib)
  2413. homeaxis(X_AXIS);
  2414. else
  2415. tmc2130_home_calibrate(X_AXIS);
  2416. }
  2417. if(home_y)
  2418. {
  2419. if (!calib)
  2420. homeaxis(Y_AXIS);
  2421. else
  2422. tmc2130_home_calibrate(Y_AXIS);
  2423. }
  2424. #else //TMC2130
  2425. if(home_x) homeaxis(X_AXIS);
  2426. if(home_y) homeaxis(Y_AXIS);
  2427. #endif //TMC2130
  2428. if(home_x_axis && home_x_value != 0)
  2429. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2430. if(home_y_axis && home_y_value != 0)
  2431. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2432. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2433. #ifndef Z_SAFE_HOMING
  2434. if(home_z) {
  2435. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2436. raise_z_above(Z_RAISE_BEFORE_HOMING);
  2437. st_synchronize();
  2438. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2439. #ifdef MESH_BED_LEVELING // If Mesh bed leveling, move X&Y to safe position for home
  2440. raise_z_above(MESH_HOME_Z_SEARCH);
  2441. st_synchronize();
  2442. if (!axis_known_position[X_AXIS]) homeaxis(X_AXIS);
  2443. if (!axis_known_position[Y_AXIS]) homeaxis(Y_AXIS);
  2444. // 1st mesh bed leveling measurement point, corrected.
  2445. world2machine_initialize();
  2446. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2447. world2machine_reset();
  2448. if (destination[Y_AXIS] < Y_MIN_POS)
  2449. destination[Y_AXIS] = Y_MIN_POS;
  2450. feedrate = homing_feedrate[X_AXIS] / 20;
  2451. enable_endstops(false);
  2452. #ifdef DEBUG_BUILD
  2453. SERIAL_ECHOLNPGM("plan_set_position()");
  2454. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2455. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2456. #endif
  2457. plan_set_position_curposXYZE();
  2458. #ifdef DEBUG_BUILD
  2459. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2460. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2461. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2462. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2463. #endif
  2464. plan_buffer_line_destinationXYZE(feedrate);
  2465. st_synchronize();
  2466. current_position[X_AXIS] = destination[X_AXIS];
  2467. current_position[Y_AXIS] = destination[Y_AXIS];
  2468. enable_endstops(true);
  2469. endstops_hit_on_purpose();
  2470. homeaxis(Z_AXIS);
  2471. #else // MESH_BED_LEVELING
  2472. homeaxis(Z_AXIS);
  2473. #endif // MESH_BED_LEVELING
  2474. }
  2475. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2476. if(home_all_axes) {
  2477. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2478. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2479. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2480. feedrate = XY_TRAVEL_SPEED/60;
  2481. current_position[Z_AXIS] = 0;
  2482. plan_set_position_curposXYZE();
  2483. plan_buffer_line_destinationXYZE(feedrate);
  2484. st_synchronize();
  2485. current_position[X_AXIS] = destination[X_AXIS];
  2486. current_position[Y_AXIS] = destination[Y_AXIS];
  2487. homeaxis(Z_AXIS);
  2488. }
  2489. // Let's see if X and Y are homed and probe is inside bed area.
  2490. if(home_z) {
  2491. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2492. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2493. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2494. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2495. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2496. current_position[Z_AXIS] = 0;
  2497. plan_set_position_curposXYZE();
  2498. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2499. feedrate = max_feedrate[Z_AXIS];
  2500. plan_buffer_line_destinationXYZE(feedrate);
  2501. st_synchronize();
  2502. homeaxis(Z_AXIS);
  2503. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2504. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2505. SERIAL_ECHO_START;
  2506. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2507. } else {
  2508. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2509. SERIAL_ECHO_START;
  2510. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2511. }
  2512. }
  2513. #endif // Z_SAFE_HOMING
  2514. #endif // Z_HOME_DIR < 0
  2515. if(home_z_axis && home_z_value != 0)
  2516. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2517. #ifdef ENABLE_AUTO_BED_LEVELING
  2518. if(home_z)
  2519. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2520. #endif
  2521. // Set the planner and stepper routine positions.
  2522. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2523. // contains the machine coordinates.
  2524. plan_set_position_curposXYZE();
  2525. clean_up_after_endstop_move(l_feedmultiply);
  2526. endstops_hit_on_purpose();
  2527. #ifndef MESH_BED_LEVELING
  2528. //-// Oct 2019 :: this part of code is (from) now probably un-compilable
  2529. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  2530. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  2531. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  2532. lcd_adjust_z();
  2533. #endif
  2534. // Load the machine correction matrix
  2535. world2machine_initialize();
  2536. // and correct the current_position XY axes to match the transformed coordinate system.
  2537. world2machine_update_current();
  2538. #ifdef MESH_BED_LEVELING
  2539. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2540. {
  2541. if (! home_z && mbl_was_active) {
  2542. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2543. mbl.active = true;
  2544. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2545. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2546. }
  2547. }
  2548. #endif
  2549. if (farm_mode) { prusa_statistics(20); };
  2550. st_synchronize();
  2551. homing_flag = false;
  2552. #if 0
  2553. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2554. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2555. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2556. #endif
  2557. }
  2558. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2559. {
  2560. #ifdef TMC2130
  2561. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2562. #else
  2563. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2564. #endif //TMC2130
  2565. }
  2566. // G80 - Automatic mesh bed leveling
  2567. static void gcode_G80()
  2568. {
  2569. st_synchronize();
  2570. if (waiting_inside_plan_buffer_line_print_aborted)
  2571. return;
  2572. mesh_bed_leveling_flag = true;
  2573. #ifndef PINDA_THERMISTOR
  2574. static bool run = false; // thermistor-less PINDA temperature compensation is running
  2575. #endif // ndef PINDA_THERMISTOR
  2576. #ifdef SUPPORT_VERBOSITY
  2577. int8_t verbosity_level = 0;
  2578. if (code_seen('V')) {
  2579. // Just 'V' without a number counts as V1.
  2580. char c = strchr_pointer[1];
  2581. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  2582. }
  2583. #endif //SUPPORT_VERBOSITY
  2584. // Firstly check if we know where we are
  2585. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2586. // We don't know where we are! HOME!
  2587. // Push the commands to the front of the message queue in the reverse order!
  2588. // There shall be always enough space reserved for these commands.
  2589. repeatcommand_front(); // repeat G80 with all its parameters
  2590. enquecommand_front_P(G28W0);
  2591. return;
  2592. }
  2593. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  2594. if (code_seen('N')) {
  2595. nMeasPoints = code_value_uint8();
  2596. if (nMeasPoints != 7) {
  2597. nMeasPoints = 3;
  2598. }
  2599. }
  2600. else {
  2601. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  2602. }
  2603. uint8_t nProbeRetry = 3;
  2604. if (code_seen('R')) {
  2605. nProbeRetry = code_value_uint8();
  2606. if (nProbeRetry > 10) {
  2607. nProbeRetry = 10;
  2608. }
  2609. }
  2610. else {
  2611. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  2612. }
  2613. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  2614. #ifndef PINDA_THERMISTOR
  2615. if (run == false && eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true && target_temperature_bed >= 50)
  2616. {
  2617. temp_compensation_start();
  2618. run = true;
  2619. repeatcommand_front(); // repeat G80 with all its parameters
  2620. enquecommand_front_P(G28W0);
  2621. break;
  2622. }
  2623. run = false;
  2624. #endif //PINDA_THERMISTOR
  2625. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  2626. CustomMsg custom_message_type_old = custom_message_type;
  2627. uint8_t custom_message_state_old = custom_message_state;
  2628. custom_message_type = CustomMsg::MeshBedLeveling;
  2629. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  2630. lcd_update(1);
  2631. mbl.reset(); //reset mesh bed leveling
  2632. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2633. babystep_undo();
  2634. // Cycle through all points and probe them
  2635. // First move up. During this first movement, the babystepping will be reverted.
  2636. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2637. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  2638. // The move to the first calibration point.
  2639. current_position[X_AXIS] = BED_X0;
  2640. current_position[Y_AXIS] = BED_Y0;
  2641. #ifdef SUPPORT_VERBOSITY
  2642. if (verbosity_level >= 1)
  2643. {
  2644. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2645. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  2646. }
  2647. #else //SUPPORT_VERBOSITY
  2648. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2649. #endif //SUPPORT_VERBOSITY
  2650. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  2651. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2652. // Wait until the move is finished.
  2653. st_synchronize();
  2654. if (waiting_inside_plan_buffer_line_print_aborted)
  2655. {
  2656. custom_message_type = custom_message_type_old;
  2657. custom_message_state = custom_message_state_old;
  2658. return;
  2659. }
  2660. uint8_t mesh_point = 0; //index number of calibration point
  2661. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  2662. 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)
  2663. #ifdef SUPPORT_VERBOSITY
  2664. if (verbosity_level >= 1) {
  2665. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  2666. }
  2667. #endif // SUPPORT_VERBOSITY
  2668. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  2669. while (mesh_point != nMeasPoints * nMeasPoints) {
  2670. // Get coords of a measuring point.
  2671. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  2672. uint8_t iy = mesh_point / nMeasPoints;
  2673. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  2674. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  2675. custom_message_state--;
  2676. mesh_point++;
  2677. continue; //skip
  2678. }*/
  2679. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  2680. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  2681. {
  2682. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  2683. }
  2684. float z0 = 0.f;
  2685. if (has_z && (mesh_point > 0)) {
  2686. uint16_t z_offset_u = 0;
  2687. if (nMeasPoints == 7) {
  2688. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  2689. }
  2690. else {
  2691. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  2692. }
  2693. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  2694. #ifdef SUPPORT_VERBOSITY
  2695. if (verbosity_level >= 1) {
  2696. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  2697. }
  2698. #endif // SUPPORT_VERBOSITY
  2699. }
  2700. // Move Z up to MESH_HOME_Z_SEARCH.
  2701. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2702. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  2703. float init_z_bckp = current_position[Z_AXIS];
  2704. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2705. st_synchronize();
  2706. // Move to XY position of the sensor point.
  2707. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  2708. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  2709. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2710. #ifdef SUPPORT_VERBOSITY
  2711. if (verbosity_level >= 1) {
  2712. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2713. SERIAL_PROTOCOL(mesh_point);
  2714. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  2715. }
  2716. #else //SUPPORT_VERBOSITY
  2717. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2718. #endif // SUPPORT_VERBOSITY
  2719. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2720. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2721. st_synchronize();
  2722. if (waiting_inside_plan_buffer_line_print_aborted)
  2723. {
  2724. custom_message_type = custom_message_type_old;
  2725. custom_message_state = custom_message_state_old;
  2726. return;
  2727. }
  2728. // Go down until endstop is hit
  2729. const float Z_CALIBRATION_THRESHOLD = 1.f;
  2730. 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
  2731. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2732. break;
  2733. }
  2734. 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.
  2735. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  2736. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2737. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2738. st_synchronize();
  2739. 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
  2740. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2741. break;
  2742. }
  2743. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  2744. puts_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken."));
  2745. break;
  2746. }
  2747. }
  2748. 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
  2749. puts_P(PSTR("Bed leveling failed. Sensor triggered too high."));
  2750. break;
  2751. }
  2752. #ifdef SUPPORT_VERBOSITY
  2753. if (verbosity_level >= 10) {
  2754. SERIAL_ECHOPGM("X: ");
  2755. MYSERIAL.print(current_position[X_AXIS], 5);
  2756. SERIAL_ECHOLNPGM("");
  2757. SERIAL_ECHOPGM("Y: ");
  2758. MYSERIAL.print(current_position[Y_AXIS], 5);
  2759. SERIAL_PROTOCOLPGM("\n");
  2760. }
  2761. #endif // SUPPORT_VERBOSITY
  2762. float offset_z = 0;
  2763. #ifdef PINDA_THERMISTOR
  2764. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  2765. #endif //PINDA_THERMISTOR
  2766. // #ifdef SUPPORT_VERBOSITY
  2767. /* if (verbosity_level >= 1)
  2768. {
  2769. SERIAL_ECHOPGM("mesh bed leveling: ");
  2770. MYSERIAL.print(current_position[Z_AXIS], 5);
  2771. SERIAL_ECHOPGM(" offset: ");
  2772. MYSERIAL.print(offset_z, 5);
  2773. SERIAL_ECHOLNPGM("");
  2774. }*/
  2775. // #endif // SUPPORT_VERBOSITY
  2776. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  2777. custom_message_state--;
  2778. mesh_point++;
  2779. lcd_update(1);
  2780. }
  2781. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2782. #ifdef SUPPORT_VERBOSITY
  2783. if (verbosity_level >= 20) {
  2784. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  2785. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  2786. MYSERIAL.print(current_position[Z_AXIS], 5);
  2787. }
  2788. #endif // SUPPORT_VERBOSITY
  2789. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2790. st_synchronize();
  2791. if (mesh_point != nMeasPoints * nMeasPoints) {
  2792. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  2793. bool bState;
  2794. do { // repeat until Z-leveling o.k.
  2795. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ...")); ////MSG_ZLEVELING_ENFORCED c=20 r=4
  2796. #ifdef TMC2130
  2797. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  2798. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  2799. #else // TMC2130
  2800. lcd_wait_for_click_delay(0); // ~ no timeout
  2801. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  2802. #endif // TMC2130
  2803. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  2804. bState=enable_z_endstop(false);
  2805. current_position[Z_AXIS] -= 1;
  2806. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2807. st_synchronize();
  2808. enable_z_endstop(true);
  2809. #ifdef TMC2130
  2810. tmc2130_home_enter(Z_AXIS_MASK);
  2811. #endif // TMC2130
  2812. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2813. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2814. st_synchronize();
  2815. #ifdef TMC2130
  2816. tmc2130_home_exit();
  2817. #endif // TMC2130
  2818. enable_z_endstop(bState);
  2819. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  2820. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  2821. custom_message_type = custom_message_type_old;
  2822. custom_message_state = custom_message_state_old;
  2823. lcd_update_enable(true); // display / status-line recovery
  2824. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  2825. repeatcommand_front(); // re-run (i.e. of "G80")
  2826. return;
  2827. }
  2828. clean_up_after_endstop_move(l_feedmultiply);
  2829. // SERIAL_ECHOLNPGM("clean up finished ");
  2830. #ifndef PINDA_THERMISTOR
  2831. if(eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  2832. #endif
  2833. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  2834. // SERIAL_ECHOLNPGM("babystep applied");
  2835. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  2836. #ifdef SUPPORT_VERBOSITY
  2837. if (verbosity_level >= 1) {
  2838. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  2839. }
  2840. #endif // SUPPORT_VERBOSITY
  2841. for (uint8_t i = 0; i < 4; ++i) {
  2842. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  2843. long correction = 0;
  2844. if (code_seen(codes[i]))
  2845. correction = code_value_long();
  2846. else if (eeprom_bed_correction_valid) {
  2847. unsigned char *addr = (i < 2) ?
  2848. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  2849. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  2850. correction = eeprom_read_int8(addr);
  2851. }
  2852. if (correction == 0)
  2853. continue;
  2854. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  2855. SERIAL_ERROR_START;
  2856. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  2857. SERIAL_ECHO(correction);
  2858. SERIAL_ECHOLNPGM(" microns");
  2859. }
  2860. else {
  2861. float offset = float(correction) * 0.001f;
  2862. switch (i) {
  2863. case 0:
  2864. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2865. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  2866. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  2867. }
  2868. }
  2869. break;
  2870. case 1:
  2871. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2872. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  2873. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  2874. }
  2875. }
  2876. break;
  2877. case 2:
  2878. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2879. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2880. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  2881. }
  2882. }
  2883. break;
  2884. case 3:
  2885. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2886. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  2887. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  2888. }
  2889. }
  2890. break;
  2891. }
  2892. }
  2893. }
  2894. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  2895. if (nMeasPoints == 3) {
  2896. 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)
  2897. }
  2898. /*
  2899. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2900. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2901. SERIAL_PROTOCOLPGM(",");
  2902. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2903. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2904. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2905. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2906. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2907. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2908. SERIAL_PROTOCOLPGM(" ");
  2909. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2910. }
  2911. SERIAL_PROTOCOLPGM("\n");
  2912. }
  2913. */
  2914. if (nMeasPoints == 7 && magnet_elimination) {
  2915. mbl_interpolation(nMeasPoints);
  2916. }
  2917. /*
  2918. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2919. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2920. SERIAL_PROTOCOLPGM(",");
  2921. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2922. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2923. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2924. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2925. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2926. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2927. SERIAL_PROTOCOLPGM(" ");
  2928. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2929. }
  2930. SERIAL_PROTOCOLPGM("\n");
  2931. }
  2932. */
  2933. // SERIAL_ECHOLNPGM("Upsample finished");
  2934. mbl.active = 1; //activate mesh bed leveling
  2935. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  2936. go_home_with_z_lift();
  2937. // SERIAL_ECHOLNPGM("Go home finished");
  2938. //unretract (after PINDA preheat retraction)
  2939. if (((int)degHotend(active_extruder) > extrude_min_temp) && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() && (target_temperature_bed >= 50)) {
  2940. current_position[E_AXIS] += default_retraction;
  2941. plan_buffer_line_curposXYZE(400);
  2942. }
  2943. KEEPALIVE_STATE(NOT_BUSY);
  2944. // Restore custom message state
  2945. lcd_setstatuspgm(MSG_WELCOME);
  2946. custom_message_type = custom_message_type_old;
  2947. custom_message_state = custom_message_state_old;
  2948. lcd_update(2);
  2949. st_synchronize();
  2950. mesh_bed_leveling_flag = false;
  2951. }
  2952. void adjust_bed_reset()
  2953. {
  2954. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2955. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2956. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2957. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2958. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2959. }
  2960. //! @brief Calibrate XYZ
  2961. //! @param onlyZ if true, calibrate only Z axis
  2962. //! @param verbosity_level
  2963. //! @retval true Succeeded
  2964. //! @retval false Failed
  2965. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2966. {
  2967. bool final_result = false;
  2968. #ifdef TMC2130
  2969. FORCE_HIGH_POWER_START;
  2970. #endif // TMC2130
  2971. FORCE_BL_ON_START;
  2972. // Only Z calibration?
  2973. if (!onlyZ)
  2974. {
  2975. setTargetBed(0);
  2976. setAllTargetHotends(0);
  2977. adjust_bed_reset(); //reset bed level correction
  2978. }
  2979. // Disable the default update procedure of the display. We will do a modal dialog.
  2980. lcd_update_enable(false);
  2981. // Let the planner use the uncorrected coordinates.
  2982. mbl.reset();
  2983. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2984. // the planner will not perform any adjustments in the XY plane.
  2985. // Wait for the motors to stop and update the current position with the absolute values.
  2986. world2machine_revert_to_uncorrected();
  2987. // Reset the baby step value applied without moving the axes.
  2988. babystep_reset();
  2989. // Mark all axes as in a need for homing.
  2990. memset(axis_known_position, 0, sizeof(axis_known_position));
  2991. // Home in the XY plane.
  2992. //set_destination_to_current();
  2993. int l_feedmultiply = setup_for_endstop_move();
  2994. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2995. raise_z_above(MESH_HOME_Z_SEARCH);
  2996. st_synchronize();
  2997. home_xy();
  2998. enable_endstops(false);
  2999. current_position[X_AXIS] += 5;
  3000. current_position[Y_AXIS] += 5;
  3001. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  3002. st_synchronize();
  3003. // Let the user move the Z axes up to the end stoppers.
  3004. #ifdef TMC2130
  3005. if (calibrate_z_auto())
  3006. {
  3007. #else //TMC2130
  3008. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  3009. {
  3010. #endif //TMC2130
  3011. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  3012. if(onlyZ){
  3013. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  3014. lcd_puts_at_P(0,3,_n("1/9"));
  3015. }else{
  3016. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  3017. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  3018. lcd_puts_at_P(0,3,_n("1/4"));
  3019. }
  3020. refresh_cmd_timeout();
  3021. #ifndef STEEL_SHEET
  3022. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  3023. {
  3024. lcd_wait_for_cool_down();
  3025. }
  3026. #endif //STEEL_SHEET
  3027. if(!onlyZ)
  3028. {
  3029. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3030. #ifdef STEEL_SHEET
  3031. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  3032. if(result) lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  3033. #endif //STEEL_SHEET
  3034. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  3035. KEEPALIVE_STATE(IN_HANDLER);
  3036. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  3037. lcd_puts_at_P(0,3,_n("1/4"));
  3038. }
  3039. bool endstops_enabled = enable_endstops(false);
  3040. current_position[Z_AXIS] -= 1; //move 1mm down with disabled endstop
  3041. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  3042. st_synchronize();
  3043. // Move the print head close to the bed.
  3044. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3045. enable_endstops(true);
  3046. #ifdef TMC2130
  3047. tmc2130_home_enter(Z_AXIS_MASK);
  3048. #endif //TMC2130
  3049. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  3050. st_synchronize();
  3051. #ifdef TMC2130
  3052. tmc2130_home_exit();
  3053. #endif //TMC2130
  3054. enable_endstops(endstops_enabled);
  3055. if ((st_get_position_mm(Z_AXIS) <= (MESH_HOME_Z_SEARCH + HOME_Z_SEARCH_THRESHOLD)) &&
  3056. (st_get_position_mm(Z_AXIS) >= (MESH_HOME_Z_SEARCH - HOME_Z_SEARCH_THRESHOLD)))
  3057. {
  3058. if (onlyZ)
  3059. {
  3060. clean_up_after_endstop_move(l_feedmultiply);
  3061. // Z only calibration.
  3062. // Load the machine correction matrix
  3063. world2machine_initialize();
  3064. // and correct the current_position to match the transformed coordinate system.
  3065. world2machine_update_current();
  3066. //FIXME
  3067. bool result = sample_mesh_and_store_reference();
  3068. if (result)
  3069. {
  3070. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  3071. {
  3072. // Shipped, the nozzle height has been set already. The user can start printing now.
  3073. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  3074. }
  3075. final_result = true;
  3076. // babystep_apply();
  3077. }
  3078. }
  3079. else
  3080. {
  3081. // Reset the baby step value and the baby step applied flag.
  3082. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  3083. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  3084. // Complete XYZ calibration.
  3085. uint8_t point_too_far_mask = 0;
  3086. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  3087. clean_up_after_endstop_move(l_feedmultiply);
  3088. // Print head up.
  3089. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3090. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  3091. st_synchronize();
  3092. //#ifndef NEW_XYZCAL
  3093. if (result >= 0)
  3094. {
  3095. #ifdef HEATBED_V2
  3096. sample_z();
  3097. #else //HEATBED_V2
  3098. point_too_far_mask = 0;
  3099. // Second half: The fine adjustment.
  3100. // Let the planner use the uncorrected coordinates.
  3101. mbl.reset();
  3102. world2machine_reset();
  3103. // Home in the XY plane.
  3104. int l_feedmultiply = setup_for_endstop_move();
  3105. home_xy();
  3106. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  3107. clean_up_after_endstop_move(l_feedmultiply);
  3108. // Print head up.
  3109. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3110. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  3111. st_synchronize();
  3112. // if (result >= 0) babystep_apply();
  3113. #endif //HEATBED_V2
  3114. }
  3115. //#endif //NEW_XYZCAL
  3116. lcd_update_enable(true);
  3117. lcd_update(2);
  3118. lcd_bed_calibration_show_result(result, point_too_far_mask);
  3119. if (result >= 0)
  3120. {
  3121. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  3122. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  3123. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  3124. final_result = true;
  3125. }
  3126. }
  3127. #ifdef TMC2130
  3128. tmc2130_home_exit();
  3129. #endif
  3130. }
  3131. else
  3132. {
  3133. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  3134. final_result = false;
  3135. }
  3136. }
  3137. else
  3138. {
  3139. // Timeouted.
  3140. }
  3141. lcd_update_enable(true);
  3142. #ifdef TMC2130
  3143. FORCE_HIGH_POWER_END;
  3144. #endif // TMC2130
  3145. FORCE_BL_ON_END;
  3146. return final_result;
  3147. }
  3148. void gcode_M114()
  3149. {
  3150. SERIAL_PROTOCOLPGM("X:");
  3151. SERIAL_PROTOCOL(current_position[X_AXIS]);
  3152. SERIAL_PROTOCOLPGM(" Y:");
  3153. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3154. SERIAL_PROTOCOLPGM(" Z:");
  3155. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3156. SERIAL_PROTOCOLPGM(" E:");
  3157. SERIAL_PROTOCOL(current_position[E_AXIS]);
  3158. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  3159. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  3160. SERIAL_PROTOCOLPGM(" Y:");
  3161. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  3162. SERIAL_PROTOCOLPGM(" Z:");
  3163. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  3164. SERIAL_PROTOCOLPGM(" E:");
  3165. SERIAL_PROTOCOLLN(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  3166. }
  3167. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3168. void gcode_M123()
  3169. {
  3170. printf_P(_N("E0:%d RPM PRN1:%d RPM E0@:%u PRN1@:%d\n"), 60*fan_speed[active_extruder], 60*fan_speed[1], newFanSpeed, fanSpeed);
  3171. }
  3172. #endif //FANCHECK and TACH_0 or TACH_1
  3173. //! extracted code to compute z_shift for M600 in case of filament change operation
  3174. //! requested from fsensors.
  3175. //! The function ensures, that the printhead lifts to at least 25mm above the heat bed
  3176. //! unlike the previous implementation, which was adding 25mm even when the head was
  3177. //! printing at e.g. 24mm height.
  3178. //! A safety margin of FILAMENTCHANGE_ZADD is added in all cases to avoid touching
  3179. //! the printout.
  3180. //! This function is templated to enable fast change of computation data type.
  3181. //! @return new z_shift value
  3182. template<typename T>
  3183. static T gcode_M600_filament_change_z_shift()
  3184. {
  3185. #ifdef FILAMENTCHANGE_ZADD
  3186. static_assert(Z_MAX_POS < (255 - FILAMENTCHANGE_ZADD), "Z-range too high, change the T type from uint8_t to uint16_t");
  3187. // avoid floating point arithmetics when not necessary - results in shorter code
  3188. T z_shift = T(FILAMENTCHANGE_ZADD); // always move above printout
  3189. T ztmp = T( current_position[Z_AXIS] );
  3190. if((ztmp + z_shift) < T(MIN_Z_FOR_SWAP)){
  3191. z_shift = T(MIN_Z_FOR_SWAP) - ztmp; // make sure to be at least 25mm above the heat bed
  3192. }
  3193. return z_shift;
  3194. #else
  3195. return T(0);
  3196. #endif
  3197. }
  3198. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/)
  3199. {
  3200. st_synchronize();
  3201. float lastpos[4];
  3202. if (farm_mode)
  3203. {
  3204. prusa_statistics(22);
  3205. }
  3206. //First backup current position and settings
  3207. int feedmultiplyBckp = feedmultiply;
  3208. float HotendTempBckp = degTargetHotend(active_extruder);
  3209. int fanSpeedBckp = fanSpeed;
  3210. lastpos[X_AXIS] = current_position[X_AXIS];
  3211. lastpos[Y_AXIS] = current_position[Y_AXIS];
  3212. lastpos[Z_AXIS] = current_position[Z_AXIS];
  3213. lastpos[E_AXIS] = current_position[E_AXIS];
  3214. //Retract E
  3215. current_position[E_AXIS] += e_shift;
  3216. plan_buffer_line_curposXYZE(FILAMENTCHANGE_RFEED);
  3217. st_synchronize();
  3218. //Lift Z
  3219. current_position[Z_AXIS] += z_shift;
  3220. clamp_to_software_endstops(current_position);
  3221. plan_buffer_line_curposXYZE(FILAMENTCHANGE_ZFEED);
  3222. st_synchronize();
  3223. //Move XY to side
  3224. current_position[X_AXIS] = x_position;
  3225. current_position[Y_AXIS] = y_position;
  3226. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3227. st_synchronize();
  3228. //Beep, manage nozzle heater and wait for user to start unload filament
  3229. if(!mmu_enabled) M600_wait_for_user(HotendTempBckp);
  3230. lcd_change_fil_state = 0;
  3231. // Unload filament
  3232. if (mmu_enabled) extr_unload(); //unload just current filament for multimaterial printers (used also in M702)
  3233. else unload_filament(true); //unload filament for single material (used also in M702)
  3234. //finish moves
  3235. st_synchronize();
  3236. if (!mmu_enabled)
  3237. {
  3238. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3239. lcd_change_fil_state = lcd_show_fullscreen_message_yes_no_and_wait_P(
  3240. _i("Was filament unload successful?"), ////MSG_UNLOAD_SUCCESSFUL c=20 r=2
  3241. false, true);
  3242. if (lcd_change_fil_state == 0)
  3243. {
  3244. lcd_clear();
  3245. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3246. current_position[X_AXIS] -= 100;
  3247. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3248. st_synchronize();
  3249. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually."));////MSG_CHECK_IDLER c=20 r=5
  3250. }
  3251. }
  3252. if (mmu_enabled)
  3253. {
  3254. if (!automatic) {
  3255. 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
  3256. mmu_M600_wait_and_beep();
  3257. if (saved_printing) {
  3258. lcd_clear();
  3259. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3260. mmu_command(MmuCmd::R0);
  3261. manage_response(false, false);
  3262. }
  3263. }
  3264. mmu_M600_load_filament(automatic, HotendTempBckp);
  3265. }
  3266. else
  3267. M600_load_filament();
  3268. if (!automatic) M600_check_state(HotendTempBckp);
  3269. lcd_update_enable(true);
  3270. //Not let's go back to print
  3271. fanSpeed = fanSpeedBckp;
  3272. //Feed a little of filament to stabilize pressure
  3273. if (!automatic)
  3274. {
  3275. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  3276. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EXFEED);
  3277. }
  3278. //Move XY back
  3279. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  3280. FILAMENTCHANGE_XYFEED, active_extruder);
  3281. st_synchronize();
  3282. //Move Z back
  3283. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS],
  3284. FILAMENTCHANGE_ZFEED, active_extruder);
  3285. st_synchronize();
  3286. //Set E position to original
  3287. plan_set_e_position(lastpos[E_AXIS]);
  3288. memcpy(current_position, lastpos, sizeof(lastpos));
  3289. set_destination_to_current();
  3290. //Recover feed rate
  3291. feedmultiply = feedmultiplyBckp;
  3292. char cmd[9];
  3293. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3294. enquecommand(cmd);
  3295. #ifdef IR_SENSOR
  3296. //this will set fsensor_watch_autoload to correct value and prevent possible M701 gcode enqueuing when M600 is finished
  3297. fsensor_check_autoload();
  3298. #endif //IR_SENSOR
  3299. lcd_setstatuspgm(MSG_WELCOME);
  3300. custom_message_type = CustomMsg::Status;
  3301. }
  3302. void gcode_M701()
  3303. {
  3304. printf_P(PSTR("gcode_M701 begin\n"));
  3305. if (farm_mode)
  3306. {
  3307. prusa_statistics(22);
  3308. }
  3309. if (mmu_enabled)
  3310. {
  3311. extr_adj(tmp_extruder);//loads current extruder
  3312. mmu_extruder = tmp_extruder;
  3313. }
  3314. else
  3315. {
  3316. enable_z();
  3317. custom_message_type = CustomMsg::FilamentLoading;
  3318. #ifdef FSENSOR_QUALITY
  3319. fsensor_oq_meassure_start(40);
  3320. #endif //FSENSOR_QUALITY
  3321. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  3322. current_position[E_AXIS] += 40;
  3323. plan_buffer_line_curposXYZE(400 / 60); //fast sequence
  3324. st_synchronize();
  3325. raise_z_above(MIN_Z_FOR_LOAD, false);
  3326. current_position[E_AXIS] += 30;
  3327. plan_buffer_line_curposXYZE(400 / 60); //fast sequence
  3328. load_filament_final_feed(); //slow sequence
  3329. st_synchronize();
  3330. Sound_MakeCustom(50,500,false);
  3331. if (!farm_mode && loading_flag) {
  3332. lcd_load_filament_color_check();
  3333. }
  3334. lcd_update_enable(true);
  3335. lcd_update(2);
  3336. lcd_setstatuspgm(MSG_WELCOME);
  3337. disable_z();
  3338. loading_flag = false;
  3339. custom_message_type = CustomMsg::Status;
  3340. #ifdef FSENSOR_QUALITY
  3341. fsensor_oq_meassure_stop();
  3342. if (!fsensor_oq_result())
  3343. {
  3344. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Fil. sensor response is poor, disable it?"), false, true);
  3345. lcd_update_enable(true);
  3346. lcd_update(2);
  3347. if (disable)
  3348. fsensor_disable();
  3349. }
  3350. #endif //FSENSOR_QUALITY
  3351. }
  3352. }
  3353. /**
  3354. * @brief Get serial number from 32U2 processor
  3355. *
  3356. * Typical format of S/N is:CZPX0917X003XC13518
  3357. *
  3358. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  3359. * reply is stored in *SN.
  3360. * Operation takes typically 23 ms. If no valid SN can be retrieved within the 250ms window, the function aborts
  3361. * and returns a general failure flag.
  3362. * The command will fail if the 32U2 processor is unpowered via USB since it is isolated from the rest of the electronics.
  3363. * In that case the value that is stored in the EEPROM should be used instead.
  3364. *
  3365. * @return 0 on success
  3366. * @return 1 on general failure
  3367. */
  3368. #ifdef PRUSA_SN_SUPPORT
  3369. static uint8_t get_PRUSA_SN(char* SN)
  3370. {
  3371. uint8_t selectedSerialPort_bak = selectedSerialPort;
  3372. uint8_t rxIndex;
  3373. bool SN_valid = false;
  3374. ShortTimer timeout;
  3375. selectedSerialPort = 0;
  3376. timeout.start();
  3377. while (!SN_valid)
  3378. {
  3379. rxIndex = 0;
  3380. _delay(50);
  3381. MYSERIAL.flush(); //clear RX buffer
  3382. SERIAL_ECHOLNRPGM(PSTR(";S"));
  3383. while (rxIndex < 19)
  3384. {
  3385. if (timeout.expired(250u))
  3386. goto exit;
  3387. if (MYSERIAL.available() > 0)
  3388. {
  3389. SN[rxIndex] = MYSERIAL.read();
  3390. rxIndex++;
  3391. }
  3392. }
  3393. SN[rxIndex] = 0;
  3394. // printf_P(PSTR("SN:%s\n"), SN);
  3395. SN_valid = (strncmp_P(SN, PSTR("CZPX"), 4) == 0);
  3396. }
  3397. exit:
  3398. selectedSerialPort = selectedSerialPort_bak;
  3399. return !SN_valid;
  3400. }
  3401. #endif //PRUSA_SN_SUPPORT
  3402. //! Detection of faulty RAMBo 1.1b boards equipped with bigger capacitors
  3403. //! at the TACH_1 pin, which causes bad detection of print fan speed.
  3404. //! Warning: This function is not to be used by ordinary users, it is here only for automated testing purposes,
  3405. //! it may even interfere with other functions of the printer! You have been warned!
  3406. //! The test idea is to measure the time necessary to charge the capacitor.
  3407. //! So the algorithm is as follows:
  3408. //! 1. Set TACH_1 pin to INPUT mode and LOW
  3409. //! 2. Wait a few ms
  3410. //! 3. disable interrupts and measure the time until the TACH_1 pin reaches HIGH
  3411. //! Repeat 1.-3. several times
  3412. //! Good RAMBo's times are in the range of approx. 260-320 us
  3413. //! Bad RAMBo's times are approx. 260-1200 us
  3414. //! So basically we are interested in maximum time, the minima are mostly the same.
  3415. //! May be that's why the bad RAMBo's still produce some fan RPM reading, but not corresponding to reality
  3416. static void gcode_PRUSA_BadRAMBoFanTest(){
  3417. //printf_P(PSTR("Enter fan pin test\n"));
  3418. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  3419. fan_measuring = false; // prevent EXTINT7 breaking into the measurement
  3420. unsigned long tach1max = 0;
  3421. uint8_t tach1cntr = 0;
  3422. for( /* nothing */; tach1cntr < 100; ++tach1cntr){
  3423. //printf_P(PSTR("TACH_1: %d\n"), tach1cntr);
  3424. SET_OUTPUT(TACH_1);
  3425. WRITE(TACH_1, LOW);
  3426. _delay(20); // the delay may be lower
  3427. unsigned long tachMeasure = _micros();
  3428. cli();
  3429. SET_INPUT(TACH_1);
  3430. // just wait brutally in an endless cycle until we reach HIGH
  3431. // if this becomes a problem it may be improved to non-endless cycle
  3432. while( READ(TACH_1) == 0 ) ;
  3433. sei();
  3434. tachMeasure = _micros() - tachMeasure;
  3435. if( tach1max < tachMeasure )
  3436. tach1max = tachMeasure;
  3437. //printf_P(PSTR("TACH_1: %d: capacitor check time=%lu us\n"), (int)tach1cntr, tachMeasure);
  3438. }
  3439. //printf_P(PSTR("TACH_1: max=%lu us\n"), tach1max);
  3440. SERIAL_PROTOCOLPGM("RAMBo FAN ");
  3441. if( tach1max > 500 ){
  3442. // bad RAMBo
  3443. SERIAL_PROTOCOLLNPGM("BAD");
  3444. } else {
  3445. SERIAL_PROTOCOLLNPGM("OK");
  3446. }
  3447. // cleanup after the test function
  3448. SET_INPUT(TACH_1);
  3449. WRITE(TACH_1, HIGH);
  3450. #endif
  3451. }
  3452. // G92 - Set current position to coordinates given
  3453. static void gcode_G92()
  3454. {
  3455. bool codes[NUM_AXIS];
  3456. float values[NUM_AXIS];
  3457. // Check which axes need to be set
  3458. for(uint8_t i = 0; i < NUM_AXIS; ++i)
  3459. {
  3460. codes[i] = code_seen(axis_codes[i]);
  3461. if(codes[i])
  3462. values[i] = code_value();
  3463. }
  3464. if((codes[E_AXIS] && values[E_AXIS] == 0) &&
  3465. (!codes[X_AXIS] && !codes[Y_AXIS] && !codes[Z_AXIS]))
  3466. {
  3467. // As a special optimization, when _just_ clearing the E position
  3468. // we schedule a flag asynchronously along with the next block to
  3469. // reset the starting E position instead of stopping the planner
  3470. current_position[E_AXIS] = 0;
  3471. plan_reset_next_e();
  3472. }
  3473. else
  3474. {
  3475. // In any other case we're forced to synchronize
  3476. st_synchronize();
  3477. for(uint8_t i = 0; i < 3; ++i)
  3478. {
  3479. if(codes[i])
  3480. current_position[i] = values[i] + cs.add_homing[i];
  3481. }
  3482. if(codes[E_AXIS])
  3483. current_position[E_AXIS] = values[E_AXIS];
  3484. // Set all at once
  3485. plan_set_position_curposXYZE();
  3486. }
  3487. }
  3488. #ifdef EXTENDED_CAPABILITIES_REPORT
  3489. static void cap_line(const char* name, bool ena = false) {
  3490. printf_P(PSTR("Cap:%S:%c\n"), name, (char)ena + '0');
  3491. }
  3492. static void extended_capabilities_report()
  3493. {
  3494. // AUTOREPORT_TEMP (M155)
  3495. cap_line(PSTR("AUTOREPORT_TEMP"), ENABLED(AUTO_REPORT));
  3496. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3497. // AUTOREPORT_FANS (M123)
  3498. cap_line(PSTR("AUTOREPORT_FANS"), ENABLED(AUTO_REPORT));
  3499. #endif //FANCHECK and TACH_0 or TACH_1
  3500. // AUTOREPORT_POSITION (M114)
  3501. cap_line(PSTR("AUTOREPORT_POSITION"), ENABLED(AUTO_REPORT));
  3502. // EXTENDED_M20 (support for L and T parameters)
  3503. cap_line(PSTR("EXTENDED_M20"), 1);
  3504. cap_line(PSTR("PRUSA_MMU2"), 1); //this will soon change to ENABLED(PRUSA_MMU2_SUPPORT)
  3505. }
  3506. #endif //EXTENDED_CAPABILITIES_REPORT
  3507. #ifdef BACKLASH_X
  3508. extern uint8_t st_backlash_x;
  3509. #endif //BACKLASH_X
  3510. #ifdef BACKLASH_Y
  3511. extern uint8_t st_backlash_y;
  3512. #endif //BACKLASH_Y
  3513. //! \ingroup marlin_main
  3514. //! @brief Parse and process commands
  3515. //!
  3516. //! look here for descriptions of G-codes: https://reprap.org/wiki/G-code
  3517. //!
  3518. //!
  3519. //! Implemented Codes
  3520. //! -------------------
  3521. //!
  3522. //! * _This list is not updated. Current documentation is maintained inside the process_cmd function._
  3523. //!
  3524. //!@n PRUSA CODES
  3525. //!@n P F - Returns FW versions
  3526. //!@n P R - Returns revision of printer
  3527. //!
  3528. //!@n G0 -> G1
  3529. //!@n G1 - Coordinated Movement X Y Z E
  3530. //!@n G2 - CW ARC
  3531. //!@n G3 - CCW ARC
  3532. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  3533. //!@n G10 - retract filament according to settings of M207
  3534. //!@n G11 - retract recover filament according to settings of M208
  3535. //!@n G28 - Home all Axes
  3536. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  3537. //!@n G30 - Single Z Probe, probes bed at current XY location.
  3538. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  3539. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  3540. //!@n G80 - Automatic mesh bed leveling
  3541. //!@n G81 - Print bed profile
  3542. //!@n G90 - Use Absolute Coordinates
  3543. //!@n G91 - Use Relative Coordinates
  3544. //!@n G92 - Set current position to coordinates given
  3545. //!
  3546. //!@n M Codes
  3547. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  3548. //!@n M1 - Same as M0
  3549. //!@n M17 - Enable/Power all stepper motors
  3550. //!@n M18 - Disable all stepper motors; same as M84
  3551. //!@n M20 - List SD card
  3552. //!@n M21 - Init SD card
  3553. //!@n M22 - Release SD card
  3554. //!@n M23 - Select SD file (M23 filename.g)
  3555. //!@n M24 - Start/resume SD print
  3556. //!@n M25 - Pause SD print
  3557. //!@n M26 - Set SD position in bytes (M26 S12345)
  3558. //!@n M27 - Report SD print status
  3559. //!@n M28 - Start SD write (M28 filename.g)
  3560. //!@n M29 - Stop SD write
  3561. //!@n M30 - Delete file from SD (M30 filename.g)
  3562. //!@n M31 - Output time since last M109 or SD card start to serial
  3563. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  3564. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  3565. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  3566. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  3567. //!@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.
  3568. //!@n M73 - Show percent done and print time remaining
  3569. //!@n M80 - Turn on Power Supply
  3570. //!@n M81 - Turn off Power Supply
  3571. //!@n M82 - Set E codes absolute (default)
  3572. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  3573. //!@n M84 - Disable steppers until next move,
  3574. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  3575. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3576. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  3577. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  3578. //!@n M104 - Set extruder target temp
  3579. //!@n M105 - Read current temp
  3580. //!@n M106 - Fan on
  3581. //!@n M107 - Fan off
  3582. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  3583. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  3584. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  3585. //!@n M112 - Emergency stop
  3586. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  3587. //!@n M114 - Output current position to serial port
  3588. //!@n M115 - Capabilities string
  3589. //!@n M117 - display message
  3590. //!@n M119 - Output Endstop status to serial port
  3591. //!@n M123 - Tachometer value
  3592. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  3593. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  3594. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3595. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3596. //!@n M140 - Set bed target temp
  3597. //!@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.
  3598. //!@n M155 - Automatically send temperatures, fan speeds, position
  3599. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3600. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3601. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3602. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3603. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  3604. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3605. //!@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
  3606. //!@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
  3607. //!@n M206 - set additional homing offset
  3608. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  3609. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  3610. //!@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.
  3611. //!@n M214 - Set Arc Parameters (Use M500 to store in eeprom) P<MM_PER_ARC_SEGMENT> S<MIN_MM_PER_ARC_SEGMENT> R<MIN_ARC_SEGMENTS> F<ARC_SEGMENTS_PER_SEC>
  3612. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3613. //!@n M220 S<factor in percent>- set speed factor override percentage
  3614. //!@n M221 S<factor in percent>- set extrude factor override percentage
  3615. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3616. //!@n M240 - Trigger a camera to take a photograph
  3617. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  3618. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3619. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  3620. //!@n M301 - Set PID parameters P I and D
  3621. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  3622. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  3623. //!@n M304 - Set bed PID parameters P I and D
  3624. //!@n M400 - Finish all moves
  3625. //!@n M401 - Lower z-probe if present
  3626. //!@n M402 - Raise z-probe if present
  3627. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  3628. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  3629. //!@n M406 - Turn off Filament Sensor extrusion control
  3630. //!@n M407 - Displays measured filament diameter
  3631. //!@n M500 - stores parameters in EEPROM
  3632. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  3633. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  3634. //!@n M503 - print the current settings (from memory not from EEPROM)
  3635. //!@n M509 - force language selection on next restart
  3636. //!@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)
  3637. //!@n M552 - Set IP address
  3638. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3639. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  3640. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  3641. //!@n M861 - Set / Read PINDA temperature compensation offsets
  3642. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  3643. //!@n M907 - Set digital trimpot motor current using axis codes.
  3644. //!@n M908 - Control digital trimpot directly.
  3645. //!@n M350 - Set microstepping mode.
  3646. //!@n M351 - Toggle MS1 MS2 pins directly.
  3647. //!
  3648. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  3649. //!@n M999 - Restart after being stopped by error
  3650. //! <br><br>
  3651. /** @defgroup marlin_main Marlin main */
  3652. /** \ingroup GCodes */
  3653. //! _This is a list of currently implemented G Codes in Prusa firmware (dynamically generated from doxygen)._
  3654. /**
  3655. They are shown in order of appearance in the code.
  3656. There are reasons why some G Codes aren't in numerical order.
  3657. */
  3658. void process_commands()
  3659. {
  3660. #ifdef FANCHECK
  3661. if(fan_check_error == EFCE_DETECTED) {
  3662. fan_check_error = EFCE_REPORTED;
  3663. if (usb_timer.running())
  3664. lcd_pause_usb_print();
  3665. else
  3666. lcd_pause_print();
  3667. }
  3668. #endif
  3669. if (!buflen) return; //empty command
  3670. #ifdef CMDBUFFER_DEBUG
  3671. SERIAL_ECHOPGM("Processing a GCODE command: ");
  3672. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  3673. SERIAL_ECHOLNPGM("");
  3674. SERIAL_ECHOPGM("In cmdqueue: ");
  3675. SERIAL_ECHO(buflen);
  3676. SERIAL_ECHOLNPGM("");
  3677. #endif /* CMDBUFFER_DEBUG */
  3678. unsigned long codenum; //throw away variable
  3679. char *starpos = NULL;
  3680. #ifdef ENABLE_AUTO_BED_LEVELING
  3681. float x_tmp, y_tmp, z_tmp, real_z;
  3682. #endif
  3683. // PRUSA GCODES
  3684. KEEPALIVE_STATE(IN_HANDLER);
  3685. /*!
  3686. ---------------------------------------------------------------------------------
  3687. ### M117 - Display Message <a href="https://reprap.org/wiki/G-code#M117:_Display_Message">M117: Display Message</a>
  3688. This causes the given message to be shown in the status line on an attached LCD.
  3689. It is processed early as to allow printing messages that contain G, M, N or T.
  3690. ---------------------------------------------------------------------------------
  3691. ### Special internal commands
  3692. These are used by internal functions to process certain actions in the right order. Some of these are also usable by the user.
  3693. They are processed early as the commands are complex (strings).
  3694. These are only available on the MK3(S) as these require TMC2130 drivers:
  3695. - CRASH DETECTED
  3696. - CRASH RECOVER
  3697. - CRASH_CANCEL
  3698. - TMC_SET_WAVE
  3699. - TMC_SET_STEP
  3700. - TMC_SET_CHOP
  3701. */
  3702. if (code_seen_P(PSTR("M117"))) //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  3703. {
  3704. starpos = (strchr(strchr_pointer + 5, '*'));
  3705. if (starpos != NULL)
  3706. *(starpos) = '\0';
  3707. lcd_setstatus(strchr_pointer + 5);
  3708. custom_message_type = CustomMsg::M117;
  3709. }
  3710. /*!
  3711. ### M0, M1 - Stop the printer <a href="https://reprap.org/wiki/G-code#M0:_Stop_or_Unconditional_stop">M0: Stop or Unconditional stop</a>
  3712. #### Usage
  3713. M0 [P<ms<] [S<sec>] [string]
  3714. M1 [P<ms>] [S<sec>] [string]
  3715. #### Parameters
  3716. - `P<ms>` - Expire time, in milliseconds
  3717. - `S<sec>` - Expire time, in seconds
  3718. - `string` - Must for M1 and optional for M0 message to display on the LCD
  3719. */
  3720. else if (code_seen_P(PSTR("M0")) || code_seen_P(PSTR("M1 "))) {// M0 and M1 - (Un)conditional stop - Wait for user button press on LCD
  3721. char *src = strchr_pointer + 2;
  3722. codenum = 0;
  3723. bool hasP = false, hasS = false;
  3724. if (code_seen('P')) {
  3725. codenum = code_value_long(); // milliseconds to wait
  3726. hasP = codenum > 0;
  3727. }
  3728. if (code_seen('S')) {
  3729. codenum = code_value_long() * 1000; // seconds to wait
  3730. hasS = codenum > 0;
  3731. }
  3732. starpos = strchr(src, '*');
  3733. if (starpos != NULL) *(starpos) = '\0';
  3734. while (*src == ' ') ++src;
  3735. custom_message_type = CustomMsg::M0Wait;
  3736. if (!hasP && !hasS && *src != '\0') {
  3737. lcd_setstatus(src);
  3738. } else {
  3739. // farmers want to abuse a bug from the previous firmware releases
  3740. // - they need to see the filename on the status screen instead of "Wait for user..."
  3741. // So we won't update the message in farm mode...
  3742. if( ! farm_mode){
  3743. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT c=20
  3744. } else {
  3745. custom_message_type = CustomMsg::Status; // let the lcd display the name of the printed G-code file in farm mode
  3746. }
  3747. }
  3748. lcd_ignore_click(); //call lcd_ignore_click also for else ???
  3749. st_synchronize();
  3750. previous_millis_cmd.start();
  3751. if (codenum > 0 ) {
  3752. codenum += _millis(); // keep track of when we started waiting
  3753. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3754. while(_millis() < codenum && !lcd_clicked()) {
  3755. manage_heater();
  3756. manage_inactivity(true);
  3757. lcd_update(0);
  3758. }
  3759. KEEPALIVE_STATE(IN_HANDLER);
  3760. lcd_ignore_click(false);
  3761. } else {
  3762. marlin_wait_for_click();
  3763. }
  3764. if (IS_SD_PRINTING)
  3765. custom_message_type = CustomMsg::Status;
  3766. else
  3767. LCD_MESSAGERPGM(MSG_WELCOME);
  3768. }
  3769. #ifdef TMC2130
  3770. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  3771. {
  3772. // ### CRASH_DETECTED - TMC2130
  3773. // ---------------------------------
  3774. if(code_seen_P(PSTR("CRASH_DETECTED")))
  3775. {
  3776. uint8_t mask = 0;
  3777. if (code_seen('X')) mask |= X_AXIS_MASK;
  3778. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  3779. crashdet_detected(mask);
  3780. }
  3781. // ### CRASH_RECOVER - TMC2130
  3782. // ----------------------------------
  3783. else if(code_seen_P(PSTR("CRASH_RECOVER")))
  3784. crashdet_recover();
  3785. // ### CRASH_CANCEL - TMC2130
  3786. // ----------------------------------
  3787. else if(code_seen_P(PSTR("CRASH_CANCEL")))
  3788. crashdet_cancel();
  3789. }
  3790. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3791. {
  3792. // ### TMC_SET_WAVE_
  3793. // --------------------
  3794. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0)
  3795. {
  3796. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3797. axis = (axis == 'E')?3:(axis - 'X');
  3798. if (axis < 4)
  3799. {
  3800. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3801. tmc2130_set_wave(axis, 247, fac);
  3802. }
  3803. }
  3804. // ### TMC_SET_STEP_
  3805. // ------------------
  3806. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0)
  3807. {
  3808. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3809. axis = (axis == 'E')?3:(axis - 'X');
  3810. if (axis < 4)
  3811. {
  3812. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3813. uint16_t res = tmc2130_get_res(axis);
  3814. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3815. }
  3816. }
  3817. // ### TMC_SET_CHOP_
  3818. // -------------------
  3819. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0)
  3820. {
  3821. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3822. axis = (axis == 'E')?3:(axis - 'X');
  3823. if (axis < 4)
  3824. {
  3825. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  3826. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3827. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3828. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3829. char* str_end = 0;
  3830. if (CMDBUFFER_CURRENT_STRING[14])
  3831. {
  3832. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3833. if (str_end && *str_end)
  3834. {
  3835. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3836. if (str_end && *str_end)
  3837. {
  3838. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3839. if (str_end && *str_end)
  3840. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3841. }
  3842. }
  3843. }
  3844. tmc2130_chopper_config[axis].toff = chop0;
  3845. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3846. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3847. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3848. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3849. //printf_P(_N("TMC_SET_CHOP_%c %d %d %d %d\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3850. }
  3851. }
  3852. }
  3853. #ifdef BACKLASH_X
  3854. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3855. {
  3856. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3857. st_backlash_x = bl;
  3858. printf_P(_N("st_backlash_x = %d\n"), st_backlash_x);
  3859. }
  3860. #endif //BACKLASH_X
  3861. #ifdef BACKLASH_Y
  3862. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3863. {
  3864. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3865. st_backlash_y = bl;
  3866. printf_P(_N("st_backlash_y = %d\n"), st_backlash_y);
  3867. }
  3868. #endif //BACKLASH_Y
  3869. #endif //TMC2130
  3870. else if(code_seen_P(PSTR("PRUSA"))){
  3871. /*!
  3872. ---------------------------------------------------------------------------------
  3873. ### PRUSA - Internal command set <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode - Notes</a>
  3874. Set of internal PRUSA commands
  3875. #### Usage
  3876. PRUSA [ Ping | PRN | FAN | fn | thx | uvlo | MMURES | RESET | fv | M28 | SN | Fir | Rev | Lang | Lz | FR ]
  3877. #### Parameters
  3878. - `Ping`
  3879. - `PRN` - Prints revision of the printer
  3880. - `FAN` - Prints fan details
  3881. - `fn` - Prints farm no.
  3882. - `thx`
  3883. - `uvlo`
  3884. - `MMURES` - Reset MMU
  3885. - `RESET` - (Careful!)
  3886. - `fv` - ?
  3887. - `M28`
  3888. - `SN`
  3889. - `Fir` - Prints firmware version
  3890. - `Rev`- Prints filament size, elelectronics, nozzle type
  3891. - `Lang` - Reset the language
  3892. - `Lz`
  3893. - `FR` - Full factory reset
  3894. - `nozzle set <diameter>` - set nozzle diameter (farm mode only), e.g. `PRUSA nozzle set 0.4`
  3895. - `nozzle D<diameter>` - check the nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle D0.4`
  3896. - `nozzle` - prints nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle`
  3897. */
  3898. if (code_seen_P(PSTR("Ping"))) { // PRUSA Ping
  3899. if (farm_mode) {
  3900. PingTime = _millis();
  3901. }
  3902. }
  3903. else if (code_seen_P(PSTR("PRN"))) { // PRUSA PRN
  3904. printf_P(_N("%u"), status_number);
  3905. } else if( code_seen_P(PSTR("FANPINTST"))){
  3906. gcode_PRUSA_BadRAMBoFanTest();
  3907. }else if (code_seen_P(PSTR("FAN"))) { // PRUSA FAN
  3908. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3909. }
  3910. else if (code_seen_P(PSTR("thx"))) // PRUSA thx
  3911. {
  3912. no_response = false;
  3913. }
  3914. else if (code_seen_P(PSTR("uvlo"))) // PRUSA uvlo
  3915. {
  3916. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3917. enquecommand_P(PSTR("M24"));
  3918. }
  3919. else if (code_seen_P(PSTR("MMURES"))) // PRUSA MMURES
  3920. {
  3921. mmu_reset();
  3922. }
  3923. else if (code_seen_P(PSTR("RESET"))) { // PRUSA RESET
  3924. #ifdef WATCHDOG
  3925. #if defined(XFLASH) && defined(BOOTAPP)
  3926. boot_app_magic = BOOT_APP_MAGIC;
  3927. boot_app_flags = BOOT_APP_FLG_RUN;
  3928. #endif //defined(XFLASH) && defined(BOOTAPP)
  3929. softReset();
  3930. #elif defined(BOOTAPP) //this is a safety precaution. This is because the new bootloader turns off the heaters, but the old one doesn't. The watchdog should be used most of the time.
  3931. asm volatile("jmp 0x3E000");
  3932. #endif
  3933. } else if (code_seen_P(PSTR("fv"))) { // PRUSA fv
  3934. // get file version
  3935. #ifdef SDSUPPORT
  3936. card.openFileReadFilteredGcode(strchr_pointer + 3,true);
  3937. while (true) {
  3938. uint16_t readByte = card.getFilteredGcodeChar();
  3939. MYSERIAL.write(readByte);
  3940. if (readByte=='\n') {
  3941. break;
  3942. }
  3943. }
  3944. card.closefile();
  3945. #endif // SDSUPPORT
  3946. }
  3947. #ifdef PRUSA_M28
  3948. else if (code_seen_P(PSTR("M28"))) { // PRUSA M28
  3949. trace();
  3950. prusa_sd_card_upload = true;
  3951. card.openFileWrite(strchr_pointer+4);
  3952. }
  3953. #endif //PRUSA_M28
  3954. #ifdef PRUSA_SN_SUPPORT
  3955. else if (code_seen_P(PSTR("SN"))) { // PRUSA SN
  3956. char SN[20];
  3957. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  3958. if (SN[19])
  3959. puts_P(PSTR("SN invalid"));
  3960. else
  3961. puts(SN);
  3962. }
  3963. #endif //PRUSA_SN_SUPPORT
  3964. else if(code_seen_P(PSTR("Fir"))){ // PRUSA Fir
  3965. SERIAL_PROTOCOLLN(FW_VERSION_FULL);
  3966. } else if(code_seen_P(PSTR("Rev"))){ // PRUSA Rev
  3967. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3968. } else if(code_seen_P(PSTR("Lang"))) { // PRUSA Lang
  3969. lang_reset();
  3970. } else if(code_seen_P(PSTR("Lz"))) { // PRUSA Lz
  3971. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  3972. } else if(code_seen_P(PSTR("FR"))) { // PRUSA FR
  3973. // Factory full reset
  3974. factory_reset(0);
  3975. } else if(code_seen_P(PSTR("MBL"))) { // PRUSA MBL
  3976. // Change the MBL status without changing the logical Z position.
  3977. if(code_seen('V')) {
  3978. bool value = code_value_short();
  3979. st_synchronize();
  3980. if(value != mbl.active) {
  3981. mbl.active = value;
  3982. // Use plan_set_z_position to reset the physical values
  3983. plan_set_z_position(current_position[Z_AXIS]);
  3984. }
  3985. }
  3986. //-//
  3987. /*
  3988. } else if(code_seen("rrr")) {
  3989. MYSERIAL.println("=== checking ===");
  3990. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_CHECK_MODE),DEC);
  3991. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER),DEC);
  3992. MYSERIAL.println(eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM),DEC);
  3993. MYSERIAL.println(farm_mode,DEC);
  3994. MYSERIAL.println(eCheckMode,DEC);
  3995. } else if(code_seen("www")) {
  3996. MYSERIAL.println("=== @ FF ===");
  3997. eeprom_update_byte((uint8_t*)EEPROM_CHECK_MODE,0xFF);
  3998. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,0xFF);
  3999. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,0xFFFF);
  4000. */
  4001. } else if (code_seen_P(PSTR("nozzle"))) { // PRUSA nozzle
  4002. uint16_t nDiameter;
  4003. if(code_seen('D'))
  4004. {
  4005. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  4006. nozzle_diameter_check(nDiameter);
  4007. }
  4008. else if(code_seen_P(PSTR("set")) && farm_mode)
  4009. {
  4010. strchr_pointer++; // skip 1st char (~ 's')
  4011. strchr_pointer++; // skip 2nd char (~ 'e')
  4012. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  4013. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  4014. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  4015. }
  4016. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  4017. //-// !!! SupportMenu
  4018. /*
  4019. // musi byt PRED "PRUSA model"
  4020. } else if (code_seen("smodel")) { //! PRUSA smodel
  4021. size_t nOffset;
  4022. // ! -> "l"
  4023. strchr_pointer+=5*sizeof(*strchr_pointer); // skip 1st - 5th char (~ 'smode')
  4024. nOffset=strspn(strchr_pointer+1," \t\n\r\v\f");
  4025. if(*(strchr_pointer+1+nOffset))
  4026. printer_smodel_check(strchr_pointer);
  4027. else SERIAL_PROTOCOLLN(PRINTER_NAME);
  4028. } else if (code_seen("model")) { //! PRUSA model
  4029. uint16_t nPrinterModel;
  4030. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'mode')
  4031. nPrinterModel=(uint16_t)code_value_long();
  4032. if(nPrinterModel!=0)
  4033. printer_model_check(nPrinterModel);
  4034. else SERIAL_PROTOCOLLN(PRINTER_TYPE);
  4035. } else if (code_seen("version")) { //! PRUSA version
  4036. strchr_pointer+=7*sizeof(*strchr_pointer); // skip 1st - 7th char (~ 'version')
  4037. while(*strchr_pointer==' ') // skip leading spaces
  4038. strchr_pointer++;
  4039. if(*strchr_pointer!=0)
  4040. fw_version_check(strchr_pointer);
  4041. else SERIAL_PROTOCOLLN(FW_VERSION);
  4042. } else if (code_seen("gcode")) { //! PRUSA gcode
  4043. uint16_t nGcodeLevel;
  4044. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'gcod')
  4045. nGcodeLevel=(uint16_t)code_value_long();
  4046. if(nGcodeLevel!=0)
  4047. gcode_level_check(nGcodeLevel);
  4048. else SERIAL_PROTOCOLLN(GCODE_LEVEL);
  4049. */
  4050. }
  4051. //else if (code_seen('Cal')) {
  4052. // lcd_calibration();
  4053. // }
  4054. }
  4055. // This prevents reading files with "^" in their names.
  4056. // Since it is unclear, if there is some usage of this construct,
  4057. // it will be deprecated in 3.9 alpha a possibly completely removed in the future:
  4058. // else if (code_seen('^')) {
  4059. // // nothing, this is a version line
  4060. // }
  4061. else if(code_seen('G'))
  4062. {
  4063. gcode_in_progress = code_value_short();
  4064. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  4065. switch (gcode_in_progress)
  4066. {
  4067. /*!
  4068. ---------------------------------------------------------------------------------
  4069. # G Codes
  4070. ### G0, G1 - Coordinated movement X Y Z E <a href="https://reprap.org/wiki/G-code#G0_.26_G1:_Move">G0 & G1: Move</a>
  4071. In Prusa Firmware G0 and G1 are the same.
  4072. #### Usage
  4073. G0 [ X | Y | Z | E | F | S ]
  4074. G1 [ X | Y | Z | E | F | S ]
  4075. #### Parameters
  4076. - `X` - The position to move to on the X axis
  4077. - `Y` - The position to move to on the Y axis
  4078. - `Z` - The position to move to on the Z axis
  4079. - `E` - The amount to extrude between the starting point and ending point
  4080. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  4081. */
  4082. case 0: // G0 -> G1
  4083. case 1: // G1
  4084. if(Stopped == false) {
  4085. get_coordinates(); // For X Y Z E F
  4086. // When recovering from a previous print move, restore the originally
  4087. // calculated target position on the first USB/SD command. This accounts
  4088. // properly for relative moves
  4089. if ((saved_target[0] != SAVED_TARGET_UNSET) &&
  4090. ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) ||
  4091. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  4092. {
  4093. memcpy(destination, saved_target, sizeof(destination));
  4094. saved_target[0] = SAVED_TARGET_UNSET;
  4095. }
  4096. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  4097. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  4098. }
  4099. #ifdef FWRETRACT
  4100. if(cs.autoretract_enabled) {
  4101. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  4102. float echange=destination[E_AXIS]-current_position[E_AXIS];
  4103. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  4104. st_synchronize();
  4105. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  4106. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  4107. retract(!retracted[active_extruder]);
  4108. return;
  4109. }
  4110. }
  4111. }
  4112. #endif //FWRETRACT
  4113. prepare_move();
  4114. //ClearToSend();
  4115. }
  4116. break;
  4117. /*!
  4118. ### G2, G3 - Controlled Arc Move <a href="https://reprap.org/wiki/G-code#G2_.26_G3:_Controlled_Arc_Move">G2 & G3: Controlled Arc Move</a>
  4119. These commands don't propperly work with MBL enabled. The compensation only happens at the end of the move, so avoid long arcs.
  4120. #### Usage
  4121. G2 [ X | Y | I | E | F ] (Clockwise Arc)
  4122. G3 [ X | Y | I | E | F ] (Counter-Clockwise Arc)
  4123. #### Parameters
  4124. - `X` - The position to move to on the X axis
  4125. - `Y` - The position to move to on the Y axis
  4126. - 'Z' - The position to move to on the Z axis
  4127. - `I` - The point in X space from the current X position to maintain a constant distance from
  4128. - `J` - The point in Y space from the current Y position to maintain a constant distance from
  4129. - `E` - The amount to extrude between the starting point and ending point
  4130. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  4131. */
  4132. case 2:
  4133. if(Stopped == false) {
  4134. get_arc_coordinates();
  4135. prepare_arc_move(true);
  4136. }
  4137. break;
  4138. // -------------------------------
  4139. case 3:
  4140. if(Stopped == false) {
  4141. get_arc_coordinates();
  4142. prepare_arc_move(false);
  4143. }
  4144. break;
  4145. /*!
  4146. ### G4 - Dwell <a href="https://reprap.org/wiki/G-code#G4:_Dwell">G4: Dwell</a>
  4147. Pause the machine for a period of time.
  4148. #### Usage
  4149. G4 [ P | S ]
  4150. #### Parameters
  4151. - `P` - Time to wait, in milliseconds
  4152. - `S` - Time to wait, in seconds
  4153. */
  4154. case 4:
  4155. codenum = 0;
  4156. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  4157. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  4158. if(codenum != 0)
  4159. {
  4160. if(custom_message_type != CustomMsg::M117)
  4161. {
  4162. LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  4163. }
  4164. }
  4165. st_synchronize();
  4166. codenum += _millis(); // keep track of when we started waiting
  4167. previous_millis_cmd.start();
  4168. while(_millis() < codenum) {
  4169. manage_heater();
  4170. manage_inactivity();
  4171. lcd_update(0);
  4172. }
  4173. break;
  4174. #ifdef FWRETRACT
  4175. /*!
  4176. ### G10 - Retract <a href="https://reprap.org/wiki/G-code#G10:_Retract">G10: Retract</a>
  4177. Retracts filament according to settings of `M207`
  4178. */
  4179. case 10:
  4180. #if EXTRUDERS > 1
  4181. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  4182. retract(true,retracted_swap[active_extruder]);
  4183. #else
  4184. retract(true);
  4185. #endif
  4186. break;
  4187. /*!
  4188. ### G11 - Retract recover <a href="https://reprap.org/wiki/G-code#G11:_Unretract">G11: Unretract</a>
  4189. Unretracts/recovers filament according to settings of `M208`
  4190. */
  4191. case 11:
  4192. #if EXTRUDERS > 1
  4193. retract(false,retracted_swap[active_extruder]);
  4194. #else
  4195. retract(false);
  4196. #endif
  4197. break;
  4198. #endif //FWRETRACT
  4199. /*!
  4200. ### G21 - Sets Units to Millimters <a href="https://reprap.org/wiki/G-code#G21:_Set_Units_to_Millimeters">G21: Set Units to Millimeters</a>
  4201. Units are in millimeters. Prusa doesn't support inches.
  4202. */
  4203. case 21:
  4204. break; //Doing nothing. This is just to prevent serial UNKOWN warnings.
  4205. /*!
  4206. ### G28 - Home all Axes one at a time <a href="https://reprap.org/wiki/G-code#G28:_Move_to_Origin_.28Home.29">G28: Move to Origin (Home)</a>
  4207. Using `G28` without any parameters will perfom homing of all axes AND mesh bed leveling, while `G28 W` will just home all axes (no mesh bed leveling).
  4208. #### Usage
  4209. G28 [ X | Y | Z | W | C ]
  4210. #### Parameters
  4211. - `X` - Flag to go back to the X axis origin
  4212. - `Y` - Flag to go back to the Y axis origin
  4213. - `Z` - Flag to go back to the Z axis origin
  4214. - `W` - Suppress mesh bed leveling if `X`, `Y` or `Z` are not provided
  4215. - `C` - Calibrate X and Y origin (home) - Only on MK3/s
  4216. */
  4217. case 28:
  4218. {
  4219. long home_x_value = 0;
  4220. long home_y_value = 0;
  4221. long home_z_value = 0;
  4222. // Which axes should be homed?
  4223. bool home_x = code_seen(axis_codes[X_AXIS]);
  4224. home_x_value = code_value_long();
  4225. bool home_y = code_seen(axis_codes[Y_AXIS]);
  4226. home_y_value = code_value_long();
  4227. bool home_z = code_seen(axis_codes[Z_AXIS]);
  4228. home_z_value = code_value_long();
  4229. bool without_mbl = code_seen('W');
  4230. // calibrate?
  4231. #ifdef TMC2130
  4232. bool calib = code_seen('C');
  4233. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  4234. #else
  4235. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  4236. #endif //TMC2130
  4237. if ((home_x || home_y || without_mbl || home_z) == false) {
  4238. gcode_G80();
  4239. }
  4240. break;
  4241. }
  4242. #ifdef ENABLE_AUTO_BED_LEVELING
  4243. /*!
  4244. ### G29 - Detailed Z-Probe <a href="https://reprap.org/wiki/G-code#G29:_Detailed_Z-Probe">G29: Detailed Z-Probe</a>
  4245. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4246. See `G81`
  4247. */
  4248. case 29:
  4249. {
  4250. #if Z_MIN_PIN == -1
  4251. #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."
  4252. #endif
  4253. // Prevent user from running a G29 without first homing in X and Y
  4254. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  4255. {
  4256. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  4257. SERIAL_ECHO_START;
  4258. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  4259. break; // abort G29, since we don't know where we are
  4260. }
  4261. st_synchronize();
  4262. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  4263. //vector_3 corrected_position = plan_get_position_mm();
  4264. //corrected_position.debug("position before G29");
  4265. plan_bed_level_matrix.set_to_identity();
  4266. vector_3 uncorrected_position = plan_get_position();
  4267. //uncorrected_position.debug("position durring G29");
  4268. current_position[X_AXIS] = uncorrected_position.x;
  4269. current_position[Y_AXIS] = uncorrected_position.y;
  4270. current_position[Z_AXIS] = uncorrected_position.z;
  4271. plan_set_position_curposXYZE();
  4272. int l_feedmultiply = setup_for_endstop_move();
  4273. feedrate = homing_feedrate[Z_AXIS];
  4274. #ifdef AUTO_BED_LEVELING_GRID
  4275. // probe at the points of a lattice grid
  4276. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4277. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4278. // solve the plane equation ax + by + d = z
  4279. // A is the matrix with rows [x y 1] for all the probed points
  4280. // B is the vector of the Z positions
  4281. // 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
  4282. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4283. // "A" matrix of the linear system of equations
  4284. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  4285. // "B" vector of Z points
  4286. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  4287. int probePointCounter = 0;
  4288. bool zig = true;
  4289. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  4290. {
  4291. int xProbe, xInc;
  4292. if (zig)
  4293. {
  4294. xProbe = LEFT_PROBE_BED_POSITION;
  4295. //xEnd = RIGHT_PROBE_BED_POSITION;
  4296. xInc = xGridSpacing;
  4297. zig = false;
  4298. } else // zag
  4299. {
  4300. xProbe = RIGHT_PROBE_BED_POSITION;
  4301. //xEnd = LEFT_PROBE_BED_POSITION;
  4302. xInc = -xGridSpacing;
  4303. zig = true;
  4304. }
  4305. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  4306. {
  4307. float z_before;
  4308. if (probePointCounter == 0)
  4309. {
  4310. // raise before probing
  4311. z_before = Z_RAISE_BEFORE_PROBING;
  4312. } else
  4313. {
  4314. // raise extruder
  4315. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  4316. }
  4317. float measured_z = probe_pt(xProbe, yProbe, z_before);
  4318. eqnBVector[probePointCounter] = measured_z;
  4319. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  4320. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  4321. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  4322. probePointCounter++;
  4323. xProbe += xInc;
  4324. }
  4325. }
  4326. clean_up_after_endstop_move(l_feedmultiply);
  4327. // solve lsq problem
  4328. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  4329. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4330. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  4331. SERIAL_PROTOCOLPGM(" b: ");
  4332. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  4333. SERIAL_PROTOCOLPGM(" d: ");
  4334. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  4335. set_bed_level_equation_lsq(plane_equation_coefficients);
  4336. free(plane_equation_coefficients);
  4337. #else // AUTO_BED_LEVELING_GRID not defined
  4338. // Probe at 3 arbitrary points
  4339. // probe 1
  4340. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  4341. // probe 2
  4342. 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);
  4343. // probe 3
  4344. 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);
  4345. clean_up_after_endstop_move(l_feedmultiply);
  4346. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  4347. #endif // AUTO_BED_LEVELING_GRID
  4348. st_synchronize();
  4349. // The following code correct the Z height difference from z-probe position and hotend tip position.
  4350. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  4351. // When the bed is uneven, this height must be corrected.
  4352. 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)
  4353. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  4354. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4355. z_tmp = current_position[Z_AXIS];
  4356. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  4357. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  4358. plan_set_position_curposXYZE();
  4359. }
  4360. break;
  4361. #ifndef Z_PROBE_SLED
  4362. /*!
  4363. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4364. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4365. */
  4366. case 30:
  4367. {
  4368. st_synchronize();
  4369. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4370. int l_feedmultiply = setup_for_endstop_move();
  4371. feedrate = homing_feedrate[Z_AXIS];
  4372. run_z_probe();
  4373. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  4374. SERIAL_PROTOCOLPGM(" X: ");
  4375. SERIAL_PROTOCOL(current_position[X_AXIS]);
  4376. SERIAL_PROTOCOLPGM(" Y: ");
  4377. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  4378. SERIAL_PROTOCOLPGM(" Z: ");
  4379. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  4380. SERIAL_PROTOCOLPGM("\n");
  4381. clean_up_after_endstop_move(l_feedmultiply);
  4382. }
  4383. break;
  4384. #else
  4385. /*!
  4386. ### G31 - Dock the sled <a href="https://reprap.org/wiki/G-code#G31:_Dock_Z_Probe_sled">G31: Dock Z Probe sled</a>
  4387. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4388. */
  4389. case 31:
  4390. dock_sled(true);
  4391. break;
  4392. /*!
  4393. ### G32 - Undock the sled <a href="https://reprap.org/wiki/G-code#G32:_Undock_Z_Probe_sled">G32: Undock Z Probe sled</a>
  4394. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4395. */
  4396. case 32:
  4397. dock_sled(false);
  4398. break;
  4399. #endif // Z_PROBE_SLED
  4400. #endif // ENABLE_AUTO_BED_LEVELING
  4401. #ifdef MESH_BED_LEVELING
  4402. /*!
  4403. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4404. Sensor must be over the bed.
  4405. The maximum travel distance before an error is triggered is 10mm.
  4406. */
  4407. case 30:
  4408. {
  4409. st_synchronize();
  4410. homing_flag = true;
  4411. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4412. int l_feedmultiply = setup_for_endstop_move();
  4413. feedrate = homing_feedrate[Z_AXIS];
  4414. find_bed_induction_sensor_point_z(-10.f, 3);
  4415. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  4416. clean_up_after_endstop_move(l_feedmultiply);
  4417. homing_flag = false;
  4418. }
  4419. break;
  4420. /*!
  4421. ### G75 - Print temperature interpolation <a href="https://reprap.org/wiki/G-code#G75:_Print_temperature_interpolation">G75: Print temperature interpolation</a>
  4422. Show/print PINDA temperature interpolating.
  4423. */
  4424. case 75:
  4425. {
  4426. for (uint8_t i = 40; i <= 110; i++)
  4427. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  4428. }
  4429. break;
  4430. /*!
  4431. ### G76 - PINDA probe temperature calibration <a href="https://reprap.org/wiki/G-code#G76:_PINDA_probe_temperature_calibration">G76: PINDA probe temperature calibration</a>
  4432. This G-code is used to calibrate the temperature drift of the PINDA (inductive Sensor).
  4433. The PINDAv2 sensor has a built-in thermistor which has the advantage that the calibration can be done once for all materials.
  4434. The Original i3 Prusa MK2/s uses PINDAv1 and this calibration improves the temperature drift, but not as good as the PINDAv2.
  4435. superPINDA sensor has internal temperature compensation and no thermistor output. There is no point of doing temperature calibration in such case.
  4436. If PINDA_THERMISTOR and SUPERPINDA_SUPPORT is defined during compilation, calibration is skipped with serial message "No PINDA thermistor".
  4437. This can be caused also if PINDA thermistor connection is broken or PINDA temperature is lower than PINDA_MINTEMP.
  4438. #### Example
  4439. ```
  4440. G76
  4441. echo PINDA probe calibration start
  4442. echo start temperature: 35.0°
  4443. echo ...
  4444. echo PINDA temperature -- Z shift (mm): 0.---
  4445. ```
  4446. */
  4447. case 76:
  4448. {
  4449. #ifdef PINDA_THERMISTOR
  4450. if (!has_temperature_compensation())
  4451. {
  4452. SERIAL_ECHOLNPGM("No PINDA thermistor");
  4453. break;
  4454. }
  4455. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  4456. //we need to know accurate position of first calibration point
  4457. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  4458. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first.")); ////MSG_RUN_XYZ c=20 r=4
  4459. break;
  4460. }
  4461. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  4462. {
  4463. // We don't know where we are! HOME!
  4464. // Push the commands to the front of the message queue in the reverse order!
  4465. // There shall be always enough space reserved for these commands.
  4466. repeatcommand_front(); // repeat G76 with all its parameters
  4467. enquecommand_front_P(G28W0);
  4468. break;
  4469. }
  4470. 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
  4471. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  4472. if (result)
  4473. {
  4474. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4475. plan_buffer_line_curposXYZE(3000 / 60);
  4476. current_position[Z_AXIS] = 50;
  4477. current_position[Y_AXIS] = 180;
  4478. plan_buffer_line_curposXYZE(3000 / 60);
  4479. st_synchronize();
  4480. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  4481. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4482. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4483. plan_buffer_line_curposXYZE(3000 / 60);
  4484. st_synchronize();
  4485. gcode_G28(false, false, true);
  4486. }
  4487. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  4488. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  4489. current_position[Z_AXIS] = 100;
  4490. plan_buffer_line_curposXYZE(3000 / 60);
  4491. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  4492. lcd_temp_cal_show_result(false);
  4493. break;
  4494. }
  4495. }
  4496. st_synchronize();
  4497. homing_flag = true; // keep homing on to avoid babystepping while the LCD is enabled
  4498. lcd_update_enable(true);
  4499. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  4500. float zero_z;
  4501. int z_shift = 0; //unit: steps
  4502. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  4503. if (start_temp < 35) start_temp = 35;
  4504. if (start_temp < current_temperature_pinda) start_temp += 5;
  4505. printf_P(_N("start temperature: %.1f\n"), start_temp);
  4506. // setTargetHotend(200, 0);
  4507. setTargetBed(70 + (start_temp - 30));
  4508. custom_message_type = CustomMsg::TempCal;
  4509. custom_message_state = 1;
  4510. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4511. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4512. plan_buffer_line_curposXYZE(3000 / 60);
  4513. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4514. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4515. plan_buffer_line_curposXYZE(3000 / 60);
  4516. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4517. plan_buffer_line_curposXYZE(3000 / 60);
  4518. st_synchronize();
  4519. while (current_temperature_pinda < start_temp)
  4520. {
  4521. delay_keep_alive(1000);
  4522. serialecho_temperatures();
  4523. }
  4524. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4525. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4526. plan_buffer_line_curposXYZE(3000 / 60);
  4527. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4528. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4529. plan_buffer_line_curposXYZE(3000 / 60);
  4530. st_synchronize();
  4531. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4532. if (find_z_result == false) {
  4533. lcd_temp_cal_show_result(find_z_result);
  4534. homing_flag = false;
  4535. break;
  4536. }
  4537. zero_z = current_position[Z_AXIS];
  4538. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4539. int i = -1; for (; i < 5; i++)
  4540. {
  4541. float temp = (40 + i * 5);
  4542. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  4543. if (i >= 0) {
  4544. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4545. }
  4546. if (start_temp <= temp) break;
  4547. }
  4548. for (i++; i < 5; i++)
  4549. {
  4550. float temp = (40 + i * 5);
  4551. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4552. custom_message_state = i + 2;
  4553. setTargetBed(50 + 10 * (temp - 30) / 5);
  4554. // setTargetHotend(255, 0);
  4555. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4556. plan_buffer_line_curposXYZE(3000 / 60);
  4557. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4558. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4559. plan_buffer_line_curposXYZE(3000 / 60);
  4560. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4561. plan_buffer_line_curposXYZE(3000 / 60);
  4562. st_synchronize();
  4563. while (current_temperature_pinda < temp)
  4564. {
  4565. delay_keep_alive(1000);
  4566. serialecho_temperatures();
  4567. }
  4568. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4569. plan_buffer_line_curposXYZE(3000 / 60);
  4570. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4571. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4572. plan_buffer_line_curposXYZE(3000 / 60);
  4573. st_synchronize();
  4574. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4575. if (find_z_result == false) {
  4576. lcd_temp_cal_show_result(find_z_result);
  4577. break;
  4578. }
  4579. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4580. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  4581. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4582. }
  4583. lcd_temp_cal_show_result(true);
  4584. homing_flag = false;
  4585. #else //PINDA_THERMISTOR
  4586. setTargetBed(PINDA_MIN_T);
  4587. float zero_z;
  4588. int z_shift = 0; //unit: steps
  4589. int t_c; // temperature
  4590. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4591. // We don't know where we are! HOME!
  4592. // Push the commands to the front of the message queue in the reverse order!
  4593. // There shall be always enough space reserved for these commands.
  4594. repeatcommand_front(); // repeat G76 with all its parameters
  4595. enquecommand_front_P(G28W0);
  4596. break;
  4597. }
  4598. puts_P(_N("PINDA probe calibration start"));
  4599. custom_message_type = CustomMsg::TempCal;
  4600. custom_message_state = 1;
  4601. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4602. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4603. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4604. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4605. plan_buffer_line_curposXYZE(3000 / 60);
  4606. st_synchronize();
  4607. while (fabs(degBed() - PINDA_MIN_T) > 1) {
  4608. delay_keep_alive(1000);
  4609. serialecho_temperatures();
  4610. }
  4611. //enquecommand_P(PSTR("M190 S50"));
  4612. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4613. delay_keep_alive(1000);
  4614. serialecho_temperatures();
  4615. }
  4616. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4617. current_position[Z_AXIS] = 5;
  4618. plan_buffer_line_curposXYZE(3000 / 60);
  4619. current_position[X_AXIS] = BED_X0;
  4620. current_position[Y_AXIS] = BED_Y0;
  4621. plan_buffer_line_curposXYZE(3000 / 60);
  4622. st_synchronize();
  4623. find_bed_induction_sensor_point_z(-1.f);
  4624. zero_z = current_position[Z_AXIS];
  4625. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4626. for (int i = 0; i<5; i++) {
  4627. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4628. custom_message_state = i + 2;
  4629. t_c = 60 + i * 10;
  4630. setTargetBed(t_c);
  4631. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4632. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4633. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4634. plan_buffer_line_curposXYZE(3000 / 60);
  4635. st_synchronize();
  4636. while (degBed() < t_c) {
  4637. delay_keep_alive(1000);
  4638. serialecho_temperatures();
  4639. }
  4640. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4641. delay_keep_alive(1000);
  4642. serialecho_temperatures();
  4643. }
  4644. current_position[Z_AXIS] = 5;
  4645. plan_buffer_line_curposXYZE(3000 / 60);
  4646. current_position[X_AXIS] = BED_X0;
  4647. current_position[Y_AXIS] = BED_Y0;
  4648. plan_buffer_line_curposXYZE(3000 / 60);
  4649. st_synchronize();
  4650. find_bed_induction_sensor_point_z(-1.f);
  4651. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4652. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  4653. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4654. }
  4655. custom_message_type = CustomMsg::Status;
  4656. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  4657. puts_P(_N("Temperature calibration done."));
  4658. disable_x();
  4659. disable_y();
  4660. disable_z();
  4661. disable_e0();
  4662. disable_e1();
  4663. disable_e2();
  4664. setTargetBed(0); //set bed target temperature back to 0
  4665. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PINDA_CALIBRATION_DONE));
  4666. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  4667. lcd_update_enable(true);
  4668. lcd_update(2);
  4669. #endif //PINDA_THERMISTOR
  4670. }
  4671. break;
  4672. /*!
  4673. ### G80 - Mesh-based Z probe <a href="https://reprap.org/wiki/G-code#G80:_Mesh-based_Z_probe">G80: Mesh-based Z probe</a>
  4674. Default 3x3 grid can be changed on MK2.5/s and MK3/s to 7x7 grid.
  4675. #### Usage
  4676. G80 [ N | R | V | L | R | F | B ]
  4677. #### Parameters
  4678. - `N` - Number of mesh points on x axis. Default is 3. Valid values are 3 and 7.
  4679. - `R` - Probe retries. Default 3 max. 10
  4680. - `V` - Verbosity level 1=low, 10=mid, 20=high. It only can be used if the firmware has been compiled with SUPPORT_VERBOSITY active.
  4681. Using the following parameters enables additional "manual" bed leveling correction. Valid values are -100 microns to 100 microns.
  4682. #### Additional Parameters
  4683. - `L` - Left Bed Level correct value in um.
  4684. - `R` - Right Bed Level correct value in um.
  4685. - `F` - Front Bed Level correct value in um.
  4686. - `B` - Back Bed Level correct value in um.
  4687. */
  4688. /*
  4689. * Probes a grid and produces a mesh to compensate for variable bed height
  4690. * The S0 report the points as below
  4691. * +----> X-axis
  4692. * |
  4693. * |
  4694. * v Y-axis
  4695. */
  4696. case 80: {
  4697. gcode_G80();
  4698. }
  4699. break;
  4700. /*!
  4701. ### G81 - Mesh bed leveling status <a href="https://reprap.org/wiki/G-code#G81:_Mesh_bed_leveling_status">G81: Mesh bed leveling status</a>
  4702. Prints mesh bed leveling status and bed profile if activated.
  4703. */
  4704. case 81:
  4705. if (mbl.active) {
  4706. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4707. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4708. SERIAL_PROTOCOL(',');
  4709. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4710. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4711. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4712. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4713. for (uint8_t y = MESH_NUM_Y_POINTS; y-- > 0;) {
  4714. for (uint8_t x = 0; x < MESH_NUM_X_POINTS; x++) {
  4715. SERIAL_PROTOCOLPGM(" ");
  4716. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4717. }
  4718. SERIAL_PROTOCOLLN();
  4719. }
  4720. }
  4721. else
  4722. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4723. break;
  4724. #if 0
  4725. /*!
  4726. ### G82: Single Z probe at current location - Not active <a href="https://reprap.org/wiki/G-code#G82:_Single_Z_probe_at_current_location">G82: Single Z probe at current location</a>
  4727. WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4728. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4729. */
  4730. case 82:
  4731. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4732. int l_feedmultiply = setup_for_endstop_move();
  4733. find_bed_induction_sensor_point_z();
  4734. clean_up_after_endstop_move(l_feedmultiply);
  4735. SERIAL_PROTOCOLPGM("Bed found at: ");
  4736. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4737. SERIAL_PROTOCOLPGM("\n");
  4738. break;
  4739. /*!
  4740. ### G83: Babystep in Z and store to EEPROM - Not active <a href="https://reprap.org/wiki/G-code#G83:_Babystep_in_Z_and_store_to_EEPROM">G83: Babystep in Z and store to EEPROM</a>
  4741. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4742. */
  4743. case 83:
  4744. {
  4745. int babystepz = code_seen('S') ? code_value() : 0;
  4746. int BabyPosition = code_seen('P') ? code_value() : 0;
  4747. if (babystepz != 0) {
  4748. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4749. // Is the axis indexed starting with zero or one?
  4750. if (BabyPosition > 4) {
  4751. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4752. }else{
  4753. // Save it to the eeprom
  4754. babystepLoadZ = babystepz;
  4755. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z0 + BabyPosition, babystepLoadZ);
  4756. // adjust the Z
  4757. babystepsTodoZadd(babystepLoadZ);
  4758. }
  4759. }
  4760. }
  4761. break;
  4762. /*!
  4763. ### G84: UNDO Babystep Z (move Z axis back) - Not active <a href="https://reprap.org/wiki/G-code#G84:_UNDO_Babystep_Z_.28move_Z_axis_back.29">G84: UNDO Babystep Z (move Z axis back)</a>
  4764. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4765. */
  4766. case 84:
  4767. babystepsTodoZsubtract(babystepLoadZ);
  4768. // babystepLoadZ = 0;
  4769. break;
  4770. /*!
  4771. ### G85: Pick best babystep - Not active <a href="https://reprap.org/wiki/G-code#G85:_Pick_best_babystep">G85: Pick best babystep</a>
  4772. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4773. */
  4774. case 85:
  4775. lcd_pick_babystep();
  4776. break;
  4777. #endif
  4778. /*!
  4779. ### G86 - Disable babystep correction after home <a href="https://reprap.org/wiki/G-code#G86:_Disable_babystep_correction_after_home">G86: Disable babystep correction after home</a>
  4780. This G-code will be performed at the start of a calibration script.
  4781. (Prusa3D specific)
  4782. */
  4783. case 86:
  4784. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4785. break;
  4786. /*!
  4787. ### G87 - Enable babystep correction after home <a href="https://reprap.org/wiki/G-code#G87:_Enable_babystep_correction_after_home">G87: Enable babystep correction after home</a>
  4788. This G-code will be performed at the end of a calibration script.
  4789. (Prusa3D specific)
  4790. */
  4791. case 87:
  4792. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4793. break;
  4794. /*!
  4795. ### G88 - Reserved <a href="https://reprap.org/wiki/G-code#G88:_Reserved">G88: Reserved</a>
  4796. Currently has no effect.
  4797. */
  4798. // Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4799. case 88:
  4800. break;
  4801. #endif // ENABLE_MESH_BED_LEVELING
  4802. /*!
  4803. ### G90 - Switch off relative mode <a href="https://reprap.org/wiki/G-code#G90:_Set_to_Absolute_Positioning">G90: Set to Absolute Positioning</a>
  4804. All coordinates from now on are absolute relative to the origin of the machine. E axis is left intact.
  4805. */
  4806. case 90: {
  4807. axis_relative_modes &= ~(X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK);
  4808. }
  4809. break;
  4810. /*!
  4811. ### G91 - Switch on relative mode <a href="https://reprap.org/wiki/G-code#G91:_Set_to_Relative_Positioning">G91: Set to Relative Positioning</a>
  4812. All coordinates from now on are relative to the last position. E axis is left intact.
  4813. */
  4814. case 91: {
  4815. axis_relative_modes |= X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK;
  4816. }
  4817. break;
  4818. /*!
  4819. ### G92 - Set position <a href="https://reprap.org/wiki/G-code#G92:_Set_Position">G92: Set Position</a>
  4820. It is used for setting the current position of each axis. The parameters are always absolute to the origin.
  4821. If a parameter is omitted, that axis will not be affected.
  4822. If `X`, `Y`, or `Z` axis are specified, the move afterwards might stutter because of Mesh Bed Leveling. `E` axis is not affected if the target position is 0 (`G92 E0`).
  4823. A G92 without coordinates will reset all axes to zero on some firmware. This is not the case for Prusa-Firmware!
  4824. #### Usage
  4825. G92 [ X | Y | Z | E ]
  4826. #### Parameters
  4827. - `X` - new X axis position
  4828. - `Y` - new Y axis position
  4829. - `Z` - new Z axis position
  4830. - `E` - new extruder position
  4831. */
  4832. case 92: {
  4833. gcode_G92();
  4834. }
  4835. break;
  4836. /*!
  4837. ### G98 - Activate farm mode <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode</a>
  4838. Enable Prusa-specific Farm functions and g-code.
  4839. See Internal Prusa commands.
  4840. */
  4841. case 98:
  4842. farm_mode = 1;
  4843. PingTime = _millis();
  4844. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  4845. SilentModeMenu = SILENT_MODE_OFF;
  4846. eeprom_update_byte((unsigned char *)EEPROM_SILENT, SilentModeMenu);
  4847. fCheckModeInit(); // alternatively invoke printer reset
  4848. break;
  4849. /*! ### G99 - Deactivate farm mode <a href="https://reprap.org/wiki/G-code#G99:_Deactivate_farm_mode">G99: Deactivate farm mode</a>
  4850. Disables Prusa-specific Farm functions and g-code.
  4851. */
  4852. case 99:
  4853. farm_mode = 0;
  4854. lcd_printer_connected();
  4855. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  4856. lcd_update(2);
  4857. fCheckModeInit(); // alternatively invoke printer reset
  4858. break;
  4859. default:
  4860. printf_P(MSG_UNKNOWN_CODE, 'G', cmdbuffer + bufindr + CMDHDRSIZE);
  4861. }
  4862. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4863. gcode_in_progress = 0;
  4864. } // end if(code_seen('G'))
  4865. /*!
  4866. ### End of G-Codes
  4867. */
  4868. /*!
  4869. ---------------------------------------------------------------------------------
  4870. # M Commands
  4871. */
  4872. else if(code_seen('M'))
  4873. {
  4874. int index;
  4875. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4876. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4877. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4878. printf_P(PSTR("Invalid M code: %s\n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4879. } else
  4880. {
  4881. mcode_in_progress = code_value_short();
  4882. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4883. switch(mcode_in_progress)
  4884. {
  4885. /*!
  4886. ### M17 - Enable all axes <a href="https://reprap.org/wiki/G-code#M17:_Enable.2FPower_all_stepper_motors">M17: Enable/Power all stepper motors</a>
  4887. */
  4888. case 17:
  4889. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE c=20
  4890. enable_x();
  4891. enable_y();
  4892. enable_z();
  4893. enable_e0();
  4894. enable_e1();
  4895. enable_e2();
  4896. break;
  4897. #ifdef SDSUPPORT
  4898. /*!
  4899. ### M20 - SD Card file list <a href="https://reprap.org/wiki/G-code#M20:_List_SD_card">M20: List SD card</a>
  4900. #### Usage
  4901. M20 [ L | T ]
  4902. #### Parameters
  4903. - `T` - Report timestamps as well. The value is one uint32_t encoded as hex. Requires host software parsing (Cap:EXTENDED_M20).
  4904. - `L` - Reports long filenames instead of just short filenames. Requires host software parsing (Cap:EXTENDED_M20).
  4905. */
  4906. case 20:
  4907. KEEPALIVE_STATE(NOT_BUSY); // do not send busy messages during listing. Inhibits the output of manage_heater()
  4908. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4909. card.ls(CardReader::ls_param(code_seen('L'), code_seen('T')));
  4910. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4911. break;
  4912. /*!
  4913. ### M21 - Init SD card <a href="https://reprap.org/wiki/G-code#M21:_Initialize_SD_card">M21: Initialize SD card</a>
  4914. */
  4915. case 21:
  4916. card.initsd();
  4917. break;
  4918. /*!
  4919. ### M22 - Release SD card <a href="https://reprap.org/wiki/G-code#M22:_Release_SD_card">M22: Release SD card</a>
  4920. */
  4921. case 22:
  4922. card.release();
  4923. break;
  4924. /*!
  4925. ### M23 - Select file <a href="https://reprap.org/wiki/G-code#M23:_Select_SD_file">M23: Select SD file</a>
  4926. #### Usage
  4927. M23 [filename]
  4928. */
  4929. case 23:
  4930. starpos = (strchr(strchr_pointer + 4,'*'));
  4931. if(starpos!=NULL)
  4932. *(starpos)='\0';
  4933. card.openFileReadFilteredGcode(strchr_pointer + 4, true);
  4934. break;
  4935. /*!
  4936. ### M24 - Start SD print <a href="https://reprap.org/wiki/G-code#M24:_Start.2Fresume_SD_print">M24: Start/resume SD print</a>
  4937. */
  4938. case 24:
  4939. if (isPrintPaused)
  4940. lcd_resume_print();
  4941. else
  4942. {
  4943. if (!card.get_sdpos())
  4944. {
  4945. // A new print has started from scratch, reset stats
  4946. failstats_reset_print();
  4947. #ifndef LA_NOCOMPAT
  4948. la10c_reset();
  4949. #endif
  4950. }
  4951. card.startFileprint();
  4952. starttime=_millis();
  4953. }
  4954. break;
  4955. /*!
  4956. ### M26 - Set SD index <a href="https://reprap.org/wiki/G-code#M26:_Set_SD_position">M26: Set SD position</a>
  4957. Set position in SD card file to index in bytes.
  4958. This command is expected to be called after M23 and before M24.
  4959. Otherwise effect of this command is undefined.
  4960. #### Usage
  4961. M26 [ S ]
  4962. #### Parameters
  4963. - `S` - Index in bytes
  4964. */
  4965. case 26:
  4966. if(card.cardOK && code_seen('S')) {
  4967. long index = code_value_long();
  4968. card.setIndex(index);
  4969. // We don't disable interrupt during update of sdpos_atomic
  4970. // as we expect, that SD card print is not active in this moment
  4971. sdpos_atomic = index;
  4972. }
  4973. break;
  4974. /*!
  4975. ### M27 - Get SD status <a href="https://reprap.org/wiki/G-code#M27:_Report_SD_print_status">M27: Report SD print status</a>
  4976. #### Usage
  4977. M27 [ P ]
  4978. #### Parameters
  4979. - `P` - Show full SFN path instead of LFN only.
  4980. */
  4981. case 27:
  4982. card.getStatus(code_seen('P'));
  4983. break;
  4984. /*!
  4985. ### M28 - Start SD write <a href="https://reprap.org/wiki/G-code#M28:_Begin_write_to_SD_card">M28: Begin write to SD card</a>
  4986. */
  4987. case 28:
  4988. starpos = (strchr(strchr_pointer + 4,'*'));
  4989. if(starpos != NULL){
  4990. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4991. strchr_pointer = strchr(npos,' ') + 1;
  4992. *(starpos) = '\0';
  4993. }
  4994. card.openFileWrite(strchr_pointer+4);
  4995. break;
  4996. /*! ### M29 - Stop SD write <a href="https://reprap.org/wiki/G-code#M29:_Stop_writing_to_SD_card">M29: Stop writing to SD card</a>
  4997. Stops writing to the SD file signaling the end of the uploaded file. It is processed very early and it's not written to the card.
  4998. */
  4999. case 29:
  5000. //processed in write to file routine above
  5001. //card,saving = false;
  5002. break;
  5003. /*!
  5004. ### M30 - Delete file <a href="https://reprap.org/wiki/G-code#M30:_Delete_a_file_on_the_SD_card">M30: Delete a file on the SD card</a>
  5005. #### Usage
  5006. M30 [filename]
  5007. */
  5008. case 30:
  5009. if (card.cardOK){
  5010. card.closefile();
  5011. starpos = (strchr(strchr_pointer + 4,'*'));
  5012. if(starpos != NULL){
  5013. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  5014. strchr_pointer = strchr(npos,' ') + 1;
  5015. *(starpos) = '\0';
  5016. }
  5017. card.removeFile(strchr_pointer + 4);
  5018. }
  5019. break;
  5020. /*!
  5021. ### M32 - Select file and start SD print <a href="https://reprap.org/wiki/G-code#M32:_Select_file_and_start_SD_print">M32: Select file and start SD print</a>
  5022. @todo What are the parameters P and S for in M32?
  5023. */
  5024. case 32:
  5025. {
  5026. if(card.sdprinting) {
  5027. st_synchronize();
  5028. }
  5029. starpos = (strchr(strchr_pointer + 4,'*'));
  5030. char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  5031. if(namestartpos==NULL)
  5032. {
  5033. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  5034. }
  5035. else
  5036. namestartpos++; //to skip the '!'
  5037. if(starpos!=NULL)
  5038. *(starpos)='\0';
  5039. bool call_procedure=(code_seen('P'));
  5040. if(strchr_pointer>namestartpos)
  5041. call_procedure=false; //false alert, 'P' found within filename
  5042. if( card.cardOK )
  5043. {
  5044. card.openFileReadFilteredGcode(namestartpos,!call_procedure);
  5045. if(code_seen('S'))
  5046. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  5047. card.setIndex(code_value_long());
  5048. card.startFileprint();
  5049. if(!call_procedure)
  5050. {
  5051. if(!card.get_sdpos())
  5052. {
  5053. // A new print has started from scratch, reset stats
  5054. failstats_reset_print();
  5055. #ifndef LA_NOCOMPAT
  5056. la10c_reset();
  5057. #endif
  5058. }
  5059. starttime=_millis(); // procedure calls count as normal print time.
  5060. }
  5061. }
  5062. } break;
  5063. /*!
  5064. ### M928 - Start SD logging <a href="https://reprap.org/wiki/G-code#M928:_Start_SD_logging">M928: Start SD logging</a>
  5065. #### Usage
  5066. M928 [filename]
  5067. */
  5068. case 928:
  5069. starpos = (strchr(strchr_pointer + 5,'*'));
  5070. if(starpos != NULL){
  5071. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  5072. strchr_pointer = strchr(npos,' ') + 1;
  5073. *(starpos) = '\0';
  5074. }
  5075. card.openLogFile(strchr_pointer+5);
  5076. break;
  5077. #endif //SDSUPPORT
  5078. /*!
  5079. ### M31 - Report current print time <a href="https://reprap.org/wiki/G-code#M31:_Output_time_since_last_M109_or_SD_card_start_to_serial">M31: Output time since last M109 or SD card start to serial</a>
  5080. */
  5081. case 31: //M31 take time since the start of the SD print or an M109 command
  5082. {
  5083. stoptime=_millis();
  5084. char time[30];
  5085. unsigned long t=(stoptime-starttime)/1000;
  5086. int sec,min;
  5087. min=t/60;
  5088. sec=t%60;
  5089. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  5090. SERIAL_ECHO_START;
  5091. SERIAL_ECHOLN(time);
  5092. lcd_setstatus(time);
  5093. autotempShutdown();
  5094. }
  5095. break;
  5096. /*!
  5097. ### M42 - Set pin state <a href="https://reprap.org/wiki/G-code#M42:_Switch_I.2FO_pin">M42: Switch I/O pin</a>
  5098. #### Usage
  5099. M42 [ P | S ]
  5100. #### Parameters
  5101. - `P` - Pin number.
  5102. - `S` - Pin value. If the pin is analog, values are from 0 to 255. If the pin is digital, values are from 0 to 1.
  5103. */
  5104. case 42:
  5105. if (code_seen('S'))
  5106. {
  5107. uint8_t pin_status = code_value_uint8();
  5108. int8_t pin_number = LED_PIN;
  5109. if (code_seen('P'))
  5110. pin_number = code_value_uint8();
  5111. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  5112. {
  5113. if ((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number)
  5114. {
  5115. pin_number = -1;
  5116. break;
  5117. }
  5118. }
  5119. #if defined(FAN_PIN) && FAN_PIN > -1
  5120. if (pin_number == FAN_PIN)
  5121. fanSpeed = pin_status;
  5122. #endif
  5123. if (pin_number > -1)
  5124. {
  5125. pinMode(pin_number, OUTPUT);
  5126. digitalWrite(pin_number, pin_status);
  5127. analogWrite(pin_number, pin_status);
  5128. }
  5129. }
  5130. break;
  5131. /*!
  5132. ### M44 - Reset the bed skew and offset calibration <a href="https://reprap.org/wiki/G-code#M44:_Reset_the_bed_skew_and_offset_calibration">M44: Reset the bed skew and offset calibration</a>
  5133. */
  5134. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  5135. // Reset the baby step value and the baby step applied flag.
  5136. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  5137. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  5138. // Reset the skew and offset in both RAM and EEPROM.
  5139. reset_bed_offset_and_skew();
  5140. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  5141. // the planner will not perform any adjustments in the XY plane.
  5142. // Wait for the motors to stop and update the current position with the absolute values.
  5143. world2machine_revert_to_uncorrected();
  5144. break;
  5145. /*!
  5146. ### M45 - Bed skew and offset with manual Z up <a href="https://reprap.org/wiki/G-code#M45:_Bed_skew_and_offset_with_manual_Z_up">M45: Bed skew and offset with manual Z up</a>
  5147. #### Usage
  5148. M45 [ V ]
  5149. #### Parameters
  5150. - `V` - Verbosity level 1, 10 and 20 (low, mid, high). Only when SUPPORT_VERBOSITY is defined. Optional.
  5151. - `Z` - If it is provided, only Z calibration will run. Otherwise full calibration is executed.
  5152. */
  5153. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  5154. {
  5155. int8_t verbosity_level = 0;
  5156. bool only_Z = code_seen('Z');
  5157. #ifdef SUPPORT_VERBOSITY
  5158. if (code_seen('V'))
  5159. {
  5160. // Just 'V' without a number counts as V1.
  5161. char c = strchr_pointer[1];
  5162. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  5163. }
  5164. #endif //SUPPORT_VERBOSITY
  5165. gcode_M45(only_Z, verbosity_level);
  5166. }
  5167. break;
  5168. /*!
  5169. ### M46 - Show the assigned IP address <a href="https://reprap.org/wiki/G-code#M46:_Show_the_assigned_IP_address">M46: Show the assigned IP address.</a>
  5170. */
  5171. case 46:
  5172. {
  5173. // M46: Prusa3D: Show the assigned IP address.
  5174. if (card.ToshibaFlashAir_isEnabled()) {
  5175. uint8_t ip[4];
  5176. if (card.ToshibaFlashAir_GetIP(ip)) {
  5177. // SERIAL_PROTOCOLPGM("Toshiba FlashAir current IP: ");
  5178. SERIAL_PROTOCOL(uint8_t(ip[0]));
  5179. SERIAL_PROTOCOL('.');
  5180. SERIAL_PROTOCOL(uint8_t(ip[1]));
  5181. SERIAL_PROTOCOL('.');
  5182. SERIAL_PROTOCOL(uint8_t(ip[2]));
  5183. SERIAL_PROTOCOL('.');
  5184. SERIAL_PROTOCOLLN(uint8_t(ip[3]));
  5185. } else {
  5186. SERIAL_PROTOCOLPGM("?Toshiba FlashAir GetIP failed\n");
  5187. }
  5188. } else {
  5189. SERIAL_PROTOCOLLNPGM("n/a");
  5190. }
  5191. break;
  5192. }
  5193. /*!
  5194. ### M47 - Show end stops dialog on the display <a href="https://reprap.org/wiki/G-code#M47:_Show_end_stops_dialog_on_the_display">M47: Show end stops dialog on the display</a>
  5195. */
  5196. case 47:
  5197. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5198. lcd_diag_show_end_stops();
  5199. KEEPALIVE_STATE(IN_HANDLER);
  5200. break;
  5201. #if 0
  5202. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  5203. {
  5204. // Disable the default update procedure of the display. We will do a modal dialog.
  5205. lcd_update_enable(false);
  5206. // Let the planner use the uncorrected coordinates.
  5207. mbl.reset();
  5208. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  5209. // the planner will not perform any adjustments in the XY plane.
  5210. // Wait for the motors to stop and update the current position with the absolute values.
  5211. world2machine_revert_to_uncorrected();
  5212. // Move the print head close to the bed.
  5213. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5214. 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);
  5215. st_synchronize();
  5216. // Home in the XY plane.
  5217. set_destination_to_current();
  5218. int l_feedmultiply = setup_for_endstop_move();
  5219. home_xy();
  5220. int8_t verbosity_level = 0;
  5221. if (code_seen('V')) {
  5222. // Just 'V' without a number counts as V1.
  5223. char c = strchr_pointer[1];
  5224. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  5225. }
  5226. bool success = scan_bed_induction_points(verbosity_level);
  5227. clean_up_after_endstop_move(l_feedmultiply);
  5228. // Print head up.
  5229. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5230. 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);
  5231. st_synchronize();
  5232. lcd_update_enable(true);
  5233. break;
  5234. }
  5235. #endif
  5236. #ifdef ENABLE_AUTO_BED_LEVELING
  5237. #ifdef Z_PROBE_REPEATABILITY_TEST
  5238. /*!
  5239. ### M48 - Z-Probe repeatability measurement function <a href="https://reprap.org/wiki/G-code#M48:_Measure_Z-Probe_repeatability">M48: Measure Z-Probe repeatability</a>
  5240. This function assumes the bed has been homed. Specifically, that a G28 command as been issued prior to invoking the M48 Z-Probe repeatability measurement function. Any information generated by a prior G29 Bed leveling command will be lost and needs to be regenerated.
  5241. The number of samples will default to 10 if not specified. You can use upper or lower case letters for any of the options EXCEPT n. n must be in lower case because Marlin uses a capital N for its communication protocol and will get horribly confused if you send it a capital N.
  5242. @todo Why would you check for both uppercase and lowercase? Seems wasteful.
  5243. #### Usage
  5244. M48 [ n | X | Y | V | L ]
  5245. #### Parameters
  5246. - `n` - Number of samples. Valid values 4-50
  5247. - `X` - X position for samples
  5248. - `Y` - Y position for samples
  5249. - `V` - Verbose level. Valid values 1-4
  5250. - `L` - Legs of movementprior to doing probe. Valid values 1-15
  5251. */
  5252. case 48: // M48 Z-Probe repeatability
  5253. {
  5254. #if Z_MIN_PIN == -1
  5255. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  5256. #endif
  5257. double sum=0.0;
  5258. double mean=0.0;
  5259. double sigma=0.0;
  5260. double sample_set[50];
  5261. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  5262. double X_current, Y_current, Z_current;
  5263. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  5264. if (code_seen('V') || code_seen('v')) {
  5265. verbose_level = code_value();
  5266. if (verbose_level<0 || verbose_level>4 ) {
  5267. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  5268. goto Sigma_Exit;
  5269. }
  5270. }
  5271. if (verbose_level > 0) {
  5272. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  5273. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  5274. }
  5275. if (code_seen('n')) {
  5276. n_samples = code_value();
  5277. if (n_samples<4 || n_samples>50 ) {
  5278. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  5279. goto Sigma_Exit;
  5280. }
  5281. }
  5282. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  5283. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  5284. Z_current = st_get_position_mm(Z_AXIS);
  5285. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5286. ext_position = st_get_position_mm(E_AXIS);
  5287. if (code_seen('X') || code_seen('x') ) {
  5288. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  5289. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  5290. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  5291. goto Sigma_Exit;
  5292. }
  5293. }
  5294. if (code_seen('Y') || code_seen('y') ) {
  5295. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  5296. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  5297. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  5298. goto Sigma_Exit;
  5299. }
  5300. }
  5301. if (code_seen('L') || code_seen('l') ) {
  5302. n_legs = code_value();
  5303. if ( n_legs==1 )
  5304. n_legs = 2;
  5305. if ( n_legs<0 || n_legs>15 ) {
  5306. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  5307. goto Sigma_Exit;
  5308. }
  5309. }
  5310. //
  5311. // Do all the preliminary setup work. First raise the probe.
  5312. //
  5313. st_synchronize();
  5314. plan_bed_level_matrix.set_to_identity();
  5315. plan_buffer_line( X_current, Y_current, Z_start_location,
  5316. ext_position,
  5317. homing_feedrate[Z_AXIS]/60,
  5318. active_extruder);
  5319. st_synchronize();
  5320. //
  5321. // Now get everything to the specified probe point So we can safely do a probe to
  5322. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  5323. // use that as a starting point for each probe.
  5324. //
  5325. if (verbose_level > 2)
  5326. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  5327. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5328. ext_position,
  5329. homing_feedrate[X_AXIS]/60,
  5330. active_extruder);
  5331. st_synchronize();
  5332. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  5333. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  5334. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5335. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  5336. //
  5337. // OK, do the inital probe to get us close to the bed.
  5338. // Then retrace the right amount and use that in subsequent probes
  5339. //
  5340. int l_feedmultiply = setup_for_endstop_move();
  5341. run_z_probe();
  5342. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5343. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5344. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5345. ext_position,
  5346. homing_feedrate[X_AXIS]/60,
  5347. active_extruder);
  5348. st_synchronize();
  5349. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5350. for( n=0; n<n_samples; n++) {
  5351. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  5352. if ( n_legs) {
  5353. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  5354. int rotational_direction, l;
  5355. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  5356. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  5357. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  5358. //SERIAL_ECHOPAIR("starting radius: ",radius);
  5359. //SERIAL_ECHOPAIR(" theta: ",theta);
  5360. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  5361. //SERIAL_PROTOCOLLNPGM("");
  5362. for( l=0; l<n_legs-1; l++) {
  5363. if (rotational_direction==1)
  5364. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5365. else
  5366. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5367. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  5368. if ( radius<0.0 )
  5369. radius = -radius;
  5370. X_current = X_probe_location + cos(theta) * radius;
  5371. Y_current = Y_probe_location + sin(theta) * radius;
  5372. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  5373. X_current = X_MIN_POS;
  5374. if ( X_current>X_MAX_POS)
  5375. X_current = X_MAX_POS;
  5376. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  5377. Y_current = Y_MIN_POS;
  5378. if ( Y_current>Y_MAX_POS)
  5379. Y_current = Y_MAX_POS;
  5380. if (verbose_level>3 ) {
  5381. SERIAL_ECHOPAIR("x: ", X_current);
  5382. SERIAL_ECHOPAIR("y: ", Y_current);
  5383. SERIAL_PROTOCOLLNPGM("");
  5384. }
  5385. do_blocking_move_to( X_current, Y_current, Z_current );
  5386. }
  5387. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5388. }
  5389. int l_feedmultiply = setup_for_endstop_move();
  5390. run_z_probe();
  5391. sample_set[n] = current_position[Z_AXIS];
  5392. //
  5393. // Get the current mean for the data points we have so far
  5394. //
  5395. sum=0.0;
  5396. for( j=0; j<=n; j++) {
  5397. sum = sum + sample_set[j];
  5398. }
  5399. mean = sum / (double (n+1));
  5400. //
  5401. // Now, use that mean to calculate the standard deviation for the
  5402. // data points we have so far
  5403. //
  5404. sum=0.0;
  5405. for( j=0; j<=n; j++) {
  5406. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5407. }
  5408. sigma = sqrt( sum / (double (n+1)) );
  5409. if (verbose_level > 1) {
  5410. SERIAL_PROTOCOL(n+1);
  5411. SERIAL_PROTOCOL(" of ");
  5412. SERIAL_PROTOCOL(n_samples);
  5413. SERIAL_PROTOCOLPGM(" z: ");
  5414. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5415. }
  5416. if (verbose_level > 2) {
  5417. SERIAL_PROTOCOL(" mean: ");
  5418. SERIAL_PROTOCOL_F(mean,6);
  5419. SERIAL_PROTOCOL(" sigma: ");
  5420. SERIAL_PROTOCOL_F(sigma,6);
  5421. }
  5422. if (verbose_level > 0)
  5423. SERIAL_PROTOCOLPGM("\n");
  5424. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5425. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5426. st_synchronize();
  5427. }
  5428. _delay(1000);
  5429. clean_up_after_endstop_move(l_feedmultiply);
  5430. // enable_endstops(true);
  5431. if (verbose_level > 0) {
  5432. SERIAL_PROTOCOLPGM("Mean: ");
  5433. SERIAL_PROTOCOL_F(mean, 6);
  5434. SERIAL_PROTOCOLPGM("\n");
  5435. }
  5436. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5437. SERIAL_PROTOCOL_F(sigma, 6);
  5438. SERIAL_PROTOCOLPGM("\n\n");
  5439. Sigma_Exit:
  5440. break;
  5441. }
  5442. #endif // Z_PROBE_REPEATABILITY_TEST
  5443. #endif // ENABLE_AUTO_BED_LEVELING
  5444. /*!
  5445. ### M73 - Set/get print progress <a href="https://reprap.org/wiki/G-code#M73:_Set.2FGet_build_percentage">M73: Set/Get build percentage</a>
  5446. #### Usage
  5447. M73 [ P | R | Q | S | C | D ]
  5448. #### Parameters
  5449. - `P` - Percent in normal mode
  5450. - `R` - Time remaining in normal mode
  5451. - `Q` - Percent in silent mode
  5452. - `S` - Time in silent mode
  5453. - `C` - Time to change/pause/user interaction in normal mode
  5454. - `D` - Time to change/pause/user interaction in silent mode
  5455. */
  5456. case 73: //M73 show percent done, time remaining and time to change/pause
  5457. {
  5458. if(code_seen('P')) print_percent_done_normal = code_value_uint8();
  5459. if(code_seen('R')) print_time_remaining_normal = code_value();
  5460. if(code_seen('Q')) print_percent_done_silent = code_value_uint8();
  5461. if(code_seen('S')) print_time_remaining_silent = code_value();
  5462. if(code_seen('C')){
  5463. float print_time_to_change_normal_f = code_value_float();
  5464. print_time_to_change_normal = ( print_time_to_change_normal_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_normal_f;
  5465. }
  5466. if(code_seen('D')){
  5467. float print_time_to_change_silent_f = code_value_float();
  5468. print_time_to_change_silent = ( print_time_to_change_silent_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_silent_f;
  5469. }
  5470. {
  5471. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %hhd; print time remaining in mins: %d; Change in mins: %d\n");
  5472. printf_P(_msg_mode_done_remain, _N("NORMAL"), int8_t(print_percent_done_normal), print_time_remaining_normal, print_time_to_change_normal);
  5473. printf_P(_msg_mode_done_remain, _N("SILENT"), int8_t(print_percent_done_silent), print_time_remaining_silent, print_time_to_change_silent);
  5474. }
  5475. break;
  5476. }
  5477. /*!
  5478. ### M104 - Set hotend temperature <a href="https://reprap.org/wiki/G-code#M104:_Set_Extruder_Temperature">M104: Set Extruder Temperature</a>
  5479. #### Usage
  5480. M104 [ S ]
  5481. #### Parameters
  5482. - `S` - Target temperature
  5483. */
  5484. case 104: // M104
  5485. {
  5486. uint8_t extruder;
  5487. if(setTargetedHotend(104,extruder)){
  5488. break;
  5489. }
  5490. if (code_seen('S'))
  5491. {
  5492. setTargetHotendSafe(code_value(), extruder);
  5493. }
  5494. break;
  5495. }
  5496. /*!
  5497. ### M112 - Emergency stop <a href="https://reprap.org/wiki/G-code#M112:_Full_.28Emergency.29_Stop">M112: Full (Emergency) Stop</a>
  5498. It is processed much earlier as to bypass the cmdqueue.
  5499. */
  5500. case 112:
  5501. kill(MSG_M112_KILL, 3);
  5502. break;
  5503. /*!
  5504. ### M140 - Set bed temperature <a href="https://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29">M140: Set Bed Temperature (Fast)</a>
  5505. #### Usage
  5506. M140 [ S ]
  5507. #### Parameters
  5508. - `S` - Target temperature
  5509. */
  5510. case 140:
  5511. if (code_seen('S')) setTargetBed(code_value());
  5512. break;
  5513. /*!
  5514. ### M105 - Report temperatures <a href="https://reprap.org/wiki/G-code#M105:_Get_Extruder_Temperature">M105: Get Extruder Temperature</a>
  5515. Prints temperatures:
  5516. - `T:` - Hotend (actual / target)
  5517. - `B:` - Bed (actual / target)
  5518. - `Tx:` - x Tool (actual / target)
  5519. - `@:` - Hotend power
  5520. - `B@:` - Bed power
  5521. - `P:` - PINDAv2 actual (only MK2.5/s and MK3/s)
  5522. - `A:` - Ambient actual (only MK3/s)
  5523. _Example:_
  5524. ok T:20.2 /0.0 B:19.1 /0.0 T0:20.2 /0.0 @:0 B@:0 P:19.8 A:26.4
  5525. */
  5526. case 105:
  5527. {
  5528. uint8_t extruder;
  5529. if(setTargetedHotend(105, extruder)){
  5530. break;
  5531. }
  5532. SERIAL_PROTOCOLPGM("ok ");
  5533. gcode_M105(extruder);
  5534. cmdqueue_pop_front(); //prevent an ok after the command since this command uses an ok at the beginning.
  5535. cmdbuffer_front_already_processed = true;
  5536. break;
  5537. }
  5538. #if defined(AUTO_REPORT)
  5539. /*!
  5540. ### M155 - Automatically send status <a href="https://reprap.org/wiki/G-code#M155:_Automatically_send_temperatures">M155: Automatically send temperatures</a>
  5541. #### Usage
  5542. M155 [ S ] [ C ]
  5543. #### Parameters
  5544. - `S` - Set autoreporting interval in seconds. 0 to disable. Maximum: 255
  5545. - `C` - Activate auto-report function (bit mask). Default is temperature.
  5546. bit 0 = Auto-report temperatures
  5547. bit 1 = Auto-report fans
  5548. bit 2 = Auto-report position
  5549. bit 3 = free
  5550. bit 4 = free
  5551. bit 5 = free
  5552. bit 6 = free
  5553. bit 7 = free
  5554. */
  5555. case 155:
  5556. {
  5557. if (code_seen('S')){
  5558. autoReportFeatures.SetPeriod( code_value_uint8() );
  5559. }
  5560. if (code_seen('C')){
  5561. autoReportFeatures.SetMask(code_value_uint8());
  5562. } else{
  5563. autoReportFeatures.SetMask(1); //Backwards compability to host systems like Octoprint to send only temp if paramerter `C`isn't used.
  5564. }
  5565. }
  5566. break;
  5567. #endif //AUTO_REPORT
  5568. /*!
  5569. ### M109 - Wait for extruder temperature <a href="https://reprap.org/wiki/G-code#M109:_Set_Extruder_Temperature_and_Wait">M109: Set Extruder Temperature and Wait</a>
  5570. #### Usage
  5571. M104 [ B | R | S ]
  5572. #### Parameters (not mandatory)
  5573. - `S` - Set extruder temperature
  5574. - `R` - Set extruder temperature
  5575. - `B` - Set max. extruder temperature, while `S` is min. temperature. Not active in default, only if AUTOTEMP is defined in source code.
  5576. Parameters S and R are treated identically.
  5577. Command always waits for both cool down and heat up.
  5578. If no parameters are supplied waits for previously set extruder temperature.
  5579. */
  5580. case 109:
  5581. {
  5582. uint8_t extruder;
  5583. if(setTargetedHotend(109, extruder)){
  5584. break;
  5585. }
  5586. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5587. heating_status = HeatingStatus::EXTRUDER_HEATING;
  5588. if (farm_mode) { prusa_statistics(1); };
  5589. #ifdef AUTOTEMP
  5590. autotemp_enabled=false;
  5591. #endif
  5592. if (code_seen('S')) {
  5593. setTargetHotendSafe(code_value(), extruder);
  5594. } else if (code_seen('R')) {
  5595. setTargetHotendSafe(code_value(), extruder);
  5596. }
  5597. #ifdef AUTOTEMP
  5598. if (code_seen('S')) autotemp_min=code_value();
  5599. if (code_seen('B')) autotemp_max=code_value();
  5600. if (code_seen('F'))
  5601. {
  5602. autotemp_factor=code_value();
  5603. autotemp_enabled=true;
  5604. }
  5605. #endif
  5606. codenum = _millis();
  5607. /* See if we are heating up or cooling down */
  5608. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5609. cancel_heatup = false;
  5610. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5611. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5612. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  5613. if (farm_mode) { prusa_statistics(2); };
  5614. //starttime=_millis();
  5615. previous_millis_cmd.start();
  5616. }
  5617. break;
  5618. /*!
  5619. ### M190 - Wait for bed temperature <a href="https://reprap.org/wiki/G-code#M190:_Wait_for_bed_temperature_to_reach_target_temp">M190: Wait for bed temperature to reach target temp</a>
  5620. #### Usage
  5621. M190 [ R | S ]
  5622. #### Parameters (not mandatory)
  5623. - `S` - Set extruder temperature and wait for heating
  5624. - `R` - Set extruder temperature and wait for heating or cooling
  5625. If no parameter is supplied, waits for heating or cooling to previously set temperature.
  5626. */
  5627. case 190:
  5628. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5629. {
  5630. bool CooldownNoWait = false;
  5631. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5632. heating_status = HeatingStatus::BED_HEATING;
  5633. if (farm_mode) { prusa_statistics(1); };
  5634. if (code_seen('S'))
  5635. {
  5636. setTargetBed(code_value());
  5637. CooldownNoWait = true;
  5638. }
  5639. else if (code_seen('R'))
  5640. {
  5641. setTargetBed(code_value());
  5642. }
  5643. codenum = _millis();
  5644. cancel_heatup = false;
  5645. target_direction = isHeatingBed(); // true if heating, false if cooling
  5646. while ( (!cancel_heatup) && (target_direction ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false))) )
  5647. {
  5648. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5649. {
  5650. if (!farm_mode) {
  5651. float tt = degHotend(active_extruder);
  5652. SERIAL_PROTOCOLPGM("T:");
  5653. SERIAL_PROTOCOL(tt);
  5654. SERIAL_PROTOCOLPGM(" E:");
  5655. SERIAL_PROTOCOL((int)active_extruder);
  5656. SERIAL_PROTOCOLPGM(" B:");
  5657. SERIAL_PROTOCOL_F(degBed(), 1);
  5658. SERIAL_PROTOCOLLN();
  5659. }
  5660. codenum = _millis();
  5661. }
  5662. manage_heater();
  5663. manage_inactivity();
  5664. lcd_update(0);
  5665. }
  5666. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5667. heating_status = HeatingStatus::BED_HEATING_COMPLETE;
  5668. previous_millis_cmd.start();
  5669. }
  5670. #endif
  5671. break;
  5672. #if defined(FAN_PIN) && FAN_PIN > -1
  5673. /*!
  5674. ### M106 - Set fan speed <a href="https://reprap.org/wiki/G-code#M106:_Fan_On">M106: Fan On</a>
  5675. #### Usage
  5676. M106 [ S ]
  5677. #### Parameters
  5678. - `S` - Specifies the duty cycle of the print fan. Allowed values are 0-255. If it's omitted, a value of 255 is used.
  5679. */
  5680. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5681. if (code_seen('S')){
  5682. fanSpeed = code_value_uint8();
  5683. }
  5684. else {
  5685. fanSpeed = 255;
  5686. }
  5687. break;
  5688. /*!
  5689. ### M107 - Fan off <a href="https://reprap.org/wiki/G-code#M107:_Fan_Off">M107: Fan Off</a>
  5690. */
  5691. case 107:
  5692. fanSpeed = 0;
  5693. break;
  5694. #endif //FAN_PIN
  5695. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5696. /*!
  5697. ### M80 - Turn on the Power Supply <a href="https://reprap.org/wiki/G-code#M80:_ATX_Power_On">M80: ATX Power On</a>
  5698. Only works if the firmware is compiled with PS_ON_PIN defined.
  5699. */
  5700. case 80:
  5701. SET_OUTPUT(PS_ON_PIN); //GND
  5702. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5703. // If you have a switch on suicide pin, this is useful
  5704. // if you want to start another print with suicide feature after
  5705. // a print without suicide...
  5706. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5707. SET_OUTPUT(SUICIDE_PIN);
  5708. WRITE(SUICIDE_PIN, HIGH);
  5709. #endif
  5710. powersupply = true;
  5711. LCD_MESSAGERPGM(MSG_WELCOME);
  5712. lcd_update(0);
  5713. break;
  5714. /*!
  5715. ### M81 - Turn off Power Supply <a href="https://reprap.org/wiki/G-code#M81:_ATX_Power_Off">M81: ATX Power Off</a>
  5716. Only works if the firmware is compiled with PS_ON_PIN defined.
  5717. */
  5718. case 81:
  5719. disable_heater();
  5720. st_synchronize();
  5721. disable_e0();
  5722. disable_e1();
  5723. disable_e2();
  5724. finishAndDisableSteppers();
  5725. fanSpeed = 0;
  5726. _delay(1000); // Wait a little before to switch off
  5727. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5728. st_synchronize();
  5729. suicide();
  5730. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5731. SET_OUTPUT(PS_ON_PIN);
  5732. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5733. #endif
  5734. powersupply = false;
  5735. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5736. lcd_update(0);
  5737. break;
  5738. #endif
  5739. /*!
  5740. ### M82 - Set E axis to absolute mode <a href="https://reprap.org/wiki/G-code#M82:_Set_extruder_to_absolute_mode">M82: Set extruder to absolute mode</a>
  5741. Makes the extruder interpret extrusion as absolute positions.
  5742. */
  5743. case 82:
  5744. axis_relative_modes &= ~E_AXIS_MASK;
  5745. break;
  5746. /*!
  5747. ### M83 - Set E axis to relative mode <a href="https://reprap.org/wiki/G-code#M83:_Set_extruder_to_relative_mode">M83: Set extruder to relative mode</a>
  5748. Makes the extruder interpret extrusion values as relative positions.
  5749. */
  5750. case 83:
  5751. axis_relative_modes |= E_AXIS_MASK;
  5752. break;
  5753. /*!
  5754. ### M84 - Disable steppers <a href="https://reprap.org/wiki/G-code#M84:_Stop_idle_hold">M84: Stop idle hold</a>
  5755. This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5756. This command can be used without any additional parameters. In that case all steppers are disabled.
  5757. The file completeness check uses this parameter to detect an incomplete file. It has to be present at the end of a file with no parameters.
  5758. M84 [ S | X | Y | Z | E ]
  5759. - `S` - Seconds
  5760. - `X` - X axis
  5761. - `Y` - Y axis
  5762. - `Z` - Z axis
  5763. - `E` - Extruder
  5764. ### M18 - Disable steppers <a href="https://reprap.org/wiki/G-code#M18:_Disable_all_stepper_motors">M18: Disable all stepper motors</a>
  5765. Equal to M84 (compatibility)
  5766. */
  5767. case 18: //compatibility
  5768. case 84: // M84
  5769. if(code_seen('S')){
  5770. stepper_inactive_time = code_value() * 1000;
  5771. }
  5772. else
  5773. {
  5774. 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])));
  5775. if(all_axis)
  5776. {
  5777. st_synchronize();
  5778. disable_e0();
  5779. disable_e1();
  5780. disable_e2();
  5781. finishAndDisableSteppers();
  5782. }
  5783. else
  5784. {
  5785. st_synchronize();
  5786. if (code_seen('X')) disable_x();
  5787. if (code_seen('Y')) disable_y();
  5788. if (code_seen('Z')) disable_z();
  5789. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5790. if (code_seen('E')) {
  5791. disable_e0();
  5792. disable_e1();
  5793. disable_e2();
  5794. }
  5795. #endif
  5796. }
  5797. }
  5798. break;
  5799. /*!
  5800. ### M85 - Set max inactive time <a href="https://reprap.org/wiki/G-code#M85:_Set_Inactivity_Shutdown_Timer">M85: Set Inactivity Shutdown Timer</a>
  5801. #### Usage
  5802. M85 [ S ]
  5803. #### Parameters
  5804. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5805. */
  5806. case 85: // M85
  5807. if(code_seen('S')) {
  5808. max_inactive_time = code_value() * 1000;
  5809. }
  5810. break;
  5811. #ifdef SAFETYTIMER
  5812. /*!
  5813. ### M86 - Set safety timer expiration time <a href="https://reprap.org/wiki/G-code#M86:_Set_Safety_Timer_expiration_time">M86: Set Safety Timer expiration time</a>
  5814. When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5815. #### Usage
  5816. M86 [ S ]
  5817. #### Parameters
  5818. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5819. */
  5820. case 86:
  5821. if (code_seen('S')) {
  5822. safetytimer_inactive_time = code_value() * 1000;
  5823. safetyTimer.start();
  5824. }
  5825. break;
  5826. #endif
  5827. /*!
  5828. ### M92 Set Axis steps-per-unit <a href="https://reprap.org/wiki/G-code#M92:_Set_axis_steps_per_unit">M92: Set axis_steps_per_unit</a>
  5829. Allows programming of steps per unit (usually mm) for motor drives. These values are reset to firmware defaults on power on, unless saved to EEPROM if available (M500 in Marlin)
  5830. #### Usage
  5831. M92 [ X | Y | Z | E ]
  5832. #### Parameters
  5833. - `X` - Steps per unit for the X drive
  5834. - `Y` - Steps per unit for the Y drive
  5835. - `Z` - Steps per unit for the Z drive
  5836. - `E` - Steps per unit for the extruder drive
  5837. */
  5838. case 92:
  5839. for(int8_t i=0; i < NUM_AXIS; i++)
  5840. {
  5841. if(code_seen(axis_codes[i]))
  5842. {
  5843. if(i == E_AXIS) { // E
  5844. float value = code_value();
  5845. if(value < 20.0) {
  5846. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5847. cs.max_jerk[E_AXIS] *= factor;
  5848. max_feedrate[i] *= factor;
  5849. axis_steps_per_sqr_second[i] *= factor;
  5850. }
  5851. cs.axis_steps_per_unit[i] = value;
  5852. #if defined(FILAMENT_SENSOR) && defined(PAT9125)
  5853. fsensor_set_axis_steps_per_unit(value);
  5854. #endif
  5855. }
  5856. else {
  5857. cs.axis_steps_per_unit[i] = code_value();
  5858. }
  5859. }
  5860. }
  5861. reset_acceleration_rates();
  5862. break;
  5863. /*!
  5864. ### M110 - Set Line number <a href="https://reprap.org/wiki/G-code#M110:_Set_Current_Line_Number">M110: Set Current Line Number</a>
  5865. Sets the line number in G-code
  5866. #### Usage
  5867. M110 [ N ]
  5868. #### Parameters
  5869. - `N` - Line number
  5870. */
  5871. case 110:
  5872. if (code_seen('N'))
  5873. gcode_LastN = code_value_long();
  5874. break;
  5875. /*!
  5876. ### M113 - Get or set host keep-alive interval <a href="https://reprap.org/wiki/G-code#M113:_Host_Keepalive">M113: Host Keepalive</a>
  5877. During some lengthy processes, such as G29, Marlin may appear to the host to have “gone away.” The “host keepalive” feature will send messages to the host when Marlin is busy or waiting for user response so the host won’t try to reconnect (or disconnect).
  5878. #### Usage
  5879. M113 [ S ]
  5880. #### Parameters
  5881. - `S` - Seconds. Default is 2 seconds between "busy" messages
  5882. */
  5883. case 113:
  5884. if (code_seen('S')) {
  5885. host_keepalive_interval = code_value_uint8();
  5886. // NOMORE(host_keepalive_interval, 60);
  5887. }
  5888. else {
  5889. SERIAL_ECHO_START;
  5890. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5891. SERIAL_PROTOCOLLN();
  5892. }
  5893. break;
  5894. /*!
  5895. ### M115 - Firmware info <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities">M115: Get Firmware Version and Capabilities</a>
  5896. Print the firmware info and capabilities
  5897. Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5898. `M115 U` Checks the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware, it will pause the print for 30s and ask the user to upgrade the firmware.
  5899. _Examples:_
  5900. `M115` results:
  5901. `FIRMWARE_NAME:Prusa-Firmware 3.8.1 based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:1.0 MACHINE_TYPE:Prusa i3 MK3S EXTRUDER_COUNT:1 UUID:00000000-0000-0000-0000-000000000000`
  5902. `M115 V` results:
  5903. `3.8.1`
  5904. `M115 U3.8.2-RC1` results on LCD display for 30s or user interaction:
  5905. `New firmware version available: 3.8.2-RC1 Please upgrade.`
  5906. #### Usage
  5907. M115 [ V | U ]
  5908. #### Parameters
  5909. - V - Report current installed firmware version
  5910. - U - Firmware version provided by G-code to be compared to current one.
  5911. */
  5912. case 115: // M115
  5913. if (code_seen('V')) {
  5914. // Report the Prusa version number.
  5915. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5916. } else if (code_seen('U')) {
  5917. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5918. // pause the print for 30s and ask the user to upgrade the firmware.
  5919. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5920. } else {
  5921. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5922. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5923. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5924. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5925. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5926. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5927. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5928. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5929. SERIAL_ECHOPGM(" UUID:");
  5930. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5931. #ifdef EXTENDED_CAPABILITIES_REPORT
  5932. extended_capabilities_report();
  5933. #endif //EXTENDED_CAPABILITIES_REPORT
  5934. }
  5935. break;
  5936. /*!
  5937. ### M114 - Get current position <a href="https://reprap.org/wiki/G-code#M114:_Get_Current_Position">M114: Get Current Position</a>
  5938. */
  5939. case 114:
  5940. gcode_M114();
  5941. break;
  5942. /*
  5943. M117 moved up to get the high priority
  5944. case 117: // M117 display message
  5945. starpos = (strchr(strchr_pointer + 5,'*'));
  5946. if(starpos!=NULL)
  5947. *(starpos)='\0';
  5948. lcd_setstatus(strchr_pointer + 5);
  5949. break;*/
  5950. #ifdef M120_M121_ENABLED
  5951. /*!
  5952. ### M120 - Enable endstops <a href="https://reprap.org/wiki/G-code#M120:_Enable_endstop_detection">M120: Enable endstop detection</a>
  5953. */
  5954. case 120:
  5955. enable_endstops(true) ;
  5956. break;
  5957. /*!
  5958. ### M121 - Disable endstops <a href="https://reprap.org/wiki/G-code#M121:_Disable_endstop_detection">M121: Disable endstop detection</a>
  5959. */
  5960. case 121:
  5961. enable_endstops(false) ;
  5962. break;
  5963. #endif //M120_M121_ENABLED
  5964. /*!
  5965. ### M119 - Get endstop states <a href="https://reprap.org/wiki/G-code#M119:_Get_Endstop_Status">M119: Get Endstop Status</a>
  5966. Returns the current state of the configured X, Y, Z endstops. Takes into account any 'inverted endstop' settings, so one can confirm that the machine is interpreting the endstops correctly.
  5967. */
  5968. case 119:
  5969. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5970. SERIAL_PROTOCOLLN();
  5971. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5972. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5973. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5974. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5975. }else{
  5976. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5977. }
  5978. SERIAL_PROTOCOLLN();
  5979. #endif
  5980. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5981. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5982. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5983. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5984. }else{
  5985. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5986. }
  5987. SERIAL_PROTOCOLLN();
  5988. #endif
  5989. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5990. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5991. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5992. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5993. }else{
  5994. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5995. }
  5996. SERIAL_PROTOCOLLN();
  5997. #endif
  5998. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5999. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  6000. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  6001. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  6002. }else{
  6003. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  6004. }
  6005. SERIAL_PROTOCOLLN();
  6006. #endif
  6007. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  6008. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  6009. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  6010. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  6011. }else{
  6012. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  6013. }
  6014. SERIAL_PROTOCOLLN();
  6015. #endif
  6016. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  6017. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  6018. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  6019. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  6020. }else{
  6021. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  6022. }
  6023. SERIAL_PROTOCOLLN();
  6024. #endif
  6025. break;
  6026. //!@todo update for all axes, use for loop
  6027. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  6028. /*!
  6029. ### M123 - Tachometer value <a href="https://www.reprap.org/wiki/G-code#M123:_Tachometer_value_.28RepRap_.26_Prusa.29">M123: Tachometer value</a>
  6030. This command is used to report fan speeds and fan pwm values.
  6031. #### Usage
  6032. M123
  6033. - E0: - Hotend fan speed in RPM
  6034. - PRN1: - Part cooling fans speed in RPM
  6035. - E0@: - Hotend fan PWM value
  6036. - PRN1@: -Part cooling fan PWM value
  6037. _Example:_
  6038. E0:3240 RPM PRN1:4560 RPM E0@:255 PRN1@:255
  6039. */
  6040. case 123:
  6041. gcode_M123();
  6042. break;
  6043. #endif //FANCHECK and TACH_0 and TACH_1
  6044. #ifdef BLINKM
  6045. /*!
  6046. ### M150 - Set RGB(W) Color <a href="https://reprap.org/wiki/G-code#M150:_Set_LED_color">M150: Set LED color</a>
  6047. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code by defining BLINKM and its dependencies.
  6048. #### Usage
  6049. M150 [ R | U | B ]
  6050. #### Parameters
  6051. - `R` - Red color value
  6052. - `U` - Green color value. It is NOT `G`!
  6053. - `B` - Blue color value
  6054. */
  6055. case 150:
  6056. {
  6057. byte red;
  6058. byte grn;
  6059. byte blu;
  6060. if(code_seen('R')) red = code_value();
  6061. if(code_seen('U')) grn = code_value();
  6062. if(code_seen('B')) blu = code_value();
  6063. SendColors(red,grn,blu);
  6064. }
  6065. break;
  6066. #endif //BLINKM
  6067. /*!
  6068. ### M200 - Set filament diameter <a href="https://reprap.org/wiki/G-code#M200:_Set_filament_diameter">M200: Set filament diameter</a>
  6069. #### Usage
  6070. M200 [ D | T ]
  6071. #### Parameters
  6072. - `D` - Diameter in mm
  6073. - `T` - Number of extruder (MMUs)
  6074. */
  6075. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  6076. {
  6077. uint8_t extruder = active_extruder;
  6078. if(code_seen('T')) {
  6079. extruder = code_value_uint8();
  6080. if(extruder >= EXTRUDERS) {
  6081. SERIAL_ECHO_START;
  6082. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  6083. break;
  6084. }
  6085. }
  6086. if(code_seen('D')) {
  6087. float diameter = code_value();
  6088. if (diameter == 0.0) {
  6089. // setting any extruder filament size disables volumetric on the assumption that
  6090. // slicers either generate in extruder values as cubic mm or as as filament feeds
  6091. // for all extruders
  6092. cs.volumetric_enabled = false;
  6093. } else {
  6094. cs.filament_size[extruder] = code_value();
  6095. // make sure all extruders have some sane value for the filament size
  6096. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  6097. #if EXTRUDERS > 1
  6098. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  6099. #if EXTRUDERS > 2
  6100. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  6101. #endif
  6102. #endif
  6103. cs.volumetric_enabled = true;
  6104. }
  6105. } else {
  6106. //reserved for setting filament diameter via UFID or filament measuring device
  6107. break;
  6108. }
  6109. calculate_extruder_multipliers();
  6110. }
  6111. break;
  6112. /*!
  6113. ### M201 - Set Print Max Acceleration <a href="https://reprap.org/wiki/G-code#M201:_Set_max_acceleration">M201: Set max printing acceleration</a>
  6114. For each axis individually.
  6115. ##### Usage
  6116. M201 [ X | Y | Z | E ]
  6117. ##### Parameters
  6118. - `X` - Acceleration for X axis in units/s^2
  6119. - `Y` - Acceleration for Y axis in units/s^2
  6120. - `Z` - Acceleration for Z axis in units/s^2
  6121. - `E` - Acceleration for the active or specified extruder in units/s^2
  6122. */
  6123. case 201:
  6124. for (int8_t i = 0; i < NUM_AXIS; i++)
  6125. {
  6126. if (code_seen(axis_codes[i]))
  6127. {
  6128. unsigned long val = code_value();
  6129. #ifdef TMC2130
  6130. unsigned long val_silent = val;
  6131. if ((i == X_AXIS) || (i == Y_AXIS))
  6132. {
  6133. if (val > NORMAL_MAX_ACCEL_XY)
  6134. val = NORMAL_MAX_ACCEL_XY;
  6135. if (val_silent > SILENT_MAX_ACCEL_XY)
  6136. val_silent = SILENT_MAX_ACCEL_XY;
  6137. }
  6138. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  6139. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  6140. #else //TMC2130
  6141. max_acceleration_units_per_sq_second[i] = val;
  6142. #endif //TMC2130
  6143. }
  6144. }
  6145. // 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)
  6146. reset_acceleration_rates();
  6147. break;
  6148. #if 0 // Not used for Sprinter/grbl gen6
  6149. case 202: // M202
  6150. for(int8_t i=0; i < NUM_AXIS; i++) {
  6151. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  6152. }
  6153. break;
  6154. #endif
  6155. /*!
  6156. ### M203 - Set Max Feedrate <a href="https://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate">M203: Set maximum feedrate</a>
  6157. For each axis individually.
  6158. ##### Usage
  6159. M203 [ X | Y | Z | E ]
  6160. ##### Parameters
  6161. - `X` - Maximum feedrate for X axis
  6162. - `Y` - Maximum feedrate for Y axis
  6163. - `Z` - Maximum feedrate for Z axis
  6164. - `E` - Maximum feedrate for extruder drives
  6165. */
  6166. case 203: // M203 max feedrate mm/sec
  6167. for (uint8_t i = 0; i < NUM_AXIS; i++)
  6168. {
  6169. if (code_seen(axis_codes[i]))
  6170. {
  6171. float val = code_value();
  6172. #ifdef TMC2130
  6173. float val_silent = val;
  6174. if ((i == X_AXIS) || (i == Y_AXIS))
  6175. {
  6176. if (val > NORMAL_MAX_FEEDRATE_XY)
  6177. val = NORMAL_MAX_FEEDRATE_XY;
  6178. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  6179. val_silent = SILENT_MAX_FEEDRATE_XY;
  6180. }
  6181. cs.max_feedrate_normal[i] = val;
  6182. cs.max_feedrate_silent[i] = val_silent;
  6183. #else //TMC2130
  6184. max_feedrate[i] = val;
  6185. #endif //TMC2130
  6186. }
  6187. }
  6188. break;
  6189. /*!
  6190. ### M204 - Acceleration settings <a href="https://reprap.org/wiki/G-code#M204:_Set_default_acceleration">M204: Set default acceleration</a>
  6191. #### Old format:
  6192. ##### Usage
  6193. M204 [ S | T ]
  6194. ##### Parameters
  6195. - `S` - normal moves
  6196. - `T` - filmanent only moves
  6197. #### New format:
  6198. ##### Usage
  6199. M204 [ P | R | T ]
  6200. ##### Parameters
  6201. - `P` - printing moves
  6202. - `R` - filmanent only moves
  6203. - `T` - travel moves (as of now T is ignored)
  6204. */
  6205. case 204:
  6206. {
  6207. if(code_seen('S')) {
  6208. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  6209. // and it is also generated by Slic3r to control acceleration per extrusion type
  6210. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  6211. cs.acceleration = cs.travel_acceleration = code_value();
  6212. // Interpret the T value as retract acceleration in the old Marlin format.
  6213. if(code_seen('T'))
  6214. cs.retract_acceleration = code_value();
  6215. } else {
  6216. // New acceleration format, compatible with the upstream Marlin.
  6217. if(code_seen('P'))
  6218. cs.acceleration = code_value();
  6219. if(code_seen('R'))
  6220. cs.retract_acceleration = code_value();
  6221. if(code_seen('T'))
  6222. cs.travel_acceleration = code_value();
  6223. }
  6224. }
  6225. break;
  6226. /*!
  6227. ### M205 - Set advanced settings <a href="https://reprap.org/wiki/G-code#M205:_Advanced_settings">M205: Advanced settings</a>
  6228. Set some advanced settings related to movement.
  6229. #### Usage
  6230. M205 [ S | T | B | X | Y | Z | E ]
  6231. #### Parameters
  6232. - `S` - Minimum feedrate for print moves (unit/s)
  6233. - `T` - Minimum feedrate for travel moves (units/s)
  6234. - `B` - Minimum segment time (us)
  6235. - `X` - Maximum X jerk (units/s)
  6236. - `Y` - Maximum Y jerk (units/s)
  6237. - `Z` - Maximum Z jerk (units/s)
  6238. - `E` - Maximum E jerk (units/s)
  6239. */
  6240. case 205:
  6241. {
  6242. if(code_seen('S')) cs.minimumfeedrate = code_value();
  6243. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  6244. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  6245. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  6246. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  6247. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  6248. if(code_seen('E'))
  6249. {
  6250. float e = code_value();
  6251. #ifndef LA_NOCOMPAT
  6252. e = la10c_jerk(e);
  6253. #endif
  6254. cs.max_jerk[E_AXIS] = e;
  6255. }
  6256. }
  6257. break;
  6258. /*!
  6259. ### M206 - Set additional homing offsets <a href="https://reprap.org/wiki/G-code#M206:_Offset_axes">M206: Offset axes</a>
  6260. #### Usage
  6261. M206 [ X | Y | Z ]
  6262. #### Parameters
  6263. - `X` - X axis offset
  6264. - `Y` - Y axis offset
  6265. - `Z` - Z axis offset
  6266. */
  6267. case 206:
  6268. for(uint8_t i=0; i < 3; i++)
  6269. {
  6270. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  6271. }
  6272. break;
  6273. #ifdef FWRETRACT
  6274. /*!
  6275. ### M207 - Set firmware retraction <a href="https://reprap.org/wiki/G-code#M207:_Set_retract_length">M207: Set retract length</a>
  6276. #### Usage
  6277. M207 [ S | F | Z ]
  6278. #### Parameters
  6279. - `S` - positive length to retract, in mm
  6280. - `F` - retraction feedrate, in mm/min
  6281. - `Z` - additional zlift/hop
  6282. */
  6283. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  6284. {
  6285. if(code_seen('S'))
  6286. {
  6287. cs.retract_length = code_value() ;
  6288. }
  6289. if(code_seen('F'))
  6290. {
  6291. cs.retract_feedrate = code_value()/60 ;
  6292. }
  6293. if(code_seen('Z'))
  6294. {
  6295. cs.retract_zlift = code_value() ;
  6296. }
  6297. }break;
  6298. /*!
  6299. ### M208 - Set retract recover length <a href="https://reprap.org/wiki/G-code#M208:_Set_unretract_length">M208: Set unretract length</a>
  6300. #### Usage
  6301. M208 [ S | F ]
  6302. #### Parameters
  6303. - `S` - positive length surplus to the M207 Snnn, in mm
  6304. - `F` - feedrate, in mm/sec
  6305. */
  6306. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  6307. {
  6308. if(code_seen('S'))
  6309. {
  6310. cs.retract_recover_length = code_value() ;
  6311. }
  6312. if(code_seen('F'))
  6313. {
  6314. cs.retract_recover_feedrate = code_value()/60 ;
  6315. }
  6316. }break;
  6317. /*!
  6318. ### M209 - Enable/disable automatict retract <a href="https://reprap.org/wiki/G-code#M209:_Enable_automatic_retract">M209: Enable automatic retract</a>
  6319. This boolean value S 1=true or 0=false enables automatic retract detect if the slicer did not support G10/G11: every normal extrude-only move will be classified as retract depending on the direction.
  6320. #### Usage
  6321. M209 [ S ]
  6322. #### Parameters
  6323. - `S` - 1=true or 0=false
  6324. */
  6325. 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.
  6326. {
  6327. if(code_seen('S'))
  6328. {
  6329. switch(code_value_uint8())
  6330. {
  6331. case 0:
  6332. {
  6333. cs.autoretract_enabled=false;
  6334. retracted[0]=false;
  6335. #if EXTRUDERS > 1
  6336. retracted[1]=false;
  6337. #endif
  6338. #if EXTRUDERS > 2
  6339. retracted[2]=false;
  6340. #endif
  6341. }break;
  6342. case 1:
  6343. {
  6344. cs.autoretract_enabled=true;
  6345. retracted[0]=false;
  6346. #if EXTRUDERS > 1
  6347. retracted[1]=false;
  6348. #endif
  6349. #if EXTRUDERS > 2
  6350. retracted[2]=false;
  6351. #endif
  6352. }break;
  6353. default:
  6354. SERIAL_ECHO_START;
  6355. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6356. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6357. SERIAL_ECHOLNPGM("\"(1)");
  6358. }
  6359. }
  6360. }break;
  6361. #endif // FWRETRACT
  6362. /*!
  6363. ### M214 - Set Arc configuration values (Use M500 to store in eeprom)
  6364. #### Usage
  6365. M214 [P] [S] [N] [R] [F]
  6366. #### Parameters
  6367. - `P` - A float representing the max and default millimeters per arc segment. Must be greater than 0.
  6368. - `S` - A float representing the minimum allowable millimeters per arc segment. Set to 0 to disable
  6369. - `N` - An int representing the number of arcs to draw before correcting the small angle approximation. Set to 0 to disable.
  6370. - `R` - An int representing the minimum number of segments per arcs of any radius,
  6371. except when the results in segment lengths greater than or less than the minimum
  6372. and maximum segment length. Set to 0 to disable.
  6373. - 'F' - An int representing the number of segments per second, unless this results in segment lengths
  6374. greater than or less than the minimum and maximum segment length. Set to 0 to disable.
  6375. */
  6376. case 214: //!@n M214 - Set Arc Parameters (Use M500 to store in eeprom) P<MM_PER_ARC_SEGMENT> S<MIN_MM_PER_ARC_SEGMENT> R<MIN_ARC_SEGMENTS> F<ARC_SEGMENTS_PER_SEC>
  6377. {
  6378. // Extract all possible parameters if they appear
  6379. float p = code_seen('P') ? code_value_float() : cs.mm_per_arc_segment;
  6380. float s = code_seen('S') ? code_value_float() : cs.min_mm_per_arc_segment;
  6381. unsigned char n = code_seen('N') ? code_value() : cs.n_arc_correction;
  6382. unsigned short r = code_seen('R') ? code_value() : cs.min_arc_segments;
  6383. unsigned short f = code_seen('F') ? code_value() : cs.arc_segments_per_sec;
  6384. // Ensure mm_per_arc_segment is greater than 0, and that min_mm_per_arc_segment is sero or greater than or equal to mm_per_arc_segment
  6385. if (p <=0 || s < 0 || p < s)
  6386. {
  6387. // Should we display some error here?
  6388. break;
  6389. }
  6390. cs.mm_per_arc_segment = p;
  6391. cs.min_mm_per_arc_segment = s;
  6392. cs.n_arc_correction = n;
  6393. cs.min_arc_segments = r;
  6394. cs.arc_segments_per_sec = f;
  6395. }break;
  6396. #if EXTRUDERS > 1
  6397. /*!
  6398. ### M218 - Set hotend offset <a href="https://reprap.org/wiki/G-code#M218:_Set_Hotend_Offset">M218: Set Hotend Offset</a>
  6399. In Prusa Firmware this G-code is only active if `EXTRUDERS` is higher then 1 in the source code. On Original i3 Prusa MK2/s MK2.5/s MK3/s it is not active.
  6400. #### Usage
  6401. M218 [ X | Y ]
  6402. #### Parameters
  6403. - `X` - X offset
  6404. - `Y` - Y offset
  6405. */
  6406. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  6407. {
  6408. uint8_t extruder;
  6409. if(setTargetedHotend(218, extruder)){
  6410. break;
  6411. }
  6412. if(code_seen('X'))
  6413. {
  6414. extruder_offset[X_AXIS][extruder] = code_value();
  6415. }
  6416. if(code_seen('Y'))
  6417. {
  6418. extruder_offset[Y_AXIS][extruder] = code_value();
  6419. }
  6420. SERIAL_ECHO_START;
  6421. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  6422. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  6423. {
  6424. SERIAL_ECHO(" ");
  6425. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  6426. SERIAL_ECHO(",");
  6427. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  6428. }
  6429. SERIAL_ECHOLN("");
  6430. }break;
  6431. #endif
  6432. /*!
  6433. ### M220 Set feedrate percentage <a href="https://reprap.org/wiki/G-code#M220:_Set_speed_factor_override_percentage">M220: Set speed factor override percentage</a>
  6434. #### Usage
  6435. M220 [ B | S | R ]
  6436. #### Parameters
  6437. - `B` - Backup current speed factor
  6438. - `S` - Speed factor override percentage (0..100 or higher)
  6439. - `R` - Restore previous speed factor
  6440. */
  6441. case 220: // M220 S<factor in percent>- set speed factor override percentage
  6442. {
  6443. bool codesWereSeen = false;
  6444. if (code_seen('B')) //backup current speed factor
  6445. {
  6446. saved_feedmultiply_mm = feedmultiply;
  6447. codesWereSeen = true;
  6448. }
  6449. if (code_seen('S'))
  6450. {
  6451. feedmultiply = code_value_short();
  6452. codesWereSeen = true;
  6453. }
  6454. if (code_seen('R')) //restore previous feedmultiply
  6455. {
  6456. feedmultiply = saved_feedmultiply_mm;
  6457. codesWereSeen = true;
  6458. }
  6459. if (!codesWereSeen)
  6460. {
  6461. printf_P(PSTR("%i%%\n"), feedmultiply);
  6462. }
  6463. }
  6464. break;
  6465. /*!
  6466. ### M221 - Set extrude factor override percentage <a href="https://reprap.org/wiki/G-code#M221:_Set_extrude_factor_override_percentage">M221: Set extrude factor override percentage</a>
  6467. #### Usage
  6468. M221 [ S | T ]
  6469. #### Parameters
  6470. - `S` - Extrude factor override percentage (0..100 or higher), default 100%
  6471. - `T` - Extruder drive number (Prusa Firmware only), default 0 if not set.
  6472. */
  6473. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  6474. {
  6475. if (code_seen('S'))
  6476. {
  6477. int tmp_code = code_value_short();
  6478. if (code_seen('T'))
  6479. {
  6480. uint8_t extruder;
  6481. if (setTargetedHotend(221, extruder))
  6482. break;
  6483. extruder_multiply[extruder] = tmp_code;
  6484. }
  6485. else
  6486. {
  6487. extrudemultiply = tmp_code ;
  6488. }
  6489. }
  6490. else
  6491. {
  6492. printf_P(PSTR("%i%%\n"), extrudemultiply);
  6493. }
  6494. calculate_extruder_multipliers();
  6495. }
  6496. break;
  6497. /*!
  6498. ### M226 - Wait for Pin state <a href="https://reprap.org/wiki/G-code#M226:_Wait_for_pin_state">M226: Wait for pin state</a>
  6499. Wait until the specified pin reaches the state required
  6500. #### Usage
  6501. M226 [ P | S ]
  6502. #### Parameters
  6503. - `P` - pin number
  6504. - `S` - pin state
  6505. */
  6506. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  6507. {
  6508. if(code_seen('P')){
  6509. int pin_number = code_value_short(); // pin number
  6510. int pin_state = -1; // required pin state - default is inverted
  6511. if(code_seen('S')) pin_state = code_value_short(); // required pin state
  6512. if(pin_state >= -1 && pin_state <= 1){
  6513. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  6514. {
  6515. if (((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number))
  6516. {
  6517. pin_number = -1;
  6518. break;
  6519. }
  6520. }
  6521. if (pin_number > -1)
  6522. {
  6523. int target = LOW;
  6524. st_synchronize();
  6525. pinMode(pin_number, INPUT);
  6526. switch(pin_state){
  6527. case 1:
  6528. target = HIGH;
  6529. break;
  6530. case 0:
  6531. target = LOW;
  6532. break;
  6533. case -1:
  6534. target = !digitalRead(pin_number);
  6535. break;
  6536. }
  6537. while(digitalRead(pin_number) != target){
  6538. manage_heater();
  6539. manage_inactivity();
  6540. lcd_update(0);
  6541. }
  6542. }
  6543. }
  6544. }
  6545. }
  6546. break;
  6547. #if NUM_SERVOS > 0
  6548. /*!
  6549. ### M280 - Set/Get servo position <a href="https://reprap.org/wiki/G-code#M280:_Set_servo_position">M280: Set servo position</a>
  6550. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6551. #### Usage
  6552. M280 [ P | S ]
  6553. #### Parameters
  6554. - `P` - Servo index (id)
  6555. - `S` - Target position
  6556. */
  6557. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6558. {
  6559. int servo_index = -1;
  6560. int servo_position = 0;
  6561. if (code_seen('P'))
  6562. servo_index = code_value();
  6563. if (code_seen('S')) {
  6564. servo_position = code_value();
  6565. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  6566. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6567. servos[servo_index].attach(0);
  6568. #endif
  6569. servos[servo_index].write(servo_position);
  6570. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6571. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  6572. servos[servo_index].detach();
  6573. #endif
  6574. }
  6575. else {
  6576. SERIAL_ECHO_START;
  6577. SERIAL_ECHO("Servo ");
  6578. SERIAL_ECHO(servo_index);
  6579. SERIAL_ECHOLN(" out of range");
  6580. }
  6581. }
  6582. else if (servo_index >= 0) {
  6583. SERIAL_PROTOCOL(MSG_OK);
  6584. SERIAL_PROTOCOL(" Servo ");
  6585. SERIAL_PROTOCOL(servo_index);
  6586. SERIAL_PROTOCOL(": ");
  6587. SERIAL_PROTOCOLLN(servos[servo_index].read());
  6588. }
  6589. }
  6590. break;
  6591. #endif // NUM_SERVOS > 0
  6592. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  6593. /*!
  6594. ### M300 - Play tone <a href="https://reprap.org/wiki/G-code#M300:_Play_beep_sound">M300: Play beep sound</a>
  6595. In Prusa Firmware the defaults are `100Hz` and `1000ms`, so that `M300` without parameters will beep for a second.
  6596. #### Usage
  6597. M300 [ S | P ]
  6598. #### Parameters
  6599. - `S` - frequency in Hz. Not all firmware versions support this parameter
  6600. - `P` - duration in milliseconds
  6601. */
  6602. case 300: // M300
  6603. {
  6604. uint16_t beepS = code_seen('S') ? code_value() : 0;
  6605. uint16_t beepP = code_seen('P') ? code_value() : 1000;
  6606. #if BEEPER > 0
  6607. if (beepP > 0)
  6608. Sound_MakeCustom(beepP,beepS,false);
  6609. #endif
  6610. }
  6611. break;
  6612. #endif // M300
  6613. #ifdef PIDTEMP
  6614. /*!
  6615. ### M301 - Set hotend PID <a href="https://reprap.org/wiki/G-code#M301:_Set_PID_parameters">M301: Set PID parameters</a>
  6616. Sets Proportional (P), Integral (I) and Derivative (D) values for hot end.
  6617. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6618. #### Usage
  6619. M301 [ P | I | D ]
  6620. #### Parameters
  6621. - `P` - proportional (Kp)
  6622. - `I` - integral (Ki)
  6623. - `D` - derivative (Kd)
  6624. */
  6625. case 301:
  6626. {
  6627. if(code_seen('P')) cs.Kp = code_value();
  6628. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  6629. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6630. updatePID();
  6631. SERIAL_PROTOCOLRPGM(MSG_OK);
  6632. SERIAL_PROTOCOLPGM(" p:");
  6633. SERIAL_PROTOCOL(cs.Kp);
  6634. SERIAL_PROTOCOLPGM(" i:");
  6635. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6636. SERIAL_PROTOCOLPGM(" d:");
  6637. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6638. SERIAL_PROTOCOLLN();
  6639. }
  6640. break;
  6641. #endif //PIDTEMP
  6642. #ifdef PIDTEMPBED
  6643. /*!
  6644. ### M304 - Set bed PID <a href="https://reprap.org/wiki/G-code#M304:_Set_PID_parameters_-_Bed">M304: Set PID parameters - Bed</a>
  6645. Sets Proportional (P), Integral (I) and Derivative (D) values for bed.
  6646. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6647. #### Usage
  6648. M304 [ P | I | D ]
  6649. #### Parameters
  6650. - `P` - proportional (Kp)
  6651. - `I` - integral (Ki)
  6652. - `D` - derivative (Kd)
  6653. */
  6654. case 304:
  6655. {
  6656. if(code_seen('P')) cs.bedKp = code_value();
  6657. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6658. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6659. updatePID();
  6660. SERIAL_PROTOCOLRPGM(MSG_OK);
  6661. SERIAL_PROTOCOLPGM(" p:");
  6662. SERIAL_PROTOCOL(cs.bedKp);
  6663. SERIAL_PROTOCOLPGM(" i:");
  6664. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6665. SERIAL_PROTOCOLPGM(" d:");
  6666. SERIAL_PROTOCOLLN(unscalePID_d(cs.bedKd));
  6667. }
  6668. break;
  6669. #endif //PIDTEMP
  6670. /*!
  6671. ### M240 - Trigger camera <a href="https://reprap.org/wiki/G-code#M240:_Trigger_camera">M240: Trigger camera</a>
  6672. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6673. You need to (re)define and assign `CHDK` or `PHOTOGRAPH_PIN` the correct pin number to be able to use the feature.
  6674. */
  6675. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6676. {
  6677. #ifdef CHDK
  6678. SET_OUTPUT(CHDK);
  6679. WRITE(CHDK, HIGH);
  6680. chdkHigh = _millis();
  6681. chdkActive = true;
  6682. #else
  6683. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6684. const uint8_t NUM_PULSES=16;
  6685. const float PULSE_LENGTH=0.01524;
  6686. for(int i=0; i < NUM_PULSES; i++) {
  6687. WRITE(PHOTOGRAPH_PIN, HIGH);
  6688. _delay_ms(PULSE_LENGTH);
  6689. WRITE(PHOTOGRAPH_PIN, LOW);
  6690. _delay_ms(PULSE_LENGTH);
  6691. }
  6692. _delay(7.33);
  6693. for(int i=0; i < NUM_PULSES; i++) {
  6694. WRITE(PHOTOGRAPH_PIN, HIGH);
  6695. _delay_ms(PULSE_LENGTH);
  6696. WRITE(PHOTOGRAPH_PIN, LOW);
  6697. _delay_ms(PULSE_LENGTH);
  6698. }
  6699. #endif
  6700. #endif //chdk end if
  6701. }
  6702. break;
  6703. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6704. /*!
  6705. ### M302 - Allow cold extrude, or set minimum extrude temperature <a href="https://reprap.org/wiki/G-code#M302:_Allow_cold_extrudes">M302: Allow cold extrudes</a>
  6706. This tells the printer to allow movement of the extruder motor above a certain temperature, or if disabled, to allow extruder movement when the hotend is below a safe printing temperature.
  6707. #### Usage
  6708. M302 [ S ]
  6709. #### Parameters
  6710. - `S` - Cold extrude minimum temperature
  6711. */
  6712. case 302:
  6713. {
  6714. int temp = 0;
  6715. if (code_seen('S')) temp=code_value_short();
  6716. set_extrude_min_temp(temp);
  6717. }
  6718. break;
  6719. #endif
  6720. /*!
  6721. ### M303 - PID autotune <a href="https://reprap.org/wiki/G-code#M303:_Run_PID_tuning">M303: Run PID tuning</a>
  6722. PID Tuning refers to a control algorithm used in some repraps to tune heating behavior for hot ends and heated beds. This command generates Proportional (Kp), Integral (Ki), and Derivative (Kd) values for the hotend or bed. Send the appropriate code and wait for the output to update the firmware values.
  6723. #### Usage
  6724. M303 [ E | S | C ]
  6725. #### Parameters
  6726. - `E` - Extruder, default `E0`. Use `E-1` to calibrate the bed PID
  6727. - `S` - Target temperature, default `210°C` for hotend, 70 for bed
  6728. - `C` - Cycles, default `5`
  6729. */
  6730. case 303:
  6731. {
  6732. float temp = 150.0;
  6733. int e = 0;
  6734. int c = 5;
  6735. if (code_seen('E')) e = code_value_short();
  6736. if (e < 0)
  6737. temp = 70;
  6738. if (code_seen('S')) temp = code_value();
  6739. if (code_seen('C')) c = code_value_short();
  6740. PID_autotune(temp, e, c);
  6741. }
  6742. break;
  6743. /*!
  6744. ### M400 - Wait for all moves to finish <a href="https://reprap.org/wiki/G-code#M400:_Wait_for_current_moves_to_finish">M400: Wait for current moves to finish</a>
  6745. Finishes all current moves and and thus clears the buffer.
  6746. Equivalent to `G4` with no parameters.
  6747. */
  6748. case 400:
  6749. {
  6750. st_synchronize();
  6751. }
  6752. break;
  6753. /*!
  6754. ### M403 - Set filament type (material) for particular extruder and notify the MMU <a href="https://reprap.org/wiki/G-code#M403:_Set_filament_type_.28material.29_for_particular_extruder_and_notify_the_MMU.">M403 - Set filament type (material) for particular extruder and notify the MMU</a>
  6755. Currently three different materials are needed (default, flex and PVA).
  6756. And storing this information for different load/unload profiles etc. in the future firmware does not have to wait for "ok" from MMU.
  6757. #### Usage
  6758. M403 [ E | F ]
  6759. #### Parameters
  6760. - `E` - Extruder number. 0-indexed.
  6761. - `F` - Filament type
  6762. */
  6763. case 403:
  6764. {
  6765. // currently three different materials are needed (default, flex and PVA)
  6766. // add storing this information for different load/unload profiles etc. in the future
  6767. // firmware does not wait for "ok" from mmu
  6768. if (mmu_enabled)
  6769. {
  6770. uint8_t extruder = 255;
  6771. uint8_t filament = FILAMENT_UNDEFINED;
  6772. if(code_seen('E')) extruder = code_value_uint8();
  6773. if(code_seen('F')) filament = code_value_uint8();
  6774. mmu_set_filament_type(extruder, filament);
  6775. }
  6776. }
  6777. break;
  6778. /*!
  6779. ### M500 - Store settings in EEPROM <a href="https://reprap.org/wiki/G-code#M500:_Store_parameters_in_non-volatile_storage">M500: Store parameters in non-volatile storage</a>
  6780. Save current parameters to EEPROM.
  6781. */
  6782. case 500:
  6783. {
  6784. Config_StoreSettings();
  6785. }
  6786. break;
  6787. /*!
  6788. ### M501 - Read settings from EEPROM <a href="https://reprap.org/wiki/G-code#M501:_Read_parameters_from_EEPROM">M501: Read parameters from EEPROM</a>
  6789. Set the active parameters to those stored in the EEPROM. This is useful to revert parameters after experimenting with them.
  6790. */
  6791. case 501:
  6792. {
  6793. Config_RetrieveSettings();
  6794. }
  6795. break;
  6796. /*!
  6797. ### M502 - Revert all settings to factory default <a href="https://reprap.org/wiki/G-code#M502:_Restore_Default_Settings">M502: Restore Default Settings</a>
  6798. This command resets all tunable parameters to their default values, as set in the firmware's configuration files. This doesn't reset any parameters stored in the EEPROM, so it must be followed by M500 to write the default settings.
  6799. */
  6800. case 502:
  6801. {
  6802. Config_ResetDefault();
  6803. }
  6804. break;
  6805. /*!
  6806. ### M503 - Repport all settings currently in memory <a href="https://reprap.org/wiki/G-code#M503:_Report_Current_Settings">M503: Report Current Settings</a>
  6807. This command asks the firmware to reply with the current print settings as set in memory. Settings will differ from EEPROM contents if changed since the last load / save. The reply output includes the G-Code commands to produce each setting. For example, Steps-Per-Unit values are displayed as an M92 command.
  6808. */
  6809. case 503:
  6810. {
  6811. Config_PrintSettings();
  6812. }
  6813. break;
  6814. /*!
  6815. ### M509 - Force language selection <a href="https://reprap.org/wiki/G-code#M509:_Force_language_selection">M509: Force language selection</a>
  6816. Resets the language to English.
  6817. Only on Original Prusa i3 MK2.5/s and MK3/s with multiple languages.
  6818. */
  6819. case 509:
  6820. {
  6821. lang_reset();
  6822. SERIAL_ECHO_START;
  6823. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6824. }
  6825. break;
  6826. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6827. /*!
  6828. ### M540 - Abort print on endstop hit (enable/disable) <a href="https://reprap.org/wiki/G-code#M540_in_Marlin:_Enable.2FDisable_.22Stop_SD_Print_on_Endstop_Hit.22">M540 in Marlin: Enable/Disable "Stop SD Print on Endstop Hit"</a>
  6829. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. You must define `ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED`.
  6830. #### Usage
  6831. M540 [ S ]
  6832. #### Parameters
  6833. - `S` - disabled=0, enabled=1
  6834. */
  6835. case 540:
  6836. {
  6837. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6838. }
  6839. break;
  6840. #endif
  6841. /*!
  6842. ### M851 - Set Z-Probe Offset <a href="https://reprap.org/wiki/G-code#M851:_Set_Z-Probe_Offset">M851: Set Z-Probe Offset"</a>
  6843. Sets the Z-probe Z offset. This offset is used to determine the actual Z position of the nozzle when using a probe to home Z with G28. This value may also be used by G81 (Prusa) / G29 (Marlin) to apply correction to the Z position.
  6844. This value represents the distance from nozzle to the bed surface at the point where the probe is triggered. This value will be negative for typical switch probes, inductive probes, and setups where the nozzle makes a circuit with a raised metal contact. This setting will be greater than zero on machines where the nozzle itself is used as the probe, pressing down on the bed to press a switch. (This is a common setup on delta machines.)
  6845. #### Usage
  6846. M851 [ Z ]
  6847. #### Parameters
  6848. - `Z` - Z offset probe to nozzle.
  6849. */
  6850. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6851. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6852. {
  6853. float value;
  6854. if (code_seen('Z'))
  6855. {
  6856. value = code_value();
  6857. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6858. {
  6859. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6860. SERIAL_ECHO_START;
  6861. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6862. SERIAL_PROTOCOLLN();
  6863. }
  6864. else
  6865. {
  6866. SERIAL_ECHO_START;
  6867. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6868. SERIAL_ECHORPGM(MSG_Z_MIN);
  6869. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6870. SERIAL_ECHORPGM(MSG_Z_MAX);
  6871. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6872. SERIAL_PROTOCOLLN();
  6873. }
  6874. }
  6875. else
  6876. {
  6877. SERIAL_ECHO_START;
  6878. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6879. SERIAL_ECHO(-cs.zprobe_zoffset);
  6880. SERIAL_PROTOCOLLN();
  6881. }
  6882. break;
  6883. }
  6884. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6885. /*!
  6886. ### M552 - Set IP address <a href="https://reprap.org/wiki/G-code#M552:_Set_IP_address.2C_enable.2Fdisable_network_interface">M552: Set IP address, enable/disable network interface"</a>
  6887. Sets the printer IP address that is shown in the support menu. Designed to be used with the help of host software.
  6888. If P is not specified nothing happens.
  6889. If the structure of the IP address is invalid, 0.0.0.0 is assumed and nothing is shown on the screen in the Support menu.
  6890. #### Usage
  6891. M552 [ P<IP_address> ]
  6892. #### Parameters
  6893. - `P` - The IP address in xxx.xxx.xxx.xxx format. Eg: P192.168.1.14
  6894. */
  6895. case 552:
  6896. {
  6897. if (code_seen('P'))
  6898. {
  6899. uint8_t valCnt = 0;
  6900. IP_address = 0;
  6901. do
  6902. {
  6903. *strchr_pointer = '*';
  6904. ((uint8_t*)&IP_address)[valCnt] = code_value_short();
  6905. valCnt++;
  6906. } while ((valCnt < 4) && code_seen('.'));
  6907. if (valCnt != 4)
  6908. IP_address = 0;
  6909. }
  6910. } break;
  6911. #ifdef FILAMENTCHANGEENABLE
  6912. /*!
  6913. ### M600 - Initiate Filament change procedure <a href="https://reprap.org/wiki/G-code#M600:_Filament_change_pause">M600: Filament change pause</a>
  6914. Initiates Filament change, it is also used during Filament Runout Sensor process.
  6915. If the `M600` is triggered under 25mm it will do a Z-lift of 25mm to prevent a filament blob.
  6916. #### Usage
  6917. M600 [ X | Y | Z | E | L | AUTO ]
  6918. - `X` - X position, default 211
  6919. - `Y` - Y position, default 0
  6920. - `Z` - relative lift Z, default 2.
  6921. - `E` - initial retract, default -2
  6922. - `L` - later retract distance for removal, default -80
  6923. - `AUTO` - Automatically (only with MMU)
  6924. */
  6925. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6926. {
  6927. st_synchronize();
  6928. float x_position = current_position[X_AXIS];
  6929. float y_position = current_position[Y_AXIS];
  6930. float z_shift = 0; // is it necessary to be a float?
  6931. float e_shift_init = 0;
  6932. float e_shift_late = 0;
  6933. bool automatic = false;
  6934. //Retract extruder
  6935. if(code_seen('E'))
  6936. {
  6937. e_shift_init = code_value();
  6938. }
  6939. else
  6940. {
  6941. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6942. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6943. #endif
  6944. }
  6945. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6946. if (code_seen('L'))
  6947. {
  6948. e_shift_late = code_value();
  6949. }
  6950. else
  6951. {
  6952. #ifdef FILAMENTCHANGE_FINALRETRACT
  6953. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6954. #endif
  6955. }
  6956. //Lift Z
  6957. if(code_seen('Z'))
  6958. {
  6959. z_shift = code_value();
  6960. }
  6961. else
  6962. {
  6963. z_shift = gcode_M600_filament_change_z_shift<uint8_t>();
  6964. }
  6965. //Move XY to side
  6966. if(code_seen('X'))
  6967. {
  6968. x_position = code_value();
  6969. }
  6970. else
  6971. {
  6972. #ifdef FILAMENTCHANGE_XPOS
  6973. x_position = FILAMENTCHANGE_XPOS;
  6974. #endif
  6975. }
  6976. if(code_seen('Y'))
  6977. {
  6978. y_position = code_value();
  6979. }
  6980. else
  6981. {
  6982. #ifdef FILAMENTCHANGE_YPOS
  6983. y_position = FILAMENTCHANGE_YPOS ;
  6984. #endif
  6985. }
  6986. if (mmu_enabled && code_seen_P(PSTR("AUTO")))
  6987. automatic = true;
  6988. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6989. }
  6990. break;
  6991. #endif //FILAMENTCHANGEENABLE
  6992. /*!
  6993. ### M601 - Pause print <a href="https://reprap.org/wiki/G-code#M601:_Pause_print">M601: Pause print</a>
  6994. */
  6995. /*!
  6996. ### M125 - Pause print (TODO: not implemented)
  6997. */
  6998. /*!
  6999. ### M25 - Pause SD print <a href="https://reprap.org/wiki/G-code#M25:_Pause_SD_print">M25: Pause SD print</a>
  7000. */
  7001. case 25:
  7002. case 601:
  7003. {
  7004. if (!isPrintPaused) {
  7005. st_synchronize();
  7006. ClearToSend(); //send OK even before the command finishes executing because we want to make sure it is not skipped because of cmdqueue_pop_front();
  7007. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  7008. lcd_pause_print();
  7009. }
  7010. }
  7011. break;
  7012. /*!
  7013. ### M602 - Resume print <a href="https://reprap.org/wiki/G-code#M602:_Resume_print">M602: Resume print</a>
  7014. */
  7015. case 602:
  7016. {
  7017. if (isPrintPaused) lcd_resume_print();
  7018. }
  7019. break;
  7020. /*!
  7021. ### M603 - Stop print <a href="https://reprap.org/wiki/G-code#M603:_Stop_print">M603: Stop print</a>
  7022. */
  7023. case 603: {
  7024. lcd_print_stop();
  7025. }
  7026. break;
  7027. #ifdef PINDA_THERMISTOR
  7028. /*!
  7029. ### M860 - Wait for extruder temperature (PINDA) <a href="https://reprap.org/wiki/G-code#M860_Wait_for_Probe_Temperature">M860 Wait for Probe Temperature</a>
  7030. Wait for PINDA thermistor to reach target temperature
  7031. #### Usage
  7032. M860 [ S ]
  7033. #### Parameters
  7034. - `S` - Target temperature
  7035. */
  7036. case 860:
  7037. {
  7038. int set_target_pinda = 0;
  7039. if (code_seen('S')) {
  7040. set_target_pinda = code_value_short();
  7041. }
  7042. else {
  7043. break;
  7044. }
  7045. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  7046. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  7047. SERIAL_PROTOCOLLN(set_target_pinda);
  7048. codenum = _millis();
  7049. cancel_heatup = false;
  7050. bool is_pinda_cooling = false;
  7051. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  7052. is_pinda_cooling = true;
  7053. }
  7054. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  7055. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  7056. {
  7057. SERIAL_PROTOCOLPGM("P:");
  7058. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  7059. SERIAL_PROTOCOL('/');
  7060. SERIAL_PROTOCOLLN(set_target_pinda);
  7061. codenum = _millis();
  7062. }
  7063. manage_heater();
  7064. manage_inactivity();
  7065. lcd_update(0);
  7066. }
  7067. LCD_MESSAGERPGM(MSG_OK);
  7068. break;
  7069. }
  7070. /*!
  7071. ### M861 - Set/Get PINDA temperature compensation offsets <a href="https://reprap.org/wiki/G-code#M861_Set_Probe_Thermal_Compensation">M861 Set Probe Thermal Compensation</a>
  7072. Set compensation ustep value `S` for compensation table index `I`.
  7073. #### Usage
  7074. M861 [ ? | ! | Z | S | I ]
  7075. #### Parameters
  7076. - `?` - Print current EEPROM offset values
  7077. - `!` - Set factory default values
  7078. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  7079. - `S` - Microsteps
  7080. - `I` - Table index
  7081. */
  7082. case 861: {
  7083. const char * const _header = PSTR("index, temp, ustep, um");
  7084. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  7085. int16_t usteps = 0;
  7086. SERIAL_PROTOCOLPGM("PINDA cal status: ");
  7087. SERIAL_PROTOCOLLN(calibration_status_pinda());
  7088. SERIAL_PROTOCOLLNRPGM(_header);
  7089. for (uint8_t i = 0; i < 6; i++)
  7090. {
  7091. if(i > 0) {
  7092. usteps = eeprom_read_word((uint16_t*) EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  7093. }
  7094. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  7095. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  7096. SERIAL_PROTOCOLPGM(", ");
  7097. SERIAL_PROTOCOL(35 + (i * 5));
  7098. SERIAL_PROTOCOLPGM(", ");
  7099. SERIAL_PROTOCOL(usteps);
  7100. SERIAL_PROTOCOLPGM(", ");
  7101. SERIAL_PROTOCOLLN(mm * 1000);
  7102. }
  7103. }
  7104. else if (code_seen('!')) { // ! - Set factory default values
  7105. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  7106. int16_t z_shift = 8; //40C - 20um - 8usteps
  7107. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT, z_shift);
  7108. z_shift = 24; //45C - 60um - 24usteps
  7109. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 1, z_shift);
  7110. z_shift = 48; //50C - 120um - 48usteps
  7111. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 2, z_shift);
  7112. z_shift = 80; //55C - 200um - 80usteps
  7113. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 3, z_shift);
  7114. z_shift = 120; //60C - 300um - 120usteps
  7115. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 4, z_shift);
  7116. SERIAL_PROTOCOLLNPGM("factory restored");
  7117. }
  7118. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  7119. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  7120. int16_t z_shift = 0;
  7121. for (uint8_t i = 0; i < 5; i++) {
  7122. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  7123. }
  7124. SERIAL_PROTOCOLLNPGM("zerorized");
  7125. }
  7126. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  7127. int16_t usteps = code_value_short();
  7128. if (code_seen('I')) {
  7129. uint8_t index = code_value_uint8();
  7130. if (index < 5) {
  7131. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + index, usteps);
  7132. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7133. SERIAL_PROTOCOLLNRPGM(_header);
  7134. for (uint8_t i = 0; i < 6; i++)
  7135. {
  7136. usteps = 0;
  7137. if (i > 0) {
  7138. usteps = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  7139. }
  7140. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  7141. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  7142. SERIAL_PROTOCOLPGM(", ");
  7143. SERIAL_PROTOCOL(35 + (i * 5));
  7144. SERIAL_PROTOCOLPGM(", ");
  7145. SERIAL_PROTOCOL(usteps);
  7146. SERIAL_PROTOCOLPGM(", ");
  7147. SERIAL_PROTOCOLLN(mm * 1000);
  7148. }
  7149. }
  7150. }
  7151. }
  7152. else {
  7153. SERIAL_PROTOCOLLNPGM("no valid command");
  7154. }
  7155. } break;
  7156. #endif //PINDA_THERMISTOR
  7157. /*!
  7158. ### M862 - Print checking <a href="https://reprap.org/wiki/G-code#M862:_Print_checking">M862: Print checking</a>
  7159. Checks the parameters of the printer and gcode and performs compatibility check
  7160. - M862.1 { P<nozzle_diameter> | Q } 0.25/0.40/0.60
  7161. - M862.2 { P<model_code> | Q }
  7162. - M862.3 { P"<model_name>" | Q }
  7163. - M862.4 { P<fw_version> | Q }
  7164. - M862.5 { P<gcode_level> | Q }
  7165. When run with P<> argument, the check is performed against the input value.
  7166. When run with Q argument, the current value is shown.
  7167. M862.3 accepts text identifiers of printer types too.
  7168. The syntax of M862.3 is (note the quotes around the type):
  7169. M862.3 P "MK3S"
  7170. Accepted printer type identifiers and their numeric counterparts:
  7171. - MK1 (100)
  7172. - MK2 (200)
  7173. - MK2MM (201)
  7174. - MK2S (202)
  7175. - MK2SMM (203)
  7176. - MK2.5 (250)
  7177. - MK2.5MMU2 (20250)
  7178. - MK2.5S (252)
  7179. - MK2.5SMMU2S (20252)
  7180. - MK3 (300)
  7181. - MK3MMU2 (20300)
  7182. - MK3S (302)
  7183. - MK3SMMU2S (20302)
  7184. */
  7185. case 862: // M862: print checking
  7186. float nDummy;
  7187. uint8_t nCommand;
  7188. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  7189. switch((ClPrintChecking)nCommand)
  7190. {
  7191. case ClPrintChecking::_Nozzle: // ~ .1
  7192. uint16_t nDiameter;
  7193. if(code_seen('P'))
  7194. {
  7195. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  7196. nozzle_diameter_check(nDiameter);
  7197. }
  7198. /*
  7199. else if(code_seen('S')&&farm_mode)
  7200. {
  7201. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  7202. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  7203. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  7204. }
  7205. */
  7206. else if(code_seen('Q'))
  7207. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  7208. break;
  7209. case ClPrintChecking::_Model: // ~ .2
  7210. if(code_seen('P'))
  7211. {
  7212. uint16_t nPrinterModel;
  7213. nPrinterModel=(uint16_t)code_value_long();
  7214. printer_model_check(nPrinterModel);
  7215. }
  7216. else if(code_seen('Q'))
  7217. SERIAL_PROTOCOLLN(nPrinterType);
  7218. break;
  7219. case ClPrintChecking::_Smodel: // ~ .3
  7220. if(code_seen('P'))
  7221. printer_smodel_check(strchr_pointer);
  7222. else if(code_seen('Q'))
  7223. SERIAL_PROTOCOLLNRPGM(sPrinterName);
  7224. break;
  7225. case ClPrintChecking::_Version: // ~ .4
  7226. if(code_seen('P'))
  7227. fw_version_check(++strchr_pointer);
  7228. else if(code_seen('Q'))
  7229. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  7230. break;
  7231. case ClPrintChecking::_Gcode: // ~ .5
  7232. if(code_seen('P'))
  7233. {
  7234. uint16_t nGcodeLevel;
  7235. nGcodeLevel=(uint16_t)code_value_long();
  7236. gcode_level_check(nGcodeLevel);
  7237. }
  7238. else if(code_seen('Q'))
  7239. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  7240. break;
  7241. }
  7242. break;
  7243. #ifdef LIN_ADVANCE
  7244. /*!
  7245. ### M900 - Set Linear advance options <a href="https://reprap.org/wiki/G-code#M900_Set_Linear_Advance_Scaling_Factors">M900 Set Linear Advance Scaling Factors</a>
  7246. Sets the advance extrusion factors for Linear Advance. If any of the R, W, H, or D parameters are set to zero the ratio will be computed dynamically during printing.
  7247. #### Usage
  7248. M900 [ K | R | W | H | D]
  7249. #### Parameters
  7250. - `K` - Advance K factor
  7251. - `R` - Set ratio directly (overrides WH/D)
  7252. - `W` - Width
  7253. - `H` - Height
  7254. - `D` - Diameter Set ratio from WH/D
  7255. */
  7256. case 900:
  7257. gcode_M900();
  7258. break;
  7259. #endif
  7260. /*!
  7261. ### M907 - Set digital trimpot motor current in mA using axis codes <a href="https://reprap.org/wiki/G-code#M907:_Set_digital_trimpot_motor">M907: Set digital trimpot motor</a>
  7262. Set digital trimpot motor current using axis codes (X, Y, Z, E, B, S).
  7263. M907 has no effect when the experimental Extruder motor current scaling mode is active (that applies to farm printing as well)
  7264. #### Usage
  7265. M907 [ X | Y | Z | E | B | S ]
  7266. #### Parameters
  7267. - `X` - X motor driver
  7268. - `Y` - Y motor driver
  7269. - `Z` - Z motor driver
  7270. - `E` - Extruder motor driver
  7271. - `B` - Second Extruder motor driver
  7272. - `S` - All motors
  7273. */
  7274. case 907:
  7275. {
  7276. #ifdef TMC2130
  7277. // See tmc2130_cur2val() for translation to 0 .. 63 range
  7278. for (uint_least8_t i = 0; i < NUM_AXIS; i++){
  7279. if(code_seen(axis_codes[i])){
  7280. if( i == E_AXIS && FarmOrUserECool() ){
  7281. SERIAL_ECHORPGM(eMotorCurrentScalingEnabled);
  7282. SERIAL_ECHOLNPGM(", M907 E ignored");
  7283. continue;
  7284. }
  7285. long cur_mA = code_value_long();
  7286. uint8_t val = tmc2130_cur2val(cur_mA);
  7287. tmc2130_set_current_h(i, val);
  7288. tmc2130_set_current_r(i, val);
  7289. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  7290. }
  7291. }
  7292. #else //TMC2130
  7293. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7294. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  7295. if(code_seen('B')) st_current_set(4,code_value());
  7296. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  7297. #endif
  7298. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  7299. if(code_seen('X')) st_current_set(0, code_value());
  7300. #endif
  7301. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  7302. if(code_seen('Z')) st_current_set(1, code_value());
  7303. #endif
  7304. #ifdef MOTOR_CURRENT_PWM_E_PIN
  7305. if(code_seen('E')) st_current_set(2, code_value());
  7306. #endif
  7307. #endif //TMC2130
  7308. }
  7309. break;
  7310. /*!
  7311. ### M908 - Control digital trimpot directly <a href="https://reprap.org/wiki/G-code#M908:_Control_digital_trimpot_directly">M908: Control digital trimpot directly</a>
  7312. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. Not usable on Prusa printers.
  7313. #### Usage
  7314. M908 [ P | S ]
  7315. #### Parameters
  7316. - `P` - channel
  7317. - `S` - current
  7318. */
  7319. case 908:
  7320. {
  7321. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7322. uint8_t channel,current;
  7323. if(code_seen('P')) channel=code_value();
  7324. if(code_seen('S')) current=code_value();
  7325. digitalPotWrite(channel, current);
  7326. #endif
  7327. }
  7328. break;
  7329. #ifdef TMC2130_SERVICE_CODES_M910_M918
  7330. /*!
  7331. ### M910 - TMC2130 init <a href="https://reprap.org/wiki/G-code#M910:_TMC2130_init">M910: TMC2130 init</a>
  7332. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7333. */
  7334. case 910:
  7335. {
  7336. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7337. }
  7338. break;
  7339. /*!
  7340. ### M911 - Set TMC2130 holding currents <a href="https://reprap.org/wiki/G-code#M911:_Set_TMC2130_holding_currents">M911: Set TMC2130 holding currents</a>
  7341. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7342. #### Usage
  7343. M911 [ X | Y | Z | E ]
  7344. #### Parameters
  7345. - `X` - X stepper driver holding current value
  7346. - `Y` - Y stepper driver holding current value
  7347. - `Z` - Z stepper driver holding current value
  7348. - `E` - Extruder stepper driver holding current value
  7349. */
  7350. case 911:
  7351. {
  7352. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  7353. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  7354. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  7355. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  7356. }
  7357. break;
  7358. /*!
  7359. ### M912 - Set TMC2130 running currents <a href="https://reprap.org/wiki/G-code#M912:_Set_TMC2130_running_currents">M912: Set TMC2130 running currents</a>
  7360. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7361. #### Usage
  7362. M912 [ X | Y | Z | E ]
  7363. #### Parameters
  7364. - `X` - X stepper driver running current value
  7365. - `Y` - Y stepper driver running current value
  7366. - `Z` - Z stepper driver running current value
  7367. - `E` - Extruder stepper driver running current value
  7368. */
  7369. case 912:
  7370. {
  7371. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  7372. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  7373. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  7374. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  7375. }
  7376. break;
  7377. /*!
  7378. ### M913 - Print TMC2130 currents <a href="https://reprap.org/wiki/G-code#M913:_Print_TMC2130_currents">M913: Print TMC2130 currents</a>
  7379. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7380. Shows TMC2130 currents.
  7381. */
  7382. case 913:
  7383. {
  7384. tmc2130_print_currents();
  7385. }
  7386. break;
  7387. /*!
  7388. ### M914 - Set TMC2130 normal mode <a href="https://reprap.org/wiki/G-code#M914:_Set_TMC2130_normal_mode">M914: Set TMC2130 normal mode</a>
  7389. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7390. */
  7391. case 914:
  7392. {
  7393. tmc2130_mode = TMC2130_MODE_NORMAL;
  7394. update_mode_profile();
  7395. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7396. }
  7397. break;
  7398. /*!
  7399. ### M915 - Set TMC2130 silent mode <a href="https://reprap.org/wiki/G-code#M915:_Set_TMC2130_silent_mode">M915: Set TMC2130 silent mode</a>
  7400. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7401. */
  7402. case 915:
  7403. {
  7404. tmc2130_mode = TMC2130_MODE_SILENT;
  7405. update_mode_profile();
  7406. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7407. }
  7408. break;
  7409. /*!
  7410. ### M916 - Set TMC2130 Stallguard sensitivity threshold <a href="https://reprap.org/wiki/G-code#M916:_Set_TMC2130_Stallguard_sensitivity_threshold">M916: Set TMC2130 Stallguard sensitivity threshold</a>
  7411. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7412. #### Usage
  7413. M916 [ X | Y | Z | E ]
  7414. #### Parameters
  7415. - `X` - X stepper driver stallguard sensitivity threshold value
  7416. - `Y` - Y stepper driver stallguard sensitivity threshold value
  7417. - `Z` - Z stepper driver stallguard sensitivity threshold value
  7418. - `E` - Extruder stepper driver stallguard sensitivity threshold value
  7419. */
  7420. case 916:
  7421. {
  7422. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  7423. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  7424. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  7425. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  7426. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  7427. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  7428. }
  7429. break;
  7430. /*!
  7431. ### M917 - Set TMC2130 PWM amplitude offset (pwm_ampl) <a href="https://reprap.org/wiki/G-code#M917:_Set_TMC2130_PWM_amplitude_offset_.28pwm_ampl.29">M917: Set TMC2130 PWM amplitude offset (pwm_ampl)</a>
  7432. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7433. #### Usage
  7434. M917 [ X | Y | Z | E ]
  7435. #### Parameters
  7436. - `X` - X stepper driver PWM amplitude offset value
  7437. - `Y` - Y stepper driver PWM amplitude offset value
  7438. - `Z` - Z stepper driver PWM amplitude offset value
  7439. - `E` - Extruder stepper driver PWM amplitude offset value
  7440. */
  7441. case 917:
  7442. {
  7443. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  7444. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  7445. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  7446. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  7447. }
  7448. break;
  7449. /*!
  7450. ### M918 - Set TMC2130 PWM amplitude gradient (pwm_grad) <a href="https://reprap.org/wiki/G-code#M918:_Set_TMC2130_PWM_amplitude_gradient_.28pwm_grad.29">M918: Set TMC2130 PWM amplitude gradient (pwm_grad)</a>
  7451. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7452. #### Usage
  7453. M918 [ X | Y | Z | E ]
  7454. #### Parameters
  7455. - `X` - X stepper driver PWM amplitude gradient value
  7456. - `Y` - Y stepper driver PWM amplitude gradient value
  7457. - `Z` - Z stepper driver PWM amplitude gradient value
  7458. - `E` - Extruder stepper driver PWM amplitude gradient value
  7459. */
  7460. case 918:
  7461. {
  7462. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  7463. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  7464. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  7465. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  7466. }
  7467. break;
  7468. #endif //TMC2130_SERVICE_CODES_M910_M918
  7469. /*!
  7470. ### M350 - Set microstepping mode <a href="https://reprap.org/wiki/G-code#M350:_Set_microstepping_mode">M350: Set microstepping mode</a>
  7471. Printers with TMC2130 drivers have `X`, `Y`, `Z` and `E` as options. The steps-per-unit value is updated accordingly. Not all resolutions are valid!
  7472. Printers without TMC2130 drivers also have `B` and `S` options. In this case, the steps-per-unit value in not changed!
  7473. #### Usage
  7474. M350 [ X | Y | Z | E | B | S ]
  7475. #### Parameters
  7476. - `X` - X new resolution
  7477. - `Y` - Y new resolution
  7478. - `Z` - Z new resolution
  7479. - `E` - E new resolution
  7480. Only valid for MK2.5(S) or printers without TMC2130 drivers
  7481. - `B` - Second extruder new resolution
  7482. - `S` - All axes new resolution
  7483. */
  7484. case 350:
  7485. {
  7486. #ifdef TMC2130
  7487. for (uint_least8_t i=0; i<NUM_AXIS; i++)
  7488. {
  7489. if(code_seen(axis_codes[i]))
  7490. {
  7491. uint16_t res_new = code_value();
  7492. #ifdef ALLOW_ALL_MRES
  7493. bool res_valid = res_new > 0 && res_new <= 256 && !(res_new & (res_new - 1)); // must be a power of two
  7494. #else
  7495. bool res_valid = (res_new == 8) || (res_new == 16) || (res_new == 32); // resolutions valid for all axis
  7496. res_valid |= (i != E_AXIS) && ((res_new == 1) || (res_new == 2) || (res_new == 4)); // resolutions valid for X Y Z only
  7497. res_valid |= (i == E_AXIS) && ((res_new == 64) || (res_new == 128)); // resolutions valid for E only
  7498. #endif
  7499. if (res_valid)
  7500. {
  7501. st_synchronize();
  7502. uint16_t res = tmc2130_get_res(i);
  7503. tmc2130_set_res(i, res_new);
  7504. cs.axis_ustep_resolution[i] = res_new;
  7505. if (res_new > res)
  7506. {
  7507. uint16_t fac = (res_new / res);
  7508. cs.axis_steps_per_unit[i] *= fac;
  7509. position[i] *= fac;
  7510. }
  7511. else
  7512. {
  7513. uint16_t fac = (res / res_new);
  7514. cs.axis_steps_per_unit[i] /= fac;
  7515. position[i] /= fac;
  7516. }
  7517. #if defined(FILAMENT_SENSOR) && defined(PAT9125)
  7518. if (i == E_AXIS)
  7519. fsensor_set_axis_steps_per_unit(cs.axis_steps_per_unit[i]);
  7520. #endif
  7521. }
  7522. }
  7523. }
  7524. reset_acceleration_rates();
  7525. #else //TMC2130
  7526. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7527. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  7528. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  7529. if(code_seen('B')) microstep_mode(4,code_value());
  7530. microstep_readings();
  7531. #endif
  7532. #endif //TMC2130
  7533. }
  7534. break;
  7535. /*!
  7536. ### M351 - Toggle Microstep Pins <a href="https://reprap.org/wiki/G-code#M351:_Toggle_MS1_MS2_pins_directly">M351: Toggle MS1 MS2 pins directly</a>
  7537. Toggle MS1 MS2 pins directly.
  7538. #### Usage
  7539. M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  7540. #### Parameters
  7541. - `X` - Update X axis
  7542. - `Y` - Update Y axis
  7543. - `Z` - Update Z axis
  7544. - `E` - Update E axis
  7545. - `S` - which MSx pin to toggle
  7546. - `B` - new pin value
  7547. */
  7548. case 351:
  7549. {
  7550. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7551. if(code_seen('S')) switch((int)code_value())
  7552. {
  7553. case 1:
  7554. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  7555. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  7556. break;
  7557. case 2:
  7558. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  7559. if(code_seen('B')) microstep_ms(4,-1,code_value());
  7560. break;
  7561. }
  7562. microstep_readings();
  7563. #endif
  7564. }
  7565. break;
  7566. /*!
  7567. ### M701 - Load filament <a href="https://reprap.org/wiki/G-code#M701:_Load_filament">M701: Load filament</a>
  7568. #### Usage
  7569. M701 [ E | T ]
  7570. #### Parameters
  7571. - `E` - ID of filament to load, ranges from 0 to 4
  7572. - `T` - Alias of `E`. Used for compatibility with Marlin
  7573. */
  7574. case 701:
  7575. {
  7576. if (mmu_enabled && (code_seen('E') || code_seen('T')))
  7577. tmp_extruder = code_value_uint8();
  7578. gcode_M701();
  7579. }
  7580. break;
  7581. /*!
  7582. ### M702 - Unload filament <a href="https://reprap.org/wiki/G-code#M702:_Unload_filament">G32: Undock Z Probe sled</a>
  7583. #### Usage
  7584. M702 [ C ]
  7585. #### Parameters
  7586. - `C` - Unload just current filament
  7587. - without any parameters unload all filaments
  7588. */
  7589. case 702:
  7590. {
  7591. if (code_seen('C')) {
  7592. if(mmu_enabled) extr_unload(); //! if "C" unload current filament; if mmu is not present no action is performed
  7593. }
  7594. else {
  7595. if(mmu_enabled) extr_unload(); //! unload current filament
  7596. else unload_filament();
  7597. }
  7598. }
  7599. break;
  7600. /*!
  7601. ### M999 - Restart after being stopped <a href="https://reprap.org/wiki/G-code#M999:_Restart_after_being_stopped_by_error">M999: Restart after being stopped by error</a>
  7602. @todo Usually doesn't work. Should be fixed or removed. Most of the time, if `Stopped` it set, the print fails and is unrecoverable.
  7603. */
  7604. case 999:
  7605. Stopped = false;
  7606. lcd_reset_alert_level();
  7607. gcode_LastN = Stopped_gcode_LastN;
  7608. FlushSerialRequestResend();
  7609. break;
  7610. /*!
  7611. #### End of M-Commands
  7612. */
  7613. default:
  7614. printf_P(MSG_UNKNOWN_CODE, 'M', cmdbuffer + bufindr + CMDHDRSIZE);
  7615. }
  7616. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  7617. mcode_in_progress = 0;
  7618. }
  7619. }
  7620. // end if(code_seen('M')) (end of M codes)
  7621. /*!
  7622. -----------------------------------------------------------------------------------------
  7623. # T Codes
  7624. T<extruder nr.> - select extruder in case of multi extruder printer. select filament in case of MMU_V2.
  7625. #### For MMU_V2:
  7626. T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  7627. @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  7628. @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.
  7629. @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  7630. */
  7631. else if(code_seen('T'))
  7632. {
  7633. static const char duplicate_Tcode_ignored[] PROGMEM = "Duplicate T-code ignored.";
  7634. int index;
  7635. bool load_to_nozzle = false;
  7636. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  7637. *(strchr_pointer + index) = tolower(*(strchr_pointer + index));
  7638. if ((*(strchr_pointer + index) < '0' || *(strchr_pointer + index) > '4') && *(strchr_pointer + index) != '?' && *(strchr_pointer + index) != 'x' && *(strchr_pointer + index) != 'c') {
  7639. SERIAL_ECHOLNPGM("Invalid T code.");
  7640. }
  7641. else if (*(strchr_pointer + index) == 'x'){ //load to bondtech gears; if mmu is not present do nothing
  7642. if (mmu_enabled)
  7643. {
  7644. tmp_extruder = choose_menu_P(_T(MSG_SELECT_FILAMENT), _T(MSG_FILAMENT));
  7645. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  7646. {
  7647. puts_P(duplicate_Tcode_ignored);
  7648. }
  7649. else
  7650. {
  7651. st_synchronize();
  7652. mmu_command(MmuCmd::T0 + tmp_extruder);
  7653. manage_response(true, true, MMU_TCODE_MOVE);
  7654. }
  7655. }
  7656. }
  7657. else if (*(strchr_pointer + index) == 'c') { //load to from bondtech gears to nozzle (nozzle should be preheated)
  7658. if (mmu_enabled)
  7659. {
  7660. st_synchronize();
  7661. mmu_continue_loading(usb_timer.running() || (lcd_commands_type == LcdCommands::Layer1Cal));
  7662. mmu_extruder = tmp_extruder; //filament change is finished
  7663. mmu_load_to_nozzle();
  7664. }
  7665. }
  7666. else {
  7667. if (*(strchr_pointer + index) == '?')
  7668. {
  7669. if(mmu_enabled)
  7670. {
  7671. tmp_extruder = choose_menu_P(_T(MSG_SELECT_FILAMENT), _T(MSG_FILAMENT));
  7672. load_to_nozzle = true;
  7673. } else
  7674. {
  7675. tmp_extruder = choose_menu_P(_T(MSG_SELECT_EXTRUDER), _T(MSG_EXTRUDER));
  7676. }
  7677. }
  7678. else {
  7679. tmp_extruder = code_value();
  7680. if (mmu_enabled && lcd_autoDepleteEnabled())
  7681. {
  7682. tmp_extruder = ad_getAlternative(tmp_extruder);
  7683. }
  7684. }
  7685. st_synchronize();
  7686. if (mmu_enabled)
  7687. {
  7688. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  7689. {
  7690. puts_P(duplicate_Tcode_ignored);
  7691. }
  7692. else
  7693. {
  7694. #if defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  7695. if (EEPROM_MMU_CUTTER_ENABLED_always == eeprom_read_byte((uint8_t*)EEPROM_MMU_CUTTER_ENABLED))
  7696. {
  7697. mmu_command(MmuCmd::K0 + tmp_extruder);
  7698. manage_response(true, true, MMU_UNLOAD_MOVE);
  7699. }
  7700. #endif //defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  7701. mmu_command(MmuCmd::T0 + tmp_extruder);
  7702. manage_response(true, true, MMU_TCODE_MOVE);
  7703. mmu_continue_loading(usb_timer.running() || (lcd_commands_type == LcdCommands::Layer1Cal));
  7704. mmu_extruder = tmp_extruder; //filament change is finished
  7705. if (load_to_nozzle)// for single material usage with mmu
  7706. {
  7707. mmu_load_to_nozzle();
  7708. }
  7709. }
  7710. }
  7711. else
  7712. {
  7713. if (tmp_extruder >= EXTRUDERS) {
  7714. SERIAL_ECHO_START;
  7715. SERIAL_ECHO('T');
  7716. SERIAL_PROTOCOLLN((int)tmp_extruder);
  7717. SERIAL_ECHOLNRPGM(_n("Invalid extruder"));////MSG_INVALID_EXTRUDER
  7718. }
  7719. else {
  7720. #if EXTRUDERS > 1
  7721. bool make_move = false;
  7722. #endif
  7723. if (code_seen('F')) {
  7724. #if EXTRUDERS > 1
  7725. make_move = true;
  7726. #endif
  7727. next_feedrate = code_value();
  7728. if (next_feedrate > 0.0) {
  7729. feedrate = next_feedrate;
  7730. }
  7731. }
  7732. #if EXTRUDERS > 1
  7733. if (tmp_extruder != active_extruder) {
  7734. // Save current position to return to after applying extruder offset
  7735. set_destination_to_current();
  7736. // Offset extruder (only by XY)
  7737. int i;
  7738. for (i = 0; i < 2; i++) {
  7739. current_position[i] = current_position[i] -
  7740. extruder_offset[i][active_extruder] +
  7741. extruder_offset[i][tmp_extruder];
  7742. }
  7743. // Set the new active extruder and position
  7744. active_extruder = tmp_extruder;
  7745. plan_set_position_curposXYZE();
  7746. // Move to the old position if 'F' was in the parameters
  7747. if (make_move && Stopped == false) {
  7748. prepare_move();
  7749. }
  7750. }
  7751. #endif
  7752. SERIAL_ECHO_START;
  7753. SERIAL_ECHORPGM(_n("Active Extruder: "));////MSG_ACTIVE_EXTRUDER
  7754. SERIAL_PROTOCOLLN((int)active_extruder);
  7755. }
  7756. }
  7757. }
  7758. } // end if(code_seen('T')) (end of T codes)
  7759. /*!
  7760. #### End of T-Codes
  7761. */
  7762. /**
  7763. *---------------------------------------------------------------------------------
  7764. *# D codes
  7765. */
  7766. else if (code_seen('D')) // D codes (debug)
  7767. {
  7768. switch(code_value_short())
  7769. {
  7770. /*!
  7771. ### D-1 - Endless Loop <a href="https://reprap.org/wiki/G-code#D-1:_Endless_Loop">D-1: Endless Loop</a>
  7772. */
  7773. case -1:
  7774. dcode__1(); break;
  7775. #ifdef DEBUG_DCODES
  7776. /*!
  7777. ### D0 - Reset <a href="https://reprap.org/wiki/G-code#D0:_Reset">D0: Reset</a>
  7778. #### Usage
  7779. D0 [ B ]
  7780. #### Parameters
  7781. - `B` - Bootloader
  7782. */
  7783. case 0:
  7784. dcode_0(); break;
  7785. /*!
  7786. *
  7787. ### D1 - Clear EEPROM and RESET <a href="https://reprap.org/wiki/G-code#D1:_Clear_EEPROM_and_RESET">D1: Clear EEPROM and RESET</a>
  7788. D1
  7789. *
  7790. */
  7791. case 1:
  7792. dcode_1(); break;
  7793. #endif
  7794. #if defined DEBUG_DCODE2 || defined DEBUG_DCODES
  7795. /*!
  7796. ### D2 - Read/Write RAM <a href="https://reprap.org/wiki/G-code#D2:_Read.2FWrite_RAM">D3: Read/Write RAM</a>
  7797. This command can be used without any additional parameters. It will read the entire RAM.
  7798. #### Usage
  7799. D2 [ A | C | X ]
  7800. #### Parameters
  7801. - `A` - Address (x0000-x1fff)
  7802. - `C` - Count (1-8192)
  7803. - `X` - Data
  7804. #### Notes
  7805. - The hex address needs to be lowercase without the 0 before the x
  7806. - Count is decimal
  7807. - The hex data needs to be lowercase
  7808. */
  7809. case 2:
  7810. dcode_2(); break;
  7811. #endif //DEBUG_DCODES
  7812. #if defined DEBUG_DCODE3 || defined DEBUG_DCODES
  7813. /*!
  7814. ### D3 - Read/Write EEPROM <a href="https://reprap.org/wiki/G-code#D3:_Read.2FWrite_EEPROM">D3: Read/Write EEPROM</a>
  7815. This command can be used without any additional parameters. It will read the entire eeprom.
  7816. #### Usage
  7817. D3 [ A | C | X ]
  7818. #### Parameters
  7819. - `A` - Address (x0000-x0fff)
  7820. - `C` - Count (1-4096)
  7821. - `X` - Data (hex)
  7822. #### Notes
  7823. - The hex address needs to be lowercase without the 0 before the x
  7824. - Count is decimal
  7825. - The hex data needs to be lowercase
  7826. */
  7827. case 3:
  7828. dcode_3(); break;
  7829. #endif //DEBUG_DCODE3
  7830. #ifdef DEBUG_DCODES
  7831. /*!
  7832. ### D4 - Read/Write PIN <a href="https://reprap.org/wiki/G-code#D4:_Read.2FWrite_PIN">D4: Read/Write PIN</a>
  7833. To read the digital value of a pin you need only to define the pin number.
  7834. #### Usage
  7835. D4 [ P | F | V ]
  7836. #### Parameters
  7837. - `P` - Pin (0-255)
  7838. - `F` - Function in/out (0/1)
  7839. - `V` - Value (0/1)
  7840. */
  7841. case 4:
  7842. dcode_4(); break;
  7843. #endif //DEBUG_DCODES
  7844. #if defined DEBUG_DCODE5 || defined DEBUG_DCODES
  7845. /*!
  7846. ### D5 - Read/Write FLASH <a href="https://reprap.org/wiki/G-code#D5:_Read.2FWrite_FLASH">D5: Read/Write Flash</a>
  7847. This command can be used without any additional parameters. It will read the 1kb FLASH.
  7848. #### Usage
  7849. D5 [ A | C | X | E ]
  7850. #### Parameters
  7851. - `A` - Address (x00000-x3ffff)
  7852. - `C` - Count (1-8192)
  7853. - `X` - Data (hex)
  7854. - `E` - Erase
  7855. #### Notes
  7856. - The hex address needs to be lowercase without the 0 before the x
  7857. - Count is decimal
  7858. - The hex data needs to be lowercase
  7859. */
  7860. case 5:
  7861. dcode_5(); break;
  7862. #endif //DEBUG_DCODE5
  7863. #if defined DEBUG_DCODE6 || defined DEBUG_DCODES
  7864. /*!
  7865. ### D6 - Read/Write external FLASH <a href="https://reprap.org/wiki/G-code#D6:_Read.2FWrite_external_FLASH">D6: Read/Write external Flash</a>
  7866. Reserved
  7867. */
  7868. case 6:
  7869. dcode_6(); break;
  7870. #endif
  7871. #ifdef DEBUG_DCODES
  7872. /*!
  7873. ### D7 - Read/Write Bootloader <a href="https://reprap.org/wiki/G-code#D7:_Read.2FWrite_Bootloader">D7: Read/Write Bootloader</a>
  7874. Reserved
  7875. */
  7876. case 7:
  7877. dcode_7(); break;
  7878. /*!
  7879. ### D8 - Read/Write PINDA <a href="https://reprap.org/wiki/G-code#D8:_Read.2FWrite_PINDA">D8: Read/Write PINDA</a>
  7880. #### Usage
  7881. D8 [ ? | ! | P | Z ]
  7882. #### Parameters
  7883. - `?` - Read PINDA temperature shift values
  7884. - `!` - Reset PINDA temperature shift values to default
  7885. - `P` - Pinda temperature [C]
  7886. - `Z` - Z Offset [mm]
  7887. */
  7888. case 8:
  7889. dcode_8(); break;
  7890. /*!
  7891. ### D9 - Read ADC <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9: Read ADC</a>
  7892. #### Usage
  7893. D9 [ I | V ]
  7894. #### Parameters
  7895. - `I` - ADC channel index
  7896. - `0` - Heater 0 temperature
  7897. - `1` - Heater 1 temperature
  7898. - `2` - Bed temperature
  7899. - `3` - PINDA temperature
  7900. - `4` - PWR voltage
  7901. - `5` - Ambient temperature
  7902. - `6` - BED voltage
  7903. - `V` Value to be written as simulated
  7904. */
  7905. case 9:
  7906. dcode_9(); break;
  7907. /*!
  7908. ### D10 - Set XYZ calibration = OK <a href="https://reprap.org/wiki/G-code#D10:_Set_XYZ_calibration_.3D_OK">D10: Set XYZ calibration = OK</a>
  7909. */
  7910. case 10:
  7911. dcode_10(); break;
  7912. /*!
  7913. ### D12 - Time <a href="https://reprap.org/wiki/G-code#D12:_Time">D12: Time</a>
  7914. Writes the current time in the log file.
  7915. */
  7916. #endif //DEBUG_DCODES
  7917. #ifdef XFLASH_DUMP
  7918. /*!
  7919. ### D20 - Generate an offline crash dump <a href="https://reprap.org/wiki/G-code#D20:_Generate_an_offline_crash_dump">D20: Generate an offline crash dump</a>
  7920. Generate a crash dump for later retrival.
  7921. #### Usage
  7922. D20 [E]
  7923. ### Parameters
  7924. - `E` - Perform an emergency crash dump (resets the printer).
  7925. ### Notes
  7926. - A crash dump can be later recovered with D21, or cleared with D22.
  7927. - An emergency crash dump includes register data, but will cause the printer to reset after the dump
  7928. is completed.
  7929. */
  7930. case 20: {
  7931. dcode_20();
  7932. break;
  7933. };
  7934. /*!
  7935. ### D21 - Print crash dump to serial <a href="https://reprap.org/wiki/G-code#D21:_Print_crash_dump_to_serial">D21: Print crash dump to serial</a>
  7936. Output the complete crash dump (if present) to the serial.
  7937. #### Usage
  7938. D21
  7939. ### Notes
  7940. - The starting address can vary between builds, but it's always at the beginning of the data section.
  7941. */
  7942. case 21: {
  7943. dcode_21();
  7944. break;
  7945. };
  7946. /*!
  7947. ### D22 - Clear crash dump state <a href="https://reprap.org/wiki/G-code#D22:_Clear_crash_dump_state">D22: Clear crash dump state</a>
  7948. Clear an existing internal crash dump.
  7949. #### Usage
  7950. D22
  7951. */
  7952. case 22: {
  7953. dcode_22();
  7954. break;
  7955. };
  7956. #endif //XFLASH_DUMP
  7957. #ifdef EMERGENCY_SERIAL_DUMP
  7958. /*!
  7959. ### D23 - Request emergency dump on serial <a href="https://reprap.org/wiki/G-code#D23:_Request_emergency_dump_on_serial">D23: Request emergency dump on serial</a>
  7960. On boards without offline dump support, request online dumps to the serial port on firmware faults.
  7961. When online dumps are enabled, the FW will dump memory on the serial before resetting.
  7962. #### Usage
  7963. D23 [E] [R]
  7964. #### Parameters
  7965. - `E` - Perform an emergency crash dump (resets the printer).
  7966. - `R` - Disable online dumps.
  7967. */
  7968. case 23: {
  7969. dcode_23();
  7970. break;
  7971. };
  7972. #endif
  7973. #ifdef HEATBED_ANALYSIS
  7974. /*!
  7975. ### D80 - Bed check <a href="https://reprap.org/wiki/G-code#D80:_Bed_check">D80: Bed check</a>
  7976. This command will log data to SD card file "mesh.txt".
  7977. #### Usage
  7978. D80 [ E | F | G | H | I | J ]
  7979. #### Parameters
  7980. - `E` - Dimension X (default 40)
  7981. - `F` - Dimention Y (default 40)
  7982. - `G` - Points X (default 40)
  7983. - `H` - Points Y (default 40)
  7984. - `I` - Offset X (default 74)
  7985. - `J` - Offset Y (default 34)
  7986. */
  7987. case 80:
  7988. dcode_80(); break;
  7989. /*!
  7990. ### D81 - Bed analysis <a href="https://reprap.org/wiki/G-code#D81:_Bed_analysis">D80: Bed analysis</a>
  7991. This command will log data to SD card file "wldsd.txt".
  7992. #### Usage
  7993. D81 [ E | F | G | H | I | J ]
  7994. #### Parameters
  7995. - `E` - Dimension X (default 40)
  7996. - `F` - Dimention Y (default 40)
  7997. - `G` - Points X (default 40)
  7998. - `H` - Points Y (default 40)
  7999. - `I` - Offset X (default 74)
  8000. - `J` - Offset Y (default 34)
  8001. */
  8002. case 81:
  8003. dcode_81(); break;
  8004. #endif //HEATBED_ANALYSIS
  8005. #ifdef DEBUG_DCODES
  8006. /*!
  8007. ### D106 - Print measured fan speed for different pwm values <a href="https://reprap.org/wiki/G-code#D106:_Print_measured_fan_speed_for_different_pwm_values">D106: Print measured fan speed for different pwm values</a>
  8008. */
  8009. case 106:
  8010. dcode_106(); break;
  8011. #ifdef TMC2130
  8012. /*!
  8013. ### D2130 - Trinamic stepper controller <a href="https://reprap.org/wiki/G-code#D2130:_Trinamic_stepper_controller">D2130: Trinamic stepper controller</a>
  8014. @todo Please review by owner of the code. RepRap Wiki Gcode needs to be updated after review of owner as well.
  8015. #### Usage
  8016. D2130 [ Axis | Command | Subcommand | Value ]
  8017. #### Parameters
  8018. - Axis
  8019. - `X` - X stepper driver
  8020. - `Y` - Y stepper driver
  8021. - `Z` - Z stepper driver
  8022. - `E` - Extruder stepper driver
  8023. - Commands
  8024. - `0` - Current off
  8025. - `1` - Current on
  8026. - `+` - Single step
  8027. - `-` - Single step oposite direction
  8028. - `NNN` - Value sereval steps
  8029. - `?` - Read register
  8030. - Subcommands for read register
  8031. - `mres` - Micro step resolution. More information in datasheet '5.5.2 CHOPCONF – Chopper Configuration'
  8032. - `step` - Step
  8033. - `mscnt` - Microstep counter. More information in datasheet '5.5 Motor Driver Registers'
  8034. - `mscuract` - Actual microstep current for motor. More information in datasheet '5.5 Motor Driver Registers'
  8035. - `wave` - Microstep linearity compensation curve
  8036. - `!` - Set register
  8037. - Subcommands for set register
  8038. - `mres` - Micro step resolution
  8039. - `step` - Step
  8040. - `wave` - Microstep linearity compensation curve
  8041. - Values for set register
  8042. - `0, 180 --> 250` - Off
  8043. - `0.9 --> 1.25` - Valid values (recommended is 1.1)
  8044. - `@` - Home calibrate axis
  8045. Examples:
  8046. D2130E?wave
  8047. Print extruder microstep linearity compensation curve
  8048. D2130E!wave0
  8049. Disable extruder linearity compensation curve, (sine curve is used)
  8050. D2130E!wave220
  8051. (sin(x))^1.1 extruder microstep compensation curve used
  8052. Notes:
  8053. For more information see https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC2130_datasheet.pdf
  8054. *
  8055. */
  8056. case 2130:
  8057. dcode_2130(); break;
  8058. #endif //TMC2130
  8059. #if (defined (FILAMENT_SENSOR) && defined(PAT9125))
  8060. /*!
  8061. ### D9125 - PAT9125 filament sensor <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9125: PAT9125 filament sensor</a>
  8062. #### Usage
  8063. D9125 [ ? | ! | R | X | Y | L ]
  8064. #### Parameters
  8065. - `?` - Print values
  8066. - `!` - Print values
  8067. - `R` - Resolution. Not active in code
  8068. - `X` - X values
  8069. - `Y` - Y values
  8070. - `L` - Activate filament sensor log
  8071. */
  8072. case 9125:
  8073. dcode_9125(); break;
  8074. #endif //FILAMENT_SENSOR
  8075. #endif //DEBUG_DCODES
  8076. default:
  8077. printf_P(MSG_UNKNOWN_CODE, 'D', cmdbuffer + bufindr + CMDHDRSIZE);
  8078. }
  8079. }
  8080. else
  8081. {
  8082. SERIAL_ECHO_START;
  8083. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  8084. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  8085. SERIAL_ECHOLNPGM("\"(2)");
  8086. }
  8087. KEEPALIVE_STATE(NOT_BUSY);
  8088. ClearToSend();
  8089. }
  8090. /*!
  8091. #### End of D-Codes
  8092. */
  8093. /** @defgroup GCodes G-Code List
  8094. */
  8095. // ---------------------------------------------------
  8096. void FlushSerialRequestResend()
  8097. {
  8098. //char cmdbuffer[bufindr][100]="Resend:";
  8099. MYSERIAL.flush();
  8100. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  8101. }
  8102. // Confirm the execution of a command, if sent from a serial line.
  8103. // Execution of a command from a SD card will not be confirmed.
  8104. void ClearToSend()
  8105. {
  8106. previous_millis_cmd.start();
  8107. if (buflen && ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  8108. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  8109. }
  8110. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8111. void update_currents() {
  8112. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  8113. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  8114. float tmp_motor[3];
  8115. //SERIAL_ECHOLNPGM("Currents updated: ");
  8116. if (destination[Z_AXIS] < Z_SILENT) {
  8117. //SERIAL_ECHOLNPGM("LOW");
  8118. for (uint8_t i = 0; i < 3; i++) {
  8119. st_current_set(i, current_low[i]);
  8120. /*MYSERIAL.print(int(i));
  8121. SERIAL_ECHOPGM(": ");
  8122. MYSERIAL.println(current_low[i]);*/
  8123. }
  8124. }
  8125. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  8126. //SERIAL_ECHOLNPGM("HIGH");
  8127. for (uint8_t i = 0; i < 3; i++) {
  8128. st_current_set(i, current_high[i]);
  8129. /*MYSERIAL.print(int(i));
  8130. SERIAL_ECHOPGM(": ");
  8131. MYSERIAL.println(current_high[i]);*/
  8132. }
  8133. }
  8134. else {
  8135. for (uint8_t i = 0; i < 3; i++) {
  8136. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  8137. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  8138. st_current_set(i, tmp_motor[i]);
  8139. /*MYSERIAL.print(int(i));
  8140. SERIAL_ECHOPGM(": ");
  8141. MYSERIAL.println(tmp_motor[i]);*/
  8142. }
  8143. }
  8144. }
  8145. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8146. void get_coordinates()
  8147. {
  8148. bool seen[4]={false,false,false,false};
  8149. for(int8_t i=0; i < NUM_AXIS; i++) {
  8150. if(code_seen(axis_codes[i]))
  8151. {
  8152. bool relative = axis_relative_modes & (1 << i);
  8153. destination[i] = code_value();
  8154. if (i == E_AXIS) {
  8155. float emult = extruder_multiplier[active_extruder];
  8156. if (emult != 1.) {
  8157. if (! relative) {
  8158. destination[i] -= current_position[i];
  8159. relative = true;
  8160. }
  8161. destination[i] *= emult;
  8162. }
  8163. }
  8164. if (relative)
  8165. destination[i] += current_position[i];
  8166. seen[i]=true;
  8167. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8168. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  8169. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8170. }
  8171. else destination[i] = current_position[i]; //Are these else lines really needed?
  8172. }
  8173. if(code_seen('F')) {
  8174. next_feedrate = code_value();
  8175. if(next_feedrate > 0.0) feedrate = next_feedrate;
  8176. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  8177. {
  8178. // float e_max_speed =
  8179. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  8180. }
  8181. }
  8182. }
  8183. void get_arc_coordinates()
  8184. {
  8185. #ifdef SF_ARC_FIX
  8186. bool relative_mode_backup = relative_mode;
  8187. relative_mode = true;
  8188. #endif
  8189. get_coordinates();
  8190. #ifdef SF_ARC_FIX
  8191. relative_mode=relative_mode_backup;
  8192. #endif
  8193. if(code_seen('I')) {
  8194. offset[0] = code_value();
  8195. }
  8196. else {
  8197. offset[0] = 0.0;
  8198. }
  8199. if(code_seen('J')) {
  8200. offset[1] = code_value();
  8201. }
  8202. else {
  8203. offset[1] = 0.0;
  8204. }
  8205. }
  8206. void clamp_to_software_endstops(float target[3])
  8207. {
  8208. #ifdef DEBUG_DISABLE_SWLIMITS
  8209. return;
  8210. #endif //DEBUG_DISABLE_SWLIMITS
  8211. world2machine_clamp(target[0], target[1]);
  8212. // Clamp the Z coordinate.
  8213. if (min_software_endstops) {
  8214. float negative_z_offset = 0;
  8215. #ifdef ENABLE_AUTO_BED_LEVELING
  8216. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  8217. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  8218. #endif
  8219. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  8220. }
  8221. if (max_software_endstops) {
  8222. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  8223. }
  8224. }
  8225. #ifdef MESH_BED_LEVELING
  8226. 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) {
  8227. float dx = x - current_position[X_AXIS];
  8228. float dy = y - current_position[Y_AXIS];
  8229. int n_segments = 0;
  8230. if (mbl.active) {
  8231. float len = fabs(dx) + fabs(dy);
  8232. if (len > 0)
  8233. // Split to 3cm segments or shorter.
  8234. n_segments = int(ceil(len / 30.f));
  8235. }
  8236. if (n_segments > 1) {
  8237. // In a multi-segment move explicitly set the final target in the plan
  8238. // as the move will be recalculated in it's entirety
  8239. float gcode_target[NUM_AXIS];
  8240. gcode_target[X_AXIS] = x;
  8241. gcode_target[Y_AXIS] = y;
  8242. gcode_target[Z_AXIS] = z;
  8243. gcode_target[E_AXIS] = e;
  8244. float dz = z - current_position[Z_AXIS];
  8245. float de = e - current_position[E_AXIS];
  8246. for (int i = 1; i < n_segments; ++ i) {
  8247. float t = float(i) / float(n_segments);
  8248. plan_buffer_line(current_position[X_AXIS] + t * dx,
  8249. current_position[Y_AXIS] + t * dy,
  8250. current_position[Z_AXIS] + t * dz,
  8251. current_position[E_AXIS] + t * de,
  8252. feed_rate, extruder, gcode_target);
  8253. if (waiting_inside_plan_buffer_line_print_aborted)
  8254. return;
  8255. }
  8256. }
  8257. // The rest of the path.
  8258. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  8259. }
  8260. #endif // MESH_BED_LEVELING
  8261. void prepare_move()
  8262. {
  8263. clamp_to_software_endstops(destination);
  8264. previous_millis_cmd.start();
  8265. // Do not use feedmultiply for E or Z only moves
  8266. if( (current_position[X_AXIS] == destination [X_AXIS]) && (current_position[Y_AXIS] == destination [Y_AXIS])) {
  8267. plan_buffer_line_destinationXYZE(feedrate/60);
  8268. }
  8269. else {
  8270. #ifdef MESH_BED_LEVELING
  8271. 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);
  8272. #else
  8273. plan_buffer_line_destinationXYZE(feedrate*feedmultiply*(1./(60.f*100.f)));
  8274. #endif
  8275. }
  8276. set_current_to_destination();
  8277. }
  8278. void prepare_arc_move(bool isclockwise) {
  8279. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  8280. // Trace the arc
  8281. mc_arc(current_position, destination, offset, feedrate * feedmultiply / 60 / 100.0, r, isclockwise, active_extruder);
  8282. // As far as the parser is concerned, the position is now == target. In reality the
  8283. // motion control system might still be processing the action and the real tool position
  8284. // in any intermediate location.
  8285. set_current_to_destination();
  8286. previous_millis_cmd.start();
  8287. }
  8288. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8289. #if defined(FAN_PIN)
  8290. #if CONTROLLERFAN_PIN == FAN_PIN
  8291. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  8292. #endif
  8293. #endif
  8294. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  8295. unsigned long lastMotorCheck = 0;
  8296. void controllerFan()
  8297. {
  8298. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  8299. {
  8300. lastMotorCheck = _millis();
  8301. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  8302. #if EXTRUDERS > 2
  8303. || !READ(E2_ENABLE_PIN)
  8304. #endif
  8305. #if EXTRUDER > 1
  8306. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  8307. || !READ(X2_ENABLE_PIN)
  8308. #endif
  8309. || !READ(E1_ENABLE_PIN)
  8310. #endif
  8311. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  8312. {
  8313. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  8314. }
  8315. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  8316. {
  8317. digitalWrite(CONTROLLERFAN_PIN, 0);
  8318. analogWrite(CONTROLLERFAN_PIN, 0);
  8319. }
  8320. else
  8321. {
  8322. // allows digital or PWM fan output to be used (see M42 handling)
  8323. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8324. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8325. }
  8326. }
  8327. }
  8328. #endif
  8329. #ifdef SAFETYTIMER
  8330. /**
  8331. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  8332. *
  8333. * Full screen blocking notification message is shown after heater turning off.
  8334. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  8335. * damage print.
  8336. *
  8337. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  8338. */
  8339. static void handleSafetyTimer()
  8340. {
  8341. #if (EXTRUDERS > 1)
  8342. #error Implemented only for one extruder.
  8343. #endif //(EXTRUDERS > 1)
  8344. if ((PRINTER_ACTIVE) || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  8345. {
  8346. safetyTimer.stop();
  8347. }
  8348. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  8349. {
  8350. safetyTimer.start();
  8351. }
  8352. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  8353. {
  8354. setTargetBed(0);
  8355. setAllTargetHotends(0);
  8356. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED c=20 r=4
  8357. }
  8358. }
  8359. #endif //SAFETYTIMER
  8360. #ifdef IR_SENSOR_ANALOG
  8361. #define FS_CHECK_COUNT 16
  8362. /// Switching mechanism of the fsensor type.
  8363. /// Called from 2 spots which have a very similar behavior
  8364. /// 1: ClFsensorPCB::_Old -> ClFsensorPCB::_Rev04 and print _i("FS v0.4 or newer")
  8365. /// 2: ClFsensorPCB::_Rev04 -> oFsensorPCB=ClFsensorPCB::_Old and print _i("FS v0.3 or older")
  8366. void manage_inactivity_IR_ANALOG_Check(uint16_t &nFSCheckCount, ClFsensorPCB isVersion, ClFsensorPCB switchTo, const char *statusLineTxt_P) {
  8367. bool bTemp = (!CHECK_ALL_HEATERS);
  8368. bTemp = bTemp && (menu_menu == lcd_status_screen);
  8369. bTemp = bTemp && ((oFsensorPCB == isVersion) || (oFsensorPCB == ClFsensorPCB::_Undef));
  8370. bTemp = bTemp && fsensor_enabled;
  8371. if (bTemp) {
  8372. nFSCheckCount++;
  8373. if (nFSCheckCount > FS_CHECK_COUNT) {
  8374. nFSCheckCount = 0; // not necessary
  8375. oFsensorPCB = switchTo;
  8376. eeprom_update_byte((uint8_t *)EEPROM_FSENSOR_PCB, (uint8_t)oFsensorPCB);
  8377. printf_IRSensorAnalogBoardChange();
  8378. lcd_setstatuspgm(statusLineTxt_P);
  8379. }
  8380. } else {
  8381. nFSCheckCount = 0;
  8382. }
  8383. }
  8384. #endif
  8385. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  8386. {
  8387. #ifdef FILAMENT_SENSOR
  8388. bool bInhibitFlag = false;
  8389. #ifdef IR_SENSOR_ANALOG
  8390. static uint16_t nFSCheckCount=0;
  8391. #endif // IR_SENSOR_ANALOG
  8392. if (mmu_enabled == false)
  8393. {
  8394. //-// if (mcode_in_progress != 600) //M600 not in progress
  8395. if (!PRINTER_ACTIVE) bInhibitFlag=(menu_menu==lcd_menu_show_sensors_state); //Block Filament sensor actions if PRINTER is not active and Support::SensorInfo menu active
  8396. #ifdef IR_SENSOR_ANALOG
  8397. bInhibitFlag=bInhibitFlag||bMenuFSDetect; // Block Filament sensor actions if Settings::HWsetup::FSdetect menu active
  8398. #endif // IR_SENSOR_ANALOG
  8399. if ((mcode_in_progress != 600) && (eFilamentAction != FilamentAction::AutoLoad) && (!bInhibitFlag) && (menu_menu != lcd_move_e)) //M600 not in progress, preHeat @ autoLoad menu not active
  8400. {
  8401. if (!moves_planned() && !IS_SD_PRINTING && !usb_timer.running() && (lcd_commands_type != LcdCommands::Layer1Cal) && ! eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE))
  8402. {
  8403. #ifdef IR_SENSOR_ANALOG
  8404. static uint16_t minVolt = Voltage2Raw(6.F), maxVolt = 0;
  8405. // detect min-max, some long term sliding window for filtration may be added
  8406. // avoiding floating point operations, thus computing in raw
  8407. if( current_voltage_raw_IR > maxVolt )maxVolt = current_voltage_raw_IR;
  8408. if( current_voltage_raw_IR < minVolt )minVolt = current_voltage_raw_IR;
  8409. #if 0 // Start: IR Sensor debug info
  8410. { // debug print
  8411. static uint16_t lastVolt = ~0U;
  8412. if( current_voltage_raw_IR != lastVolt ){
  8413. printf_P(PSTR("fs volt=%4.2fV (min=%4.2f max=%4.2f)\n"), Raw2Voltage(current_voltage_raw_IR), Raw2Voltage(minVolt), Raw2Voltage(maxVolt) );
  8414. lastVolt = current_voltage_raw_IR;
  8415. }
  8416. }
  8417. #endif // End: IR Sensor debug info
  8418. //! The trouble is, I can hold the filament in the hole in such a way, that it creates the exact voltage
  8419. //! to be detected as the new fsensor
  8420. //! We can either fake it by extending the detection window to a looooong time
  8421. //! or do some other countermeasures
  8422. //! what we want to detect:
  8423. //! if minvolt gets below ~0.3V, it means there is an old fsensor
  8424. //! if maxvolt gets above 4.6V, it means we either have an old fsensor or broken cables/fsensor
  8425. //! So I'm waiting for a situation, when minVolt gets to range <0, 1.5> and maxVolt gets into range <3.0, 5>
  8426. //! If and only if minVolt is in range <0.3, 1.5> and maxVolt is in range <3.0, 4.6>, I'm considering a situation with the new fsensor
  8427. if( minVolt >= IRsensor_Ldiode_TRESHOLD && minVolt <= IRsensor_Lmax_TRESHOLD
  8428. && maxVolt >= IRsensor_Hmin_TRESHOLD && maxVolt <= IRsensor_Hopen_TRESHOLD
  8429. ){
  8430. manage_inactivity_IR_ANALOG_Check(nFSCheckCount, ClFsensorPCB::_Old, ClFsensorPCB::_Rev04, _i("FS v0.4 or newer") ); ////MSG_FS_V_04_OR_NEWER c=18
  8431. }
  8432. //! If and only if minVolt is in range <0.0, 0.3> and maxVolt is in range <4.6, 5.0V>, I'm considering a situation with the old fsensor
  8433. //! Note, we are not relying on one voltage here - getting just +5V can mean an old fsensor or a broken new sensor - that's why
  8434. //! we need to have both voltages detected correctly to allow switching back to the old fsensor.
  8435. else if( minVolt < IRsensor_Ldiode_TRESHOLD
  8436. && maxVolt > IRsensor_Hopen_TRESHOLD && maxVolt <= IRsensor_VMax_TRESHOLD
  8437. ){
  8438. manage_inactivity_IR_ANALOG_Check(nFSCheckCount, ClFsensorPCB::_Rev04, oFsensorPCB=ClFsensorPCB::_Old, _i("FS v0.3 or older")); ////MSG_FS_V_03_OR_OLDER c=18
  8439. }
  8440. #endif // IR_SENSOR_ANALOG
  8441. if (fsensor_check_autoload())
  8442. {
  8443. #ifdef PAT9125
  8444. fsensor_autoload_check_stop();
  8445. #endif //PAT9125
  8446. //-// if ((int)degHotend0() > extrude_min_temp)
  8447. if(0)
  8448. {
  8449. Sound_MakeCustom(50,1000,false);
  8450. loading_flag = true;
  8451. enquecommand_front_P((PSTR("M701")));
  8452. }
  8453. else
  8454. {
  8455. /*
  8456. lcd_update_enable(false);
  8457. show_preheat_nozzle_warning();
  8458. lcd_update_enable(true);
  8459. */
  8460. eFilamentAction=FilamentAction::AutoLoad;
  8461. bFilamentFirstRun=false;
  8462. if(target_temperature[0] >= extrude_min_temp){
  8463. bFilamentPreheatState=true;
  8464. // mFilamentItem(target_temperature[0],target_temperature_bed);
  8465. menu_submenu(mFilamentItemForce);
  8466. } else {
  8467. menu_submenu(lcd_generic_preheat_menu);
  8468. lcd_timeoutToStatus.start();
  8469. }
  8470. }
  8471. }
  8472. }
  8473. else
  8474. {
  8475. #ifdef PAT9125
  8476. fsensor_autoload_check_stop();
  8477. #endif //PAT9125
  8478. if (fsensor_enabled && !saved_printing)
  8479. fsensor_update();
  8480. }
  8481. }
  8482. }
  8483. #endif //FILAMENT_SENSOR
  8484. #ifdef SAFETYTIMER
  8485. handleSafetyTimer();
  8486. #endif //SAFETYTIMER
  8487. #if defined(KILL_PIN) && KILL_PIN > -1
  8488. static int killCount = 0; // make the inactivity button a bit less responsive
  8489. const int KILL_DELAY = 10000;
  8490. #endif
  8491. if(buflen < (BUFSIZE-1)){
  8492. get_command();
  8493. }
  8494. if(previous_millis_cmd.expired(max_inactive_time))
  8495. if(max_inactive_time)
  8496. kill(_n("Inactivity Shutdown"), 4);
  8497. if(stepper_inactive_time) {
  8498. if(previous_millis_cmd.expired(stepper_inactive_time))
  8499. {
  8500. if(blocks_queued() == false && ignore_stepper_queue == false) {
  8501. disable_x();
  8502. disable_y();
  8503. disable_z();
  8504. disable_e0();
  8505. disable_e1();
  8506. disable_e2();
  8507. }
  8508. }
  8509. }
  8510. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  8511. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  8512. {
  8513. chdkActive = false;
  8514. WRITE(CHDK, LOW);
  8515. }
  8516. #endif
  8517. #if defined(KILL_PIN) && KILL_PIN > -1
  8518. // Check if the kill button was pressed and wait just in case it was an accidental
  8519. // key kill key press
  8520. // -------------------------------------------------------------------------------
  8521. if( 0 == READ(KILL_PIN) )
  8522. {
  8523. killCount++;
  8524. }
  8525. else if (killCount > 0)
  8526. {
  8527. killCount--;
  8528. }
  8529. // Exceeded threshold and we can confirm that it was not accidental
  8530. // KILL the machine
  8531. // ----------------------------------------------------------------
  8532. if ( killCount >= KILL_DELAY)
  8533. {
  8534. kill(NULL, 5);
  8535. }
  8536. #endif
  8537. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8538. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  8539. #endif
  8540. #ifdef EXTRUDER_RUNOUT_PREVENT
  8541. if(previous_millis_cmd.expired(EXTRUDER_RUNOUT_SECONDS*1000))
  8542. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  8543. {
  8544. bool oldstatus=READ(E0_ENABLE_PIN);
  8545. enable_e0();
  8546. float oldepos=current_position[E_AXIS];
  8547. float oldedes=destination[E_AXIS];
  8548. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  8549. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  8550. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  8551. current_position[E_AXIS]=oldepos;
  8552. destination[E_AXIS]=oldedes;
  8553. plan_set_e_position(oldepos);
  8554. previous_millis_cmd.start();
  8555. st_synchronize();
  8556. WRITE(E0_ENABLE_PIN,oldstatus);
  8557. }
  8558. #endif
  8559. check_axes_activity();
  8560. mmu_loop();
  8561. // handle longpress
  8562. if(lcd_longpress_trigger)
  8563. {
  8564. // long press is not possible in modal mode, wait until ready
  8565. if (lcd_longpress_func && lcd_update_enabled)
  8566. {
  8567. lcd_longpress_func();
  8568. lcd_longpress_trigger = 0;
  8569. }
  8570. }
  8571. #if defined(AUTO_REPORT)
  8572. host_autoreport();
  8573. #endif //AUTO_REPORT
  8574. host_keepalive();
  8575. }
  8576. void kill(const char *full_screen_message, unsigned char id)
  8577. {
  8578. printf_P(_N("KILL: %d\n"), id);
  8579. //return;
  8580. cli(); // Stop interrupts
  8581. disable_heater();
  8582. disable_x();
  8583. // SERIAL_ECHOLNPGM("kill - disable Y");
  8584. disable_y();
  8585. poweroff_z();
  8586. disable_e0();
  8587. disable_e1();
  8588. disable_e2();
  8589. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  8590. pinMode(PS_ON_PIN,INPUT);
  8591. #endif
  8592. SERIAL_ERROR_START;
  8593. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  8594. if (full_screen_message != NULL) {
  8595. SERIAL_ERRORLNRPGM(full_screen_message);
  8596. lcd_display_message_fullscreen_P(full_screen_message);
  8597. } else {
  8598. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  8599. }
  8600. // FMC small patch to update the LCD before ending
  8601. sei(); // enable interrupts
  8602. for ( int i=5; i--; lcd_update(0))
  8603. {
  8604. _delay(200);
  8605. }
  8606. cli(); // disable interrupts
  8607. suicide();
  8608. while(1)
  8609. {
  8610. #ifdef WATCHDOG
  8611. wdt_reset();
  8612. #endif //WATCHDOG
  8613. /* Intentionally left empty */
  8614. } // Wait for reset
  8615. }
  8616. void UnconditionalStop()
  8617. {
  8618. CRITICAL_SECTION_START;
  8619. // Disable all heaters and unroll the temperature wait loop stack
  8620. disable_heater();
  8621. cancel_heatup = true;
  8622. // Clear any saved printing state
  8623. cancel_saved_printing();
  8624. // Abort the planner
  8625. planner_abort_hard();
  8626. // Reset the queue
  8627. cmdqueue_reset();
  8628. cmdqueue_serial_disabled = false;
  8629. // Reset the sd status
  8630. card.sdprinting = false;
  8631. card.closefile();
  8632. st_reset_timer();
  8633. CRITICAL_SECTION_END;
  8634. }
  8635. // Stop: Emergency stop used by overtemp functions which allows recovery
  8636. //
  8637. // In addition to stopping the print, this prevents subsequent G[0-3] commands to be
  8638. // processed via USB (using "Stopped") until the print is resumed via M999 or
  8639. // manually started from scratch with the LCD.
  8640. //
  8641. // Note that the current instruction is completely discarded, so resuming from Stop()
  8642. // will introduce either over/under extrusion on the current segment, and will not
  8643. // survive a power panic. Switching Stop() to use the pause machinery instead (with
  8644. // the addition of disabling the headers) could allow true recovery in the future.
  8645. void Stop()
  8646. {
  8647. // Keep disabling heaters
  8648. disable_heater();
  8649. // Call the regular stop function if that's the first time during a new print
  8650. if(Stopped == false) {
  8651. Stopped = true;
  8652. lcd_print_stop();
  8653. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  8654. // Eventually report the stopped status (though this is usually overridden by a
  8655. // higher-priority alert status message)
  8656. SERIAL_ERROR_START;
  8657. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  8658. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  8659. }
  8660. // Return to the status screen to stop any pending menu action which could have been
  8661. // started by the user while stuck in the Stopped state. This also ensures the NEW
  8662. // error is immediately shown.
  8663. if (menu_menu != lcd_status_screen)
  8664. lcd_return_to_status();
  8665. }
  8666. bool IsStopped() { return Stopped; };
  8667. void finishAndDisableSteppers()
  8668. {
  8669. st_synchronize();
  8670. disable_x();
  8671. disable_y();
  8672. disable_z();
  8673. disable_e0();
  8674. disable_e1();
  8675. disable_e2();
  8676. #ifndef LA_NOCOMPAT
  8677. // Steppers are disabled both when a print is stopped and also via M84 (which is additionally
  8678. // checked-for to indicate a complete file), so abuse this function to reset the LA detection
  8679. // state for the next print.
  8680. la10c_reset();
  8681. #endif
  8682. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  8683. print_time_remaining_init();
  8684. }
  8685. #ifdef FAST_PWM_FAN
  8686. void setPwmFrequency(uint8_t pin, int val)
  8687. {
  8688. val &= 0x07;
  8689. switch(digitalPinToTimer(pin))
  8690. {
  8691. #if defined(TCCR0A)
  8692. case TIMER0A:
  8693. case TIMER0B:
  8694. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8695. // TCCR0B |= val;
  8696. break;
  8697. #endif
  8698. #if defined(TCCR1A)
  8699. case TIMER1A:
  8700. case TIMER1B:
  8701. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8702. // TCCR1B |= val;
  8703. break;
  8704. #endif
  8705. #if defined(TCCR2)
  8706. case TIMER2:
  8707. case TIMER2:
  8708. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8709. TCCR2 |= val;
  8710. break;
  8711. #endif
  8712. #if defined(TCCR2A)
  8713. case TIMER2A:
  8714. case TIMER2B:
  8715. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8716. TCCR2B |= val;
  8717. break;
  8718. #endif
  8719. #if defined(TCCR3A)
  8720. case TIMER3A:
  8721. case TIMER3B:
  8722. case TIMER3C:
  8723. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8724. TCCR3B |= val;
  8725. break;
  8726. #endif
  8727. #if defined(TCCR4A)
  8728. case TIMER4A:
  8729. case TIMER4B:
  8730. case TIMER4C:
  8731. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8732. TCCR4B |= val;
  8733. break;
  8734. #endif
  8735. #if defined(TCCR5A)
  8736. case TIMER5A:
  8737. case TIMER5B:
  8738. case TIMER5C:
  8739. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8740. TCCR5B |= val;
  8741. break;
  8742. #endif
  8743. }
  8744. }
  8745. #endif //FAST_PWM_FAN
  8746. //! @brief Get and validate extruder number
  8747. //!
  8748. //! If it is not specified, active_extruder is returned in parameter extruder.
  8749. //! @param [in] code M code number
  8750. //! @param [out] extruder
  8751. //! @return error
  8752. //! @retval true Invalid extruder specified in T code
  8753. //! @retval false Valid extruder specified in T code, or not specifiead
  8754. bool setTargetedHotend(int code, uint8_t &extruder)
  8755. {
  8756. extruder = active_extruder;
  8757. if(code_seen('T')) {
  8758. extruder = code_value_uint8();
  8759. if(extruder >= EXTRUDERS) {
  8760. SERIAL_ECHO_START;
  8761. switch(code){
  8762. case 104:
  8763. SERIAL_ECHORPGM(_n("M104 Invalid extruder "));////MSG_M104_INVALID_EXTRUDER
  8764. break;
  8765. case 105:
  8766. SERIAL_ECHORPGM(_n("M105 Invalid extruder "));////MSG_M105_INVALID_EXTRUDER
  8767. break;
  8768. case 109:
  8769. SERIAL_ECHORPGM(_n("M109 Invalid extruder "));////MSG_M109_INVALID_EXTRUDER
  8770. break;
  8771. case 218:
  8772. SERIAL_ECHORPGM(_n("M218 Invalid extruder "));////MSG_M218_INVALID_EXTRUDER
  8773. break;
  8774. case 221:
  8775. SERIAL_ECHORPGM(_n("M221 Invalid extruder "));////MSG_M221_INVALID_EXTRUDER
  8776. break;
  8777. }
  8778. SERIAL_PROTOCOLLN((int)extruder);
  8779. return true;
  8780. }
  8781. }
  8782. return false;
  8783. }
  8784. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  8785. {
  8786. 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)
  8787. {
  8788. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  8789. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  8790. }
  8791. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  8792. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  8793. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  8794. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  8795. total_filament_used = 0;
  8796. }
  8797. float calculate_extruder_multiplier(float diameter) {
  8798. float out = 1.f;
  8799. if (cs.volumetric_enabled && diameter > 0.f) {
  8800. float area = M_PI * diameter * diameter * 0.25;
  8801. out = 1.f / area;
  8802. }
  8803. if (extrudemultiply != 100)
  8804. out *= float(extrudemultiply) * 0.01f;
  8805. return out;
  8806. }
  8807. void calculate_extruder_multipliers() {
  8808. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  8809. #if EXTRUDERS > 1
  8810. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  8811. #if EXTRUDERS > 2
  8812. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  8813. #endif
  8814. #endif
  8815. }
  8816. void delay_keep_alive(unsigned int ms)
  8817. {
  8818. for (;;) {
  8819. manage_heater();
  8820. // Manage inactivity, but don't disable steppers on timeout.
  8821. manage_inactivity(true);
  8822. lcd_update(0);
  8823. if (ms == 0)
  8824. break;
  8825. else if (ms >= 50) {
  8826. _delay(50);
  8827. ms -= 50;
  8828. } else {
  8829. _delay(ms);
  8830. ms = 0;
  8831. }
  8832. }
  8833. }
  8834. static void wait_for_heater(long codenum, uint8_t extruder) {
  8835. if (!degTargetHotend(extruder))
  8836. return;
  8837. #ifdef TEMP_RESIDENCY_TIME
  8838. long residencyStart;
  8839. residencyStart = -1;
  8840. /* continue to loop until we have reached the target temp
  8841. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  8842. cancel_heatup = false;
  8843. while ((!cancel_heatup) && ((residencyStart == -1) ||
  8844. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  8845. #else
  8846. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  8847. #endif //TEMP_RESIDENCY_TIME
  8848. if ((_millis() - codenum) > 1000UL)
  8849. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  8850. if (!farm_mode) {
  8851. SERIAL_PROTOCOLPGM("T:");
  8852. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  8853. SERIAL_PROTOCOLPGM(" E:");
  8854. SERIAL_PROTOCOL((int)extruder);
  8855. #ifdef TEMP_RESIDENCY_TIME
  8856. SERIAL_PROTOCOLPGM(" W:");
  8857. if (residencyStart > -1)
  8858. {
  8859. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  8860. SERIAL_PROTOCOLLN(codenum);
  8861. }
  8862. else
  8863. {
  8864. SERIAL_PROTOCOLLN('?');
  8865. }
  8866. }
  8867. #else
  8868. SERIAL_PROTOCOLLN();
  8869. #endif
  8870. codenum = _millis();
  8871. }
  8872. manage_heater();
  8873. manage_inactivity(true); //do not disable steppers
  8874. lcd_update(0);
  8875. #ifdef TEMP_RESIDENCY_TIME
  8876. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  8877. or when current temp falls outside the hysteresis after target temp was reached */
  8878. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  8879. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  8880. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  8881. {
  8882. residencyStart = _millis();
  8883. }
  8884. #endif //TEMP_RESIDENCY_TIME
  8885. }
  8886. }
  8887. void check_babystep()
  8888. {
  8889. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8890. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  8891. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  8892. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  8893. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  8894. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8895. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  8896. babystep_z);
  8897. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  8898. lcd_update_enable(true);
  8899. }
  8900. }
  8901. #ifdef HEATBED_ANALYSIS
  8902. void d_setup()
  8903. {
  8904. pinMode(D_DATACLOCK, INPUT_PULLUP);
  8905. pinMode(D_DATA, INPUT_PULLUP);
  8906. pinMode(D_REQUIRE, OUTPUT);
  8907. digitalWrite(D_REQUIRE, HIGH);
  8908. }
  8909. float d_ReadData()
  8910. {
  8911. int digit[13];
  8912. String mergeOutput;
  8913. float output;
  8914. digitalWrite(D_REQUIRE, HIGH);
  8915. for (int i = 0; i<13; i++)
  8916. {
  8917. for (int j = 0; j < 4; j++)
  8918. {
  8919. while (digitalRead(D_DATACLOCK) == LOW) {}
  8920. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8921. bitWrite(digit[i], j, digitalRead(D_DATA));
  8922. }
  8923. }
  8924. digitalWrite(D_REQUIRE, LOW);
  8925. mergeOutput = "";
  8926. output = 0;
  8927. for (int r = 5; r <= 10; r++) //Merge digits
  8928. {
  8929. mergeOutput += digit[r];
  8930. }
  8931. output = mergeOutput.toFloat();
  8932. if (digit[4] == 8) //Handle sign
  8933. {
  8934. output *= -1;
  8935. }
  8936. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8937. {
  8938. output /= 10;
  8939. }
  8940. return output;
  8941. }
  8942. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8943. int t1 = 0;
  8944. int t_delay = 0;
  8945. int digit[13];
  8946. int m;
  8947. char str[3];
  8948. //String mergeOutput;
  8949. char mergeOutput[15];
  8950. float output;
  8951. int mesh_point = 0; //index number of calibration point
  8952. 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
  8953. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8954. float mesh_home_z_search = 4;
  8955. float measure_z_height = 0.2f;
  8956. float row[x_points_num];
  8957. int ix = 0;
  8958. int iy = 0;
  8959. const char* filename_wldsd = "mesh.txt";
  8960. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  8961. char numb_wldsd[8]; // (" -A.BCD" + null)
  8962. #ifdef MICROMETER_LOGGING
  8963. d_setup();
  8964. #endif //MICROMETER_LOGGING
  8965. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8966. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8967. unsigned int custom_message_type_old = custom_message_type;
  8968. unsigned int custom_message_state_old = custom_message_state;
  8969. custom_message_type = CustomMsg::MeshBedLeveling;
  8970. custom_message_state = (x_points_num * y_points_num) + 10;
  8971. lcd_update(1);
  8972. //mbl.reset();
  8973. babystep_undo();
  8974. card.openFile(filename_wldsd, false);
  8975. /*destination[Z_AXIS] = mesh_home_z_search;
  8976. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8977. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8978. for(int8_t i=0; i < NUM_AXIS; i++) {
  8979. current_position[i] = destination[i];
  8980. }
  8981. st_synchronize();
  8982. */
  8983. destination[Z_AXIS] = measure_z_height;
  8984. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8985. for(int8_t i=0; i < NUM_AXIS; i++) {
  8986. current_position[i] = destination[i];
  8987. }
  8988. st_synchronize();
  8989. /*int l_feedmultiply = */setup_for_endstop_move(false);
  8990. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8991. SERIAL_PROTOCOL(x_points_num);
  8992. SERIAL_PROTOCOLPGM(",");
  8993. SERIAL_PROTOCOL(y_points_num);
  8994. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8995. SERIAL_PROTOCOL(mesh_home_z_search);
  8996. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8997. SERIAL_PROTOCOL(x_dimension);
  8998. SERIAL_PROTOCOLPGM(",");
  8999. SERIAL_PROTOCOL(y_dimension);
  9000. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  9001. while (mesh_point != x_points_num * y_points_num) {
  9002. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  9003. iy = mesh_point / x_points_num;
  9004. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  9005. float z0 = 0.f;
  9006. /*destination[Z_AXIS] = mesh_home_z_search;
  9007. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  9008. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  9009. for(int8_t i=0; i < NUM_AXIS; i++) {
  9010. current_position[i] = destination[i];
  9011. }
  9012. st_synchronize();*/
  9013. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  9014. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  9015. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  9016. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  9017. mesh_plan_buffer_line_destinationXYZE(XY_AXIS_FEEDRATE/6);
  9018. set_current_to_destination();
  9019. st_synchronize();
  9020. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  9021. delay_keep_alive(1000);
  9022. #ifdef MICROMETER_LOGGING
  9023. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  9024. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  9025. //strcat(data_wldsd, numb_wldsd);
  9026. //MYSERIAL.println(data_wldsd);
  9027. //delay(1000);
  9028. //delay(3000);
  9029. //t1 = millis();
  9030. //while (digitalRead(D_DATACLOCK) == LOW) {}
  9031. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  9032. memset(digit, 0, sizeof(digit));
  9033. //cli();
  9034. digitalWrite(D_REQUIRE, LOW);
  9035. for (int i = 0; i<13; i++)
  9036. {
  9037. //t1 = millis();
  9038. for (int j = 0; j < 4; j++)
  9039. {
  9040. while (digitalRead(D_DATACLOCK) == LOW) {}
  9041. while (digitalRead(D_DATACLOCK) == HIGH) {}
  9042. //printf_P(PSTR("Done %d\n"), j);
  9043. bitWrite(digit[i], j, digitalRead(D_DATA));
  9044. }
  9045. //t_delay = (millis() - t1);
  9046. //SERIAL_PROTOCOLPGM(" ");
  9047. //SERIAL_PROTOCOL_F(t_delay, 5);
  9048. //SERIAL_PROTOCOLPGM(" ");
  9049. }
  9050. //sei();
  9051. digitalWrite(D_REQUIRE, HIGH);
  9052. mergeOutput[0] = '\0';
  9053. output = 0;
  9054. for (int r = 5; r <= 10; r++) //Merge digits
  9055. {
  9056. sprintf(str, "%d", digit[r]);
  9057. strcat(mergeOutput, str);
  9058. }
  9059. output = atof(mergeOutput);
  9060. if (digit[4] == 8) //Handle sign
  9061. {
  9062. output *= -1;
  9063. }
  9064. for (int i = digit[11]; i > 0; i--) //Handle floating point
  9065. {
  9066. output *= 0.1;
  9067. }
  9068. //output = d_ReadData();
  9069. //row[ix] = current_position[Z_AXIS];
  9070. //row[ix] = d_ReadData();
  9071. row[ix] = output;
  9072. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  9073. memset(data_wldsd, 0, sizeof(data_wldsd));
  9074. for (int i = 0; i < x_points_num; i++) {
  9075. SERIAL_PROTOCOLPGM(" ");
  9076. SERIAL_PROTOCOL_F(row[i], 5);
  9077. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  9078. dtostrf(row[i], 7, 3, numb_wldsd);
  9079. strcat(data_wldsd, numb_wldsd);
  9080. }
  9081. card.write_command(data_wldsd);
  9082. SERIAL_PROTOCOLPGM("\n");
  9083. }
  9084. custom_message_state--;
  9085. mesh_point++;
  9086. lcd_update(1);
  9087. }
  9088. #endif //MICROMETER_LOGGING
  9089. card.closefile();
  9090. //clean_up_after_endstop_move(l_feedmultiply);
  9091. }
  9092. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  9093. int t1 = 0;
  9094. int t_delay = 0;
  9095. int digit[13];
  9096. int m;
  9097. char str[3];
  9098. //String mergeOutput;
  9099. char mergeOutput[15];
  9100. float output;
  9101. int mesh_point = 0; //index number of calibration point
  9102. 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
  9103. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  9104. float mesh_home_z_search = 4;
  9105. float row[x_points_num];
  9106. int ix = 0;
  9107. int iy = 0;
  9108. const char* filename_wldsd = "wldsd.txt";
  9109. char data_wldsd[70];
  9110. char numb_wldsd[10];
  9111. d_setup();
  9112. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  9113. // We don't know where we are! HOME!
  9114. // Push the commands to the front of the message queue in the reverse order!
  9115. // There shall be always enough space reserved for these commands.
  9116. repeatcommand_front(); // repeat G80 with all its parameters
  9117. enquecommand_front_P(G28W0);
  9118. enquecommand_front_P((PSTR("G1 Z5")));
  9119. return;
  9120. }
  9121. unsigned int custom_message_type_old = custom_message_type;
  9122. unsigned int custom_message_state_old = custom_message_state;
  9123. custom_message_type = CustomMsg::MeshBedLeveling;
  9124. custom_message_state = (x_points_num * y_points_num) + 10;
  9125. lcd_update(1);
  9126. mbl.reset();
  9127. babystep_undo();
  9128. card.openFile(filename_wldsd, false);
  9129. current_position[Z_AXIS] = mesh_home_z_search;
  9130. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  9131. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  9132. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  9133. int l_feedmultiply = setup_for_endstop_move(false);
  9134. SERIAL_PROTOCOLPGM("Num X,Y: ");
  9135. SERIAL_PROTOCOL(x_points_num);
  9136. SERIAL_PROTOCOLPGM(",");
  9137. SERIAL_PROTOCOL(y_points_num);
  9138. SERIAL_PROTOCOLPGM("\nZ search height: ");
  9139. SERIAL_PROTOCOL(mesh_home_z_search);
  9140. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  9141. SERIAL_PROTOCOL(x_dimension);
  9142. SERIAL_PROTOCOLPGM(",");
  9143. SERIAL_PROTOCOL(y_dimension);
  9144. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  9145. while (mesh_point != x_points_num * y_points_num) {
  9146. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  9147. iy = mesh_point / x_points_num;
  9148. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  9149. float z0 = 0.f;
  9150. current_position[Z_AXIS] = mesh_home_z_search;
  9151. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  9152. st_synchronize();
  9153. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  9154. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  9155. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  9156. st_synchronize();
  9157. 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
  9158. break;
  9159. card.closefile();
  9160. }
  9161. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  9162. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  9163. //strcat(data_wldsd, numb_wldsd);
  9164. //MYSERIAL.println(data_wldsd);
  9165. //_delay(1000);
  9166. //_delay(3000);
  9167. //t1 = _millis();
  9168. //while (digitalRead(D_DATACLOCK) == LOW) {}
  9169. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  9170. memset(digit, 0, sizeof(digit));
  9171. //cli();
  9172. digitalWrite(D_REQUIRE, LOW);
  9173. for (int i = 0; i<13; i++)
  9174. {
  9175. //t1 = _millis();
  9176. for (int j = 0; j < 4; j++)
  9177. {
  9178. while (digitalRead(D_DATACLOCK) == LOW) {}
  9179. while (digitalRead(D_DATACLOCK) == HIGH) {}
  9180. bitWrite(digit[i], j, digitalRead(D_DATA));
  9181. }
  9182. //t_delay = (_millis() - t1);
  9183. //SERIAL_PROTOCOLPGM(" ");
  9184. //SERIAL_PROTOCOL_F(t_delay, 5);
  9185. //SERIAL_PROTOCOLPGM(" ");
  9186. }
  9187. //sei();
  9188. digitalWrite(D_REQUIRE, HIGH);
  9189. mergeOutput[0] = '\0';
  9190. output = 0;
  9191. for (int r = 5; r <= 10; r++) //Merge digits
  9192. {
  9193. sprintf(str, "%d", digit[r]);
  9194. strcat(mergeOutput, str);
  9195. }
  9196. output = atof(mergeOutput);
  9197. if (digit[4] == 8) //Handle sign
  9198. {
  9199. output *= -1;
  9200. }
  9201. for (int i = digit[11]; i > 0; i--) //Handle floating point
  9202. {
  9203. output *= 0.1;
  9204. }
  9205. //output = d_ReadData();
  9206. //row[ix] = current_position[Z_AXIS];
  9207. memset(data_wldsd, 0, sizeof(data_wldsd));
  9208. for (int i = 0; i <3; i++) {
  9209. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  9210. dtostrf(current_position[i], 8, 5, numb_wldsd);
  9211. strcat(data_wldsd, numb_wldsd);
  9212. strcat(data_wldsd, ";");
  9213. }
  9214. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  9215. dtostrf(output, 8, 5, numb_wldsd);
  9216. strcat(data_wldsd, numb_wldsd);
  9217. //strcat(data_wldsd, ";");
  9218. card.write_command(data_wldsd);
  9219. //row[ix] = d_ReadData();
  9220. row[ix] = output; // current_position[Z_AXIS];
  9221. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  9222. for (int i = 0; i < x_points_num; i++) {
  9223. SERIAL_PROTOCOLPGM(" ");
  9224. SERIAL_PROTOCOL_F(row[i], 5);
  9225. }
  9226. SERIAL_PROTOCOLPGM("\n");
  9227. }
  9228. custom_message_state--;
  9229. mesh_point++;
  9230. lcd_update(1);
  9231. }
  9232. card.closefile();
  9233. clean_up_after_endstop_move(l_feedmultiply);
  9234. }
  9235. #endif //HEATBED_ANALYSIS
  9236. #ifndef PINDA_THERMISTOR
  9237. static void temp_compensation_start() {
  9238. custom_message_type = CustomMsg::TempCompPreheat;
  9239. custom_message_state = PINDA_HEAT_T + 1;
  9240. lcd_update(2);
  9241. if ((int)degHotend(active_extruder) > extrude_min_temp) {
  9242. current_position[E_AXIS] -= default_retraction;
  9243. }
  9244. plan_buffer_line_curposXYZE(400, active_extruder);
  9245. current_position[X_AXIS] = PINDA_PREHEAT_X;
  9246. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  9247. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  9248. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  9249. st_synchronize();
  9250. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  9251. for (int i = 0; i < PINDA_HEAT_T; i++) {
  9252. delay_keep_alive(1000);
  9253. custom_message_state = PINDA_HEAT_T - i;
  9254. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  9255. else lcd_update(1);
  9256. }
  9257. custom_message_type = CustomMsg::Status;
  9258. custom_message_state = 0;
  9259. }
  9260. static void temp_compensation_apply() {
  9261. int i_add;
  9262. int z_shift = 0;
  9263. float z_shift_mm;
  9264. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  9265. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  9266. i_add = (target_temperature_bed - 60) / 10;
  9267. z_shift = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i_add);
  9268. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  9269. }else {
  9270. //interpolation
  9271. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  9272. }
  9273. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  9274. 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);
  9275. st_synchronize();
  9276. plan_set_z_position(current_position[Z_AXIS]);
  9277. }
  9278. else {
  9279. //we have no temp compensation data
  9280. }
  9281. }
  9282. #endif //ndef PINDA_THERMISTOR
  9283. float temp_comp_interpolation(float inp_temperature) {
  9284. //cubic spline interpolation
  9285. int n, i, j;
  9286. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  9287. int shift[10];
  9288. int temp_C[10];
  9289. n = 6; //number of measured points
  9290. shift[0] = 0;
  9291. for (i = 0; i < n; i++) {
  9292. if (i > 0) {
  9293. //read shift in steps from EEPROM
  9294. shift[i] = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  9295. }
  9296. temp_C[i] = 50 + i * 10; //temperature in C
  9297. #ifdef PINDA_THERMISTOR
  9298. constexpr int start_compensating_temp = 35;
  9299. temp_C[i] = start_compensating_temp + i * 5; //temperature in degrees C
  9300. #ifdef SUPERPINDA_SUPPORT
  9301. static_assert(start_compensating_temp >= PINDA_MINTEMP, "Temperature compensation start point is lower than PINDA_MINTEMP.");
  9302. #endif //SUPERPINDA_SUPPORT
  9303. #else
  9304. temp_C[i] = 50 + i * 10; //temperature in C
  9305. #endif
  9306. x[i] = (float)temp_C[i];
  9307. f[i] = (float)shift[i];
  9308. }
  9309. if (inp_temperature < x[0]) return 0;
  9310. for (i = n - 1; i>0; i--) {
  9311. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  9312. h[i - 1] = x[i] - x[i - 1];
  9313. }
  9314. //*********** formation of h, s , f matrix **************
  9315. for (i = 1; i<n - 1; i++) {
  9316. m[i][i] = 2 * (h[i - 1] + h[i]);
  9317. if (i != 1) {
  9318. m[i][i - 1] = h[i - 1];
  9319. m[i - 1][i] = h[i - 1];
  9320. }
  9321. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  9322. }
  9323. //*********** forward elimination **************
  9324. for (i = 1; i<n - 2; i++) {
  9325. temp = (m[i + 1][i] / m[i][i]);
  9326. for (j = 1; j <= n - 1; j++)
  9327. m[i + 1][j] -= temp*m[i][j];
  9328. }
  9329. //*********** backward substitution *********
  9330. for (i = n - 2; i>0; i--) {
  9331. sum = 0;
  9332. for (j = i; j <= n - 2; j++)
  9333. sum += m[i][j] * s[j];
  9334. s[i] = (m[i][n - 1] - sum) / m[i][i];
  9335. }
  9336. for (i = 0; i<n - 1; i++)
  9337. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  9338. a = (s[i + 1] - s[i]) / (6 * h[i]);
  9339. b = s[i] / 2;
  9340. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  9341. d = f[i];
  9342. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  9343. }
  9344. return sum;
  9345. }
  9346. #ifdef PINDA_THERMISTOR
  9347. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  9348. {
  9349. if (!eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE)) return 0;
  9350. if (!calibration_status_pinda()) return 0;
  9351. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  9352. }
  9353. #endif //PINDA_THERMISTOR
  9354. void long_pause() //long pause print
  9355. {
  9356. st_synchronize();
  9357. start_pause_print = _millis();
  9358. // Stop heaters
  9359. setAllTargetHotends(0);
  9360. //lift z
  9361. current_position[Z_AXIS] += Z_PAUSE_LIFT;
  9362. clamp_to_software_endstops(current_position);
  9363. plan_buffer_line_curposXYZE(15);
  9364. //Move XY to side
  9365. current_position[X_AXIS] = X_PAUSE_POS;
  9366. current_position[Y_AXIS] = Y_PAUSE_POS;
  9367. plan_buffer_line_curposXYZE(50);
  9368. // Turn off the print fan
  9369. fanSpeed = 0;
  9370. }
  9371. void serialecho_temperatures() {
  9372. float tt = degHotend(active_extruder);
  9373. SERIAL_PROTOCOLPGM("T:");
  9374. SERIAL_PROTOCOL(tt);
  9375. SERIAL_PROTOCOLPGM(" E:");
  9376. SERIAL_PROTOCOL((int)active_extruder);
  9377. SERIAL_PROTOCOLPGM(" B:");
  9378. SERIAL_PROTOCOL_F(degBed(), 1);
  9379. SERIAL_PROTOCOLLN();
  9380. }
  9381. #ifdef UVLO_SUPPORT
  9382. void uvlo_drain_reset()
  9383. {
  9384. // burn all that residual power
  9385. wdt_enable(WDTO_1S);
  9386. WRITE(BEEPER,HIGH);
  9387. lcd_clear();
  9388. lcd_puts_at_P(0, 1, MSG_POWERPANIC_DETECTED);
  9389. while(1);
  9390. }
  9391. void uvlo_()
  9392. {
  9393. unsigned long time_start = _millis();
  9394. bool sd_print = card.sdprinting;
  9395. // Conserve power as soon as possible.
  9396. #ifdef LCD_BL_PIN
  9397. backlightMode = BACKLIGHT_MODE_DIM;
  9398. backlightLevel_LOW = 0;
  9399. backlight_update();
  9400. #endif //LCD_BL_PIN
  9401. disable_x();
  9402. disable_y();
  9403. #ifdef TMC2130
  9404. tmc2130_set_current_h(Z_AXIS, 20);
  9405. tmc2130_set_current_r(Z_AXIS, 20);
  9406. tmc2130_set_current_h(E_AXIS, 20);
  9407. tmc2130_set_current_r(E_AXIS, 20);
  9408. #endif //TMC2130
  9409. // Stop all heaters
  9410. uint8_t saved_target_temperature_bed = target_temperature_bed;
  9411. uint16_t saved_target_temperature_ext = target_temperature[active_extruder];
  9412. setAllTargetHotends(0);
  9413. setTargetBed(0);
  9414. // Calculate the file position, from which to resume this print.
  9415. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  9416. {
  9417. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9418. sd_position -= sdlen_planner;
  9419. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9420. sd_position -= sdlen_cmdqueue;
  9421. if (sd_position < 0) sd_position = 0;
  9422. }
  9423. // save the global state at planning time
  9424. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9425. uint16_t feedrate_bckp;
  9426. if (current_block && !pos_invalid)
  9427. {
  9428. memcpy(saved_target, current_block->gcode_target, sizeof(saved_target));
  9429. feedrate_bckp = current_block->gcode_feedrate;
  9430. }
  9431. else
  9432. {
  9433. saved_target[0] = SAVED_TARGET_UNSET;
  9434. feedrate_bckp = feedrate;
  9435. }
  9436. // From this point on and up to the print recovery, Z should not move during X/Y travels and
  9437. // should be controlled precisely. Reset the MBL status before planner_abort_hard in order to
  9438. // get the physical Z for further manipulation.
  9439. bool mbl_was_active = mbl.active;
  9440. mbl.active = false;
  9441. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  9442. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  9443. // are in action.
  9444. planner_abort_hard();
  9445. // Store the print logical Z position, which we need to recover (a slight error here would be
  9446. // recovered on the next Gcode instruction, while a physical location error would not)
  9447. float logical_z = current_position[Z_AXIS];
  9448. if(mbl_was_active) logical_z -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  9449. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z, logical_z);
  9450. // Store the print E position before we lose track
  9451. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), current_position[E_AXIS]);
  9452. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, (axis_relative_modes & E_AXIS_MASK)?0:1);
  9453. // Clean the input command queue, inhibit serial processing using saved_printing
  9454. cmdqueue_reset();
  9455. card.sdprinting = false;
  9456. saved_printing = true;
  9457. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9458. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9459. sei();
  9460. // Retract
  9461. current_position[E_AXIS] -= default_retraction;
  9462. plan_buffer_line_curposXYZE(95);
  9463. st_synchronize();
  9464. disable_e0();
  9465. // Read out the current Z motor microstep counter to move the axis up towards
  9466. // a full step before powering off. NOTE: we need to ensure to schedule more
  9467. // than "dropsegments" steps in order to move (this is always the case here
  9468. // due to UVLO_Z_AXIS_SHIFT being used)
  9469. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9470. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9471. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9472. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9473. + UVLO_Z_AXIS_SHIFT;
  9474. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9475. st_synchronize();
  9476. poweroff_z();
  9477. // Write the file position.
  9478. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  9479. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9480. for (uint8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9481. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9482. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9483. // Scale the z value to 1u resolution.
  9484. int16_t v = mbl_was_active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  9485. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  9486. }
  9487. // Write the _final_ Z position and motor microstep counter (unused).
  9488. eeprom_update_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z, current_position[Z_AXIS]);
  9489. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9490. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9491. // Store the current position.
  9492. if (pos_invalid)
  9493. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), X_COORD_INVALID);
  9494. else
  9495. {
  9496. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  9497. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  9498. }
  9499. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  9500. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDRATE, feedrate_bckp);
  9501. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY, feedmultiply);
  9502. eeprom_update_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND, saved_target_temperature_ext);
  9503. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, saved_target_temperature_bed);
  9504. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  9505. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  9506. #if EXTRUDERS > 1
  9507. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  9508. #if EXTRUDERS > 2
  9509. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  9510. #endif
  9511. #endif
  9512. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  9513. eeprom_update_float((float*)(EEPROM_UVLO_ACCELL), cs.acceleration);
  9514. eeprom_update_float((float*)(EEPROM_UVLO_RETRACT_ACCELL), cs.retract_acceleration);
  9515. eeprom_update_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL), cs.travel_acceleration);
  9516. // Store the saved target
  9517. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+0*4), saved_target[X_AXIS]);
  9518. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+1*4), saved_target[Y_AXIS]);
  9519. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+2*4), saved_target[Z_AXIS]);
  9520. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+3*4), saved_target[E_AXIS]);
  9521. #ifdef LIN_ADVANCE
  9522. eeprom_update_float((float*)(EEPROM_UVLO_LA_K), extruder_advance_K);
  9523. #endif
  9524. // Finaly store the "power outage" flag.
  9525. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  9526. // Increment power failure counter
  9527. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9528. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9529. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  9530. WRITE(BEEPER,HIGH);
  9531. // All is set: with all the juice left, try to move extruder away to detach the nozzle completely from the print
  9532. poweron_z();
  9533. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  9534. plan_buffer_line_curposXYZE(500);
  9535. st_synchronize();
  9536. wdt_enable(WDTO_1S);
  9537. while(1);
  9538. }
  9539. void uvlo_tiny()
  9540. {
  9541. unsigned long time_start = _millis();
  9542. // Conserve power as soon as possible.
  9543. disable_x();
  9544. disable_y();
  9545. disable_e0();
  9546. #ifdef TMC2130
  9547. tmc2130_set_current_h(Z_AXIS, 20);
  9548. tmc2130_set_current_r(Z_AXIS, 20);
  9549. #endif //TMC2130
  9550. // Stop all heaters
  9551. setAllTargetHotends(0);
  9552. setTargetBed(0);
  9553. // When power is interrupted on the _first_ recovery an attempt can be made to raise the
  9554. // extruder, causing the Z position to change. Similarly, when recovering, the Z position is
  9555. // lowered. In such cases we cannot just save Z, we need to re-align the steppers to a fullstep.
  9556. // Disable MBL (if not already) to work with physical coordinates.
  9557. mbl.active = false;
  9558. planner_abort_hard();
  9559. // Allow for small roundoffs to be ignored
  9560. if(fabs(current_position[Z_AXIS] - eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z))) >= 1.f/cs.axis_steps_per_unit[Z_AXIS])
  9561. {
  9562. // Clean the input command queue, inhibit serial processing using saved_printing
  9563. cmdqueue_reset();
  9564. card.sdprinting = false;
  9565. saved_printing = true;
  9566. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9567. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9568. sei();
  9569. // The axis was moved: adjust Z as done on a regular UVLO.
  9570. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9571. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9572. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9573. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9574. + UVLO_TINY_Z_AXIS_SHIFT;
  9575. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9576. st_synchronize();
  9577. poweroff_z();
  9578. // Update Z position
  9579. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  9580. // Update the _final_ Z motor microstep counter (unused).
  9581. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9582. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9583. }
  9584. // Update the the "power outage" flag.
  9585. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  9586. // Increment power failure counter
  9587. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9588. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9589. printf_P(_N("UVLO_TINY - end %d\n"), _millis() - time_start);
  9590. uvlo_drain_reset();
  9591. }
  9592. #endif //UVLO_SUPPORT
  9593. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  9594. void setup_fan_interrupt() {
  9595. //INT7
  9596. DDRE &= ~(1 << 7); //input pin
  9597. PORTE &= ~(1 << 7); //no internal pull-up
  9598. //start with sensing rising edge
  9599. EICRB &= ~(1 << 6);
  9600. EICRB |= (1 << 7);
  9601. //enable INT7 interrupt
  9602. EIMSK |= (1 << 7);
  9603. }
  9604. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  9605. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  9606. ISR(INT7_vect) {
  9607. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  9608. #ifdef FAN_SOFT_PWM
  9609. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  9610. #else //FAN_SOFT_PWM
  9611. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  9612. #endif //FAN_SOFT_PWM
  9613. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  9614. t_fan_rising_edge = millis_nc();
  9615. }
  9616. else { //interrupt was triggered by falling edge
  9617. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  9618. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  9619. }
  9620. }
  9621. EICRB ^= (1 << 6); //change edge
  9622. }
  9623. #endif
  9624. #ifdef UVLO_SUPPORT
  9625. void setup_uvlo_interrupt() {
  9626. DDRE &= ~(1 << 4); //input pin
  9627. PORTE &= ~(1 << 4); //no internal pull-up
  9628. // sensing falling edge
  9629. EICRB |= (1 << 0);
  9630. EICRB &= ~(1 << 1);
  9631. // enable INT4 interrupt
  9632. EIMSK |= (1 << 4);
  9633. // check if power was lost before we armed the interrupt
  9634. if(!(PINE & (1 << 4)) && eeprom_read_byte((uint8_t*)EEPROM_UVLO))
  9635. {
  9636. SERIAL_ECHOLNPGM("INT4");
  9637. uvlo_drain_reset();
  9638. }
  9639. }
  9640. ISR(INT4_vect) {
  9641. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  9642. SERIAL_ECHOLNPGM("INT4");
  9643. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  9644. if(PRINTER_ACTIVE && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  9645. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  9646. }
  9647. void recover_print(uint8_t automatic) {
  9648. char cmd[30];
  9649. lcd_update_enable(true);
  9650. lcd_update(2);
  9651. lcd_setstatuspgm(_i("Recovering print"));////MSG_RECOVERING_PRINT c=20
  9652. // Recover position, temperatures and extrude_multipliers
  9653. bool mbl_was_active = recover_machine_state_after_power_panic();
  9654. // Lift the print head 25mm, first to avoid collisions with oozed material with the print,
  9655. // and second also so one may remove the excess priming material.
  9656. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 1)
  9657. {
  9658. sprintf_P(cmd, PSTR("G1 Z%.3f F800"), current_position[Z_AXIS] + 25);
  9659. enquecommand(cmd);
  9660. }
  9661. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine
  9662. // transformation status. G28 will not touch Z when MBL is off.
  9663. enquecommand_P(PSTR("G28 X Y"));
  9664. // Set the target bed and nozzle temperatures and wait.
  9665. sprintf_P(cmd, PSTR("M104 S%d"), target_temperature[active_extruder]);
  9666. enquecommand(cmd);
  9667. sprintf_P(cmd, PSTR("M190 S%d"), target_temperature_bed);
  9668. enquecommand(cmd);
  9669. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  9670. enquecommand(cmd);
  9671. enquecommand_P(PSTR("M83")); //E axis relative mode
  9672. // If not automatically recoreverd (long power loss)
  9673. if(automatic == 0){
  9674. //Extrude some filament to stabilize the pressure
  9675. enquecommand_P(PSTR("G1 E5 F120"));
  9676. // Retract to be consistent with a short pause
  9677. sprintf_P(cmd, PSTR("G1 E%-0.3f F2700"), default_retraction);
  9678. enquecommand(cmd);
  9679. }
  9680. 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]);
  9681. // Restart the print.
  9682. restore_print_from_eeprom(mbl_was_active);
  9683. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  9684. }
  9685. bool recover_machine_state_after_power_panic()
  9686. {
  9687. // 1) Preset some dummy values for the XY axes
  9688. current_position[X_AXIS] = 0;
  9689. current_position[Y_AXIS] = 0;
  9690. // 2) Restore the mesh bed leveling offsets, but not the MBL status.
  9691. // This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9692. bool mbl_was_active = false;
  9693. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9694. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9695. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9696. // Scale the z value to 10u resolution.
  9697. int16_t v;
  9698. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  9699. if (v != 0)
  9700. mbl_was_active = true;
  9701. mbl.z_values[iy][ix] = float(v) * 0.001f;
  9702. }
  9703. // Recover the physical coordinate of the Z axis at the time of the power panic.
  9704. // The current position after power panic is moved to the next closest 0th full step.
  9705. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z));
  9706. // Recover last E axis position
  9707. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9708. // 3) Initialize the logical to physical coordinate system transformation.
  9709. world2machine_initialize();
  9710. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9711. // print_mesh_bed_leveling_table();
  9712. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  9713. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  9714. babystep_load();
  9715. // 5) Set the physical positions from the logical positions using the world2machine transformation
  9716. // This is only done to inizialize Z/E axes with physical locations, since X/Y are unknown.
  9717. clamp_to_software_endstops(current_position);
  9718. set_destination_to_current();
  9719. plan_set_position_curposXYZE();
  9720. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9721. print_world_coordinates();
  9722. // 6) Power up the Z motors, mark their positions as known.
  9723. axis_known_position[Z_AXIS] = true;
  9724. enable_z();
  9725. // 7) Recover the target temperatures.
  9726. target_temperature[active_extruder] = eeprom_read_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND);
  9727. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  9728. // 8) Recover extruder multipilers
  9729. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  9730. #if EXTRUDERS > 1
  9731. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  9732. #if EXTRUDERS > 2
  9733. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  9734. #endif
  9735. #endif
  9736. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  9737. // 9) Recover the saved target
  9738. saved_target[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+0*4));
  9739. saved_target[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+1*4));
  9740. saved_target[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+2*4));
  9741. saved_target[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+3*4));
  9742. #ifdef LIN_ADVANCE
  9743. extruder_advance_K = eeprom_read_float((float*)EEPROM_UVLO_LA_K);
  9744. #endif
  9745. return mbl_was_active;
  9746. }
  9747. void restore_print_from_eeprom(bool mbl_was_active) {
  9748. int feedrate_rec;
  9749. int feedmultiply_rec;
  9750. uint8_t fan_speed_rec;
  9751. char cmd[48];
  9752. char filename[13];
  9753. uint8_t depth = 0;
  9754. char dir_name[9];
  9755. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  9756. feedrate_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDRATE);
  9757. feedmultiply_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY);
  9758. SERIAL_ECHOPGM("Feedrate:");
  9759. MYSERIAL.print(feedrate_rec);
  9760. SERIAL_ECHOPGM(", feedmultiply:");
  9761. MYSERIAL.println(feedmultiply_rec);
  9762. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  9763. MYSERIAL.println(int(depth));
  9764. for (uint8_t i = 0; i < depth; i++) {
  9765. for (uint8_t j = 0; j < 8; j++) {
  9766. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  9767. }
  9768. dir_name[8] = '\0';
  9769. MYSERIAL.println(dir_name);
  9770. // strcpy(card.dir_names[i], dir_name);
  9771. card.chdir(dir_name, false);
  9772. }
  9773. for (uint8_t i = 0; i < 8; i++) {
  9774. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  9775. }
  9776. filename[8] = '\0';
  9777. MYSERIAL.print(filename);
  9778. strcat_P(filename, PSTR(".gco"));
  9779. sprintf_P(cmd, PSTR("M23 %s"), filename);
  9780. enquecommand(cmd);
  9781. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  9782. SERIAL_ECHOPGM("Position read from eeprom:");
  9783. MYSERIAL.println(position);
  9784. // Move to the XY print position in logical coordinates, where the print has been killed, but
  9785. // without shifting Z along the way. This requires performing the move without mbl.
  9786. float pos_x = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  9787. float pos_y = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  9788. if (pos_x != X_COORD_INVALID)
  9789. {
  9790. sprintf_P(cmd, PSTR("G1 X%f Y%f F3000"), pos_x, pos_y);
  9791. enquecommand(cmd);
  9792. }
  9793. // Enable MBL and switch to logical positioning
  9794. if (mbl_was_active)
  9795. enquecommand_P(PSTR("PRUSA MBL V1"));
  9796. // Move the Z axis down to the print, in logical coordinates.
  9797. sprintf_P(cmd, PSTR("G1 Z%f"), eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)));
  9798. enquecommand(cmd);
  9799. // Restore acceleration settings
  9800. float acceleration = eeprom_read_float((float*)(EEPROM_UVLO_ACCELL));
  9801. float retract_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_RETRACT_ACCELL));
  9802. float travel_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL));
  9803. sprintf_P(cmd, PSTR("M204 P%f R%f T%f"), acceleration, retract_acceleration, travel_acceleration);
  9804. enquecommand(cmd);
  9805. // Unretract.
  9806. sprintf_P(cmd, PSTR("G1 E%0.3f F2700"), default_retraction);
  9807. enquecommand(cmd);
  9808. // Recover final E axis position and mode
  9809. float pos_e = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9810. sprintf_P(cmd, PSTR("G92 E%6.3f"), pos_e);
  9811. enquecommand(cmd);
  9812. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  9813. enquecommand_P(PSTR("M82")); //E axis abslute mode
  9814. // Set the feedrates saved at the power panic.
  9815. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  9816. enquecommand(cmd);
  9817. sprintf_P(cmd, PSTR("M220 S%d"), feedmultiply_rec);
  9818. enquecommand(cmd);
  9819. // Set the fan speed saved at the power panic.
  9820. strcpy_P(cmd, PSTR("M106 S"));
  9821. strcat(cmd, itostr3(int(fan_speed_rec)));
  9822. enquecommand(cmd);
  9823. // Set a position in the file.
  9824. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  9825. enquecommand(cmd);
  9826. enquecommand_P(PSTR("G4 S0"));
  9827. enquecommand_P(PSTR("PRUSA uvlo"));
  9828. }
  9829. #endif //UVLO_SUPPORT
  9830. //! @brief Immediately stop print moves
  9831. //!
  9832. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  9833. //! If printing from sd card, position in file is saved.
  9834. //! If printing from USB, line number is saved.
  9835. //!
  9836. //! @param z_move
  9837. //! @param e_move
  9838. void stop_and_save_print_to_ram(float z_move, float e_move)
  9839. {
  9840. if (saved_printing) return;
  9841. #if 0
  9842. unsigned char nplanner_blocks;
  9843. #endif
  9844. unsigned char nlines;
  9845. uint16_t sdlen_planner;
  9846. uint16_t sdlen_cmdqueue;
  9847. cli();
  9848. if (card.sdprinting) {
  9849. #if 0
  9850. nplanner_blocks = number_of_blocks();
  9851. #endif
  9852. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  9853. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9854. saved_sdpos -= sdlen_planner;
  9855. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9856. saved_sdpos -= sdlen_cmdqueue;
  9857. saved_printing_type = PRINTING_TYPE_SD;
  9858. }
  9859. else if (usb_timer.running()) { //reuse saved_sdpos for storing line number
  9860. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  9861. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  9862. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  9863. saved_sdpos -= nlines;
  9864. saved_sdpos -= buflen; //number of blocks in cmd buffer
  9865. saved_printing_type = PRINTING_TYPE_USB;
  9866. }
  9867. else {
  9868. saved_printing_type = PRINTING_TYPE_NONE;
  9869. //not sd printing nor usb printing
  9870. }
  9871. #if 0
  9872. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  9873. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  9874. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  9875. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  9876. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  9877. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  9878. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  9879. {
  9880. card.setIndex(saved_sdpos);
  9881. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  9882. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  9883. MYSERIAL.print(char(card.get()));
  9884. SERIAL_ECHOLNPGM("Content of command buffer: ");
  9885. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  9886. MYSERIAL.print(char(card.get()));
  9887. SERIAL_ECHOLNPGM("End of command buffer");
  9888. }
  9889. {
  9890. // Print the content of the planner buffer, line by line:
  9891. card.setIndex(saved_sdpos);
  9892. int8_t iline = 0;
  9893. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  9894. SERIAL_ECHOPGM("Planner line (from file): ");
  9895. MYSERIAL.print(int(iline), DEC);
  9896. SERIAL_ECHOPGM(", length: ");
  9897. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  9898. SERIAL_ECHOPGM(", steps: (");
  9899. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  9900. SERIAL_ECHOPGM(",");
  9901. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  9902. SERIAL_ECHOPGM(",");
  9903. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  9904. SERIAL_ECHOPGM(",");
  9905. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  9906. SERIAL_ECHOPGM("), events: ");
  9907. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  9908. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  9909. MYSERIAL.print(char(card.get()));
  9910. }
  9911. }
  9912. {
  9913. // Print the content of the command buffer, line by line:
  9914. int8_t iline = 0;
  9915. union {
  9916. struct {
  9917. char lo;
  9918. char hi;
  9919. } lohi;
  9920. uint16_t value;
  9921. } sdlen_single;
  9922. int _bufindr = bufindr;
  9923. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  9924. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  9925. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  9926. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  9927. }
  9928. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  9929. MYSERIAL.print(int(iline), DEC);
  9930. SERIAL_ECHOPGM(", type: ");
  9931. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  9932. SERIAL_ECHOPGM(", len: ");
  9933. MYSERIAL.println(sdlen_single.value, DEC);
  9934. // Print the content of the buffer line.
  9935. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  9936. SERIAL_ECHOPGM("Buffer line (from file): ");
  9937. MYSERIAL.println(int(iline), DEC);
  9938. for (; sdlen_single.value > 0; -- sdlen_single.value)
  9939. MYSERIAL.print(char(card.get()));
  9940. if (-- _buflen == 0)
  9941. break;
  9942. // First skip the current command ID and iterate up to the end of the string.
  9943. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  9944. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  9945. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9946. // If the end of the buffer was empty,
  9947. if (_bufindr == sizeof(cmdbuffer)) {
  9948. // skip to the start and find the nonzero command.
  9949. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9950. }
  9951. }
  9952. }
  9953. #endif
  9954. // save the global state at planning time
  9955. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9956. if (current_block && !pos_invalid)
  9957. {
  9958. memcpy(saved_target, current_block->gcode_target, sizeof(saved_target));
  9959. saved_feedrate2 = current_block->gcode_feedrate;
  9960. }
  9961. else
  9962. {
  9963. saved_target[0] = SAVED_TARGET_UNSET;
  9964. saved_feedrate2 = feedrate;
  9965. }
  9966. planner_abort_hard(); //abort printing
  9967. memcpy(saved_pos, current_position, sizeof(saved_pos));
  9968. if (pos_invalid) saved_pos[X_AXIS] = X_COORD_INVALID;
  9969. saved_feedmultiply2 = feedmultiply; //save feedmultiply
  9970. saved_active_extruder = active_extruder; //save active_extruder
  9971. saved_extruder_temperature = degTargetHotend(active_extruder);
  9972. saved_extruder_relative_mode = axis_relative_modes & E_AXIS_MASK;
  9973. saved_fanSpeed = fanSpeed;
  9974. cmdqueue_reset(); //empty cmdqueue
  9975. card.sdprinting = false;
  9976. // card.closefile();
  9977. saved_printing = true;
  9978. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  9979. st_reset_timer();
  9980. sei();
  9981. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  9982. #if 1
  9983. // Rather than calling plan_buffer_line directly, push the move into the command queue so that
  9984. // the caller can continue processing. This is used during powerpanic to save the state as we
  9985. // move away from the print.
  9986. char buf[48];
  9987. if(e_move)
  9988. {
  9989. // First unretract (relative extrusion)
  9990. if(!saved_extruder_relative_mode){
  9991. enquecommand(PSTR("M83"), true);
  9992. }
  9993. //retract 45mm/s
  9994. // A single sprintf may not be faster, but is definitely 20B shorter
  9995. // than a sequence of commands building the string piece by piece
  9996. // A snprintf would have been a safer call, but since it is not used
  9997. // in the whole program, its implementation would bring more bytes to the total size
  9998. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  9999. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  10000. enquecommand(buf, false);
  10001. }
  10002. if(z_move)
  10003. {
  10004. // Then lift Z axis
  10005. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  10006. enquecommand(buf, false);
  10007. }
  10008. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  10009. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  10010. repeatcommand_front();
  10011. #else
  10012. 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);
  10013. st_synchronize(); //wait moving
  10014. memcpy(current_position, saved_pos, sizeof(saved_pos));
  10015. set_destination_to_current();
  10016. #endif
  10017. waiting_inside_plan_buffer_line_print_aborted = true; //unroll the stack
  10018. }
  10019. }
  10020. //! @brief Restore print from ram
  10021. //!
  10022. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  10023. //! print fan speed, waits for extruder temperature restore, then restores
  10024. //! position and continues print moves.
  10025. //!
  10026. //! Internally lcd_update() is called by wait_for_heater().
  10027. //!
  10028. //! @param e_move
  10029. void restore_print_from_ram_and_continue(float e_move)
  10030. {
  10031. if (!saved_printing) return;
  10032. #ifdef FANCHECK
  10033. // Do not allow resume printing if fans are still not ok
  10034. if ((fan_check_error != EFCE_OK) && (fan_check_error != EFCE_FIXED)) return;
  10035. if (fan_check_error == EFCE_FIXED) fan_check_error = EFCE_OK; //reenable serial stream processing if printing from usb
  10036. #endif
  10037. // for (int axis = X_AXIS; axis <= E_AXIS; axis++)
  10038. // current_position[axis] = st_get_position_mm(axis);
  10039. active_extruder = saved_active_extruder; //restore active_extruder
  10040. fanSpeed = saved_fanSpeed;
  10041. if (degTargetHotend(saved_active_extruder) != saved_extruder_temperature)
  10042. {
  10043. setTargetHotendSafe(saved_extruder_temperature, saved_active_extruder);
  10044. heating_status = HeatingStatus::EXTRUDER_HEATING;
  10045. wait_for_heater(_millis(), saved_active_extruder);
  10046. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  10047. }
  10048. axis_relative_modes ^= (-saved_extruder_relative_mode ^ axis_relative_modes) & E_AXIS_MASK;
  10049. float e = saved_pos[E_AXIS] - e_move;
  10050. plan_set_e_position(e);
  10051. #ifdef FANCHECK
  10052. fans_check_enabled = false;
  10053. #endif
  10054. // do not restore XY for commands that do not require that
  10055. if (saved_pos[X_AXIS] == X_COORD_INVALID)
  10056. {
  10057. saved_pos[X_AXIS] = current_position[X_AXIS];
  10058. saved_pos[Y_AXIS] = current_position[Y_AXIS];
  10059. }
  10060. //first move print head in XY to the saved position:
  10061. 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);
  10062. //then move Z
  10063. 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);
  10064. //and finaly unretract (35mm/s)
  10065. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  10066. st_synchronize();
  10067. #ifdef FANCHECK
  10068. fans_check_enabled = true;
  10069. #endif
  10070. // restore original feedrate/feedmultiply _after_ restoring the extruder position
  10071. feedrate = saved_feedrate2;
  10072. feedmultiply = saved_feedmultiply2;
  10073. memcpy(current_position, saved_pos, sizeof(saved_pos));
  10074. set_destination_to_current();
  10075. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  10076. card.setIndex(saved_sdpos);
  10077. sdpos_atomic = saved_sdpos;
  10078. card.sdprinting = true;
  10079. }
  10080. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  10081. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  10082. serial_count = 0;
  10083. FlushSerialRequestResend();
  10084. }
  10085. else {
  10086. //not sd printing nor usb printing
  10087. }
  10088. lcd_setstatuspgm(MSG_WELCOME);
  10089. saved_printing_type = PRINTING_TYPE_NONE;
  10090. saved_printing = false;
  10091. waiting_inside_plan_buffer_line_print_aborted = true; //unroll the stack
  10092. }
  10093. // Cancel the state related to a currently saved print
  10094. void cancel_saved_printing()
  10095. {
  10096. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  10097. saved_target[0] = SAVED_TARGET_UNSET;
  10098. saved_printing_type = PRINTING_TYPE_NONE;
  10099. saved_printing = false;
  10100. }
  10101. void print_world_coordinates()
  10102. {
  10103. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  10104. }
  10105. void print_physical_coordinates()
  10106. {
  10107. 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));
  10108. }
  10109. void print_mesh_bed_leveling_table()
  10110. {
  10111. SERIAL_ECHOPGM("mesh bed leveling: ");
  10112. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  10113. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  10114. MYSERIAL.print(mbl.z_values[y][x], 3);
  10115. SERIAL_ECHO(' ');
  10116. }
  10117. SERIAL_ECHOLN();
  10118. }
  10119. uint8_t calc_percent_done()
  10120. {
  10121. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  10122. uint8_t percent_done = 0;
  10123. #ifdef TMC2130
  10124. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100)
  10125. {
  10126. percent_done = print_percent_done_normal;
  10127. }
  10128. else if (print_percent_done_silent <= 100)
  10129. {
  10130. percent_done = print_percent_done_silent;
  10131. }
  10132. #else
  10133. if (print_percent_done_normal <= 100)
  10134. {
  10135. percent_done = print_percent_done_normal;
  10136. }
  10137. #endif //TMC2130
  10138. else
  10139. {
  10140. percent_done = card.percentDone();
  10141. }
  10142. return percent_done;
  10143. }
  10144. static void print_time_remaining_init()
  10145. {
  10146. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  10147. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  10148. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  10149. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  10150. print_time_to_change_normal = PRINT_TIME_REMAINING_INIT;
  10151. print_time_to_change_silent = PRINT_TIME_REMAINING_INIT;
  10152. }
  10153. void load_filament_final_feed()
  10154. {
  10155. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  10156. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FINAL);
  10157. }
  10158. //! @brief Wait for user to check the state
  10159. //! @par nozzle_temp nozzle temperature to load filament
  10160. void M600_check_state(float nozzle_temp)
  10161. {
  10162. lcd_change_fil_state = 0;
  10163. while (lcd_change_fil_state != 1)
  10164. {
  10165. lcd_change_fil_state = 0;
  10166. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10167. lcd_alright();
  10168. KEEPALIVE_STATE(IN_HANDLER);
  10169. switch(lcd_change_fil_state)
  10170. {
  10171. // Filament failed to load so load it again
  10172. case 2:
  10173. if (mmu_enabled)
  10174. mmu_M600_load_filament(false, nozzle_temp); //nonautomatic load; change to "wrong filament loaded" option?
  10175. else
  10176. M600_load_filament_movements();
  10177. break;
  10178. // Filament loaded properly but color is not clear
  10179. case 3:
  10180. st_synchronize();
  10181. load_filament_final_feed();
  10182. lcd_loading_color();
  10183. st_synchronize();
  10184. break;
  10185. // Everything good
  10186. default:
  10187. lcd_change_success();
  10188. break;
  10189. }
  10190. }
  10191. }
  10192. //! @brief Wait for user action
  10193. //!
  10194. //! Beep, manage nozzle heater and wait for user to start unload filament
  10195. //! If times out, active extruder temperature is set to 0.
  10196. //!
  10197. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  10198. void M600_wait_for_user(float HotendTempBckp) {
  10199. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10200. int counterBeep = 0;
  10201. unsigned long waiting_start_time = _millis();
  10202. uint8_t wait_for_user_state = 0;
  10203. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  10204. bool bFirst=true;
  10205. while (!(wait_for_user_state == 0 && lcd_clicked())){
  10206. manage_heater();
  10207. manage_inactivity(true);
  10208. #if BEEPER > 0
  10209. if (counterBeep == 500) {
  10210. counterBeep = 0;
  10211. }
  10212. SET_OUTPUT(BEEPER);
  10213. if (counterBeep == 0) {
  10214. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  10215. {
  10216. bFirst=false;
  10217. WRITE(BEEPER, HIGH);
  10218. }
  10219. }
  10220. if (counterBeep == 20) {
  10221. WRITE(BEEPER, LOW);
  10222. }
  10223. counterBeep++;
  10224. #endif //BEEPER > 0
  10225. switch (wait_for_user_state) {
  10226. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  10227. delay_keep_alive(4);
  10228. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  10229. lcd_display_message_fullscreen_P(_i("Press the knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  10230. wait_for_user_state = 1;
  10231. setAllTargetHotends(0);
  10232. st_synchronize();
  10233. disable_e0();
  10234. disable_e1();
  10235. disable_e2();
  10236. }
  10237. break;
  10238. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  10239. delay_keep_alive(4);
  10240. if (lcd_clicked()) {
  10241. setTargetHotend(HotendTempBckp, active_extruder);
  10242. lcd_wait_for_heater();
  10243. wait_for_user_state = 2;
  10244. }
  10245. break;
  10246. case 2: //waiting for nozzle to reach target temperature
  10247. if (fabs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  10248. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  10249. waiting_start_time = _millis();
  10250. wait_for_user_state = 0;
  10251. }
  10252. else {
  10253. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  10254. lcd_set_cursor(1, 4);
  10255. lcd_printf_P(PSTR("%3d"), (int16_t)degHotend(active_extruder));
  10256. }
  10257. break;
  10258. }
  10259. }
  10260. WRITE(BEEPER, LOW);
  10261. }
  10262. void M600_load_filament_movements()
  10263. {
  10264. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED;
  10265. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST);
  10266. load_filament_final_feed();
  10267. lcd_loading_filament();
  10268. st_synchronize();
  10269. }
  10270. void M600_load_filament() {
  10271. //load filament for single material and MMU
  10272. lcd_wait_interact();
  10273. //load_filament_time = _millis();
  10274. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10275. #ifdef PAT9125
  10276. fsensor_autoload_check_start();
  10277. #endif //PAT9125
  10278. while(!lcd_clicked())
  10279. {
  10280. manage_heater();
  10281. manage_inactivity(true);
  10282. #ifdef FILAMENT_SENSOR
  10283. if (fsensor_check_autoload())
  10284. {
  10285. Sound_MakeCustom(50,1000,false);
  10286. break;
  10287. }
  10288. #endif //FILAMENT_SENSOR
  10289. }
  10290. #ifdef PAT9125
  10291. fsensor_autoload_check_stop();
  10292. #endif //PAT9125
  10293. KEEPALIVE_STATE(IN_HANDLER);
  10294. #ifdef FSENSOR_QUALITY
  10295. fsensor_oq_meassure_start(70);
  10296. #endif //FSENSOR_QUALITY
  10297. M600_load_filament_movements();
  10298. Sound_MakeCustom(50,1000,false);
  10299. #ifdef FSENSOR_QUALITY
  10300. fsensor_oq_meassure_stop();
  10301. if (!fsensor_oq_result())
  10302. {
  10303. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Fil. sensor response is poor, disable it?"), false, true);
  10304. lcd_update_enable(true);
  10305. lcd_update(2);
  10306. if (disable)
  10307. fsensor_disable();
  10308. }
  10309. #endif //FSENSOR_QUALITY
  10310. lcd_update_enable(false);
  10311. }
  10312. //! @brief Wait for click
  10313. //!
  10314. //! Set
  10315. void marlin_wait_for_click()
  10316. {
  10317. int8_t busy_state_backup = busy_state;
  10318. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10319. lcd_consume_click();
  10320. while(!lcd_clicked())
  10321. {
  10322. manage_heater();
  10323. manage_inactivity(true);
  10324. lcd_update(0);
  10325. }
  10326. KEEPALIVE_STATE(busy_state_backup);
  10327. }
  10328. #define FIL_LOAD_LENGTH 60
  10329. #ifdef PSU_Delta
  10330. bool bEnableForce_z;
  10331. void init_force_z()
  10332. {
  10333. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  10334. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  10335. disable_force_z();
  10336. }
  10337. void check_force_z()
  10338. {
  10339. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  10340. init_force_z(); // causes enforced switching into disable-state
  10341. }
  10342. void disable_force_z()
  10343. {
  10344. if(!bEnableForce_z) return; // motor already disabled (may be ;-p )
  10345. bEnableForce_z=false;
  10346. // switching to silent mode
  10347. #ifdef TMC2130
  10348. tmc2130_mode=TMC2130_MODE_SILENT;
  10349. update_mode_profile();
  10350. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10351. #endif // TMC2130
  10352. }
  10353. void enable_force_z()
  10354. {
  10355. if(bEnableForce_z)
  10356. return; // motor already enabled (may be ;-p )
  10357. bEnableForce_z=true;
  10358. // mode recovering
  10359. #ifdef TMC2130
  10360. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  10361. update_mode_profile();
  10362. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10363. #endif // TMC2130
  10364. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  10365. }
  10366. #endif // PSU_Delta