Marlin_main.cpp 238 KB

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