Marlin_main.cpp 275 KB

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