Marlin_main.cpp 221 KB

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