Marlin_main.cpp 275 KB

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