Marlin_main.cpp 243 KB

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