Marlin_main.cpp 290 KB

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