Marlin_main.cpp 232 KB

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