Marlin_main.cpp 230 KB

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