Marlin_main.cpp 283 KB

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