Marlin_main.cpp 293 KB

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