Marlin_main.cpp 288 KB

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