Marlin_main.cpp 288 KB

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