Marlin_main.cpp 390 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647
  1. /* -*- c++ -*- */
  2. /**
  3. * @file
  4. */
  5. /**
  6. * @mainpage Reprap 3D printer firmware based on Sprinter and grbl.
  7. *
  8. * @section intro_sec Introduction
  9. *
  10. * This firmware is a mashup between Sprinter and grbl.
  11. * https://github.com/kliment/Sprinter
  12. * https://github.com/simen/grbl/tree
  13. *
  14. * It has preliminary support for Matthew Roberts advance algorithm
  15. * http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
  16. *
  17. * Prusa Research s.r.o. https://www.prusa3d.cz
  18. *
  19. * @section copyright_sec Copyright
  20. *
  21. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  22. *
  23. * This program is free software: you can redistribute it and/or modify
  24. * it under the terms of the GNU General Public License as published by
  25. * the Free Software Foundation, either version 3 of the License, or
  26. * (at your option) any later version.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU General Public License
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  35. *
  36. * @section notes_sec Notes
  37. *
  38. * * Do not create static objects in global functions.
  39. * Otherwise constructor guard against concurrent calls is generated costing
  40. * about 8B RAM and 14B flash.
  41. *
  42. *
  43. */
  44. //-//
  45. #include "Configuration.h"
  46. #include "Marlin.h"
  47. #ifdef ENABLE_AUTO_BED_LEVELING
  48. #include "vector_3.h"
  49. #ifdef AUTO_BED_LEVELING_GRID
  50. #include "qr_solve.h"
  51. #endif
  52. #endif // ENABLE_AUTO_BED_LEVELING
  53. #ifdef MESH_BED_LEVELING
  54. #include "mesh_bed_leveling.h"
  55. #include "mesh_bed_calibration.h"
  56. #endif
  57. #include "printers.h"
  58. #include "menu.h"
  59. #include "ultralcd.h"
  60. #include "backlight.h"
  61. #include "planner.h"
  62. #include "stepper.h"
  63. #include "temperature.h"
  64. #include "motion_control.h"
  65. #include "cardreader.h"
  66. #include "ConfigurationStore.h"
  67. #include "language.h"
  68. #include "pins_arduino.h"
  69. #include "math.h"
  70. #include "util.h"
  71. #include "Timer.h"
  72. #include <avr/wdt.h>
  73. #include <avr/pgmspace.h>
  74. #include "Dcodes.h"
  75. #include "AutoDeplete.h"
  76. #ifndef LA_NOCOMPAT
  77. #include "la10compat.h"
  78. #endif
  79. #ifdef SWSPI
  80. #include "swspi.h"
  81. #endif //SWSPI
  82. #include "spi.h"
  83. #ifdef SWI2C
  84. #include "swi2c.h"
  85. #endif //SWI2C
  86. #ifdef FILAMENT_SENSOR
  87. #include "fsensor.h"
  88. #endif //FILAMENT_SENSOR
  89. #ifdef TMC2130
  90. #include "tmc2130.h"
  91. #endif //TMC2130
  92. #ifdef W25X20CL
  93. #include "w25x20cl.h"
  94. #include "optiboot_w25x20cl.h"
  95. #endif //W25X20CL
  96. #ifdef BLINKM
  97. #include "BlinkM.h"
  98. #include "Wire.h"
  99. #endif
  100. #ifdef ULTRALCD
  101. #include "ultralcd.h"
  102. #endif
  103. #if NUM_SERVOS > 0
  104. #include "Servo.h"
  105. #endif
  106. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  107. #include <SPI.h>
  108. #endif
  109. #include "mmu.h"
  110. #define VERSION_STRING "1.0.2"
  111. #include "ultralcd.h"
  112. #include "sound.h"
  113. #include "cmdqueue.h"
  114. #include "io_atmega2560.h"
  115. // Macros for bit masks
  116. #define BIT(b) (1<<(b))
  117. #define TEST(n,b) (((n)&BIT(b))!=0)
  118. #define SET_BIT(n,b,value) (n) ^= ((-value)^(n)) & (BIT(b))
  119. //Macro for print fan speed
  120. #define FAN_PULSE_WIDTH_LIMIT ((fanSpeed > 100) ? 3 : 4) //time in ms
  121. //filament types
  122. #define FILAMENT_DEFAULT 0
  123. #define FILAMENT_FLEX 1
  124. #define FILAMENT_PVA 2
  125. #define FILAMENT_UNDEFINED 255
  126. //Stepper Movement Variables
  127. //===========================================================================
  128. //=============================imported variables============================
  129. //===========================================================================
  130. //===========================================================================
  131. //=============================public variables=============================
  132. //===========================================================================
  133. #ifdef SDSUPPORT
  134. CardReader card;
  135. #endif
  136. unsigned long PingTime = _millis();
  137. unsigned long NcTime;
  138. uint8_t mbl_z_probe_nr = 3; //numer of Z measurements for each point in mesh bed leveling calibration
  139. //used for PINDA temp calibration and pause print
  140. #define DEFAULT_RETRACTION 1
  141. #define DEFAULT_RETRACTION_MM 4 //MM
  142. float default_retraction = DEFAULT_RETRACTION;
  143. float homing_feedrate[] = HOMING_FEEDRATE;
  144. // Currently only the extruder axis may be switched to a relative mode.
  145. // Other axes are always absolute or relative based on the common relative_mode flag.
  146. bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
  147. int feedmultiply=100; //100->1 200->2
  148. int extrudemultiply=100; //100->1 200->2
  149. int extruder_multiply[EXTRUDERS] = {100
  150. #if EXTRUDERS > 1
  151. , 100
  152. #if EXTRUDERS > 2
  153. , 100
  154. #endif
  155. #endif
  156. };
  157. int bowden_length[4] = {385, 385, 385, 385};
  158. bool is_usb_printing = false;
  159. bool homing_flag = false;
  160. bool temp_cal_active = false;
  161. unsigned long kicktime = _millis()+100000;
  162. unsigned int usb_printing_counter;
  163. int8_t lcd_change_fil_state = 0;
  164. unsigned long pause_time = 0;
  165. unsigned long start_pause_print = _millis();
  166. unsigned long t_fan_rising_edge = _millis();
  167. LongTimer safetyTimer;
  168. static LongTimer crashDetTimer;
  169. //unsigned long load_filament_time;
  170. bool mesh_bed_leveling_flag = false;
  171. bool mesh_bed_run_from_menu = false;
  172. bool prusa_sd_card_upload = false;
  173. unsigned int status_number = 0;
  174. unsigned long total_filament_used;
  175. unsigned int heating_status;
  176. unsigned int heating_status_counter;
  177. bool loading_flag = false;
  178. char snmm_filaments_used = 0;
  179. bool fan_state[2];
  180. int fan_edge_counter[2];
  181. int fan_speed[2];
  182. char dir_names[3][9];
  183. bool sortAlpha = false;
  184. float extruder_multiplier[EXTRUDERS] = {1.0
  185. #if EXTRUDERS > 1
  186. , 1.0
  187. #if EXTRUDERS > 2
  188. , 1.0
  189. #endif
  190. #endif
  191. };
  192. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  193. //shortcuts for more readable code
  194. #define _x current_position[X_AXIS]
  195. #define _y current_position[Y_AXIS]
  196. #define _z current_position[Z_AXIS]
  197. #define _e current_position[E_AXIS]
  198. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  199. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  200. bool axis_known_position[3] = {false, false, false};
  201. // Extruder offset
  202. #if EXTRUDERS > 1
  203. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  204. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  205. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  206. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  207. #endif
  208. };
  209. #endif
  210. uint8_t active_extruder = 0;
  211. int fanSpeed=0;
  212. #ifdef FWRETRACT
  213. bool retracted[EXTRUDERS]={false
  214. #if EXTRUDERS > 1
  215. , false
  216. #if EXTRUDERS > 2
  217. , false
  218. #endif
  219. #endif
  220. };
  221. bool retracted_swap[EXTRUDERS]={false
  222. #if EXTRUDERS > 1
  223. , false
  224. #if EXTRUDERS > 2
  225. , false
  226. #endif
  227. #endif
  228. };
  229. float retract_length_swap = RETRACT_LENGTH_SWAP;
  230. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  231. #endif
  232. #ifdef PS_DEFAULT_OFF
  233. bool powersupply = false;
  234. #else
  235. bool powersupply = true;
  236. #endif
  237. bool cancel_heatup = false ;
  238. int8_t busy_state = NOT_BUSY;
  239. static long prev_busy_signal_ms = -1;
  240. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  241. const char errormagic[] PROGMEM = "Error:";
  242. const char echomagic[] PROGMEM = "echo:";
  243. bool no_response = false;
  244. uint8_t important_status;
  245. uint8_t saved_filament_type;
  246. #define SAVED_TARGET_UNSET (X_MIN_POS-1)
  247. float saved_target[NUM_AXIS] = {SAVED_TARGET_UNSET, 0, 0, 0};
  248. // save/restore printing in case that mmu was not responding
  249. bool mmu_print_saved = false;
  250. // storing estimated time to end of print counted by slicer
  251. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  252. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  253. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  254. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  255. //===========================================================================
  256. //=============================Private Variables=============================
  257. //===========================================================================
  258. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  259. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  260. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  261. // For tracing an arc
  262. static float offset[3] = {0.0, 0.0, 0.0};
  263. // Current feedrate
  264. float feedrate = 1500.0;
  265. // Feedrate for the next move
  266. static float next_feedrate;
  267. // Original feedrate saved during homing moves
  268. static float saved_feedrate;
  269. const int sensitive_pins[] = SENSITIVE_PINS; // Sensitive pin list for M42
  270. //static float tt = 0;
  271. //static float bt = 0;
  272. //Inactivity shutdown variables
  273. static unsigned long previous_millis_cmd = 0;
  274. unsigned long max_inactive_time = 0;
  275. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  276. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  277. unsigned long starttime=0;
  278. unsigned long stoptime=0;
  279. unsigned long _usb_timer = 0;
  280. bool Stopped=false;
  281. #if NUM_SERVOS > 0
  282. Servo servos[NUM_SERVOS];
  283. #endif
  284. bool target_direction;
  285. //Insert variables if CHDK is defined
  286. #ifdef CHDK
  287. unsigned long chdkHigh = 0;
  288. boolean chdkActive = false;
  289. #endif
  290. //! @name RAM save/restore printing
  291. //! @{
  292. bool saved_printing = false; //!< Print is paused and saved in RAM
  293. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  294. uint8_t saved_printing_type = PRINTING_TYPE_SD;
  295. static float saved_pos[4] = { 0, 0, 0, 0 };
  296. static uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
  297. static int saved_feedmultiply2 = 0;
  298. static uint8_t saved_active_extruder = 0;
  299. static float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  300. static bool saved_extruder_relative_mode = false;
  301. static int saved_fanSpeed = 0; //!< Print fan speed
  302. //! @}
  303. static int saved_feedmultiply_mm = 100;
  304. //===========================================================================
  305. //=============================Routines======================================
  306. //===========================================================================
  307. static void get_arc_coordinates();
  308. static bool setTargetedHotend(int code, uint8_t &extruder);
  309. static void print_time_remaining_init();
  310. static void wait_for_heater(long codenum, uint8_t extruder);
  311. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
  312. static void temp_compensation_start();
  313. static void temp_compensation_apply();
  314. uint16_t gcode_in_progress = 0;
  315. uint16_t mcode_in_progress = 0;
  316. void serial_echopair_P(const char *s_P, float v)
  317. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  318. void serial_echopair_P(const char *s_P, double v)
  319. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  320. void serial_echopair_P(const char *s_P, unsigned long v)
  321. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  322. /*FORCE_INLINE*/ void serialprintPGM(const char *str)
  323. {
  324. #if 0
  325. char ch=pgm_read_byte(str);
  326. while(ch)
  327. {
  328. MYSERIAL.write(ch);
  329. ch=pgm_read_byte(++str);
  330. }
  331. #else
  332. // hmm, same size as the above version, the compiler did a good job optimizing the above
  333. while( uint8_t ch = pgm_read_byte(str) ){
  334. MYSERIAL.write((char)ch);
  335. ++str;
  336. }
  337. #endif
  338. }
  339. #ifdef SDSUPPORT
  340. #include "SdFatUtil.h"
  341. int freeMemory() { return SdFatUtil::FreeRam(); }
  342. #else
  343. extern "C" {
  344. extern unsigned int __bss_end;
  345. extern unsigned int __heap_start;
  346. extern void *__brkval;
  347. int freeMemory() {
  348. int free_memory;
  349. if ((int)__brkval == 0)
  350. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  351. else
  352. free_memory = ((int)&free_memory) - ((int)__brkval);
  353. return free_memory;
  354. }
  355. }
  356. #endif //!SDSUPPORT
  357. void setup_killpin()
  358. {
  359. #if defined(KILL_PIN) && KILL_PIN > -1
  360. SET_INPUT(KILL_PIN);
  361. WRITE(KILL_PIN,HIGH);
  362. #endif
  363. }
  364. // Set home pin
  365. void setup_homepin(void)
  366. {
  367. #if defined(HOME_PIN) && HOME_PIN > -1
  368. SET_INPUT(HOME_PIN);
  369. WRITE(HOME_PIN,HIGH);
  370. #endif
  371. }
  372. void setup_photpin()
  373. {
  374. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  375. SET_OUTPUT(PHOTOGRAPH_PIN);
  376. WRITE(PHOTOGRAPH_PIN, LOW);
  377. #endif
  378. }
  379. void setup_powerhold()
  380. {
  381. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  382. SET_OUTPUT(SUICIDE_PIN);
  383. WRITE(SUICIDE_PIN, HIGH);
  384. #endif
  385. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  386. SET_OUTPUT(PS_ON_PIN);
  387. #if defined(PS_DEFAULT_OFF)
  388. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  389. #else
  390. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  391. #endif
  392. #endif
  393. }
  394. void suicide()
  395. {
  396. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  397. SET_OUTPUT(SUICIDE_PIN);
  398. WRITE(SUICIDE_PIN, LOW);
  399. #endif
  400. }
  401. void servo_init()
  402. {
  403. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  404. servos[0].attach(SERVO0_PIN);
  405. #endif
  406. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  407. servos[1].attach(SERVO1_PIN);
  408. #endif
  409. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  410. servos[2].attach(SERVO2_PIN);
  411. #endif
  412. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  413. servos[3].attach(SERVO3_PIN);
  414. #endif
  415. #if (NUM_SERVOS >= 5)
  416. #error "TODO: enter initalisation code for more servos"
  417. #endif
  418. }
  419. bool fans_check_enabled = true;
  420. #ifdef TMC2130
  421. void crashdet_stop_and_save_print()
  422. {
  423. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  424. }
  425. void crashdet_restore_print_and_continue()
  426. {
  427. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  428. // babystep_apply();
  429. }
  430. void crashdet_stop_and_save_print2()
  431. {
  432. cli();
  433. planner_abort_hard(); //abort printing
  434. cmdqueue_reset(); //empty cmdqueue
  435. card.sdprinting = false;
  436. card.closefile();
  437. // Reset and re-enable the stepper timer just before the global interrupts are enabled.
  438. st_reset_timer();
  439. sei();
  440. }
  441. void crashdet_detected(uint8_t mask)
  442. {
  443. st_synchronize();
  444. static uint8_t crashDet_counter = 0;
  445. bool automatic_recovery_after_crash = true;
  446. if (crashDet_counter++ == 0) {
  447. crashDetTimer.start();
  448. }
  449. else if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)){
  450. crashDetTimer.stop();
  451. crashDet_counter = 0;
  452. }
  453. else if(crashDet_counter == CRASHDET_COUNTER_MAX){
  454. automatic_recovery_after_crash = false;
  455. crashDetTimer.stop();
  456. crashDet_counter = 0;
  457. }
  458. else {
  459. crashDetTimer.start();
  460. }
  461. lcd_update_enable(true);
  462. lcd_clear();
  463. lcd_update(2);
  464. if (mask & X_AXIS_MASK)
  465. {
  466. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_X, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_X) + 1);
  467. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT) + 1);
  468. }
  469. if (mask & Y_AXIS_MASK)
  470. {
  471. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_Y, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_Y) + 1);
  472. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT) + 1);
  473. }
  474. lcd_update_enable(true);
  475. lcd_update(2);
  476. lcd_setstatuspgm(_T(MSG_CRASH_DETECTED));
  477. gcode_G28(true, true, false); //home X and Y
  478. st_synchronize();
  479. if (automatic_recovery_after_crash) {
  480. enquecommand_P(PSTR("CRASH_RECOVER"));
  481. }else{
  482. setTargetHotend(0, active_extruder);
  483. bool yesno = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Crash detected. Resume print?"), false);
  484. lcd_update_enable(true);
  485. if (yesno)
  486. {
  487. enquecommand_P(PSTR("CRASH_RECOVER"));
  488. }
  489. else
  490. {
  491. enquecommand_P(PSTR("CRASH_CANCEL"));
  492. }
  493. }
  494. }
  495. void crashdet_recover()
  496. {
  497. crashdet_restore_print_and_continue();
  498. if (lcd_crash_detect_enabled()) tmc2130_sg_stop_on_crash = true;
  499. }
  500. void crashdet_cancel()
  501. {
  502. saved_printing = false;
  503. tmc2130_sg_stop_on_crash = true;
  504. if (saved_printing_type == PRINTING_TYPE_SD) {
  505. lcd_print_stop();
  506. }else if(saved_printing_type == PRINTING_TYPE_USB){
  507. SERIAL_ECHOLNRPGM(MSG_OCTOPRINT_CANCEL); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  508. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  509. }
  510. }
  511. #endif //TMC2130
  512. void failstats_reset_print()
  513. {
  514. fsensor_softfail = 0;
  515. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  516. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  517. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  518. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  519. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  520. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  521. }
  522. #ifdef MESH_BED_LEVELING
  523. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  524. #endif
  525. // Factory reset function
  526. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  527. // Level input parameter sets depth of reset
  528. int er_progress = 0;
  529. static void factory_reset(char level)
  530. {
  531. lcd_clear();
  532. switch (level) {
  533. // Level 0: Language reset
  534. case 0:
  535. Sound_MakeCustom(100,0,false);
  536. lang_reset();
  537. break;
  538. //Level 1: Reset statistics
  539. case 1:
  540. Sound_MakeCustom(100,0,false);
  541. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  542. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  543. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  544. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  545. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  546. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  547. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  548. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  549. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  550. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  551. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  552. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  553. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  554. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  555. lcd_menu_statistics();
  556. break;
  557. // Level 2: Prepare for shipping
  558. case 2:
  559. //lcd_puts_P(PSTR("Factory RESET"));
  560. //lcd_puts_at_P(1,2,PSTR("Shipping prep"));
  561. // Force language selection at the next boot up.
  562. lang_reset();
  563. // Force the "Follow calibration flow" message at the next boot up.
  564. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  565. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  566. farm_no = 0;
  567. farm_mode = false;
  568. eeprom_update_byte((uint8_t*)EEPROM_FARM_MODE, farm_mode);
  569. EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
  570. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  571. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  572. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  573. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  574. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  575. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  576. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  577. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  578. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  579. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  580. #ifdef FILAMENT_SENSOR
  581. fsensor_enable();
  582. fsensor_autoload_set(true);
  583. #endif //FILAMENT_SENSOR
  584. Sound_MakeCustom(100,0,false);
  585. //_delay_ms(2000);
  586. break;
  587. // Level 3: erase everything, whole EEPROM will be set to 0xFF
  588. case 3:
  589. lcd_puts_P(PSTR("Factory RESET"));
  590. lcd_puts_at_P(1, 2, PSTR("ERASING all data"));
  591. Sound_MakeCustom(100,0,false);
  592. er_progress = 0;
  593. lcd_puts_at_P(3, 3, PSTR(" "));
  594. lcd_set_cursor(3, 3);
  595. lcd_print(er_progress);
  596. // Erase EEPROM
  597. for (int i = 0; i < 4096; i++) {
  598. eeprom_update_byte((uint8_t*)i, 0xFF);
  599. if (i % 41 == 0) {
  600. er_progress++;
  601. lcd_puts_at_P(3, 3, PSTR(" "));
  602. lcd_set_cursor(3, 3);
  603. lcd_print(er_progress);
  604. lcd_puts_P(PSTR("%"));
  605. }
  606. }
  607. break;
  608. case 4:
  609. bowden_menu();
  610. break;
  611. default:
  612. break;
  613. }
  614. }
  615. extern "C" {
  616. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  617. }
  618. int uart_putchar(char c, FILE *)
  619. {
  620. MYSERIAL.write(c);
  621. return 0;
  622. }
  623. void lcd_splash()
  624. {
  625. lcd_clear(); // clears display and homes screen
  626. lcd_puts_P(PSTR("\n Original Prusa i3\n Prusa Research"));
  627. }
  628. void factory_reset()
  629. {
  630. KEEPALIVE_STATE(PAUSED_FOR_USER);
  631. if (!READ(BTN_ENC))
  632. {
  633. _delay_ms(1000);
  634. if (!READ(BTN_ENC))
  635. {
  636. lcd_clear();
  637. lcd_puts_P(PSTR("Factory RESET"));
  638. SET_OUTPUT(BEEPER);
  639. if(eSoundMode!=e_SOUND_MODE_SILENT)
  640. WRITE(BEEPER, HIGH);
  641. while (!READ(BTN_ENC));
  642. WRITE(BEEPER, LOW);
  643. _delay_ms(2000);
  644. char level = reset_menu();
  645. factory_reset(level);
  646. switch (level) {
  647. case 0: _delay_ms(0); break;
  648. case 1: _delay_ms(0); break;
  649. case 2: _delay_ms(0); break;
  650. case 3: _delay_ms(0); break;
  651. }
  652. }
  653. }
  654. KEEPALIVE_STATE(IN_HANDLER);
  655. }
  656. void show_fw_version_warnings() {
  657. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  658. switch (FW_DEV_VERSION) {
  659. case(FW_VERSION_ALPHA): lcd_show_fullscreen_message_and_wait_P(_i("You are using firmware alpha version. This is development version. Using this version is not recommended and may cause printer damage.")); break;////MSG_FW_VERSION_ALPHA c=20 r=8
  660. case(FW_VERSION_BETA): lcd_show_fullscreen_message_and_wait_P(_i("You are using firmware beta version. This is development version. Using this version is not recommended and may cause printer damage.")); break;////MSG_FW_VERSION_BETA c=20 r=8
  661. case(FW_VERSION_DEVEL):
  662. case(FW_VERSION_DEBUG):
  663. lcd_update_enable(false);
  664. lcd_clear();
  665. #if FW_DEV_VERSION == FW_VERSION_DEVEL
  666. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  667. #else
  668. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  669. #endif
  670. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  671. lcd_puts_at_P(0, 2, PSTR("ver ")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  672. lcd_puts_at_P(0, 3, PSTR(FW_REPOSITORY));
  673. lcd_wait_for_click();
  674. break;
  675. // default: lcd_show_fullscreen_message_and_wait_P(_i("WARNING: This is an unofficial, unsupported build. Use at your own risk!")); break;////MSG_FW_VERSION_UNKNOWN c=20 r=8
  676. }
  677. lcd_update_enable(true);
  678. }
  679. //! @brief try to check if firmware is on right type of printer
  680. static void check_if_fw_is_on_right_printer(){
  681. #ifdef FILAMENT_SENSOR
  682. if((PRINTER_TYPE == PRINTER_MK3) || (PRINTER_TYPE == PRINTER_MK3S)){
  683. #ifdef IR_SENSOR
  684. swi2c_init();
  685. const uint8_t pat9125_detected = swi2c_readByte_A8(PAT9125_I2C_ADDR,0x00,NULL);
  686. if (pat9125_detected){
  687. lcd_show_fullscreen_message_and_wait_P(_i("MK3S firmware detected on MK3 printer"));}
  688. #endif //IR_SENSOR
  689. #ifdef PAT9125
  690. //will return 1 only if IR can detect filament in bondtech extruder so this may fail even when we have IR sensor
  691. const uint8_t ir_detected = !(PIN_GET(IR_SENSOR_PIN));
  692. if (ir_detected){
  693. lcd_show_fullscreen_message_and_wait_P(_i("MK3 firmware detected on MK3S printer"));}
  694. #endif //PAT9125
  695. }
  696. #endif //FILAMENT_SENSOR
  697. }
  698. uint8_t check_printer_version()
  699. {
  700. uint8_t version_changed = 0;
  701. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  702. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  703. if (printer_type != PRINTER_TYPE) {
  704. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  705. else version_changed |= 0b10;
  706. }
  707. if (motherboard != MOTHERBOARD) {
  708. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  709. else version_changed |= 0b01;
  710. }
  711. return version_changed;
  712. }
  713. #ifdef BOOTAPP
  714. #include "bootapp.h" //bootloader support
  715. #endif //BOOTAPP
  716. #if (LANG_MODE != 0) //secondary language support
  717. #ifdef W25X20CL
  718. // language update from external flash
  719. #define LANGBOOT_BLOCKSIZE 0x1000u
  720. #define LANGBOOT_RAMBUFFER 0x0800
  721. void update_sec_lang_from_external_flash()
  722. {
  723. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  724. {
  725. uint8_t lang = boot_reserved >> 4;
  726. uint8_t state = boot_reserved & 0xf;
  727. lang_table_header_t header;
  728. uint32_t src_addr;
  729. if (lang_get_header(lang, &header, &src_addr))
  730. {
  731. lcd_puts_at_P(1,3,PSTR("Language update."));
  732. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  733. _delay(100);
  734. boot_reserved = (state + 1) | (lang << 4);
  735. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  736. {
  737. cli();
  738. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  739. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  740. w25x20cl_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  741. if (state == 0)
  742. {
  743. //TODO - check header integrity
  744. }
  745. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  746. }
  747. else
  748. {
  749. //TODO - check sec lang data integrity
  750. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  751. }
  752. }
  753. }
  754. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  755. }
  756. #ifdef DEBUG_W25X20CL
  757. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  758. {
  759. lang_table_header_t header;
  760. uint8_t count = 0;
  761. uint32_t addr = 0x00000;
  762. while (1)
  763. {
  764. printf_P(_n("LANGTABLE%d:"), count);
  765. w25x20cl_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  766. if (header.magic != LANG_MAGIC)
  767. {
  768. printf_P(_n("NG!\n"));
  769. break;
  770. }
  771. printf_P(_n("OK\n"));
  772. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  773. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  774. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  775. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  776. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  777. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  778. addr += header.size;
  779. codes[count] = header.code;
  780. count ++;
  781. }
  782. return count;
  783. }
  784. void list_sec_lang_from_external_flash()
  785. {
  786. uint16_t codes[8];
  787. uint8_t count = lang_xflash_enum_codes(codes);
  788. printf_P(_n("XFlash lang count = %hhd\n"), count);
  789. }
  790. #endif //DEBUG_W25X20CL
  791. #endif //W25X20CL
  792. #endif //(LANG_MODE != 0)
  793. static void w25x20cl_err_msg()
  794. {
  795. lcd_clear();
  796. lcd_puts_P(_n("External SPI flash\nW25X20CL is not res-\nponding. Language\nswitch unavailable."));
  797. }
  798. // "Setup" function is called by the Arduino framework on startup.
  799. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  800. // are initialized by the main() routine provided by the Arduino framework.
  801. void setup()
  802. {
  803. mmu_init();
  804. ultralcd_init();
  805. spi_init();
  806. lcd_splash();
  807. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  808. #ifdef W25X20CL
  809. bool w25x20cl_success = w25x20cl_init();
  810. if (w25x20cl_success)
  811. {
  812. optiboot_w25x20cl_enter();
  813. #if (LANG_MODE != 0) //secondary language support
  814. update_sec_lang_from_external_flash();
  815. #endif //(LANG_MODE != 0)
  816. }
  817. else
  818. {
  819. w25x20cl_err_msg();
  820. }
  821. #else
  822. const bool w25x20cl_success = true;
  823. #endif //W25X20CL
  824. setup_killpin();
  825. setup_powerhold();
  826. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  827. EEPROM_read_B(EEPROM_FARM_NUMBER, &farm_no);
  828. if ((farm_mode == 0xFF && farm_no == 0) || ((uint16_t)farm_no == 0xFFFF))
  829. 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
  830. if ((uint16_t)farm_no == 0xFFFF) farm_no = 0;
  831. selectedSerialPort = eeprom_read_byte((uint8_t*)EEPROM_SECOND_SERIAL_ACTIVE);
  832. if (selectedSerialPort == 0xFF) selectedSerialPort = 0;
  833. if (farm_mode)
  834. {
  835. no_response = true; //we need confirmation by recieving PRUSA thx
  836. important_status = 8;
  837. prusa_statistics(8);
  838. selectedSerialPort = 1;
  839. #ifdef TMC2130
  840. //increased extruder current (PFW363)
  841. tmc2130_current_h[E_AXIS] = 36;
  842. tmc2130_current_r[E_AXIS] = 36;
  843. #endif //TMC2130
  844. #ifdef FILAMENT_SENSOR
  845. //disabled filament autoload (PFW360)
  846. fsensor_autoload_set(false);
  847. #endif //FILAMENT_SENSOR
  848. // ~ FanCheck -> on
  849. if(!(eeprom_read_byte((uint8_t*)EEPROM_FAN_CHECK_ENABLED)))
  850. eeprom_update_byte((unsigned char *)EEPROM_FAN_CHECK_ENABLED,true);
  851. }
  852. MYSERIAL.begin(BAUDRATE);
  853. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  854. #ifndef W25X20CL
  855. SERIAL_PROTOCOLLNPGM("start");
  856. #endif //W25X20CL
  857. stdout = uartout;
  858. SERIAL_ECHO_START;
  859. printf_P(PSTR(" " FW_VERSION_FULL "\n"));
  860. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  861. #ifdef DEBUG_SEC_LANG
  862. lang_table_header_t header;
  863. uint32_t src_addr = 0x00000;
  864. if (lang_get_header(1, &header, &src_addr))
  865. {
  866. //this is comparsion of some printing-methods regarding to flash space usage and code size/readability
  867. #define LT_PRINT_TEST 2
  868. // flash usage
  869. // total p.test
  870. //0 252718 t+c text code
  871. //1 253142 424 170 254
  872. //2 253040 322 164 158
  873. //3 253248 530 135 395
  874. #if (LT_PRINT_TEST==1) //not optimized printf
  875. printf_P(_n(" _src_addr = 0x%08lx\n"), src_addr);
  876. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  877. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  878. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  879. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  880. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  881. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  882. #elif (LT_PRINT_TEST==2) //optimized printf
  883. printf_P(
  884. _n(
  885. " _src_addr = 0x%08lx\n"
  886. " _lt_magic = 0x%08lx %S\n"
  887. " _lt_size = 0x%04x (%d)\n"
  888. " _lt_count = 0x%04x (%d)\n"
  889. " _lt_chsum = 0x%04x\n"
  890. " _lt_code = 0x%04x (%c%c)\n"
  891. " _lt_resv1 = 0x%08lx\n"
  892. ),
  893. src_addr,
  894. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  895. header.size, header.size,
  896. header.count, header.count,
  897. header.checksum,
  898. header.code, header.code >> 8, header.code & 0xff,
  899. header.signature
  900. );
  901. #elif (LT_PRINT_TEST==3) //arduino print/println (leading zeros not solved)
  902. MYSERIAL.print(" _src_addr = 0x");
  903. MYSERIAL.println(src_addr, 16);
  904. MYSERIAL.print(" _lt_magic = 0x");
  905. MYSERIAL.print(header.magic, 16);
  906. MYSERIAL.println((header.magic==LANG_MAGIC)?" OK":" NA");
  907. MYSERIAL.print(" _lt_size = 0x");
  908. MYSERIAL.print(header.size, 16);
  909. MYSERIAL.print(" (");
  910. MYSERIAL.print(header.size, 10);
  911. MYSERIAL.println(")");
  912. MYSERIAL.print(" _lt_count = 0x");
  913. MYSERIAL.print(header.count, 16);
  914. MYSERIAL.print(" (");
  915. MYSERIAL.print(header.count, 10);
  916. MYSERIAL.println(")");
  917. MYSERIAL.print(" _lt_chsum = 0x");
  918. MYSERIAL.println(header.checksum, 16);
  919. MYSERIAL.print(" _lt_code = 0x");
  920. MYSERIAL.print(header.code, 16);
  921. MYSERIAL.print(" (");
  922. MYSERIAL.print((char)(header.code >> 8), 0);
  923. MYSERIAL.print((char)(header.code & 0xff), 0);
  924. MYSERIAL.println(")");
  925. MYSERIAL.print(" _lt_resv1 = 0x");
  926. MYSERIAL.println(header.signature, 16);
  927. #endif //(LT_PRINT_TEST==)
  928. #undef LT_PRINT_TEST
  929. #if 0
  930. w25x20cl_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  931. for (uint16_t i = 0; i < 1024; i++)
  932. {
  933. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  934. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  935. if ((i % 16) == 15) putchar('\n');
  936. }
  937. #endif
  938. uint16_t sum = 0;
  939. for (uint16_t i = 0; i < header.size; i++)
  940. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  941. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  942. sum -= header.checksum; //subtract checksum
  943. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  944. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  945. if (sum == header.checksum)
  946. printf_P(_n("Checksum OK\n"), sum);
  947. else
  948. printf_P(_n("Checksum NG\n"), sum);
  949. }
  950. else
  951. printf_P(_n("lang_get_header failed!\n"));
  952. #if 0
  953. for (uint16_t i = 0; i < 1024*10; i++)
  954. {
  955. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  956. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  957. if ((i % 16) == 15) putchar('\n');
  958. }
  959. #endif
  960. #if 0
  961. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  962. for (int i = 0; i < 4096; ++i) {
  963. int b = eeprom_read_byte((unsigned char*)i);
  964. if (b != 255) {
  965. SERIAL_ECHO(i);
  966. SERIAL_ECHO(":");
  967. SERIAL_ECHO(b);
  968. SERIAL_ECHOLN("");
  969. }
  970. }
  971. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  972. #endif
  973. #endif //DEBUG_SEC_LANG
  974. // Check startup - does nothing if bootloader sets MCUSR to 0
  975. byte mcu = MCUSR;
  976. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  977. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  978. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  979. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  980. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  981. if (mcu & 1) puts_P(MSG_POWERUP);
  982. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  983. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  984. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  985. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  986. MCUSR = 0;
  987. //SERIAL_ECHORPGM(MSG_MARLIN);
  988. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  989. #ifdef STRING_VERSION_CONFIG_H
  990. #ifdef STRING_CONFIG_H_AUTHOR
  991. SERIAL_ECHO_START;
  992. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  993. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  994. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  995. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  996. SERIAL_ECHOPGM("Compiled: ");
  997. SERIAL_ECHOLNPGM(__DATE__);
  998. #endif
  999. #endif
  1000. SERIAL_ECHO_START;
  1001. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1002. SERIAL_ECHO(freeMemory());
  1003. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1004. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1005. //lcd_update_enable(false); // why do we need this?? - andre
  1006. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1007. bool previous_settings_retrieved = false;
  1008. uint8_t hw_changed = check_printer_version();
  1009. if (!(hw_changed & 0b10)) { //if printer version wasn't changed, check for eeprom version and retrieve settings from eeprom in case that version wasn't changed
  1010. previous_settings_retrieved = Config_RetrieveSettings();
  1011. }
  1012. else { //printer version was changed so use default settings
  1013. Config_ResetDefault();
  1014. }
  1015. SdFatUtil::set_stack_guard(); //writes magic number at the end of static variables to protect against overwriting static memory by stack
  1016. tp_init(); // Initialize temperature loop
  1017. if (w25x20cl_success) lcd_splash(); // we need to do this again, because tp_init() kills lcd
  1018. else
  1019. {
  1020. w25x20cl_err_msg();
  1021. printf_P(_n("W25X20CL not responding.\n"));
  1022. }
  1023. plan_init(); // Initialize planner;
  1024. factory_reset();
  1025. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  1026. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff)
  1027. {
  1028. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  1029. // where all the EEPROM entries are set to 0x0ff.
  1030. // Once a firmware boots up, it forces at least a language selection, which changes
  1031. // EEPROM_LANG to number lower than 0x0ff.
  1032. // 1) Set a high power mode.
  1033. eeprom_update_byte((uint8_t*)EEPROM_SILENT, SILENT_MODE_OFF);
  1034. #ifdef TMC2130
  1035. tmc2130_mode = TMC2130_MODE_NORMAL;
  1036. #endif //TMC2130
  1037. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  1038. }
  1039. lcd_encoder_diff=0;
  1040. #ifdef TMC2130
  1041. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1042. if (silentMode == 0xff) silentMode = 0;
  1043. tmc2130_mode = TMC2130_MODE_NORMAL;
  1044. if (lcd_crash_detect_enabled() && !farm_mode)
  1045. {
  1046. lcd_crash_detect_enable();
  1047. puts_P(_N("CrashDetect ENABLED!"));
  1048. }
  1049. else
  1050. {
  1051. lcd_crash_detect_disable();
  1052. puts_P(_N("CrashDetect DISABLED"));
  1053. }
  1054. #ifdef TMC2130_LINEARITY_CORRECTION
  1055. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1056. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1057. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1058. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1059. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1060. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1061. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1062. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1063. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1064. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1065. #endif //TMC2130_LINEARITY_CORRECTION
  1066. #ifdef TMC2130_VARIABLE_RESOLUTION
  1067. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1068. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1069. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1070. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1071. #else //TMC2130_VARIABLE_RESOLUTION
  1072. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1073. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1074. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1075. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1076. #endif //TMC2130_VARIABLE_RESOLUTION
  1077. #endif //TMC2130
  1078. st_init(); // Initialize stepper, this enables interrupts!
  1079. #ifdef TMC2130
  1080. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1081. update_mode_profile();
  1082. tmc2130_init();
  1083. #endif //TMC2130
  1084. #ifdef PSU_Delta
  1085. init_force_z(); // ! important for correct Z-axis initialization
  1086. #endif // PSU_Delta
  1087. setup_photpin();
  1088. servo_init();
  1089. // Reset the machine correction matrix.
  1090. // It does not make sense to load the correction matrix until the machine is homed.
  1091. world2machine_reset();
  1092. #ifdef FILAMENT_SENSOR
  1093. fsensor_init();
  1094. #endif //FILAMENT_SENSOR
  1095. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1096. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1097. #endif
  1098. setup_homepin();
  1099. #if defined(Z_AXIS_ALWAYS_ON)
  1100. enable_z();
  1101. #endif
  1102. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  1103. EEPROM_read_B(EEPROM_FARM_NUMBER, &farm_no);
  1104. if ((farm_mode == 0xFF && farm_no == 0) || (farm_no == static_cast<int>(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
  1105. if (farm_no == static_cast<int>(0xFFFF)) farm_no = 0;
  1106. if (farm_mode)
  1107. {
  1108. prusa_statistics(8);
  1109. }
  1110. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1111. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1112. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1113. // but this times out if a blocking dialog is shown in setup().
  1114. card.initsd();
  1115. #ifdef DEBUG_SD_SPEED_TEST
  1116. if (card.cardOK)
  1117. {
  1118. uint8_t* buff = (uint8_t*)block_buffer;
  1119. uint32_t block = 0;
  1120. uint32_t sumr = 0;
  1121. uint32_t sumw = 0;
  1122. for (int i = 0; i < 1024; i++)
  1123. {
  1124. uint32_t u = _micros();
  1125. bool res = card.card.readBlock(i, buff);
  1126. u = _micros() - u;
  1127. if (res)
  1128. {
  1129. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1130. sumr += u;
  1131. u = _micros();
  1132. res = card.card.writeBlock(i, buff);
  1133. u = _micros() - u;
  1134. if (res)
  1135. {
  1136. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1137. sumw += u;
  1138. }
  1139. else
  1140. {
  1141. printf_P(PSTR("writeBlock %4d error\n"), i);
  1142. break;
  1143. }
  1144. }
  1145. else
  1146. {
  1147. printf_P(PSTR("readBlock %4d error\n"), i);
  1148. break;
  1149. }
  1150. }
  1151. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1152. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1153. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1154. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1155. }
  1156. else
  1157. printf_P(PSTR("Card NG!\n"));
  1158. #endif //DEBUG_SD_SPEED_TEST
  1159. eeprom_init();
  1160. #ifdef SNMM
  1161. if (eeprom_read_dword((uint32_t*)EEPROM_BOWDEN_LENGTH) == 0x0ffffffff) { //bowden length used for SNMM
  1162. int _z = BOWDEN_LENGTH;
  1163. for(int i = 0; i<4; i++) EEPROM_save_B(EEPROM_BOWDEN_LENGTH + i * 2, &_z);
  1164. }
  1165. #endif
  1166. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1167. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1168. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1169. #if (LANG_MODE != 0) //secondary language support
  1170. #ifdef DEBUG_W25X20CL
  1171. W25X20CL_SPI_ENTER();
  1172. uint8_t uid[8]; // 64bit unique id
  1173. w25x20cl_rd_uid(uid);
  1174. puts_P(_n("W25X20CL UID="));
  1175. for (uint8_t i = 0; i < 8; i ++)
  1176. printf_P(PSTR("%02hhx"), uid[i]);
  1177. putchar('\n');
  1178. list_sec_lang_from_external_flash();
  1179. #endif //DEBUG_W25X20CL
  1180. // lang_reset();
  1181. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1182. lcd_language();
  1183. #ifdef DEBUG_SEC_LANG
  1184. uint16_t sec_lang_code = lang_get_code(1);
  1185. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1186. printf_P(_n("lang_selected=%d\nlang_table=0x%04x\nSEC_LANG_CODE=0x%04x (%c%c)\n"), lang_selected, ui, sec_lang_code, sec_lang_code >> 8, sec_lang_code & 0xff);
  1187. lang_print_sec_lang(uartout);
  1188. #endif //DEBUG_SEC_LANG
  1189. #endif //(LANG_MODE != 0)
  1190. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  1191. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1192. temp_cal_active = false;
  1193. } else temp_cal_active = eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE);
  1194. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1195. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1196. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1197. int16_t z_shift = 0;
  1198. for (uint8_t i = 0; i < 5; i++) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  1199. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1200. temp_cal_active = false;
  1201. }
  1202. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 255) {
  1203. eeprom_write_byte((uint8_t*)EEPROM_UVLO, 0);
  1204. }
  1205. if (eeprom_read_byte((uint8_t*)EEPROM_SD_SORT) == 255) {
  1206. eeprom_write_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1207. }
  1208. //mbl_mode_init();
  1209. mbl_settings_init();
  1210. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1211. if (SilentModeMenu_MMU == 255) {
  1212. SilentModeMenu_MMU = 1;
  1213. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1214. }
  1215. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1216. setup_fan_interrupt();
  1217. #endif //DEBUG_DISABLE_FANCHECK
  1218. #ifdef PAT9125
  1219. fsensor_setup_interrupt();
  1220. #endif //PAT9125
  1221. for (int i = 0; i<4; i++) EEPROM_read_B(EEPROM_BOWDEN_LENGTH + i * 2, &bowden_length[i]);
  1222. #ifndef DEBUG_DISABLE_STARTMSGS
  1223. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1224. if (!farm_mode) {
  1225. check_if_fw_is_on_right_printer();
  1226. show_fw_version_warnings();
  1227. }
  1228. switch (hw_changed) {
  1229. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1230. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1231. case(0b01):
  1232. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1233. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1234. break;
  1235. case(0b10):
  1236. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1237. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1238. break;
  1239. case(0b11):
  1240. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1241. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1242. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1243. break;
  1244. default: break; //no change, show no message
  1245. }
  1246. if (!previous_settings_retrieved) {
  1247. lcd_show_fullscreen_message_and_wait_P(_i("Old settings found. Default PID, Esteps etc. will be set.")); //if EEPROM version or printer type was changed, inform user that default setting were loaded////MSG_DEFAULT_SETTINGS_LOADED c=20 r=4
  1248. Config_StoreSettings();
  1249. }
  1250. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 1) {
  1251. lcd_wizard(WizState::Run);
  1252. }
  1253. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1254. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1255. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1256. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1257. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1258. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  1259. // Show the message.
  1260. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1261. }
  1262. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1263. // Show the message.
  1264. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1265. lcd_update_enable(true);
  1266. }
  1267. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && temp_cal_active == true && calibration_status_pinda() == false) {
  1268. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1269. lcd_update_enable(true);
  1270. }
  1271. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1272. // Show the message.
  1273. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1274. }
  1275. }
  1276. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1277. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1278. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1279. update_current_firmware_version_to_eeprom();
  1280. lcd_selftest();
  1281. }
  1282. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1283. KEEPALIVE_STATE(IN_PROCESS);
  1284. #endif //DEBUG_DISABLE_STARTMSGS
  1285. lcd_update_enable(true);
  1286. lcd_clear();
  1287. lcd_update(2);
  1288. // Store the currently running firmware into an eeprom,
  1289. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1290. update_current_firmware_version_to_eeprom();
  1291. #ifdef TMC2130
  1292. tmc2130_home_origin[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN);
  1293. tmc2130_home_bsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS);
  1294. tmc2130_home_fsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS);
  1295. if (tmc2130_home_origin[X_AXIS] == 0xff) tmc2130_home_origin[X_AXIS] = 0;
  1296. if (tmc2130_home_bsteps[X_AXIS] == 0xff) tmc2130_home_bsteps[X_AXIS] = 48;
  1297. if (tmc2130_home_fsteps[X_AXIS] == 0xff) tmc2130_home_fsteps[X_AXIS] = 48;
  1298. tmc2130_home_origin[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN);
  1299. tmc2130_home_bsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS);
  1300. tmc2130_home_fsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS);
  1301. if (tmc2130_home_origin[Y_AXIS] == 0xff) tmc2130_home_origin[Y_AXIS] = 0;
  1302. if (tmc2130_home_bsteps[Y_AXIS] == 0xff) tmc2130_home_bsteps[Y_AXIS] = 48;
  1303. if (tmc2130_home_fsteps[Y_AXIS] == 0xff) tmc2130_home_fsteps[Y_AXIS] = 48;
  1304. tmc2130_home_enabled = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED);
  1305. if (tmc2130_home_enabled == 0xff) tmc2130_home_enabled = 0;
  1306. #endif //TMC2130
  1307. #ifdef UVLO_SUPPORT
  1308. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1309. /*
  1310. if (lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1311. else {
  1312. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1313. lcd_update_enable(true);
  1314. lcd_update(2);
  1315. lcd_setstatuspgm(_T(WELCOME_MSG));
  1316. }
  1317. */
  1318. manage_heater(); // Update temperatures
  1319. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1320. printf_P(_N("Power panic detected!\nCurrent bed temp:%d\nSaved bed temp:%d\n"), (int)degBed(), eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED));
  1321. #endif
  1322. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1323. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1324. puts_P(_N("Automatic recovery!"));
  1325. #endif
  1326. recover_print(1);
  1327. }
  1328. else{
  1329. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1330. puts_P(_N("Normal recovery!"));
  1331. #endif
  1332. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) ) recover_print(0);
  1333. else {
  1334. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1335. lcd_update_enable(true);
  1336. lcd_update(2);
  1337. lcd_setstatuspgm(_T(WELCOME_MSG));
  1338. }
  1339. }
  1340. }
  1341. // Only arm the uvlo interrupt _after_ a recovering print has been initialized and
  1342. // the entire state machine initialized.
  1343. setup_uvlo_interrupt();
  1344. #endif //UVLO_SUPPORT
  1345. fCheckModeInit();
  1346. fSetMmuMode(mmu_enabled);
  1347. KEEPALIVE_STATE(NOT_BUSY);
  1348. #ifdef WATCHDOG
  1349. wdt_enable(WDTO_4S);
  1350. #endif //WATCHDOG
  1351. }
  1352. void trace();
  1353. #define CHUNK_SIZE 64 // bytes
  1354. #define SAFETY_MARGIN 1
  1355. char chunk[CHUNK_SIZE+SAFETY_MARGIN];
  1356. int chunkHead = 0;
  1357. void serial_read_stream() {
  1358. setAllTargetHotends(0);
  1359. setTargetBed(0);
  1360. lcd_clear();
  1361. lcd_puts_P(PSTR(" Upload in progress"));
  1362. // first wait for how many bytes we will receive
  1363. uint32_t bytesToReceive;
  1364. // receive the four bytes
  1365. char bytesToReceiveBuffer[4];
  1366. for (int i=0; i<4; i++) {
  1367. int data;
  1368. while ((data = MYSERIAL.read()) == -1) {};
  1369. bytesToReceiveBuffer[i] = data;
  1370. }
  1371. // make it a uint32
  1372. memcpy(&bytesToReceive, &bytesToReceiveBuffer, 4);
  1373. // we're ready, notify the sender
  1374. MYSERIAL.write('+');
  1375. // lock in the routine
  1376. uint32_t receivedBytes = 0;
  1377. while (prusa_sd_card_upload) {
  1378. int i;
  1379. for (i=0; i<CHUNK_SIZE; i++) {
  1380. int data;
  1381. // check if we're not done
  1382. if (receivedBytes == bytesToReceive) {
  1383. break;
  1384. }
  1385. // read the next byte
  1386. while ((data = MYSERIAL.read()) == -1) {};
  1387. receivedBytes++;
  1388. // save it to the chunk
  1389. chunk[i] = data;
  1390. }
  1391. // write the chunk to SD
  1392. card.write_command_no_newline(&chunk[0]);
  1393. // notify the sender we're ready for more data
  1394. MYSERIAL.write('+');
  1395. // for safety
  1396. manage_heater();
  1397. // check if we're done
  1398. if(receivedBytes == bytesToReceive) {
  1399. trace(); // beep
  1400. card.closefile();
  1401. prusa_sd_card_upload = false;
  1402. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1403. }
  1404. }
  1405. }
  1406. /**
  1407. * Output a "busy" message at regular intervals
  1408. * while the machine is not accepting commands.
  1409. */
  1410. void host_keepalive() {
  1411. #ifndef HOST_KEEPALIVE_FEATURE
  1412. return;
  1413. #endif //HOST_KEEPALIVE_FEATURE
  1414. if (farm_mode) return;
  1415. long ms = _millis();
  1416. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1417. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1418. switch (busy_state) {
  1419. case IN_HANDLER:
  1420. case IN_PROCESS:
  1421. SERIAL_ECHO_START;
  1422. SERIAL_ECHOLNPGM("busy: processing");
  1423. break;
  1424. case PAUSED_FOR_USER:
  1425. SERIAL_ECHO_START;
  1426. SERIAL_ECHOLNPGM("busy: paused for user");
  1427. break;
  1428. case PAUSED_FOR_INPUT:
  1429. SERIAL_ECHO_START;
  1430. SERIAL_ECHOLNPGM("busy: paused for input");
  1431. break;
  1432. default:
  1433. break;
  1434. }
  1435. }
  1436. prev_busy_signal_ms = ms;
  1437. }
  1438. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1439. // Before loop(), the setup() function is called by the main() routine.
  1440. void loop()
  1441. {
  1442. KEEPALIVE_STATE(NOT_BUSY);
  1443. if ((usb_printing_counter > 0) && ((_millis()-_usb_timer) > 1000))
  1444. {
  1445. is_usb_printing = true;
  1446. usb_printing_counter--;
  1447. _usb_timer = _millis();
  1448. }
  1449. if (usb_printing_counter == 0)
  1450. {
  1451. is_usb_printing = false;
  1452. }
  1453. if (isPrintPaused && saved_printing_type == PRINTING_TYPE_USB) //keep believing that usb is being printed. Prevents accessing dangerous menus while pausing.
  1454. {
  1455. is_usb_printing = true;
  1456. }
  1457. #ifdef FANCHECK
  1458. if (fan_check_error && isPrintPaused)
  1459. {
  1460. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1461. host_keepalive(); //prevent timeouts since usb processing is disabled until print is resumed. This is for a crude way of pausing a print on all hosts.
  1462. }
  1463. #endif
  1464. if (prusa_sd_card_upload)
  1465. {
  1466. //we read byte-by byte
  1467. serial_read_stream();
  1468. }
  1469. else
  1470. {
  1471. get_command();
  1472. #ifdef SDSUPPORT
  1473. card.checkautostart(false);
  1474. #endif
  1475. if(buflen)
  1476. {
  1477. cmdbuffer_front_already_processed = false;
  1478. #ifdef SDSUPPORT
  1479. if(card.saving)
  1480. {
  1481. // Saving a G-code file onto an SD-card is in progress.
  1482. // Saving starts with M28, saving until M29 is seen.
  1483. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1484. card.write_command(CMDBUFFER_CURRENT_STRING);
  1485. if(card.logging)
  1486. process_commands();
  1487. else
  1488. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1489. } else {
  1490. card.closefile();
  1491. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1492. }
  1493. } else {
  1494. process_commands();
  1495. }
  1496. #else
  1497. process_commands();
  1498. #endif //SDSUPPORT
  1499. if (! cmdbuffer_front_already_processed && buflen)
  1500. {
  1501. // ptr points to the start of the block currently being processed.
  1502. // The first character in the block is the block type.
  1503. char *ptr = cmdbuffer + bufindr;
  1504. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1505. // To support power panic, move the lenght of the command on the SD card to a planner buffer.
  1506. union {
  1507. struct {
  1508. char lo;
  1509. char hi;
  1510. } lohi;
  1511. uint16_t value;
  1512. } sdlen;
  1513. sdlen.value = 0;
  1514. {
  1515. // This block locks the interrupts globally for 3.25 us,
  1516. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1517. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1518. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1519. cli();
  1520. // Reset the command to something, which will be ignored by the power panic routine,
  1521. // so this buffer length will not be counted twice.
  1522. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1523. // Extract the current buffer length.
  1524. sdlen.lohi.lo = *ptr ++;
  1525. sdlen.lohi.hi = *ptr;
  1526. // and pass it to the planner queue.
  1527. planner_add_sd_length(sdlen.value);
  1528. sei();
  1529. }
  1530. }
  1531. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1532. cli();
  1533. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1534. // and one for each command to previous block in the planner queue.
  1535. planner_add_sd_length(1);
  1536. sei();
  1537. }
  1538. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1539. // this block's SD card length will not be counted twice as its command type has been replaced
  1540. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1541. cmdqueue_pop_front();
  1542. }
  1543. host_keepalive();
  1544. }
  1545. }
  1546. //check heater every n milliseconds
  1547. manage_heater();
  1548. isPrintPaused ? manage_inactivity(true) : manage_inactivity(false);
  1549. checkHitEndstops();
  1550. lcd_update(0);
  1551. #ifdef TMC2130
  1552. tmc2130_check_overtemp();
  1553. if (tmc2130_sg_crash)
  1554. {
  1555. uint8_t crash = tmc2130_sg_crash;
  1556. tmc2130_sg_crash = 0;
  1557. // crashdet_stop_and_save_print();
  1558. switch (crash)
  1559. {
  1560. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1561. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1562. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1563. }
  1564. }
  1565. #endif //TMC2130
  1566. mmu_loop();
  1567. }
  1568. #define DEFINE_PGM_READ_ANY(type, reader) \
  1569. static inline type pgm_read_any(const type *p) \
  1570. { return pgm_read_##reader##_near(p); }
  1571. DEFINE_PGM_READ_ANY(float, float);
  1572. DEFINE_PGM_READ_ANY(signed char, byte);
  1573. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1574. static const PROGMEM type array##_P[3] = \
  1575. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1576. static inline type array(int axis) \
  1577. { return pgm_read_any(&array##_P[axis]); } \
  1578. type array##_ext(int axis) \
  1579. { return pgm_read_any(&array##_P[axis]); }
  1580. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1581. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1582. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1583. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1584. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1585. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1586. static void axis_is_at_home(int axis) {
  1587. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1588. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1589. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1590. }
  1591. inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); }
  1592. inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); }
  1593. //! @return original feedmultiply
  1594. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1595. saved_feedrate = feedrate;
  1596. int l_feedmultiply = feedmultiply;
  1597. feedmultiply = 100;
  1598. previous_millis_cmd = _millis();
  1599. enable_endstops(enable_endstops_now);
  1600. return l_feedmultiply;
  1601. }
  1602. //! @param original_feedmultiply feedmultiply to restore
  1603. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1604. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1605. enable_endstops(false);
  1606. #endif
  1607. feedrate = saved_feedrate;
  1608. feedmultiply = original_feedmultiply;
  1609. previous_millis_cmd = _millis();
  1610. }
  1611. #ifdef ENABLE_AUTO_BED_LEVELING
  1612. #ifdef AUTO_BED_LEVELING_GRID
  1613. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1614. {
  1615. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1616. planeNormal.debug("planeNormal");
  1617. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1618. //bedLevel.debug("bedLevel");
  1619. //plan_bed_level_matrix.debug("bed level before");
  1620. //vector_3 uncorrected_position = plan_get_position_mm();
  1621. //uncorrected_position.debug("position before");
  1622. vector_3 corrected_position = plan_get_position();
  1623. // corrected_position.debug("position after");
  1624. current_position[X_AXIS] = corrected_position.x;
  1625. current_position[Y_AXIS] = corrected_position.y;
  1626. current_position[Z_AXIS] = corrected_position.z;
  1627. // put the bed at 0 so we don't go below it.
  1628. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1629. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1630. }
  1631. #else // not AUTO_BED_LEVELING_GRID
  1632. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1633. plan_bed_level_matrix.set_to_identity();
  1634. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1635. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1636. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1637. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1638. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1639. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1640. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1641. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1642. vector_3 corrected_position = plan_get_position();
  1643. current_position[X_AXIS] = corrected_position.x;
  1644. current_position[Y_AXIS] = corrected_position.y;
  1645. current_position[Z_AXIS] = corrected_position.z;
  1646. // put the bed at 0 so we don't go below it.
  1647. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1648. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1649. }
  1650. #endif // AUTO_BED_LEVELING_GRID
  1651. static void run_z_probe() {
  1652. plan_bed_level_matrix.set_to_identity();
  1653. feedrate = homing_feedrate[Z_AXIS];
  1654. // move down until you find the bed
  1655. float zPosition = -10;
  1656. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1657. st_synchronize();
  1658. // we have to let the planner know where we are right now as it is not where we said to go.
  1659. zPosition = st_get_position_mm(Z_AXIS);
  1660. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1661. // move up the retract distance
  1662. zPosition += home_retract_mm(Z_AXIS);
  1663. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1664. st_synchronize();
  1665. // move back down slowly to find bed
  1666. feedrate = homing_feedrate[Z_AXIS]/4;
  1667. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1668. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1669. st_synchronize();
  1670. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1671. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1672. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1673. }
  1674. static void do_blocking_move_to(float x, float y, float z) {
  1675. float oldFeedRate = feedrate;
  1676. feedrate = homing_feedrate[Z_AXIS];
  1677. current_position[Z_AXIS] = z;
  1678. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1679. st_synchronize();
  1680. feedrate = XY_TRAVEL_SPEED;
  1681. current_position[X_AXIS] = x;
  1682. current_position[Y_AXIS] = y;
  1683. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1684. st_synchronize();
  1685. feedrate = oldFeedRate;
  1686. }
  1687. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1688. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1689. }
  1690. /// Probe bed height at position (x,y), returns the measured z value
  1691. static float probe_pt(float x, float y, float z_before) {
  1692. // move to right place
  1693. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1694. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1695. run_z_probe();
  1696. float measured_z = current_position[Z_AXIS];
  1697. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1698. SERIAL_PROTOCOLPGM(" x: ");
  1699. SERIAL_PROTOCOL(x);
  1700. SERIAL_PROTOCOLPGM(" y: ");
  1701. SERIAL_PROTOCOL(y);
  1702. SERIAL_PROTOCOLPGM(" z: ");
  1703. SERIAL_PROTOCOL(measured_z);
  1704. SERIAL_PROTOCOLPGM("\n");
  1705. return measured_z;
  1706. }
  1707. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1708. #ifdef LIN_ADVANCE
  1709. /**
  1710. * M900: Set and/or Get advance K factor
  1711. *
  1712. * K<factor> Set advance K factor
  1713. */
  1714. inline void gcode_M900() {
  1715. float newK = code_seen('K') ? code_value_float() : -2;
  1716. #ifdef LA_NOCOMPAT
  1717. if (newK >= 0 && newK < 10)
  1718. extruder_advance_K = newK;
  1719. else
  1720. SERIAL_ECHOLNPGM("K out of allowed range!");
  1721. #else
  1722. if (newK == 0)
  1723. extruder_advance_K = 0;
  1724. else if (newK == -1)
  1725. la10c_reset();
  1726. else
  1727. {
  1728. newK = la10c_value(newK);
  1729. if (newK < 0)
  1730. SERIAL_ECHOLNPGM("K out of allowed range!");
  1731. else
  1732. extruder_advance_K = newK;
  1733. }
  1734. #endif
  1735. SERIAL_ECHO_START;
  1736. SERIAL_ECHOPGM("Advance K=");
  1737. SERIAL_ECHOLN(extruder_advance_K);
  1738. }
  1739. #endif // LIN_ADVANCE
  1740. bool check_commands() {
  1741. bool end_command_found = false;
  1742. while (buflen)
  1743. {
  1744. if ((code_seen("M84")) || (code_seen("M 84"))) end_command_found = true;
  1745. if (!cmdbuffer_front_already_processed)
  1746. cmdqueue_pop_front();
  1747. cmdbuffer_front_already_processed = false;
  1748. }
  1749. return end_command_found;
  1750. }
  1751. // raise_z_above: slowly raise Z to the requested height
  1752. //
  1753. // contrarily to a simple move, this function will carefully plan a move
  1754. // when the current Z position is unknown. In such cases, stallguard is
  1755. // enabled and will prevent prolonged pushing against the Z tops
  1756. void raise_z_above(float target, bool plan)
  1757. {
  1758. if (current_position[Z_AXIS] >= target)
  1759. return;
  1760. // Z needs raising
  1761. current_position[Z_AXIS] = target;
  1762. #if defined(Z_MIN_PIN) && (Z_MIN_PIN > -1) && !defined(DEBUG_DISABLE_ZMINLIMIT)
  1763. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1764. #else
  1765. bool z_min_endstop = false;
  1766. #endif
  1767. if (axis_known_position[Z_AXIS] || z_min_endstop)
  1768. {
  1769. // current position is known or very low, it's safe to raise Z
  1770. if(plan) plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS], active_extruder);
  1771. return;
  1772. }
  1773. // ensure Z is powered in normal mode to overcome initial load
  1774. enable_z();
  1775. st_synchronize();
  1776. // rely on crashguard to limit damage
  1777. bool z_endstop_enabled = enable_z_endstop(true);
  1778. #ifdef TMC2130
  1779. tmc2130_home_enter(Z_AXIS_MASK);
  1780. #endif //TMC2130
  1781. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  1782. st_synchronize();
  1783. #ifdef TMC2130
  1784. if (endstop_z_hit_on_purpose())
  1785. {
  1786. // not necessarily exact, but will avoid further vertical moves
  1787. current_position[Z_AXIS] = max_pos[Z_AXIS];
  1788. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS],
  1789. current_position[Z_AXIS], current_position[E_AXIS]);
  1790. }
  1791. tmc2130_home_exit();
  1792. #endif //TMC2130
  1793. enable_z_endstop(z_endstop_enabled);
  1794. }
  1795. #ifdef TMC2130
  1796. bool calibrate_z_auto()
  1797. {
  1798. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1799. lcd_clear();
  1800. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1801. bool endstops_enabled = enable_endstops(true);
  1802. int axis_up_dir = -home_dir(Z_AXIS);
  1803. tmc2130_home_enter(Z_AXIS_MASK);
  1804. current_position[Z_AXIS] = 0;
  1805. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1806. set_destination_to_current();
  1807. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1808. feedrate = homing_feedrate[Z_AXIS];
  1809. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / 60, active_extruder);
  1810. st_synchronize();
  1811. // current_position[axis] = 0;
  1812. // plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1813. tmc2130_home_exit();
  1814. enable_endstops(false);
  1815. current_position[Z_AXIS] = 0;
  1816. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1817. set_destination_to_current();
  1818. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1819. feedrate = homing_feedrate[Z_AXIS] / 2;
  1820. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / 60, active_extruder);
  1821. st_synchronize();
  1822. enable_endstops(endstops_enabled);
  1823. if (PRINTER_TYPE == PRINTER_MK3) {
  1824. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1825. }
  1826. else {
  1827. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1828. }
  1829. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1830. return true;
  1831. }
  1832. #endif //TMC2130
  1833. #ifdef TMC2130
  1834. void homeaxis(int axis, uint8_t cnt, uint8_t* pstep)
  1835. #else
  1836. void homeaxis(int axis, uint8_t cnt)
  1837. #endif //TMC2130
  1838. {
  1839. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1840. #define HOMEAXIS_DO(LETTER) \
  1841. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1842. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1843. {
  1844. int axis_home_dir = home_dir(axis);
  1845. feedrate = homing_feedrate[axis];
  1846. #ifdef TMC2130
  1847. tmc2130_home_enter(X_AXIS_MASK << axis);
  1848. #endif //TMC2130
  1849. // Move away a bit, so that the print head does not touch the end position,
  1850. // and the following movement to endstop has a chance to achieve the required velocity
  1851. // for the stall guard to work.
  1852. current_position[axis] = 0;
  1853. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1854. set_destination_to_current();
  1855. // destination[axis] = 11.f;
  1856. destination[axis] = -3.f * axis_home_dir;
  1857. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1858. st_synchronize();
  1859. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1860. endstops_hit_on_purpose();
  1861. enable_endstops(false);
  1862. current_position[axis] = 0;
  1863. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1864. destination[axis] = 1. * axis_home_dir;
  1865. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1866. st_synchronize();
  1867. // Now continue to move up to the left end stop with the collision detection enabled.
  1868. enable_endstops(true);
  1869. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1870. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1871. st_synchronize();
  1872. for (uint8_t i = 0; i < cnt; i++)
  1873. {
  1874. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1875. endstops_hit_on_purpose();
  1876. enable_endstops(false);
  1877. current_position[axis] = 0;
  1878. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1879. destination[axis] = -10.f * axis_home_dir;
  1880. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1881. st_synchronize();
  1882. endstops_hit_on_purpose();
  1883. // Now move left up to the collision, this time with a repeatable velocity.
  1884. enable_endstops(true);
  1885. destination[axis] = 11.f * axis_home_dir;
  1886. #ifdef TMC2130
  1887. feedrate = homing_feedrate[axis];
  1888. #else //TMC2130
  1889. feedrate = homing_feedrate[axis] / 2;
  1890. #endif //TMC2130
  1891. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1892. st_synchronize();
  1893. #ifdef TMC2130
  1894. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1895. if (pstep) pstep[i] = mscnt >> 4;
  1896. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1897. #endif //TMC2130
  1898. }
  1899. endstops_hit_on_purpose();
  1900. enable_endstops(false);
  1901. #ifdef TMC2130
  1902. uint8_t orig = tmc2130_home_origin[axis];
  1903. uint8_t back = tmc2130_home_bsteps[axis];
  1904. if (tmc2130_home_enabled && (orig <= 63))
  1905. {
  1906. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1907. if (back > 0)
  1908. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1909. }
  1910. else
  1911. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1912. tmc2130_home_exit();
  1913. #endif //TMC2130
  1914. axis_is_at_home(axis);
  1915. axis_known_position[axis] = true;
  1916. // Move from minimum
  1917. #ifdef TMC2130
  1918. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1919. #else //TMC2130
  1920. float dist = - axis_home_dir * 0.01f * 64;
  1921. #endif //TMC2130
  1922. current_position[axis] -= dist;
  1923. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1924. current_position[axis] += dist;
  1925. destination[axis] = current_position[axis];
  1926. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], 0.5f*feedrate/60, active_extruder);
  1927. st_synchronize();
  1928. feedrate = 0.0;
  1929. }
  1930. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1931. {
  1932. #ifdef TMC2130
  1933. FORCE_HIGH_POWER_START;
  1934. #endif
  1935. int axis_home_dir = home_dir(axis);
  1936. current_position[axis] = 0;
  1937. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1938. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1939. feedrate = homing_feedrate[axis];
  1940. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1941. st_synchronize();
  1942. #ifdef TMC2130
  1943. if (READ(Z_TMC2130_DIAG) != 0) { //Z crash
  1944. FORCE_HIGH_POWER_END;
  1945. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1946. return;
  1947. }
  1948. #endif //TMC2130
  1949. current_position[axis] = 0;
  1950. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1951. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1952. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1953. st_synchronize();
  1954. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1955. feedrate = homing_feedrate[axis]/2 ;
  1956. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1957. st_synchronize();
  1958. #ifdef TMC2130
  1959. if (READ(Z_TMC2130_DIAG) != 0) { //Z crash
  1960. FORCE_HIGH_POWER_END;
  1961. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1962. return;
  1963. }
  1964. #endif //TMC2130
  1965. axis_is_at_home(axis);
  1966. destination[axis] = current_position[axis];
  1967. feedrate = 0.0;
  1968. endstops_hit_on_purpose();
  1969. axis_known_position[axis] = true;
  1970. #ifdef TMC2130
  1971. FORCE_HIGH_POWER_END;
  1972. #endif
  1973. }
  1974. enable_endstops(endstops_enabled);
  1975. }
  1976. /**/
  1977. void home_xy()
  1978. {
  1979. set_destination_to_current();
  1980. homeaxis(X_AXIS);
  1981. homeaxis(Y_AXIS);
  1982. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1983. endstops_hit_on_purpose();
  1984. }
  1985. void refresh_cmd_timeout(void)
  1986. {
  1987. previous_millis_cmd = _millis();
  1988. }
  1989. #ifdef FWRETRACT
  1990. void retract(bool retracting, bool swapretract = false) {
  1991. if(retracting && !retracted[active_extruder]) {
  1992. destination[X_AXIS]=current_position[X_AXIS];
  1993. destination[Y_AXIS]=current_position[Y_AXIS];
  1994. destination[Z_AXIS]=current_position[Z_AXIS];
  1995. destination[E_AXIS]=current_position[E_AXIS];
  1996. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  1997. plan_set_e_position(current_position[E_AXIS]);
  1998. float oldFeedrate = feedrate;
  1999. feedrate=cs.retract_feedrate*60;
  2000. retracted[active_extruder]=true;
  2001. prepare_move();
  2002. current_position[Z_AXIS]-=cs.retract_zlift;
  2003. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2004. prepare_move();
  2005. feedrate = oldFeedrate;
  2006. } else if(!retracting && retracted[active_extruder]) {
  2007. destination[X_AXIS]=current_position[X_AXIS];
  2008. destination[Y_AXIS]=current_position[Y_AXIS];
  2009. destination[Z_AXIS]=current_position[Z_AXIS];
  2010. destination[E_AXIS]=current_position[E_AXIS];
  2011. current_position[Z_AXIS]+=cs.retract_zlift;
  2012. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2013. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  2014. plan_set_e_position(current_position[E_AXIS]);
  2015. float oldFeedrate = feedrate;
  2016. feedrate=cs.retract_recover_feedrate*60;
  2017. retracted[active_extruder]=false;
  2018. prepare_move();
  2019. feedrate = oldFeedrate;
  2020. }
  2021. } //retract
  2022. #endif //FWRETRACT
  2023. void trace() {
  2024. Sound_MakeCustom(25,440,true);
  2025. }
  2026. /*
  2027. void ramming() {
  2028. // float tmp[4] = DEFAULT_MAX_FEEDRATE;
  2029. if (current_temperature[0] < 230) {
  2030. //PLA
  2031. max_feedrate[E_AXIS] = 50;
  2032. //current_position[E_AXIS] -= 8;
  2033. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2034. //current_position[E_AXIS] += 8;
  2035. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2036. current_position[E_AXIS] += 5.4;
  2037. plan_buffer_line_curposXYZE(2800 / 60, active_extruder);
  2038. current_position[E_AXIS] += 3.2;
  2039. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  2040. current_position[E_AXIS] += 3;
  2041. plan_buffer_line_curposXYZE(3400 / 60, active_extruder);
  2042. st_synchronize();
  2043. max_feedrate[E_AXIS] = 80;
  2044. current_position[E_AXIS] -= 82;
  2045. plan_buffer_line_curposXYZE(9500 / 60, active_extruder);
  2046. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  2047. current_position[E_AXIS] -= 20;
  2048. plan_buffer_line_curposXYZE(1200 / 60, active_extruder);
  2049. current_position[E_AXIS] += 5;
  2050. plan_buffer_line_curposXYZE(400 / 60, active_extruder);
  2051. current_position[E_AXIS] += 5;
  2052. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2053. current_position[E_AXIS] -= 10;
  2054. st_synchronize();
  2055. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2056. current_position[E_AXIS] += 10;
  2057. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2058. current_position[E_AXIS] -= 10;
  2059. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2060. current_position[E_AXIS] += 10;
  2061. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2062. current_position[E_AXIS] -= 10;
  2063. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2064. st_synchronize();
  2065. }
  2066. else {
  2067. //ABS
  2068. max_feedrate[E_AXIS] = 50;
  2069. //current_position[E_AXIS] -= 8;
  2070. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2071. //current_position[E_AXIS] += 8;
  2072. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2073. current_position[E_AXIS] += 3.1;
  2074. plan_buffer_line_curposXYZE(2000 / 60, active_extruder);
  2075. current_position[E_AXIS] += 3.1;
  2076. plan_buffer_line_curposXYZE(2500 / 60, active_extruder);
  2077. current_position[E_AXIS] += 4;
  2078. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  2079. st_synchronize();
  2080. //current_position[X_AXIS] += 23; //delay
  2081. //plan_buffer_line_curposXYZE(600/60, active_extruder); //delay
  2082. //current_position[X_AXIS] -= 23; //delay
  2083. //plan_buffer_line_curposXYZE(600/60, active_extruder); //delay
  2084. _delay(4700);
  2085. max_feedrate[E_AXIS] = 80;
  2086. current_position[E_AXIS] -= 92;
  2087. plan_buffer_line_curposXYZE(9900 / 60, active_extruder);
  2088. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  2089. current_position[E_AXIS] -= 5;
  2090. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2091. current_position[E_AXIS] += 5;
  2092. plan_buffer_line_curposXYZE(400 / 60, active_extruder);
  2093. current_position[E_AXIS] -= 5;
  2094. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2095. st_synchronize();
  2096. current_position[E_AXIS] += 5;
  2097. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2098. current_position[E_AXIS] -= 5;
  2099. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2100. current_position[E_AXIS] += 5;
  2101. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2102. current_position[E_AXIS] -= 5;
  2103. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2104. st_synchronize();
  2105. }
  2106. }
  2107. */
  2108. #ifdef TMC2130
  2109. void force_high_power_mode(bool start_high_power_section) {
  2110. #ifdef PSU_Delta
  2111. if (start_high_power_section == true) enable_force_z();
  2112. #endif //PSU_Delta
  2113. uint8_t silent;
  2114. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2115. if (silent == 1) {
  2116. //we are in silent mode, set to normal mode to enable crash detection
  2117. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2118. st_synchronize();
  2119. cli();
  2120. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2121. update_mode_profile();
  2122. tmc2130_init();
  2123. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2124. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2125. st_reset_timer();
  2126. sei();
  2127. }
  2128. }
  2129. #endif //TMC2130
  2130. #ifdef TMC2130
  2131. static void gcode_G28(bool home_x_axis, long home_x_value, bool home_y_axis, long home_y_value, bool home_z_axis, long home_z_value, bool calib, bool without_mbl)
  2132. #else
  2133. static void gcode_G28(bool home_x_axis, long home_x_value, bool home_y_axis, long home_y_value, bool home_z_axis, long home_z_value, bool without_mbl)
  2134. #endif //TMC2130
  2135. {
  2136. st_synchronize();
  2137. #if 0
  2138. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2139. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2140. #endif
  2141. // Flag for the display update routine and to disable the print cancelation during homing.
  2142. homing_flag = true;
  2143. // Which axes should be homed?
  2144. bool home_x = home_x_axis;
  2145. bool home_y = home_y_axis;
  2146. bool home_z = home_z_axis;
  2147. // Either all X,Y,Z codes are present, or none of them.
  2148. bool home_all_axes = home_x == home_y && home_x == home_z;
  2149. if (home_all_axes)
  2150. // No X/Y/Z code provided means to home all axes.
  2151. home_x = home_y = home_z = true;
  2152. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2153. if (home_all_axes) {
  2154. raise_z_above(MESH_HOME_Z_SEARCH);
  2155. st_synchronize();
  2156. }
  2157. #ifdef ENABLE_AUTO_BED_LEVELING
  2158. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2159. #endif //ENABLE_AUTO_BED_LEVELING
  2160. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2161. // the planner will not perform any adjustments in the XY plane.
  2162. // Wait for the motors to stop and update the current position with the absolute values.
  2163. world2machine_revert_to_uncorrected();
  2164. // For mesh bed leveling deactivate the matrix temporarily.
  2165. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2166. // in a single axis only.
  2167. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2168. #ifdef MESH_BED_LEVELING
  2169. uint8_t mbl_was_active = mbl.active;
  2170. mbl.active = 0;
  2171. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2172. #endif
  2173. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  2174. // consumed during the first movements following this statement.
  2175. if (home_z)
  2176. babystep_undo();
  2177. saved_feedrate = feedrate;
  2178. int l_feedmultiply = feedmultiply;
  2179. feedmultiply = 100;
  2180. previous_millis_cmd = _millis();
  2181. enable_endstops(true);
  2182. memcpy(destination, current_position, sizeof(destination));
  2183. feedrate = 0.0;
  2184. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2185. if(home_z)
  2186. homeaxis(Z_AXIS);
  2187. #endif
  2188. #ifdef QUICK_HOME
  2189. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2190. if(home_x && home_y) //first diagonal move
  2191. {
  2192. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2193. int x_axis_home_dir = home_dir(X_AXIS);
  2194. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2195. 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);
  2196. feedrate = homing_feedrate[X_AXIS];
  2197. if(homing_feedrate[Y_AXIS]<feedrate)
  2198. feedrate = homing_feedrate[Y_AXIS];
  2199. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2200. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2201. } else {
  2202. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2203. }
  2204. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  2205. st_synchronize();
  2206. axis_is_at_home(X_AXIS);
  2207. axis_is_at_home(Y_AXIS);
  2208. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2209. destination[X_AXIS] = current_position[X_AXIS];
  2210. destination[Y_AXIS] = current_position[Y_AXIS];
  2211. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  2212. feedrate = 0.0;
  2213. st_synchronize();
  2214. endstops_hit_on_purpose();
  2215. current_position[X_AXIS] = destination[X_AXIS];
  2216. current_position[Y_AXIS] = destination[Y_AXIS];
  2217. current_position[Z_AXIS] = destination[Z_AXIS];
  2218. }
  2219. #endif /* QUICK_HOME */
  2220. #ifdef TMC2130
  2221. if(home_x)
  2222. {
  2223. if (!calib)
  2224. homeaxis(X_AXIS);
  2225. else
  2226. tmc2130_home_calibrate(X_AXIS);
  2227. }
  2228. if(home_y)
  2229. {
  2230. if (!calib)
  2231. homeaxis(Y_AXIS);
  2232. else
  2233. tmc2130_home_calibrate(Y_AXIS);
  2234. }
  2235. #else //TMC2130
  2236. if(home_x) homeaxis(X_AXIS);
  2237. if(home_y) homeaxis(Y_AXIS);
  2238. #endif //TMC2130
  2239. if(home_x_axis && home_x_value != 0)
  2240. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2241. if(home_y_axis && home_y_value != 0)
  2242. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2243. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2244. #ifndef Z_SAFE_HOMING
  2245. if(home_z) {
  2246. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2247. raise_z_above(Z_RAISE_BEFORE_HOMING);
  2248. st_synchronize();
  2249. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2250. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP)) // If Mesh bed leveling, move X&Y to safe position for home
  2251. raise_z_above(MESH_HOME_Z_SEARCH);
  2252. st_synchronize();
  2253. if (!axis_known_position[X_AXIS]) homeaxis(X_AXIS);
  2254. if (!axis_known_position[Y_AXIS]) homeaxis(Y_AXIS);
  2255. // 1st mesh bed leveling measurement point, corrected.
  2256. world2machine_initialize();
  2257. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2258. world2machine_reset();
  2259. if (destination[Y_AXIS] < Y_MIN_POS)
  2260. destination[Y_AXIS] = Y_MIN_POS;
  2261. feedrate = homing_feedrate[X_AXIS] / 20;
  2262. enable_endstops(false);
  2263. #ifdef DEBUG_BUILD
  2264. SERIAL_ECHOLNPGM("plan_set_position()");
  2265. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2266. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2267. #endif
  2268. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2269. #ifdef DEBUG_BUILD
  2270. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2271. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2272. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2273. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2274. #endif
  2275. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2276. st_synchronize();
  2277. current_position[X_AXIS] = destination[X_AXIS];
  2278. current_position[Y_AXIS] = destination[Y_AXIS];
  2279. enable_endstops(true);
  2280. endstops_hit_on_purpose();
  2281. homeaxis(Z_AXIS);
  2282. #else // MESH_BED_LEVELING
  2283. homeaxis(Z_AXIS);
  2284. #endif // MESH_BED_LEVELING
  2285. }
  2286. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2287. if(home_all_axes) {
  2288. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2289. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2290. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2291. feedrate = XY_TRAVEL_SPEED/60;
  2292. current_position[Z_AXIS] = 0;
  2293. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2294. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2295. st_synchronize();
  2296. current_position[X_AXIS] = destination[X_AXIS];
  2297. current_position[Y_AXIS] = destination[Y_AXIS];
  2298. homeaxis(Z_AXIS);
  2299. }
  2300. // Let's see if X and Y are homed and probe is inside bed area.
  2301. if(home_z) {
  2302. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2303. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2304. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2305. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2306. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2307. current_position[Z_AXIS] = 0;
  2308. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2309. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2310. feedrate = max_feedrate[Z_AXIS];
  2311. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2312. st_synchronize();
  2313. homeaxis(Z_AXIS);
  2314. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2315. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2316. SERIAL_ECHO_START;
  2317. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2318. } else {
  2319. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2320. SERIAL_ECHO_START;
  2321. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2322. }
  2323. }
  2324. #endif // Z_SAFE_HOMING
  2325. #endif // Z_HOME_DIR < 0
  2326. if(home_z_axis && home_z_value != 0)
  2327. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2328. #ifdef ENABLE_AUTO_BED_LEVELING
  2329. if(home_z)
  2330. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2331. #endif
  2332. // Set the planner and stepper routine positions.
  2333. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2334. // contains the machine coordinates.
  2335. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2336. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  2337. enable_endstops(false);
  2338. #endif
  2339. feedrate = saved_feedrate;
  2340. feedmultiply = l_feedmultiply;
  2341. previous_millis_cmd = _millis();
  2342. endstops_hit_on_purpose();
  2343. #ifndef MESH_BED_LEVELING
  2344. //-// Oct 2019 :: this part of code is (from) now probably un-compilable
  2345. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  2346. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  2347. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  2348. lcd_adjust_z();
  2349. #endif
  2350. // Load the machine correction matrix
  2351. world2machine_initialize();
  2352. // and correct the current_position XY axes to match the transformed coordinate system.
  2353. world2machine_update_current();
  2354. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP))
  2355. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2356. {
  2357. if (! home_z && mbl_was_active) {
  2358. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2359. mbl.active = true;
  2360. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2361. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2362. }
  2363. }
  2364. else
  2365. {
  2366. st_synchronize();
  2367. homing_flag = false;
  2368. }
  2369. #endif
  2370. if (farm_mode) { prusa_statistics(20); };
  2371. homing_flag = false;
  2372. #if 0
  2373. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2374. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2375. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2376. #endif
  2377. }
  2378. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2379. {
  2380. #ifdef TMC2130
  2381. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2382. #else
  2383. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2384. #endif //TMC2130
  2385. }
  2386. void adjust_bed_reset()
  2387. {
  2388. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2389. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2390. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2391. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2392. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2393. }
  2394. //! @brief Calibrate XYZ
  2395. //! @param onlyZ if true, calibrate only Z axis
  2396. //! @param verbosity_level
  2397. //! @retval true Succeeded
  2398. //! @retval false Failed
  2399. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2400. {
  2401. bool final_result = false;
  2402. #ifdef TMC2130
  2403. FORCE_HIGH_POWER_START;
  2404. #endif // TMC2130
  2405. FORCE_BL_ON_START;
  2406. // Only Z calibration?
  2407. if (!onlyZ)
  2408. {
  2409. setTargetBed(0);
  2410. setAllTargetHotends(0);
  2411. adjust_bed_reset(); //reset bed level correction
  2412. }
  2413. // Disable the default update procedure of the display. We will do a modal dialog.
  2414. lcd_update_enable(false);
  2415. // Let the planner use the uncorrected coordinates.
  2416. mbl.reset();
  2417. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2418. // the planner will not perform any adjustments in the XY plane.
  2419. // Wait for the motors to stop and update the current position with the absolute values.
  2420. world2machine_revert_to_uncorrected();
  2421. // Reset the baby step value applied without moving the axes.
  2422. babystep_reset();
  2423. // Mark all axes as in a need for homing.
  2424. memset(axis_known_position, 0, sizeof(axis_known_position));
  2425. // Home in the XY plane.
  2426. //set_destination_to_current();
  2427. int l_feedmultiply = setup_for_endstop_move();
  2428. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2429. home_xy();
  2430. enable_endstops(false);
  2431. current_position[X_AXIS] += 5;
  2432. current_position[Y_AXIS] += 5;
  2433. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40, active_extruder);
  2434. st_synchronize();
  2435. // Let the user move the Z axes up to the end stoppers.
  2436. #ifdef TMC2130
  2437. if (calibrate_z_auto())
  2438. {
  2439. #else //TMC2130
  2440. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2441. {
  2442. #endif //TMC2130
  2443. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2444. if(onlyZ){
  2445. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2446. lcd_set_cursor(0, 3);
  2447. lcd_print(1);
  2448. lcd_puts_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE2));
  2449. }else{
  2450. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2451. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2452. lcd_set_cursor(0, 2);
  2453. lcd_print(1);
  2454. lcd_puts_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE2));
  2455. }
  2456. refresh_cmd_timeout();
  2457. #ifndef STEEL_SHEET
  2458. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2459. {
  2460. lcd_wait_for_cool_down();
  2461. }
  2462. #endif //STEEL_SHEET
  2463. if(!onlyZ)
  2464. {
  2465. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2466. #ifdef STEEL_SHEET
  2467. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  2468. if(result) lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2469. #endif //STEEL_SHEET
  2470. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2471. KEEPALIVE_STATE(IN_HANDLER);
  2472. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2473. lcd_set_cursor(0, 2);
  2474. lcd_print(1);
  2475. lcd_puts_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE2));
  2476. }
  2477. bool endstops_enabled = enable_endstops(false);
  2478. current_position[Z_AXIS] -= 1; //move 1mm down with disabled endstop
  2479. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40, active_extruder);
  2480. st_synchronize();
  2481. // Move the print head close to the bed.
  2482. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2483. enable_endstops(true);
  2484. #ifdef TMC2130
  2485. tmc2130_home_enter(Z_AXIS_MASK);
  2486. #endif //TMC2130
  2487. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40, active_extruder);
  2488. st_synchronize();
  2489. #ifdef TMC2130
  2490. tmc2130_home_exit();
  2491. #endif //TMC2130
  2492. enable_endstops(endstops_enabled);
  2493. if ((st_get_position_mm(Z_AXIS) <= (MESH_HOME_Z_SEARCH + HOME_Z_SEARCH_THRESHOLD)) &&
  2494. (st_get_position_mm(Z_AXIS) >= (MESH_HOME_Z_SEARCH - HOME_Z_SEARCH_THRESHOLD)))
  2495. {
  2496. if (onlyZ)
  2497. {
  2498. clean_up_after_endstop_move(l_feedmultiply);
  2499. // Z only calibration.
  2500. // Load the machine correction matrix
  2501. world2machine_initialize();
  2502. // and correct the current_position to match the transformed coordinate system.
  2503. world2machine_update_current();
  2504. //FIXME
  2505. bool result = sample_mesh_and_store_reference();
  2506. if (result)
  2507. {
  2508. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2509. // Shipped, the nozzle height has been set already. The user can start printing now.
  2510. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2511. final_result = true;
  2512. // babystep_apply();
  2513. }
  2514. }
  2515. else
  2516. {
  2517. // Reset the baby step value and the baby step applied flag.
  2518. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2519. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  2520. // Complete XYZ calibration.
  2521. uint8_t point_too_far_mask = 0;
  2522. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2523. clean_up_after_endstop_move(l_feedmultiply);
  2524. // Print head up.
  2525. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2526. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40, active_extruder);
  2527. st_synchronize();
  2528. //#ifndef NEW_XYZCAL
  2529. if (result >= 0)
  2530. {
  2531. #ifdef HEATBED_V2
  2532. sample_z();
  2533. #else //HEATBED_V2
  2534. point_too_far_mask = 0;
  2535. // Second half: The fine adjustment.
  2536. // Let the planner use the uncorrected coordinates.
  2537. mbl.reset();
  2538. world2machine_reset();
  2539. // Home in the XY plane.
  2540. int l_feedmultiply = setup_for_endstop_move();
  2541. home_xy();
  2542. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2543. clean_up_after_endstop_move(l_feedmultiply);
  2544. // Print head up.
  2545. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2546. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40, active_extruder);
  2547. st_synchronize();
  2548. // if (result >= 0) babystep_apply();
  2549. #endif //HEATBED_V2
  2550. }
  2551. //#endif //NEW_XYZCAL
  2552. lcd_update_enable(true);
  2553. lcd_update(2);
  2554. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2555. if (result >= 0)
  2556. {
  2557. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2558. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2559. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2560. final_result = true;
  2561. }
  2562. }
  2563. #ifdef TMC2130
  2564. tmc2130_home_exit();
  2565. #endif
  2566. }
  2567. else
  2568. {
  2569. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2570. final_result = false;
  2571. }
  2572. }
  2573. else
  2574. {
  2575. // Timeouted.
  2576. }
  2577. lcd_update_enable(true);
  2578. #ifdef TMC2130
  2579. FORCE_HIGH_POWER_END;
  2580. #endif // TMC2130
  2581. FORCE_BL_ON_END;
  2582. return final_result;
  2583. }
  2584. void gcode_M114()
  2585. {
  2586. SERIAL_PROTOCOLPGM("X:");
  2587. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2588. SERIAL_PROTOCOLPGM(" Y:");
  2589. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2590. SERIAL_PROTOCOLPGM(" Z:");
  2591. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2592. SERIAL_PROTOCOLPGM(" E:");
  2593. SERIAL_PROTOCOL(current_position[E_AXIS]);
  2594. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  2595. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  2596. SERIAL_PROTOCOLPGM(" Y:");
  2597. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  2598. SERIAL_PROTOCOLPGM(" Z:");
  2599. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  2600. SERIAL_PROTOCOLPGM(" E:");
  2601. SERIAL_PROTOCOL(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  2602. SERIAL_PROTOCOLLN("");
  2603. }
  2604. //! extracted code to compute z_shift for M600 in case of filament change operation
  2605. //! requested from fsensors.
  2606. //! The function ensures, that the printhead lifts to at least 25mm above the heat bed
  2607. //! unlike the previous implementation, which was adding 25mm even when the head was
  2608. //! printing at e.g. 24mm height.
  2609. //! A safety margin of FILAMENTCHANGE_ZADD is added in all cases to avoid touching
  2610. //! the printout.
  2611. //! This function is templated to enable fast change of computation data type.
  2612. //! @return new z_shift value
  2613. template<typename T>
  2614. static T gcode_M600_filament_change_z_shift()
  2615. {
  2616. #ifdef FILAMENTCHANGE_ZADD
  2617. static_assert(Z_MAX_POS < (255 - FILAMENTCHANGE_ZADD), "Z-range too high, change the T type from uint8_t to uint16_t");
  2618. // avoid floating point arithmetics when not necessary - results in shorter code
  2619. T ztmp = T( current_position[Z_AXIS] );
  2620. T z_shift = 0;
  2621. if(ztmp < T(25)){
  2622. z_shift = T(25) - ztmp; // make sure to be at least 25mm above the heat bed
  2623. }
  2624. return z_shift + T(FILAMENTCHANGE_ZADD); // always move above printout
  2625. #else
  2626. return T(0);
  2627. #endif
  2628. }
  2629. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/)
  2630. {
  2631. st_synchronize();
  2632. float lastpos[4];
  2633. if (farm_mode)
  2634. {
  2635. prusa_statistics(22);
  2636. }
  2637. //First backup current position and settings
  2638. int feedmultiplyBckp = feedmultiply;
  2639. float HotendTempBckp = degTargetHotend(active_extruder);
  2640. int fanSpeedBckp = fanSpeed;
  2641. lastpos[X_AXIS] = current_position[X_AXIS];
  2642. lastpos[Y_AXIS] = current_position[Y_AXIS];
  2643. lastpos[Z_AXIS] = current_position[Z_AXIS];
  2644. lastpos[E_AXIS] = current_position[E_AXIS];
  2645. //Retract E
  2646. current_position[E_AXIS] += e_shift;
  2647. plan_buffer_line_curposXYZE(FILAMENTCHANGE_RFEED, active_extruder);
  2648. st_synchronize();
  2649. //Lift Z
  2650. current_position[Z_AXIS] += z_shift;
  2651. plan_buffer_line_curposXYZE(FILAMENTCHANGE_ZFEED, active_extruder);
  2652. st_synchronize();
  2653. //Move XY to side
  2654. current_position[X_AXIS] = x_position;
  2655. current_position[Y_AXIS] = y_position;
  2656. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED, active_extruder);
  2657. st_synchronize();
  2658. //Beep, manage nozzle heater and wait for user to start unload filament
  2659. if(!mmu_enabled) M600_wait_for_user(HotendTempBckp);
  2660. lcd_change_fil_state = 0;
  2661. // Unload filament
  2662. if (mmu_enabled) extr_unload(); //unload just current filament for multimaterial printers (used also in M702)
  2663. else unload_filament(); //unload filament for single material (used also in M702)
  2664. //finish moves
  2665. st_synchronize();
  2666. if (!mmu_enabled)
  2667. {
  2668. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2669. lcd_change_fil_state = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Was filament unload successful?"),
  2670. false, true); ////MSG_UNLOAD_SUCCESSFUL c=20 r=2
  2671. if (lcd_change_fil_state == 0)
  2672. {
  2673. lcd_clear();
  2674. lcd_set_cursor(0, 2);
  2675. lcd_puts_P(_T(MSG_PLEASE_WAIT));
  2676. current_position[X_AXIS] -= 100;
  2677. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED, active_extruder);
  2678. st_synchronize();
  2679. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually."));////MSG_CHECK_IDLER c=20 r=4
  2680. }
  2681. }
  2682. if (mmu_enabled)
  2683. {
  2684. if (!automatic) {
  2685. if (saved_printing) mmu_eject_filament(mmu_extruder, false); //if M600 was invoked by filament senzor (FINDA) eject filament so user can easily remove it
  2686. mmu_M600_wait_and_beep();
  2687. if (saved_printing) {
  2688. lcd_clear();
  2689. lcd_set_cursor(0, 2);
  2690. lcd_puts_P(_T(MSG_PLEASE_WAIT));
  2691. mmu_command(MmuCmd::R0);
  2692. manage_response(false, false);
  2693. }
  2694. }
  2695. mmu_M600_load_filament(automatic, HotendTempBckp);
  2696. }
  2697. else
  2698. M600_load_filament();
  2699. if (!automatic) M600_check_state(HotendTempBckp);
  2700. lcd_update_enable(true);
  2701. //Not let's go back to print
  2702. fanSpeed = fanSpeedBckp;
  2703. //Feed a little of filament to stabilize pressure
  2704. if (!automatic)
  2705. {
  2706. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  2707. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EXFEED, active_extruder);
  2708. }
  2709. //Move XY back
  2710. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  2711. FILAMENTCHANGE_XYFEED, active_extruder);
  2712. st_synchronize();
  2713. //Move Z back
  2714. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS],
  2715. FILAMENTCHANGE_ZFEED, active_extruder);
  2716. st_synchronize();
  2717. //Set E position to original
  2718. plan_set_e_position(lastpos[E_AXIS]);
  2719. memcpy(current_position, lastpos, sizeof(lastpos));
  2720. memcpy(destination, current_position, sizeof(current_position));
  2721. //Recover feed rate
  2722. feedmultiply = feedmultiplyBckp;
  2723. char cmd[9];
  2724. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  2725. enquecommand(cmd);
  2726. #ifdef IR_SENSOR
  2727. //this will set fsensor_watch_autoload to correct value and prevent possible M701 gcode enqueuing when M600 is finished
  2728. fsensor_check_autoload();
  2729. #endif //IR_SENSOR
  2730. lcd_setstatuspgm(_T(WELCOME_MSG));
  2731. custom_message_type = CustomMsg::Status;
  2732. }
  2733. void gcode_M701()
  2734. {
  2735. printf_P(PSTR("gcode_M701 begin\n"));
  2736. if (farm_mode)
  2737. {
  2738. prusa_statistics(22);
  2739. }
  2740. if (mmu_enabled)
  2741. {
  2742. extr_adj(tmp_extruder);//loads current extruder
  2743. mmu_extruder = tmp_extruder;
  2744. }
  2745. else
  2746. {
  2747. enable_z();
  2748. custom_message_type = CustomMsg::FilamentLoading;
  2749. #ifdef FSENSOR_QUALITY
  2750. fsensor_oq_meassure_start(40);
  2751. #endif //FSENSOR_QUALITY
  2752. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  2753. current_position[E_AXIS] += 40;
  2754. plan_buffer_line_curposXYZE(400 / 60, active_extruder); //fast sequence
  2755. st_synchronize();
  2756. raise_z_above(MIN_Z_FOR_LOAD, false);
  2757. current_position[E_AXIS] += 30;
  2758. plan_buffer_line_curposXYZE(400 / 60, active_extruder); //fast sequence
  2759. load_filament_final_feed(); //slow sequence
  2760. st_synchronize();
  2761. Sound_MakeCustom(50,500,false);
  2762. if (!farm_mode && loading_flag) {
  2763. lcd_load_filament_color_check();
  2764. }
  2765. lcd_update_enable(true);
  2766. lcd_update(2);
  2767. lcd_setstatuspgm(_T(WELCOME_MSG));
  2768. disable_z();
  2769. loading_flag = false;
  2770. custom_message_type = CustomMsg::Status;
  2771. #ifdef FSENSOR_QUALITY
  2772. fsensor_oq_meassure_stop();
  2773. if (!fsensor_oq_result())
  2774. {
  2775. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Fil. sensor response is poor, disable it?"), false, true);
  2776. lcd_update_enable(true);
  2777. lcd_update(2);
  2778. if (disable)
  2779. fsensor_disable();
  2780. }
  2781. #endif //FSENSOR_QUALITY
  2782. }
  2783. }
  2784. /**
  2785. * @brief Get serial number from 32U2 processor
  2786. *
  2787. * Typical format of S/N is:CZPX0917X003XC13518
  2788. *
  2789. * Command operates only in farm mode, if not in farm mode, "Not in farm mode." is written to MYSERIAL.
  2790. *
  2791. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  2792. * reply is transmitted to serial port 1 character by character.
  2793. * Operation takes typically 23 ms. If the retransmit is not finished until 100 ms,
  2794. * it is interrupted, so less, or no characters are retransmitted, only newline character is send
  2795. * in any case.
  2796. */
  2797. static void gcode_PRUSA_SN()
  2798. {
  2799. if (farm_mode) {
  2800. selectedSerialPort = 0;
  2801. putchar(';');
  2802. putchar('S');
  2803. int numbersRead = 0;
  2804. ShortTimer timeout;
  2805. timeout.start();
  2806. while (numbersRead < 19) {
  2807. while (MSerial.available() > 0) {
  2808. uint8_t serial_char = MSerial.read();
  2809. selectedSerialPort = 1;
  2810. putchar(serial_char);
  2811. numbersRead++;
  2812. selectedSerialPort = 0;
  2813. }
  2814. if (timeout.expired(100u)) break;
  2815. }
  2816. selectedSerialPort = 1;
  2817. putchar('\n');
  2818. #if 0
  2819. for (int b = 0; b < 3; b++) {
  2820. _tone(BEEPER, 110);
  2821. _delay(50);
  2822. _noTone(BEEPER);
  2823. _delay(50);
  2824. }
  2825. #endif
  2826. } else {
  2827. puts_P(_N("Not in farm mode."));
  2828. }
  2829. }
  2830. //! Detection of faulty RAMBo 1.1b boards equipped with bigger capacitors
  2831. //! at the TACH_1 pin, which causes bad detection of print fan speed.
  2832. //! Warning: This function is not to be used by ordinary users, it is here only for automated testing purposes,
  2833. //! it may even interfere with other functions of the printer! You have been warned!
  2834. //! The test idea is to measure the time necessary to charge the capacitor.
  2835. //! So the algorithm is as follows:
  2836. //! 1. Set TACH_1 pin to INPUT mode and LOW
  2837. //! 2. Wait a few ms
  2838. //! 3. disable interrupts and measure the time until the TACH_1 pin reaches HIGH
  2839. //! Repeat 1.-3. several times
  2840. //! Good RAMBo's times are in the range of approx. 260-320 us
  2841. //! Bad RAMBo's times are approx. 260-1200 us
  2842. //! So basically we are interested in maximum time, the minima are mostly the same.
  2843. //! May be that's why the bad RAMBo's still produce some fan RPM reading, but not corresponding to reality
  2844. static void gcode_PRUSA_BadRAMBoFanTest(){
  2845. //printf_P(PSTR("Enter fan pin test\n"));
  2846. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  2847. fan_measuring = false; // prevent EXTINT7 breaking into the measurement
  2848. unsigned long tach1max = 0;
  2849. uint8_t tach1cntr = 0;
  2850. for( /* nothing */; tach1cntr < 100; ++tach1cntr){
  2851. //printf_P(PSTR("TACH_1: %d\n"), tach1cntr);
  2852. SET_OUTPUT(TACH_1);
  2853. WRITE(TACH_1, LOW);
  2854. _delay(20); // the delay may be lower
  2855. unsigned long tachMeasure = _micros();
  2856. cli();
  2857. SET_INPUT(TACH_1);
  2858. // just wait brutally in an endless cycle until we reach HIGH
  2859. // if this becomes a problem it may be improved to non-endless cycle
  2860. while( READ(TACH_1) == 0 ) ;
  2861. sei();
  2862. tachMeasure = _micros() - tachMeasure;
  2863. if( tach1max < tachMeasure )
  2864. tach1max = tachMeasure;
  2865. //printf_P(PSTR("TACH_1: %d: capacitor check time=%lu us\n"), (int)tach1cntr, tachMeasure);
  2866. }
  2867. //printf_P(PSTR("TACH_1: max=%lu us\n"), tach1max);
  2868. SERIAL_PROTOCOLPGM("RAMBo FAN ");
  2869. if( tach1max > 500 ){
  2870. // bad RAMBo
  2871. SERIAL_PROTOCOLLNPGM("BAD");
  2872. } else {
  2873. SERIAL_PROTOCOLLNPGM("OK");
  2874. }
  2875. // cleanup after the test function
  2876. SET_INPUT(TACH_1);
  2877. WRITE(TACH_1, HIGH);
  2878. #endif
  2879. }
  2880. // G92 - Set current position to coordinates given
  2881. static void gcode_G92()
  2882. {
  2883. bool codes[NUM_AXIS];
  2884. float values[NUM_AXIS];
  2885. // Check which axes need to be set
  2886. for(uint8_t i = 0; i < NUM_AXIS; ++i)
  2887. {
  2888. codes[i] = code_seen(axis_codes[i]);
  2889. if(codes[i])
  2890. values[i] = code_value();
  2891. }
  2892. if((codes[E_AXIS] && values[E_AXIS] == 0) &&
  2893. (!codes[X_AXIS] && !codes[Y_AXIS] && !codes[Z_AXIS]))
  2894. {
  2895. // As a special optimization, when _just_ clearing the E position
  2896. // we schedule a flag asynchronously along with the next block to
  2897. // reset the starting E position instead of stopping the planner
  2898. current_position[E_AXIS] = 0;
  2899. plan_reset_next_e();
  2900. }
  2901. else
  2902. {
  2903. // In any other case we're forced to synchronize
  2904. st_synchronize();
  2905. for(uint8_t i = 0; i < 3; ++i)
  2906. {
  2907. if(codes[i])
  2908. current_position[i] = values[i] + cs.add_homing[i];
  2909. }
  2910. if(codes[E_AXIS])
  2911. current_position[E_AXIS] = values[E_AXIS];
  2912. // Set all at once
  2913. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS],
  2914. current_position[Z_AXIS], current_position[E_AXIS]);
  2915. }
  2916. }
  2917. #ifdef BACKLASH_X
  2918. extern uint8_t st_backlash_x;
  2919. #endif //BACKLASH_X
  2920. #ifdef BACKLASH_Y
  2921. extern uint8_t st_backlash_y;
  2922. #endif //BACKLASH_Y
  2923. //! \ingroup marlin_main
  2924. //! @brief Parse and process commands
  2925. //!
  2926. //! look here for descriptions of G-codes: https://reprap.org/wiki/G-code
  2927. //!
  2928. //!
  2929. //! Implemented Codes
  2930. //! -------------------
  2931. //!
  2932. //! * _This list is not updated. Current documentation is maintained inside the process_cmd function._
  2933. //!
  2934. //!@n PRUSA CODES
  2935. //!@n P F - Returns FW versions
  2936. //!@n P R - Returns revision of printer
  2937. //!
  2938. //!@n G0 -> G1
  2939. //!@n G1 - Coordinated Movement X Y Z E
  2940. //!@n G2 - CW ARC
  2941. //!@n G3 - CCW ARC
  2942. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  2943. //!@n G10 - retract filament according to settings of M207
  2944. //!@n G11 - retract recover filament according to settings of M208
  2945. //!@n G28 - Home all Axes
  2946. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  2947. //!@n G30 - Single Z Probe, probes bed at current XY location.
  2948. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  2949. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  2950. //!@n G80 - Automatic mesh bed leveling
  2951. //!@n G81 - Print bed profile
  2952. //!@n G90 - Use Absolute Coordinates
  2953. //!@n G91 - Use Relative Coordinates
  2954. //!@n G92 - Set current position to coordinates given
  2955. //!
  2956. //!@n M Codes
  2957. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  2958. //!@n M1 - Same as M0
  2959. //!@n M17 - Enable/Power all stepper motors
  2960. //!@n M18 - Disable all stepper motors; same as M84
  2961. //!@n M20 - List SD card
  2962. //!@n M21 - Init SD card
  2963. //!@n M22 - Release SD card
  2964. //!@n M23 - Select SD file (M23 filename.g)
  2965. //!@n M24 - Start/resume SD print
  2966. //!@n M25 - Pause SD print
  2967. //!@n M26 - Set SD position in bytes (M26 S12345)
  2968. //!@n M27 - Report SD print status
  2969. //!@n M28 - Start SD write (M28 filename.g)
  2970. //!@n M29 - Stop SD write
  2971. //!@n M30 - Delete file from SD (M30 filename.g)
  2972. //!@n M31 - Output time since last M109 or SD card start to serial
  2973. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  2974. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  2975. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  2976. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  2977. //!@n 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.
  2978. //!@n M73 - Show percent done and print time remaining
  2979. //!@n M80 - Turn on Power Supply
  2980. //!@n M81 - Turn off Power Supply
  2981. //!@n M82 - Set E codes absolute (default)
  2982. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  2983. //!@n M84 - Disable steppers until next move,
  2984. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  2985. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  2986. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  2987. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  2988. //!@n M104 - Set extruder target temp
  2989. //!@n M105 - Read current temp
  2990. //!@n M106 - Fan on
  2991. //!@n M107 - Fan off
  2992. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  2993. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  2994. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  2995. //!@n M112 - Emergency stop
  2996. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  2997. //!@n M114 - Output current position to serial port
  2998. //!@n M115 - Capabilities string
  2999. //!@n M117 - display message
  3000. //!@n M119 - Output Endstop status to serial port
  3001. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  3002. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  3003. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3004. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3005. //!@n M140 - Set bed target temp
  3006. //!@n 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.
  3007. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3008. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3009. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3010. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3011. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  3012. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3013. //!@n 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
  3014. //!@n 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
  3015. //!@n M206 - set additional homing offset
  3016. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  3017. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  3018. //!@n 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.
  3019. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3020. //!@n M220 S<factor in percent>- set speed factor override percentage
  3021. //!@n M221 S<factor in percent>- set extrude factor override percentage
  3022. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3023. //!@n M240 - Trigger a camera to take a photograph
  3024. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  3025. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3026. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  3027. //!@n M301 - Set PID parameters P I and D
  3028. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  3029. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  3030. //!@n M304 - Set bed PID parameters P I and D
  3031. //!@n M400 - Finish all moves
  3032. //!@n M401 - Lower z-probe if present
  3033. //!@n M402 - Raise z-probe if present
  3034. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  3035. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  3036. //!@n M406 - Turn off Filament Sensor extrusion control
  3037. //!@n M407 - Displays measured filament diameter
  3038. //!@n M500 - stores parameters in EEPROM
  3039. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  3040. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  3041. //!@n M503 - print the current settings (from memory not from EEPROM)
  3042. //!@n M509 - force language selection on next restart
  3043. //!@n M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  3044. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3045. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  3046. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  3047. //!@n M861 - Set / Read PINDA temperature compensation offsets
  3048. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  3049. //!@n M907 - Set digital trimpot motor current using axis codes.
  3050. //!@n M908 - Control digital trimpot directly.
  3051. //!@n M350 - Set microstepping mode.
  3052. //!@n M351 - Toggle MS1 MS2 pins directly.
  3053. //!
  3054. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  3055. //!@n M999 - Restart after being stopped by error
  3056. //! <br><br>
  3057. /** @defgroup marlin_main Marlin main */
  3058. /** \ingroup GCodes */
  3059. //! _This is a list of currently implemented G Codes in Prusa firmware (dynamically generated from doxygen)._
  3060. /**
  3061. They are shown in order of appearance in the code.
  3062. There are reasons why some G Codes aren't in numerical order.
  3063. */
  3064. void process_commands()
  3065. {
  3066. #ifdef FANCHECK
  3067. if(fan_check_error){
  3068. if(fan_check_error == EFCE_DETECTED){
  3069. fan_check_error = EFCE_REPORTED;
  3070. // SERIAL_PROTOCOLLNRPGM(MSG_OCTOPRINT_PAUSED);
  3071. lcd_pause_print();
  3072. } // otherwise it has already been reported, so just ignore further processing
  3073. return; //ignore usb stream. It is reenabled by selecting resume from the lcd.
  3074. }
  3075. #endif
  3076. if (!buflen) return; //empty command
  3077. #ifdef FILAMENT_RUNOUT_SUPPORT
  3078. SET_INPUT(FR_SENS);
  3079. #endif
  3080. #ifdef CMDBUFFER_DEBUG
  3081. SERIAL_ECHOPGM("Processing a GCODE command: ");
  3082. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  3083. SERIAL_ECHOLNPGM("");
  3084. SERIAL_ECHOPGM("In cmdqueue: ");
  3085. SERIAL_ECHO(buflen);
  3086. SERIAL_ECHOLNPGM("");
  3087. #endif /* CMDBUFFER_DEBUG */
  3088. unsigned long codenum; //throw away variable
  3089. char *starpos = NULL;
  3090. #ifdef ENABLE_AUTO_BED_LEVELING
  3091. float x_tmp, y_tmp, z_tmp, real_z;
  3092. #endif
  3093. // PRUSA GCODES
  3094. KEEPALIVE_STATE(IN_HANDLER);
  3095. #ifdef SNMM
  3096. float tmp_motor[3] = DEFAULT_PWM_MOTOR_CURRENT;
  3097. float tmp_motor_loud[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  3098. int8_t SilentMode;
  3099. #endif
  3100. /*!
  3101. ---------------------------------------------------------------------------------
  3102. ### M117 - Display Message <a href="https://reprap.org/wiki/G-code#M117:_Display_Message">M117: Display Message</a>
  3103. This causes the given message to be shown in the status line on an attached LCD.
  3104. It is processed early as to allow printing messages that contain G, M, N or T.
  3105. ---------------------------------------------------------------------------------
  3106. ### Special internal commands
  3107. These are used by internal functions to process certain actions in the right order. Some of these are also usable by the user.
  3108. They are processed early as the commands are complex (strings).
  3109. These are only available on the MK3(S) as these require TMC2130 drivers:
  3110. - CRASH DETECTED
  3111. - CRASH RECOVER
  3112. - CRASH_CANCEL
  3113. - TMC_SET_WAVE
  3114. - TMC_SET_STEP
  3115. - TMC_SET_CHOP
  3116. */
  3117. if (code_seen("M117")) { //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  3118. starpos = (strchr(strchr_pointer + 5, '*'));
  3119. if (starpos != NULL)
  3120. *(starpos) = '\0';
  3121. lcd_setstatus(strchr_pointer + 5);
  3122. }
  3123. #ifdef TMC2130
  3124. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  3125. {
  3126. // ### CRASH_DETECTED - TMC2130
  3127. // ---------------------------------
  3128. if(code_seen("CRASH_DETECTED"))
  3129. {
  3130. uint8_t mask = 0;
  3131. if (code_seen('X')) mask |= X_AXIS_MASK;
  3132. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  3133. crashdet_detected(mask);
  3134. }
  3135. // ### CRASH_RECOVER - TMC2130
  3136. // ----------------------------------
  3137. else if(code_seen("CRASH_RECOVER"))
  3138. crashdet_recover();
  3139. // ### CRASH_CANCEL - TMC2130
  3140. // ----------------------------------
  3141. else if(code_seen("CRASH_CANCEL"))
  3142. crashdet_cancel();
  3143. }
  3144. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3145. {
  3146. // ### TMC_SET_WAVE_
  3147. // --------------------
  3148. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0)
  3149. {
  3150. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3151. axis = (axis == 'E')?3:(axis - 'X');
  3152. if (axis < 4)
  3153. {
  3154. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3155. tmc2130_set_wave(axis, 247, fac);
  3156. }
  3157. }
  3158. // ### TMC_SET_STEP_
  3159. // ------------------
  3160. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0)
  3161. {
  3162. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3163. axis = (axis == 'E')?3:(axis - 'X');
  3164. if (axis < 4)
  3165. {
  3166. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3167. uint16_t res = tmc2130_get_res(axis);
  3168. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3169. }
  3170. }
  3171. // ### TMC_SET_CHOP_
  3172. // -------------------
  3173. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0)
  3174. {
  3175. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3176. axis = (axis == 'E')?3:(axis - 'X');
  3177. if (axis < 4)
  3178. {
  3179. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  3180. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3181. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3182. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3183. char* str_end = 0;
  3184. if (CMDBUFFER_CURRENT_STRING[14])
  3185. {
  3186. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3187. if (str_end && *str_end)
  3188. {
  3189. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3190. if (str_end && *str_end)
  3191. {
  3192. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3193. if (str_end && *str_end)
  3194. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3195. }
  3196. }
  3197. }
  3198. tmc2130_chopper_config[axis].toff = chop0;
  3199. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3200. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3201. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3202. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3203. //printf_P(_N("TMC_SET_CHOP_%c %hhd %hhd %hhd %hhd\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3204. }
  3205. }
  3206. }
  3207. #ifdef BACKLASH_X
  3208. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3209. {
  3210. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3211. st_backlash_x = bl;
  3212. printf_P(_N("st_backlash_x = %hhd\n"), st_backlash_x);
  3213. }
  3214. #endif //BACKLASH_X
  3215. #ifdef BACKLASH_Y
  3216. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3217. {
  3218. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3219. st_backlash_y = bl;
  3220. printf_P(_N("st_backlash_y = %hhd\n"), st_backlash_y);
  3221. }
  3222. #endif //BACKLASH_Y
  3223. #endif //TMC2130
  3224. else if(code_seen("PRUSA")){
  3225. /*!
  3226. ---------------------------------------------------------------------------------
  3227. ### PRUSA - Internal command set <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode - Notes</a>
  3228. Set of internal PRUSA commands
  3229. #### Usage
  3230. PRUSA [ Ping | PRN | FAN | fn | thx | uvlo | MMURES | RESET | fv | M28 | SN | Fir | Rev | Lang | Lz | Beat | FR ]
  3231. #### Parameters
  3232. - `Ping`
  3233. - `PRN` - Prints revision of the printer
  3234. - `FAN` - Prints fan details
  3235. - `fn` - Prints farm no.
  3236. - `thx`
  3237. - `uvlo`
  3238. - `MMURES` - Reset MMU
  3239. - `RESET` - (Careful!)
  3240. - `fv` - ?
  3241. - `M28`
  3242. - `SN`
  3243. - `Fir` - Prints firmware version
  3244. - `Rev`- Prints filament size, elelectronics, nozzle type
  3245. - `Lang` - Reset the language
  3246. - `Lz`
  3247. - `Beat` - Kick farm link timer
  3248. - `FR` - Full factory reset
  3249. - `nozzle set <diameter>` - set nozzle diameter (farm mode only), e.g. `PRUSA nozzle set 0.4`
  3250. - `nozzle D<diameter>` - check the nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle D0.4`
  3251. - `nozzle` - prints nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle`
  3252. */
  3253. if (code_seen("Ping")) { // PRUSA Ping
  3254. if (farm_mode) {
  3255. PingTime = _millis();
  3256. //MYSERIAL.print(farm_no); MYSERIAL.println(": OK");
  3257. }
  3258. }
  3259. else if (code_seen("PRN")) { // PRUSA PRN
  3260. printf_P(_N("%d"), status_number);
  3261. } else if( code_seen("FANPINTST") ){
  3262. gcode_PRUSA_BadRAMBoFanTest();
  3263. }else if (code_seen("FAN")) { // PRUSA FAN
  3264. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3265. }else if (code_seen("fn")) { // PRUSA fn
  3266. if (farm_mode) {
  3267. printf_P(_N("%d"), farm_no);
  3268. }
  3269. else {
  3270. puts_P(_N("Not in farm mode."));
  3271. }
  3272. }
  3273. else if (code_seen("thx")) // PRUSA thx
  3274. {
  3275. no_response = false;
  3276. }
  3277. else if (code_seen("uvlo")) // PRUSA uvlo
  3278. {
  3279. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3280. enquecommand_P(PSTR("M24"));
  3281. }
  3282. else if (code_seen("MMURES")) // PRUSA MMURES
  3283. {
  3284. mmu_reset();
  3285. }
  3286. else if (code_seen("RESET")) { // PRUSA RESET
  3287. // careful!
  3288. if (farm_mode) {
  3289. #if (defined(WATCHDOG) && (MOTHERBOARD == BOARD_EINSY_1_0a))
  3290. boot_app_magic = BOOT_APP_MAGIC;
  3291. boot_app_flags = BOOT_APP_FLG_RUN;
  3292. wdt_enable(WDTO_15MS);
  3293. cli();
  3294. while(1);
  3295. #else //WATCHDOG
  3296. asm volatile("jmp 0x3E000");
  3297. #endif //WATCHDOG
  3298. }
  3299. else {
  3300. MYSERIAL.println("Not in farm mode.");
  3301. }
  3302. }else if (code_seen("fv")) { // PRUSA fv
  3303. // get file version
  3304. #ifdef SDSUPPORT
  3305. card.openFile(strchr_pointer + 3,true);
  3306. while (true) {
  3307. uint16_t readByte = card.get();
  3308. MYSERIAL.write(readByte);
  3309. if (readByte=='\n') {
  3310. break;
  3311. }
  3312. }
  3313. card.closefile();
  3314. #endif // SDSUPPORT
  3315. } else if (code_seen("M28")) { // PRUSA M28
  3316. trace();
  3317. prusa_sd_card_upload = true;
  3318. card.openFile(strchr_pointer+4,false);
  3319. } else if (code_seen("SN")) { // PRUSA SN
  3320. gcode_PRUSA_SN();
  3321. } else if(code_seen("Fir")){ // PRUSA Fir
  3322. SERIAL_PROTOCOLLN(FW_VERSION_FULL);
  3323. } else if(code_seen("Rev")){ // PRUSA Rev
  3324. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3325. } else if(code_seen("Lang")) { // PRUSA Lang
  3326. lang_reset();
  3327. } else if(code_seen("Lz")) { // PRUSA Lz
  3328. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  3329. } else if(code_seen("Beat")) { // PRUSA Beat
  3330. // Kick farm link timer
  3331. kicktime = _millis();
  3332. } else if(code_seen("FR")) { // PRUSA FR
  3333. // Factory full reset
  3334. factory_reset(0);
  3335. } else if(code_seen("MBL")) { // PRUSA MBL
  3336. // Change the MBL status without changing the logical Z position.
  3337. if(code_seen("V")) {
  3338. bool value = code_value_short();
  3339. st_synchronize();
  3340. if(value != mbl.active) {
  3341. mbl.active = value;
  3342. // Use plan_set_z_position to reset the physical values
  3343. plan_set_z_position(current_position[Z_AXIS]);
  3344. }
  3345. }
  3346. //-//
  3347. /*
  3348. } else if(code_seen("rrr")) {
  3349. MYSERIAL.println("=== checking ===");
  3350. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_CHECK_MODE),DEC);
  3351. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER),DEC);
  3352. MYSERIAL.println(eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM),DEC);
  3353. MYSERIAL.println(farm_mode,DEC);
  3354. MYSERIAL.println(eCheckMode,DEC);
  3355. } else if(code_seen("www")) {
  3356. MYSERIAL.println("=== @ FF ===");
  3357. eeprom_update_byte((uint8_t*)EEPROM_CHECK_MODE,0xFF);
  3358. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,0xFF);
  3359. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,0xFFFF);
  3360. */
  3361. } else if (code_seen("nozzle")) { // PRUSA nozzle
  3362. uint16_t nDiameter;
  3363. if(code_seen('D'))
  3364. {
  3365. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3366. nozzle_diameter_check(nDiameter);
  3367. }
  3368. else if(code_seen("set") && farm_mode)
  3369. {
  3370. strchr_pointer++; // skip 1st char (~ 's')
  3371. strchr_pointer++; // skip 2nd char (~ 'e')
  3372. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3373. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  3374. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  3375. }
  3376. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  3377. //-// !!! SupportMenu
  3378. /*
  3379. // musi byt PRED "PRUSA model"
  3380. } else if (code_seen("smodel")) { //! PRUSA smodel
  3381. size_t nOffset;
  3382. // ! -> "l"
  3383. strchr_pointer+=5*sizeof(*strchr_pointer); // skip 1st - 5th char (~ 'smode')
  3384. nOffset=strspn(strchr_pointer+1," \t\n\r\v\f");
  3385. if(*(strchr_pointer+1+nOffset))
  3386. printer_smodel_check(strchr_pointer);
  3387. else SERIAL_PROTOCOLLN(PRINTER_NAME);
  3388. } else if (code_seen("model")) { //! PRUSA model
  3389. uint16_t nPrinterModel;
  3390. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'mode')
  3391. nPrinterModel=(uint16_t)code_value_long();
  3392. if(nPrinterModel!=0)
  3393. printer_model_check(nPrinterModel);
  3394. else SERIAL_PROTOCOLLN(PRINTER_TYPE);
  3395. } else if (code_seen("version")) { //! PRUSA version
  3396. strchr_pointer+=7*sizeof(*strchr_pointer); // skip 1st - 7th char (~ 'version')
  3397. while(*strchr_pointer==' ') // skip leading spaces
  3398. strchr_pointer++;
  3399. if(*strchr_pointer!=0)
  3400. fw_version_check(strchr_pointer);
  3401. else SERIAL_PROTOCOLLN(FW_VERSION);
  3402. } else if (code_seen("gcode")) { //! PRUSA gcode
  3403. uint16_t nGcodeLevel;
  3404. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'gcod')
  3405. nGcodeLevel=(uint16_t)code_value_long();
  3406. if(nGcodeLevel!=0)
  3407. gcode_level_check(nGcodeLevel);
  3408. else SERIAL_PROTOCOLLN(GCODE_LEVEL);
  3409. */
  3410. }
  3411. //else if (code_seen('Cal')) {
  3412. // lcd_calibration();
  3413. // }
  3414. }
  3415. // This prevents reading files with "^" in their names.
  3416. // Since it is unclear, if there is some usage of this construct,
  3417. // it will be deprecated in 3.9 alpha a possibly completely removed in the future:
  3418. // else if (code_seen('^')) {
  3419. // // nothing, this is a version line
  3420. // }
  3421. else if(code_seen('G'))
  3422. {
  3423. gcode_in_progress = (int)code_value();
  3424. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3425. switch (gcode_in_progress)
  3426. {
  3427. /*!
  3428. ---------------------------------------------------------------------------------
  3429. # G Codes
  3430. ### G0, G1 - Coordinated movement X Y Z E <a href="https://reprap.org/wiki/G-code#G0_.26_G1:_Move">G0 & G1: Move</a>
  3431. In Prusa Firmware G0 and G1 are the same.
  3432. #### Usage
  3433. G0 [ X | Y | Z | E | F | S ]
  3434. G1 [ X | Y | Z | E | F | S ]
  3435. #### Parameters
  3436. - `X` - The position to move to on the X axis
  3437. - `Y` - The position to move to on the Y axis
  3438. - `Z` - The position to move to on the Z axis
  3439. - `E` - The amount to extrude between the starting point and ending point
  3440. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3441. */
  3442. case 0: // G0 -> G1
  3443. case 1: // G1
  3444. if(Stopped == false) {
  3445. #ifdef FILAMENT_RUNOUT_SUPPORT
  3446. if(READ(FR_SENS)){
  3447. int feedmultiplyBckp=feedmultiply;
  3448. float target[4];
  3449. float lastpos[4];
  3450. target[X_AXIS]=current_position[X_AXIS];
  3451. target[Y_AXIS]=current_position[Y_AXIS];
  3452. target[Z_AXIS]=current_position[Z_AXIS];
  3453. target[E_AXIS]=current_position[E_AXIS];
  3454. lastpos[X_AXIS]=current_position[X_AXIS];
  3455. lastpos[Y_AXIS]=current_position[Y_AXIS];
  3456. lastpos[Z_AXIS]=current_position[Z_AXIS];
  3457. lastpos[E_AXIS]=current_position[E_AXIS];
  3458. //retract by E
  3459. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT ;
  3460. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  3461. target[Z_AXIS]+= FILAMENTCHANGE_ZADD ;
  3462. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 300, active_extruder);
  3463. target[X_AXIS]= FILAMENTCHANGE_XPOS ;
  3464. target[Y_AXIS]= FILAMENTCHANGE_YPOS ;
  3465. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder);
  3466. target[E_AXIS]+= FILAMENTCHANGE_FINALRETRACT ;
  3467. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3468. //finish moves
  3469. st_synchronize();
  3470. //disable extruder steppers so filament can be removed
  3471. disable_e0();
  3472. disable_e1();
  3473. disable_e2();
  3474. _delay(100);
  3475. //LCD_ALERTMESSAGEPGM(_T(MSG_FILAMENTCHANGE));
  3476. uint8_t cnt=0;
  3477. int counterBeep = 0;
  3478. lcd_wait_interact();
  3479. while(!lcd_clicked()){
  3480. cnt++;
  3481. manage_heater();
  3482. manage_inactivity(true);
  3483. //lcd_update(0);
  3484. if(cnt==0)
  3485. {
  3486. #if BEEPER > 0
  3487. if (counterBeep== 500){
  3488. counterBeep = 0;
  3489. }
  3490. SET_OUTPUT(BEEPER);
  3491. if (counterBeep== 0){
  3492. if(eSoundMode!=e_SOUND_MODE_SILENT)
  3493. WRITE(BEEPER,HIGH);
  3494. }
  3495. if (counterBeep== 20){
  3496. WRITE(BEEPER,LOW);
  3497. }
  3498. counterBeep++;
  3499. #else
  3500. #endif
  3501. }
  3502. }
  3503. WRITE(BEEPER,LOW);
  3504. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3505. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3506. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3507. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3508. lcd_change_fil_state = 0;
  3509. lcd_loading_filament();
  3510. while ((lcd_change_fil_state == 0)||(lcd_change_fil_state != 1)){
  3511. lcd_change_fil_state = 0;
  3512. lcd_alright();
  3513. switch(lcd_change_fil_state){
  3514. case 2:
  3515. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3516. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3517. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3518. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3519. lcd_loading_filament();
  3520. break;
  3521. case 3:
  3522. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3523. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3524. lcd_loading_color();
  3525. break;
  3526. default:
  3527. lcd_change_success();
  3528. break;
  3529. }
  3530. }
  3531. target[E_AXIS]+= 5;
  3532. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3533. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT;
  3534. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  3535. //current_position[E_AXIS]=target[E_AXIS]; //the long retract of L is compensated by manual filament feeding
  3536. //plan_set_e_position(current_position[E_AXIS]);
  3537. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //should do nothing
  3538. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //move xy back
  3539. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 200, active_extruder); //move z back
  3540. target[E_AXIS]= target[E_AXIS] - FILAMENTCHANGE_FIRSTRETRACT;
  3541. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 5, active_extruder); //final untretract
  3542. plan_set_e_position(lastpos[E_AXIS]);
  3543. feedmultiply=feedmultiplyBckp;
  3544. char cmd[9];
  3545. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3546. enquecommand(cmd);
  3547. }
  3548. #endif
  3549. get_coordinates(); // For X Y Z E F
  3550. // When recovering from a previous print move, restore the originally
  3551. // calculated target position on the first USB/SD command. This accounts
  3552. // properly for relative moves
  3553. if ((saved_target[0] != SAVED_TARGET_UNSET) &&
  3554. ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) ||
  3555. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  3556. {
  3557. memcpy(destination, saved_target, sizeof(destination));
  3558. saved_target[0] = SAVED_TARGET_UNSET;
  3559. }
  3560. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3561. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3562. }
  3563. #ifdef FWRETRACT
  3564. if(cs.autoretract_enabled)
  3565. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3566. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3567. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3568. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3569. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3570. retract(!retracted[active_extruder]);
  3571. return;
  3572. }
  3573. }
  3574. #endif //FWRETRACT
  3575. prepare_move();
  3576. //ClearToSend();
  3577. }
  3578. break;
  3579. /*!
  3580. ### G2, G3 - Controlled Arc Move <a href="https://reprap.org/wiki/G-code#G2_.26_G3:_Controlled_Arc_Move">G2 & G3: Controlled Arc Move</a>
  3581. These commands don't propperly work with MBL enabled. The compensation only happens at the end of the move, so avoid long arcs.
  3582. #### Usage
  3583. G2 [ X | Y | I | E | F ] (Clockwise Arc)
  3584. G3 [ X | Y | I | E | F ] (Counter-Clockwise Arc)
  3585. #### Parameters
  3586. - `X` - The position to move to on the X axis
  3587. - `Y` - The position to move to on the Y axis
  3588. - `I` - The point in X space from the current X position to maintain a constant distance from
  3589. - `J` - The point in Y space from the current Y position to maintain a constant distance from
  3590. - `E` - The amount to extrude between the starting point and ending point
  3591. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3592. */
  3593. case 2:
  3594. if(Stopped == false) {
  3595. get_arc_coordinates();
  3596. prepare_arc_move(true);
  3597. }
  3598. break;
  3599. // -------------------------------
  3600. case 3:
  3601. if(Stopped == false) {
  3602. get_arc_coordinates();
  3603. prepare_arc_move(false);
  3604. }
  3605. break;
  3606. /*!
  3607. ### G4 - Dwell <a href="https://reprap.org/wiki/G-code#G4:_Dwell">G4: Dwell</a>
  3608. Pause the machine for a period of time.
  3609. #### Usage
  3610. G4 [ P | S ]
  3611. #### Parameters
  3612. - `P` - Time to wait, in milliseconds
  3613. - `S` - Time to wait, in seconds
  3614. */
  3615. case 4:
  3616. codenum = 0;
  3617. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3618. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3619. if(codenum != 0) LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  3620. st_synchronize();
  3621. codenum += _millis(); // keep track of when we started waiting
  3622. previous_millis_cmd = _millis();
  3623. while(_millis() < codenum) {
  3624. manage_heater();
  3625. manage_inactivity();
  3626. lcd_update(0);
  3627. }
  3628. break;
  3629. #ifdef FWRETRACT
  3630. /*!
  3631. ### G10 - Retract <a href="https://reprap.org/wiki/G-code#G10:_Retract">G10: Retract</a>
  3632. Retracts filament according to settings of `M207`
  3633. */
  3634. case 10:
  3635. #if EXTRUDERS > 1
  3636. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  3637. retract(true,retracted_swap[active_extruder]);
  3638. #else
  3639. retract(true);
  3640. #endif
  3641. break;
  3642. /*!
  3643. ### G11 - Retract recover <a href="https://reprap.org/wiki/G-code#G11:_Unretract">G11: Unretract</a>
  3644. Unretracts/recovers filament according to settings of `M208`
  3645. */
  3646. case 11:
  3647. #if EXTRUDERS > 1
  3648. retract(false,retracted_swap[active_extruder]);
  3649. #else
  3650. retract(false);
  3651. #endif
  3652. break;
  3653. #endif //FWRETRACT
  3654. /*!
  3655. ### G28 - Home all Axes one at a time <a href="https://reprap.org/wiki/G-code#G28:_Move_to_Origin_.28Home.29">G28: Move to Origin (Home)</a>
  3656. Using `G28` without any parameters will perfom homing of all axes AND mesh bed leveling, while `G28 W` will just home all axes (no mesh bed leveling).
  3657. #### Usage
  3658. G28 [ X | Y | Z | W | C ]
  3659. #### Parameters
  3660. - `X` - Flag to go back to the X axis origin
  3661. - `Y` - Flag to go back to the Y axis origin
  3662. - `Z` - Flag to go back to the Z axis origin
  3663. - `W` - Suppress mesh bed leveling if `X`, `Y` or `Z` are not provided
  3664. - `C` - Calibrate X and Y origin (home) - Only on MK3/s
  3665. */
  3666. case 28:
  3667. {
  3668. long home_x_value = 0;
  3669. long home_y_value = 0;
  3670. long home_z_value = 0;
  3671. // Which axes should be homed?
  3672. bool home_x = code_seen(axis_codes[X_AXIS]);
  3673. home_x_value = code_value_long();
  3674. bool home_y = code_seen(axis_codes[Y_AXIS]);
  3675. home_y_value = code_value_long();
  3676. bool home_z = code_seen(axis_codes[Z_AXIS]);
  3677. home_z_value = code_value_long();
  3678. bool without_mbl = code_seen('W');
  3679. // calibrate?
  3680. #ifdef TMC2130
  3681. bool calib = code_seen('C');
  3682. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  3683. #else
  3684. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  3685. #endif //TMC2130
  3686. if ((home_x || home_y || without_mbl || home_z) == false) {
  3687. // Push the commands to the front of the message queue in the reverse order!
  3688. // There shall be always enough space reserved for these commands.
  3689. goto case_G80;
  3690. }
  3691. break;
  3692. }
  3693. #ifdef ENABLE_AUTO_BED_LEVELING
  3694. /*!
  3695. ### G29 - Detailed Z-Probe <a href="https://reprap.org/wiki/G-code#G29:_Detailed_Z-Probe">G29: Detailed Z-Probe</a>
  3696. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  3697. See `G81`
  3698. */
  3699. case 29:
  3700. {
  3701. #if Z_MIN_PIN == -1
  3702. #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."
  3703. #endif
  3704. // Prevent user from running a G29 without first homing in X and Y
  3705. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  3706. {
  3707. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  3708. SERIAL_ECHO_START;
  3709. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  3710. break; // abort G29, since we don't know where we are
  3711. }
  3712. st_synchronize();
  3713. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  3714. //vector_3 corrected_position = plan_get_position_mm();
  3715. //corrected_position.debug("position before G29");
  3716. plan_bed_level_matrix.set_to_identity();
  3717. vector_3 uncorrected_position = plan_get_position();
  3718. //uncorrected_position.debug("position durring G29");
  3719. current_position[X_AXIS] = uncorrected_position.x;
  3720. current_position[Y_AXIS] = uncorrected_position.y;
  3721. current_position[Z_AXIS] = uncorrected_position.z;
  3722. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  3723. int l_feedmultiply = setup_for_endstop_move();
  3724. feedrate = homing_feedrate[Z_AXIS];
  3725. #ifdef AUTO_BED_LEVELING_GRID
  3726. // probe at the points of a lattice grid
  3727. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  3728. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  3729. // solve the plane equation ax + by + d = z
  3730. // A is the matrix with rows [x y 1] for all the probed points
  3731. // B is the vector of the Z positions
  3732. // 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
  3733. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  3734. // "A" matrix of the linear system of equations
  3735. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  3736. // "B" vector of Z points
  3737. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  3738. int probePointCounter = 0;
  3739. bool zig = true;
  3740. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  3741. {
  3742. int xProbe, xInc;
  3743. if (zig)
  3744. {
  3745. xProbe = LEFT_PROBE_BED_POSITION;
  3746. //xEnd = RIGHT_PROBE_BED_POSITION;
  3747. xInc = xGridSpacing;
  3748. zig = false;
  3749. } else // zag
  3750. {
  3751. xProbe = RIGHT_PROBE_BED_POSITION;
  3752. //xEnd = LEFT_PROBE_BED_POSITION;
  3753. xInc = -xGridSpacing;
  3754. zig = true;
  3755. }
  3756. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  3757. {
  3758. float z_before;
  3759. if (probePointCounter == 0)
  3760. {
  3761. // raise before probing
  3762. z_before = Z_RAISE_BEFORE_PROBING;
  3763. } else
  3764. {
  3765. // raise extruder
  3766. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  3767. }
  3768. float measured_z = probe_pt(xProbe, yProbe, z_before);
  3769. eqnBVector[probePointCounter] = measured_z;
  3770. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  3771. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  3772. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  3773. probePointCounter++;
  3774. xProbe += xInc;
  3775. }
  3776. }
  3777. clean_up_after_endstop_move(l_feedmultiply);
  3778. // solve lsq problem
  3779. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  3780. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  3781. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  3782. SERIAL_PROTOCOLPGM(" b: ");
  3783. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  3784. SERIAL_PROTOCOLPGM(" d: ");
  3785. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  3786. set_bed_level_equation_lsq(plane_equation_coefficients);
  3787. free(plane_equation_coefficients);
  3788. #else // AUTO_BED_LEVELING_GRID not defined
  3789. // Probe at 3 arbitrary points
  3790. // probe 1
  3791. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  3792. // probe 2
  3793. 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);
  3794. // probe 3
  3795. 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);
  3796. clean_up_after_endstop_move(l_feedmultiply);
  3797. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  3798. #endif // AUTO_BED_LEVELING_GRID
  3799. st_synchronize();
  3800. // The following code correct the Z height difference from z-probe position and hotend tip position.
  3801. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  3802. // When the bed is uneven, this height must be corrected.
  3803. real_z = float(st_get_position(Z_AXIS))/cs.axis_steps_per_unit[Z_AXIS]; //get the real Z (since the auto bed leveling is already correcting the plane)
  3804. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  3805. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  3806. z_tmp = current_position[Z_AXIS];
  3807. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  3808. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  3809. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  3810. }
  3811. break;
  3812. #ifndef Z_PROBE_SLED
  3813. /*!
  3814. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  3815. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  3816. */
  3817. case 30:
  3818. {
  3819. st_synchronize();
  3820. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  3821. int l_feedmultiply = setup_for_endstop_move();
  3822. feedrate = homing_feedrate[Z_AXIS];
  3823. run_z_probe();
  3824. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  3825. SERIAL_PROTOCOLPGM(" X: ");
  3826. SERIAL_PROTOCOL(current_position[X_AXIS]);
  3827. SERIAL_PROTOCOLPGM(" Y: ");
  3828. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3829. SERIAL_PROTOCOLPGM(" Z: ");
  3830. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3831. SERIAL_PROTOCOLPGM("\n");
  3832. clean_up_after_endstop_move(l_feedmultiply);
  3833. }
  3834. break;
  3835. #else
  3836. /*!
  3837. ### G31 - Dock the sled <a href="https://reprap.org/wiki/G-code#G31:_Dock_Z_Probe_sled">G31: Dock Z Probe sled</a>
  3838. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  3839. */
  3840. case 31:
  3841. dock_sled(true);
  3842. break;
  3843. /*!
  3844. ### G32 - Undock the sled <a href="https://reprap.org/wiki/G-code#G32:_Undock_Z_Probe_sled">G32: Undock Z Probe sled</a>
  3845. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  3846. */
  3847. case 32:
  3848. dock_sled(false);
  3849. break;
  3850. #endif // Z_PROBE_SLED
  3851. #endif // ENABLE_AUTO_BED_LEVELING
  3852. #ifdef MESH_BED_LEVELING
  3853. /*!
  3854. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  3855. Sensor must be over the bed.
  3856. The maximum travel distance before an error is triggered is 10mm.
  3857. */
  3858. case 30:
  3859. {
  3860. st_synchronize();
  3861. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  3862. int l_feedmultiply = setup_for_endstop_move();
  3863. feedrate = homing_feedrate[Z_AXIS];
  3864. find_bed_induction_sensor_point_z(-10.f, 3);
  3865. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  3866. clean_up_after_endstop_move(l_feedmultiply);
  3867. }
  3868. break;
  3869. /*!
  3870. ### G75 - Print temperature interpolation <a href="https://reprap.org/wiki/G-code#G75:_Print_temperature_interpolation">G75: Print temperature interpolation</a>
  3871. Show/print PINDA temperature interpolating.
  3872. */
  3873. case 75:
  3874. {
  3875. for (int i = 40; i <= 110; i++)
  3876. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  3877. }
  3878. break;
  3879. /*!
  3880. ### G76 - PINDA probe temperature calibration <a href="https://reprap.org/wiki/G-code#G76:_PINDA_probe_temperature_calibration">G76: PINDA probe temperature calibration</a>
  3881. This G-code is used to calibrate the temperature drift of the PINDA (inductive Sensor).
  3882. The PINDAv2 sensor has a built-in thermistor which has the advantage that the calibration can be done once for all materials.
  3883. The Original i3 Prusa MK2/s uses PINDAv1 and this calibration improves the temperature drift, but not as good as the PINDAv2.
  3884. #### Example
  3885. ```
  3886. G76
  3887. echo PINDA probe calibration start
  3888. echo start temperature: 35.0°
  3889. echo ...
  3890. echo PINDA temperature -- Z shift (mm): 0.---
  3891. ```
  3892. */
  3893. case 76:
  3894. {
  3895. #ifdef PINDA_THERMISTOR
  3896. if (true)
  3897. {
  3898. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  3899. //we need to know accurate position of first calibration point
  3900. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  3901. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first."));
  3902. break;
  3903. }
  3904. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  3905. {
  3906. // We don't know where we are! HOME!
  3907. // Push the commands to the front of the message queue in the reverse order!
  3908. // There shall be always enough space reserved for these commands.
  3909. repeatcommand_front(); // repeat G76 with all its parameters
  3910. enquecommand_front_P((PSTR("G28 W0")));
  3911. break;
  3912. }
  3913. lcd_show_fullscreen_message_and_wait_P(_i("Stable ambient temperature 21-26C is needed a rigid stand is required."));////MSG_TEMP_CAL_WARNING c=20 r=4
  3914. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  3915. if (result)
  3916. {
  3917. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3918. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3919. current_position[Z_AXIS] = 50;
  3920. current_position[Y_AXIS] = 180;
  3921. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3922. st_synchronize();
  3923. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  3924. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  3925. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  3926. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3927. st_synchronize();
  3928. gcode_G28(false, false, true);
  3929. }
  3930. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  3931. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  3932. current_position[Z_AXIS] = 100;
  3933. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3934. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  3935. lcd_temp_cal_show_result(false);
  3936. break;
  3937. }
  3938. }
  3939. lcd_update_enable(true);
  3940. KEEPALIVE_STATE(NOT_BUSY); //no need to print busy messages as we print current temperatures periodicaly
  3941. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  3942. float zero_z;
  3943. int z_shift = 0; //unit: steps
  3944. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  3945. if (start_temp < 35) start_temp = 35;
  3946. if (start_temp < current_temperature_pinda) start_temp += 5;
  3947. printf_P(_N("start temperature: %.1f\n"), start_temp);
  3948. // setTargetHotend(200, 0);
  3949. setTargetBed(70 + (start_temp - 30));
  3950. custom_message_type = CustomMsg::TempCal;
  3951. custom_message_state = 1;
  3952. lcd_setstatuspgm(_T(MSG_TEMP_CALIBRATION));
  3953. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3954. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3955. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3956. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3957. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3958. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3959. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3960. st_synchronize();
  3961. while (current_temperature_pinda < start_temp)
  3962. {
  3963. delay_keep_alive(1000);
  3964. serialecho_temperatures();
  3965. }
  3966. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  3967. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3968. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3969. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  3970. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  3971. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3972. st_synchronize();
  3973. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  3974. if (find_z_result == false) {
  3975. lcd_temp_cal_show_result(find_z_result);
  3976. break;
  3977. }
  3978. zero_z = current_position[Z_AXIS];
  3979. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  3980. int i = -1; for (; i < 5; i++)
  3981. {
  3982. float temp = (40 + i * 5);
  3983. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  3984. if (i >= 0) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  3985. if (start_temp <= temp) break;
  3986. }
  3987. for (i++; i < 5; i++)
  3988. {
  3989. float temp = (40 + i * 5);
  3990. printf_P(_N("\nStep: %d/6\n"), i + 2);
  3991. custom_message_state = i + 2;
  3992. setTargetBed(50 + 10 * (temp - 30) / 5);
  3993. // setTargetHotend(255, 0);
  3994. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3995. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3996. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3997. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3998. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3999. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4000. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  4001. st_synchronize();
  4002. while (current_temperature_pinda < temp)
  4003. {
  4004. delay_keep_alive(1000);
  4005. serialecho_temperatures();
  4006. }
  4007. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4008. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  4009. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4010. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4011. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  4012. st_synchronize();
  4013. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4014. if (find_z_result == false) {
  4015. lcd_temp_cal_show_result(find_z_result);
  4016. break;
  4017. }
  4018. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4019. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  4020. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  4021. }
  4022. lcd_temp_cal_show_result(true);
  4023. break;
  4024. }
  4025. #endif //PINDA_THERMISTOR
  4026. setTargetBed(PINDA_MIN_T);
  4027. float zero_z;
  4028. int z_shift = 0; //unit: steps
  4029. int t_c; // temperature
  4030. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4031. // We don't know where we are! HOME!
  4032. // Push the commands to the front of the message queue in the reverse order!
  4033. // There shall be always enough space reserved for these commands.
  4034. repeatcommand_front(); // repeat G76 with all its parameters
  4035. enquecommand_front_P((PSTR("G28 W0")));
  4036. break;
  4037. }
  4038. puts_P(_N("PINDA probe calibration start"));
  4039. custom_message_type = CustomMsg::TempCal;
  4040. custom_message_state = 1;
  4041. lcd_setstatuspgm(_T(MSG_TEMP_CALIBRATION));
  4042. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4043. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4044. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4045. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  4046. st_synchronize();
  4047. while (abs(degBed() - PINDA_MIN_T) > 1) {
  4048. delay_keep_alive(1000);
  4049. serialecho_temperatures();
  4050. }
  4051. //enquecommand_P(PSTR("M190 S50"));
  4052. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4053. delay_keep_alive(1000);
  4054. serialecho_temperatures();
  4055. }
  4056. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4057. current_position[Z_AXIS] = 5;
  4058. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  4059. current_position[X_AXIS] = BED_X0;
  4060. current_position[Y_AXIS] = BED_Y0;
  4061. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  4062. st_synchronize();
  4063. find_bed_induction_sensor_point_z(-1.f);
  4064. zero_z = current_position[Z_AXIS];
  4065. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4066. for (int i = 0; i<5; i++) {
  4067. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4068. custom_message_state = i + 2;
  4069. t_c = 60 + i * 10;
  4070. setTargetBed(t_c);
  4071. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4072. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4073. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4074. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  4075. st_synchronize();
  4076. while (degBed() < t_c) {
  4077. delay_keep_alive(1000);
  4078. serialecho_temperatures();
  4079. }
  4080. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4081. delay_keep_alive(1000);
  4082. serialecho_temperatures();
  4083. }
  4084. current_position[Z_AXIS] = 5;
  4085. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  4086. current_position[X_AXIS] = BED_X0;
  4087. current_position[Y_AXIS] = BED_Y0;
  4088. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  4089. st_synchronize();
  4090. find_bed_induction_sensor_point_z(-1.f);
  4091. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4092. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  4093. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i*2, &z_shift);
  4094. }
  4095. custom_message_type = CustomMsg::Status;
  4096. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  4097. puts_P(_N("Temperature calibration done."));
  4098. disable_x();
  4099. disable_y();
  4100. disable_z();
  4101. disable_e0();
  4102. disable_e1();
  4103. disable_e2();
  4104. setTargetBed(0); //set bed target temperature back to 0
  4105. lcd_show_fullscreen_message_and_wait_P(_T(MSG_TEMP_CALIBRATION_DONE));
  4106. temp_cal_active = true;
  4107. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  4108. lcd_update_enable(true);
  4109. lcd_update(2);
  4110. }
  4111. break;
  4112. /*!
  4113. ### G80 - Mesh-based Z probe <a href="https://reprap.org/wiki/G-code#G80:_Mesh-based_Z_probe">G80: Mesh-based Z probe</a>
  4114. Default 3x3 grid can be changed on MK2.5/s and MK3/s to 7x7 grid.
  4115. #### Usage
  4116. G80 [ N | R | V | L | R | F | B ]
  4117. #### Parameters
  4118. - `N` - Number of mesh points on x axis. Default is 3. Valid values are 3 and 7.
  4119. - `R` - Probe retries. Default 3 max. 10
  4120. - `V` - Verbosity level 1=low, 10=mid, 20=high. It only can be used if the firmware has been compiled with SUPPORT_VERBOSITY active.
  4121. Using the following parameters enables additional "manual" bed leveling correction. Valid values are -100 microns to 100 microns.
  4122. #### Additional Parameters
  4123. - `L` - Left Bed Level correct value in um.
  4124. - `R` - Right Bed Level correct value in um.
  4125. - `F` - Front Bed Level correct value in um.
  4126. - `B` - Back Bed Level correct value in um.
  4127. */
  4128. /*
  4129. * Probes a grid and produces a mesh to compensate for variable bed height
  4130. * The S0 report the points as below
  4131. * +----> X-axis
  4132. * |
  4133. * |
  4134. * v Y-axis
  4135. */
  4136. case 80:
  4137. #ifdef MK1BP
  4138. break;
  4139. #endif //MK1BP
  4140. case_G80:
  4141. {
  4142. mesh_bed_leveling_flag = true;
  4143. #ifndef LA_NOCOMPAT
  4144. // When printing via USB there's no clear boundary between prints. Abuse MBL to indicate
  4145. // the beginning of a new print, allowing a new autodetected setting just after G80.
  4146. la10c_reset();
  4147. #endif
  4148. #ifndef PINDA_THERMISTOR
  4149. static bool run = false; // thermistor-less PINDA temperature compensation is running
  4150. #endif // ndef PINDA_THERMISTOR
  4151. #ifdef SUPPORT_VERBOSITY
  4152. int8_t verbosity_level = 0;
  4153. if (code_seen('V')) {
  4154. // Just 'V' without a number counts as V1.
  4155. char c = strchr_pointer[1];
  4156. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4157. }
  4158. #endif //SUPPORT_VERBOSITY
  4159. // Firstly check if we know where we are
  4160. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4161. // We don't know where we are! HOME!
  4162. // Push the commands to the front of the message queue in the reverse order!
  4163. // There shall be always enough space reserved for these commands.
  4164. repeatcommand_front(); // repeat G80 with all its parameters
  4165. enquecommand_front_P((PSTR("G28 W0")));
  4166. break;
  4167. }
  4168. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  4169. if (code_seen('N')) {
  4170. nMeasPoints = code_value_uint8();
  4171. if (nMeasPoints != 7) {
  4172. nMeasPoints = 3;
  4173. }
  4174. }
  4175. else {
  4176. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  4177. }
  4178. uint8_t nProbeRetry = 3;
  4179. if (code_seen('R')) {
  4180. nProbeRetry = code_value_uint8();
  4181. if (nProbeRetry > 10) {
  4182. nProbeRetry = 10;
  4183. }
  4184. }
  4185. else {
  4186. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  4187. }
  4188. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  4189. #ifndef PINDA_THERMISTOR
  4190. if (run == false && temp_cal_active == true && calibration_status_pinda() == true && target_temperature_bed >= 50)
  4191. {
  4192. temp_compensation_start();
  4193. run = true;
  4194. repeatcommand_front(); // repeat G80 with all its parameters
  4195. enquecommand_front_P((PSTR("G28 W0")));
  4196. break;
  4197. }
  4198. run = false;
  4199. #endif //PINDA_THERMISTOR
  4200. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  4201. CustomMsg custom_message_type_old = custom_message_type;
  4202. unsigned int custom_message_state_old = custom_message_state;
  4203. custom_message_type = CustomMsg::MeshBedLeveling;
  4204. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  4205. lcd_update(1);
  4206. mbl.reset(); //reset mesh bed leveling
  4207. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  4208. // consumed during the first movements following this statement.
  4209. babystep_undo();
  4210. // Cycle through all points and probe them
  4211. // First move up. During this first movement, the babystepping will be reverted.
  4212. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4213. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  4214. // The move to the first calibration point.
  4215. current_position[X_AXIS] = BED_X0;
  4216. current_position[Y_AXIS] = BED_Y0;
  4217. #ifdef SUPPORT_VERBOSITY
  4218. if (verbosity_level >= 1)
  4219. {
  4220. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4221. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  4222. }
  4223. #else //SUPPORT_VERBOSITY
  4224. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4225. #endif //SUPPORT_VERBOSITY
  4226. plan_buffer_line_curposXYZE(homing_feedrate[X_AXIS] / 30, active_extruder);
  4227. // Wait until the move is finished.
  4228. st_synchronize();
  4229. uint8_t mesh_point = 0; //index number of calibration point
  4230. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  4231. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  4232. 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)
  4233. #ifdef SUPPORT_VERBOSITY
  4234. if (verbosity_level >= 1) {
  4235. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  4236. }
  4237. #endif // SUPPORT_VERBOSITY
  4238. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  4239. const char *kill_message = NULL;
  4240. while (mesh_point != nMeasPoints * nMeasPoints) {
  4241. // Get coords of a measuring point.
  4242. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  4243. uint8_t iy = mesh_point / nMeasPoints;
  4244. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  4245. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  4246. custom_message_state--;
  4247. mesh_point++;
  4248. continue; //skip
  4249. }*/
  4250. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  4251. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  4252. {
  4253. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  4254. }
  4255. float z0 = 0.f;
  4256. if (has_z && (mesh_point > 0)) {
  4257. uint16_t z_offset_u = 0;
  4258. if (nMeasPoints == 7) {
  4259. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  4260. }
  4261. else {
  4262. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  4263. }
  4264. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  4265. #ifdef SUPPORT_VERBOSITY
  4266. if (verbosity_level >= 1) {
  4267. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  4268. }
  4269. #endif // SUPPORT_VERBOSITY
  4270. }
  4271. // Move Z up to MESH_HOME_Z_SEARCH.
  4272. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4273. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  4274. float init_z_bckp = current_position[Z_AXIS];
  4275. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  4276. st_synchronize();
  4277. // Move to XY position of the sensor point.
  4278. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  4279. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  4280. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  4281. #ifdef SUPPORT_VERBOSITY
  4282. if (verbosity_level >= 1) {
  4283. clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4284. SERIAL_PROTOCOL(mesh_point);
  4285. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  4286. }
  4287. #else //SUPPORT_VERBOSITY
  4288. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4289. #endif // SUPPORT_VERBOSITY
  4290. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  4291. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  4292. st_synchronize();
  4293. // Go down until endstop is hit
  4294. const float Z_CALIBRATION_THRESHOLD = 1.f;
  4295. if (!find_bed_induction_sensor_point_z((has_z && mesh_point > 0) ? z0 - Z_CALIBRATION_THRESHOLD : -10.f, nProbeRetry)) { //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
  4296. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  4297. break;
  4298. }
  4299. if (init_z_bckp - current_position[Z_AXIS] < 0.1f) { //broken cable or initial Z coordinate too low. Go to MESH_HOME_Z_SEARCH and repeat last step (z-probe) again to distinguish between these two cases.
  4300. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  4301. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4302. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  4303. st_synchronize();
  4304. if (!find_bed_induction_sensor_point_z((has_z && mesh_point > 0) ? z0 - Z_CALIBRATION_THRESHOLD : -10.f, nProbeRetry)) { //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
  4305. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  4306. break;
  4307. }
  4308. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  4309. printf_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken.\n"));
  4310. break;
  4311. }
  4312. }
  4313. 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
  4314. printf_P(PSTR("Bed leveling failed. Sensor triggered too high.\n"));
  4315. break;
  4316. }
  4317. #ifdef SUPPORT_VERBOSITY
  4318. if (verbosity_level >= 10) {
  4319. SERIAL_ECHOPGM("X: ");
  4320. MYSERIAL.print(current_position[X_AXIS], 5);
  4321. SERIAL_ECHOLNPGM("");
  4322. SERIAL_ECHOPGM("Y: ");
  4323. MYSERIAL.print(current_position[Y_AXIS], 5);
  4324. SERIAL_PROTOCOLPGM("\n");
  4325. }
  4326. #endif // SUPPORT_VERBOSITY
  4327. float offset_z = 0;
  4328. #ifdef PINDA_THERMISTOR
  4329. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  4330. #endif //PINDA_THERMISTOR
  4331. // #ifdef SUPPORT_VERBOSITY
  4332. /* if (verbosity_level >= 1)
  4333. {
  4334. SERIAL_ECHOPGM("mesh bed leveling: ");
  4335. MYSERIAL.print(current_position[Z_AXIS], 5);
  4336. SERIAL_ECHOPGM(" offset: ");
  4337. MYSERIAL.print(offset_z, 5);
  4338. SERIAL_ECHOLNPGM("");
  4339. }*/
  4340. // #endif // SUPPORT_VERBOSITY
  4341. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  4342. custom_message_state--;
  4343. mesh_point++;
  4344. lcd_update(1);
  4345. }
  4346. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4347. #ifdef SUPPORT_VERBOSITY
  4348. if (verbosity_level >= 20) {
  4349. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  4350. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  4351. MYSERIAL.print(current_position[Z_AXIS], 5);
  4352. }
  4353. #endif // SUPPORT_VERBOSITY
  4354. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  4355. st_synchronize();
  4356. if (mesh_point != nMeasPoints * nMeasPoints) {
  4357. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  4358. bool bState;
  4359. do { // repeat until Z-leveling o.k.
  4360. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ..."));
  4361. #ifdef TMC2130
  4362. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  4363. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  4364. #else // TMC2130
  4365. lcd_wait_for_click_delay(0); // ~ no timeout
  4366. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  4367. #endif // TMC2130
  4368. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  4369. bState=enable_z_endstop(false);
  4370. current_position[Z_AXIS] -= 1;
  4371. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40, active_extruder);
  4372. st_synchronize();
  4373. enable_z_endstop(true);
  4374. #ifdef TMC2130
  4375. tmc2130_home_enter(Z_AXIS_MASK);
  4376. #endif // TMC2130
  4377. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4378. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40, active_extruder);
  4379. st_synchronize();
  4380. #ifdef TMC2130
  4381. tmc2130_home_exit();
  4382. #endif // TMC2130
  4383. enable_z_endstop(bState);
  4384. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  4385. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  4386. custom_message_type=CustomMsg::Status; // display / status-line recovery
  4387. lcd_update_enable(true); // display / status-line recovery
  4388. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  4389. repeatcommand_front(); // re-run (i.e. of "G80")
  4390. break;
  4391. }
  4392. clean_up_after_endstop_move(l_feedmultiply);
  4393. // SERIAL_ECHOLNPGM("clean up finished ");
  4394. #ifndef PINDA_THERMISTOR
  4395. if(temp_cal_active == true && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  4396. #endif
  4397. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  4398. // SERIAL_ECHOLNPGM("babystep applied");
  4399. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  4400. #ifdef SUPPORT_VERBOSITY
  4401. if (verbosity_level >= 1) {
  4402. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  4403. }
  4404. #endif // SUPPORT_VERBOSITY
  4405. for (uint8_t i = 0; i < 4; ++i) {
  4406. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  4407. long correction = 0;
  4408. if (code_seen(codes[i]))
  4409. correction = code_value_long();
  4410. else if (eeprom_bed_correction_valid) {
  4411. unsigned char *addr = (i < 2) ?
  4412. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  4413. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  4414. correction = eeprom_read_int8(addr);
  4415. }
  4416. if (correction == 0)
  4417. continue;
  4418. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  4419. SERIAL_ERROR_START;
  4420. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  4421. SERIAL_ECHO(correction);
  4422. SERIAL_ECHOLNPGM(" microns");
  4423. }
  4424. else {
  4425. float offset = float(correction) * 0.001f;
  4426. switch (i) {
  4427. case 0:
  4428. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  4429. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  4430. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  4431. }
  4432. }
  4433. break;
  4434. case 1:
  4435. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  4436. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  4437. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  4438. }
  4439. }
  4440. break;
  4441. case 2:
  4442. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  4443. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  4444. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  4445. }
  4446. }
  4447. break;
  4448. case 3:
  4449. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  4450. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  4451. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  4452. }
  4453. }
  4454. break;
  4455. }
  4456. }
  4457. }
  4458. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  4459. if (nMeasPoints == 3) {
  4460. mbl.upsample_3x3(); //interpolation from 3x3 to 7x7 points using largrangian polynomials while using the same array z_values[iy][ix] for storing (just coppying measured data to new destination and interpolating between them)
  4461. }
  4462. /*
  4463. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4464. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4465. SERIAL_PROTOCOLPGM(",");
  4466. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4467. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4468. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4469. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4470. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4471. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4472. SERIAL_PROTOCOLPGM(" ");
  4473. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4474. }
  4475. SERIAL_PROTOCOLPGM("\n");
  4476. }
  4477. */
  4478. if (nMeasPoints == 7 && magnet_elimination) {
  4479. mbl_interpolation(nMeasPoints);
  4480. }
  4481. /*
  4482. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4483. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4484. SERIAL_PROTOCOLPGM(",");
  4485. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4486. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4487. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4488. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4489. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4490. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4491. SERIAL_PROTOCOLPGM(" ");
  4492. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4493. }
  4494. SERIAL_PROTOCOLPGM("\n");
  4495. }
  4496. */
  4497. // SERIAL_ECHOLNPGM("Upsample finished");
  4498. mbl.active = 1; //activate mesh bed leveling
  4499. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  4500. go_home_with_z_lift();
  4501. // SERIAL_ECHOLNPGM("Go home finished");
  4502. //unretract (after PINDA preheat retraction)
  4503. if (degHotend(active_extruder) > EXTRUDE_MINTEMP && temp_cal_active == true && calibration_status_pinda() == true && target_temperature_bed >= 50) {
  4504. current_position[E_AXIS] += default_retraction;
  4505. plan_buffer_line_curposXYZE(400, active_extruder);
  4506. }
  4507. KEEPALIVE_STATE(NOT_BUSY);
  4508. // Restore custom message state
  4509. lcd_setstatuspgm(_T(WELCOME_MSG));
  4510. custom_message_type = custom_message_type_old;
  4511. custom_message_state = custom_message_state_old;
  4512. mesh_bed_leveling_flag = false;
  4513. mesh_bed_run_from_menu = false;
  4514. lcd_update(2);
  4515. }
  4516. break;
  4517. /*!
  4518. ### G81 - Mesh bed leveling status <a href="https://reprap.org/wiki/G-code#G81:_Mesh_bed_leveling_status">G81: Mesh bed leveling status</a>
  4519. Prints mesh bed leveling status and bed profile if activated.
  4520. */
  4521. case 81:
  4522. if (mbl.active) {
  4523. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4524. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4525. SERIAL_PROTOCOLPGM(",");
  4526. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4527. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4528. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4529. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4530. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4531. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4532. SERIAL_PROTOCOLPGM(" ");
  4533. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4534. }
  4535. SERIAL_PROTOCOLPGM("\n");
  4536. }
  4537. }
  4538. else
  4539. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4540. break;
  4541. #if 0
  4542. /*!
  4543. ### G82: Single Z probe at current location - Not active <a href="https://reprap.org/wiki/G-code#G82:_Single_Z_probe_at_current_location">G82: Single Z probe at current location</a>
  4544. WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4545. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4546. */
  4547. case 82:
  4548. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4549. int l_feedmultiply = setup_for_endstop_move();
  4550. find_bed_induction_sensor_point_z();
  4551. clean_up_after_endstop_move(l_feedmultiply);
  4552. SERIAL_PROTOCOLPGM("Bed found at: ");
  4553. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4554. SERIAL_PROTOCOLPGM("\n");
  4555. break;
  4556. /*!
  4557. ### G83: Babystep in Z and store to EEPROM - Not active <a href="https://reprap.org/wiki/G-code#G83:_Babystep_in_Z_and_store_to_EEPROM">G83: Babystep in Z and store to EEPROM</a>
  4558. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4559. */
  4560. case 83:
  4561. {
  4562. int babystepz = code_seen('S') ? code_value() : 0;
  4563. int BabyPosition = code_seen('P') ? code_value() : 0;
  4564. if (babystepz != 0) {
  4565. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4566. // Is the axis indexed starting with zero or one?
  4567. if (BabyPosition > 4) {
  4568. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4569. }else{
  4570. // Save it to the eeprom
  4571. babystepLoadZ = babystepz;
  4572. EEPROM_save_B(EEPROM_BABYSTEP_Z0+(BabyPosition*2),&babystepLoadZ);
  4573. // adjust the Z
  4574. babystepsTodoZadd(babystepLoadZ);
  4575. }
  4576. }
  4577. }
  4578. break;
  4579. /*!
  4580. ### G84: UNDO Babystep Z (move Z axis back) - Not active <a href="https://reprap.org/wiki/G-code#G84:_UNDO_Babystep_Z_.28move_Z_axis_back.29">G84: UNDO Babystep Z (move Z axis back)</a>
  4581. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4582. */
  4583. case 84:
  4584. babystepsTodoZsubtract(babystepLoadZ);
  4585. // babystepLoadZ = 0;
  4586. break;
  4587. /*!
  4588. ### G85: Pick best babystep - Not active <a href="https://reprap.org/wiki/G-code#G85:_Pick_best_babystep">G85: Pick best babystep</a>
  4589. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4590. */
  4591. case 85:
  4592. lcd_pick_babystep();
  4593. break;
  4594. #endif
  4595. /*!
  4596. ### G86 - Disable babystep correction after home <a href="https://reprap.org/wiki/G-code#G86:_Disable_babystep_correction_after_home">G86: Disable babystep correction after home</a>
  4597. This G-code will be performed at the start of a calibration script.
  4598. (Prusa3D specific)
  4599. */
  4600. case 86:
  4601. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4602. break;
  4603. /*!
  4604. ### G87 - Enable babystep correction after home <a href="https://reprap.org/wiki/G-code#G87:_Enable_babystep_correction_after_home">G87: Enable babystep correction after home</a>
  4605. This G-code will be performed at the end of a calibration script.
  4606. (Prusa3D specific)
  4607. */
  4608. case 87:
  4609. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4610. break;
  4611. /*!
  4612. ### G88 - Reserved <a href="https://reprap.org/wiki/G-code#G88:_Reserved">G88: Reserved</a>
  4613. Currently has no effect.
  4614. */
  4615. // Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4616. case 88:
  4617. break;
  4618. #endif // ENABLE_MESH_BED_LEVELING
  4619. /*!
  4620. ### G90 - Switch off relative mode <a href="https://reprap.org/wiki/G-code#G90:_Set_to_Absolute_Positioning">G90: Set to Absolute Positioning</a>
  4621. All coordinates from now on are absolute relative to the origin of the machine. E axis is also switched to absolute mode.
  4622. */
  4623. case 90: {
  4624. for(uint8_t i = 0; i != NUM_AXIS; ++i)
  4625. axis_relative_modes[i] = false;
  4626. }
  4627. break;
  4628. /*!
  4629. ### G91 - Switch on relative mode <a href="https://reprap.org/wiki/G-code#G91:_Set_to_Relative_Positioning">G91: Set to Relative Positioning</a>
  4630. All coordinates from now on are relative to the last position. E axis is also switched to relative mode.
  4631. */
  4632. case 91: {
  4633. for(uint8_t i = 0; i != NUM_AXIS; ++i)
  4634. axis_relative_modes[i] = true;
  4635. }
  4636. break;
  4637. /*!
  4638. ### G92 - Set position <a href="https://reprap.org/wiki/G-code#G92:_Set_Position">G92: Set Position</a>
  4639. It is used for setting the current position of each axis. The parameters are always absolute to the origin.
  4640. If a parameter is omitted, that axis will not be affected.
  4641. If `X`, `Y`, or `Z` axis are specified, the move afterwards might stutter because of Mesh Bed Leveling. `E` axis is not affected if the target position is 0 (`G92 E0`).
  4642. A G92 without coordinates will reset all axes to zero on some firmware. This is not the case for Prusa-Firmware!
  4643. #### Usage
  4644. G92 [ X | Y | Z | E ]
  4645. #### Parameters
  4646. - `X` - new X axis position
  4647. - `Y` - new Y axis position
  4648. - `Z` - new Z axis position
  4649. - `E` - new extruder position
  4650. */
  4651. case 92: {
  4652. gcode_G92();
  4653. }
  4654. break;
  4655. /*!
  4656. ### G98 - Activate farm mode <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode</a>
  4657. Enable Prusa-specific Farm functions and g-code.
  4658. See Internal Prusa commands.
  4659. */
  4660. case 98:
  4661. farm_mode = 1;
  4662. PingTime = _millis();
  4663. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  4664. EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
  4665. SilentModeMenu = SILENT_MODE_OFF;
  4666. eeprom_update_byte((unsigned char *)EEPROM_SILENT, SilentModeMenu);
  4667. fCheckModeInit(); // alternatively invoke printer reset
  4668. break;
  4669. /*! ### G99 - Deactivate farm mode <a href="https://reprap.org/wiki/G-code#G99:_Deactivate_farm_mode">G99: Deactivate farm mode</a>
  4670. Disables Prusa-specific Farm functions and g-code.
  4671. */
  4672. case 99:
  4673. farm_mode = 0;
  4674. lcd_printer_connected();
  4675. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  4676. lcd_update(2);
  4677. fCheckModeInit(); // alternatively invoke printer reset
  4678. break;
  4679. default:
  4680. printf_P(PSTR("Unknown G code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4681. }
  4682. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4683. gcode_in_progress = 0;
  4684. } // end if(code_seen('G'))
  4685. /*!
  4686. ### End of G-Codes
  4687. */
  4688. /*!
  4689. ---------------------------------------------------------------------------------
  4690. # M Commands
  4691. */
  4692. else if(code_seen('M'))
  4693. {
  4694. int index;
  4695. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4696. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4697. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4698. printf_P(PSTR("Invalid M code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4699. } else
  4700. {
  4701. mcode_in_progress = (int)code_value();
  4702. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4703. switch(mcode_in_progress)
  4704. {
  4705. /*!
  4706. ### M0, M1 - Stop the printer <a href="https://reprap.org/wiki/G-code#M0:_Stop_or_Unconditional_stop">M0: Stop or Unconditional stop</a>
  4707. */
  4708. case 0: // M0 - Unconditional stop - Wait for user button press on LCD
  4709. case 1: // M1 - Conditional stop - Wait for user button press on LCD
  4710. {
  4711. char *src = strchr_pointer + 2;
  4712. codenum = 0;
  4713. bool hasP = false, hasS = false;
  4714. if (code_seen('P')) {
  4715. codenum = code_value(); // milliseconds to wait
  4716. hasP = codenum > 0;
  4717. }
  4718. if (code_seen('S')) {
  4719. codenum = code_value() * 1000; // seconds to wait
  4720. hasS = codenum > 0;
  4721. }
  4722. starpos = strchr(src, '*');
  4723. if (starpos != NULL) *(starpos) = '\0';
  4724. while (*src == ' ') ++src;
  4725. if (!hasP && !hasS && *src != '\0') {
  4726. lcd_setstatus(src);
  4727. } else {
  4728. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT
  4729. }
  4730. lcd_ignore_click(); //call lcd_ignore_click aslo for else ???
  4731. st_synchronize();
  4732. previous_millis_cmd = _millis();
  4733. if (codenum > 0){
  4734. codenum += _millis(); // keep track of when we started waiting
  4735. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4736. while(_millis() < codenum && !lcd_clicked()){
  4737. manage_heater();
  4738. manage_inactivity(true);
  4739. lcd_update(0);
  4740. }
  4741. KEEPALIVE_STATE(IN_HANDLER);
  4742. lcd_ignore_click(false);
  4743. }else{
  4744. marlin_wait_for_click();
  4745. }
  4746. if (IS_SD_PRINTING)
  4747. LCD_MESSAGERPGM(_T(MSG_RESUMING_PRINT));
  4748. else
  4749. LCD_MESSAGERPGM(_T(WELCOME_MSG));
  4750. }
  4751. break;
  4752. /*!
  4753. ### M17 - Enable all axes <a href="https://reprap.org/wiki/G-code#M17:_Enable.2FPower_all_stepper_motors">M17: Enable/Power all stepper motors</a>
  4754. */
  4755. case 17:
  4756. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE
  4757. enable_x();
  4758. enable_y();
  4759. enable_z();
  4760. enable_e0();
  4761. enable_e1();
  4762. enable_e2();
  4763. break;
  4764. #ifdef SDSUPPORT
  4765. /*!
  4766. ### M20 - SD Card file list <a href="https://reprap.org/wiki/G-code#M20:_List_SD_card">M20: List SD card</a>
  4767. */
  4768. case 20:
  4769. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4770. card.ls();
  4771. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4772. break;
  4773. /*!
  4774. ### M21 - Init SD card <a href="https://reprap.org/wiki/G-code#M21:_Initialize_SD_card">M21: Initialize SD card</a>
  4775. */
  4776. case 21:
  4777. card.initsd();
  4778. break;
  4779. /*!
  4780. ### M22 - Release SD card <a href="https://reprap.org/wiki/G-code#M22:_Release_SD_card">M22: Release SD card</a>
  4781. */
  4782. case 22:
  4783. card.release();
  4784. break;
  4785. /*!
  4786. ### M23 - Select file <a href="https://reprap.org/wiki/G-code#M23:_Select_SD_file">M23: Select SD file</a>
  4787. #### Usage
  4788. M23 [filename]
  4789. */
  4790. case 23:
  4791. starpos = (strchr(strchr_pointer + 4,'*'));
  4792. if(starpos!=NULL)
  4793. *(starpos)='\0';
  4794. card.openFile(strchr_pointer + 4,true);
  4795. break;
  4796. /*!
  4797. ### M24 - Start SD print <a href="https://reprap.org/wiki/G-code#M24:_Start.2Fresume_SD_print">M24: Start/resume SD print</a>
  4798. */
  4799. case 24:
  4800. if (isPrintPaused)
  4801. lcd_resume_print();
  4802. else
  4803. {
  4804. if (!card.get_sdpos())
  4805. {
  4806. // A new print has started from scratch, reset stats
  4807. failstats_reset_print();
  4808. #ifndef LA_NOCOMPAT
  4809. la10c_reset();
  4810. #endif
  4811. }
  4812. card.startFileprint();
  4813. starttime=_millis();
  4814. }
  4815. break;
  4816. /*!
  4817. ### M26 - Set SD index <a href="https://reprap.org/wiki/G-code#M26:_Set_SD_position">M26: Set SD position</a>
  4818. Set position in SD card file to index in bytes.
  4819. This command is expected to be called after M23 and before M24.
  4820. Otherwise effect of this command is undefined.
  4821. #### Usage
  4822. M26 [ S ]
  4823. #### Parameters
  4824. - `S` - Index in bytes
  4825. */
  4826. case 26:
  4827. if(card.cardOK && code_seen('S')) {
  4828. long index = code_value_long();
  4829. card.setIndex(index);
  4830. // We don't disable interrupt during update of sdpos_atomic
  4831. // as we expect, that SD card print is not active in this moment
  4832. sdpos_atomic = index;
  4833. }
  4834. break;
  4835. /*!
  4836. ### M27 - Get SD status <a href="https://reprap.org/wiki/G-code#M27:_Report_SD_print_status">M27: Report SD print status</a>
  4837. */
  4838. case 27:
  4839. card.getStatus();
  4840. break;
  4841. /*!
  4842. ### M28 - Start SD write <a href="https://reprap.org/wiki/G-code#M28:_Begin_write_to_SD_card">M28: Begin write to SD card</a>
  4843. */
  4844. case 28:
  4845. starpos = (strchr(strchr_pointer + 4,'*'));
  4846. if(starpos != NULL){
  4847. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4848. strchr_pointer = strchr(npos,' ') + 1;
  4849. *(starpos) = '\0';
  4850. }
  4851. card.openFile(strchr_pointer+4,false);
  4852. break;
  4853. /*! ### M29 - Stop SD write <a href="https://reprap.org/wiki/G-code#M29:_Stop_writing_to_SD_card">M29: Stop writing to SD card</a>
  4854. Stops writing to the SD file signaling the end of the uploaded file. It is processed very early and it's not written to the card.
  4855. */
  4856. case 29:
  4857. //processed in write to file routine above
  4858. //card,saving = false;
  4859. break;
  4860. /*!
  4861. ### M30 - Delete file <a href="https://reprap.org/wiki/G-code#M30:_Delete_a_file_on_the_SD_card">M30: Delete a file on the SD card</a>
  4862. #### Usage
  4863. M30 [filename]
  4864. */
  4865. case 30:
  4866. if (card.cardOK){
  4867. card.closefile();
  4868. starpos = (strchr(strchr_pointer + 4,'*'));
  4869. if(starpos != NULL){
  4870. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4871. strchr_pointer = strchr(npos,' ') + 1;
  4872. *(starpos) = '\0';
  4873. }
  4874. card.removeFile(strchr_pointer + 4);
  4875. }
  4876. break;
  4877. /*!
  4878. ### M32 - Select file and start SD print <a href="https://reprap.org/wiki/G-code#M32:_Select_file_and_start_SD_print">M32: Select file and start SD print</a>
  4879. @todo What are the parameters P and S for in M32?
  4880. */
  4881. case 32:
  4882. {
  4883. if(card.sdprinting) {
  4884. st_synchronize();
  4885. }
  4886. starpos = (strchr(strchr_pointer + 4,'*'));
  4887. char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4888. if(namestartpos==NULL)
  4889. {
  4890. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4891. }
  4892. else
  4893. namestartpos++; //to skip the '!'
  4894. if(starpos!=NULL)
  4895. *(starpos)='\0';
  4896. bool call_procedure=(code_seen('P'));
  4897. if(strchr_pointer>namestartpos)
  4898. call_procedure=false; //false alert, 'P' found within filename
  4899. if( card.cardOK )
  4900. {
  4901. card.openFile(namestartpos,true,!call_procedure);
  4902. if(code_seen('S'))
  4903. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4904. card.setIndex(code_value_long());
  4905. card.startFileprint();
  4906. if(!call_procedure)
  4907. {
  4908. if(!card.get_sdpos())
  4909. {
  4910. // A new print has started from scratch, reset stats
  4911. failstats_reset_print();
  4912. #ifndef LA_NOCOMPAT
  4913. la10c_reset();
  4914. #endif
  4915. }
  4916. starttime=_millis(); // procedure calls count as normal print time.
  4917. }
  4918. }
  4919. } break;
  4920. /*!
  4921. ### M928 - Start SD logging <a href="https://reprap.org/wiki/G-code#M928:_Start_SD_logging">M928: Start SD logging</a>
  4922. #### Usage
  4923. M928 [filename]
  4924. */
  4925. case 928:
  4926. starpos = (strchr(strchr_pointer + 5,'*'));
  4927. if(starpos != NULL){
  4928. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4929. strchr_pointer = strchr(npos,' ') + 1;
  4930. *(starpos) = '\0';
  4931. }
  4932. card.openLogFile(strchr_pointer+5);
  4933. break;
  4934. #endif //SDSUPPORT
  4935. /*!
  4936. ### M31 - Report current print time <a href="https://reprap.org/wiki/G-code#M31:_Output_time_since_last_M109_or_SD_card_start_to_serial">M31: Output time since last M109 or SD card start to serial</a>
  4937. */
  4938. case 31: //M31 take time since the start of the SD print or an M109 command
  4939. {
  4940. stoptime=_millis();
  4941. char time[30];
  4942. unsigned long t=(stoptime-starttime)/1000;
  4943. int sec,min;
  4944. min=t/60;
  4945. sec=t%60;
  4946. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4947. SERIAL_ECHO_START;
  4948. SERIAL_ECHOLN(time);
  4949. lcd_setstatus(time);
  4950. autotempShutdown();
  4951. }
  4952. break;
  4953. /*!
  4954. ### M42 - Set pin state <a href="https://reprap.org/wiki/G-code#M42:_Switch_I.2FO_pin">M42: Switch I/O pin</a>
  4955. #### Usage
  4956. M42 [ P | S ]
  4957. #### Parameters
  4958. - `P` - Pin number.
  4959. - `S` - Pin value. If the pin is analog, values are from 0 to 255. If the pin is digital, values are from 0 to 1.
  4960. */
  4961. case 42:
  4962. if (code_seen('S'))
  4963. {
  4964. int pin_status = code_value();
  4965. int pin_number = LED_PIN;
  4966. if (code_seen('P') && pin_status >= 0 && pin_status <= 255)
  4967. pin_number = code_value();
  4968. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  4969. {
  4970. if (sensitive_pins[i] == pin_number)
  4971. {
  4972. pin_number = -1;
  4973. break;
  4974. }
  4975. }
  4976. #if defined(FAN_PIN) && FAN_PIN > -1
  4977. if (pin_number == FAN_PIN)
  4978. fanSpeed = pin_status;
  4979. #endif
  4980. if (pin_number > -1)
  4981. {
  4982. pinMode(pin_number, OUTPUT);
  4983. digitalWrite(pin_number, pin_status);
  4984. analogWrite(pin_number, pin_status);
  4985. }
  4986. }
  4987. break;
  4988. /*!
  4989. ### M44 - Reset the bed skew and offset calibration <a href="https://reprap.org/wiki/G-code#M44:_Reset_the_bed_skew_and_offset_calibration">M44: Reset the bed skew and offset calibration</a>
  4990. */
  4991. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  4992. // Reset the baby step value and the baby step applied flag.
  4993. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4994. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  4995. // Reset the skew and offset in both RAM and EEPROM.
  4996. reset_bed_offset_and_skew();
  4997. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4998. // the planner will not perform any adjustments in the XY plane.
  4999. // Wait for the motors to stop and update the current position with the absolute values.
  5000. world2machine_revert_to_uncorrected();
  5001. break;
  5002. /*!
  5003. ### M45 - Bed skew and offset with manual Z up <a href="https://reprap.org/wiki/G-code#M45:_Bed_skew_and_offset_with_manual_Z_up">M45: Bed skew and offset with manual Z up</a>
  5004. #### Usage
  5005. M45 [ V ]
  5006. #### Parameters
  5007. - `V` - Verbosity level 1, 10 and 20 (low, mid, high). Only when SUPPORT_VERBOSITY is defined. Optional.
  5008. - `Z` - If it is provided, only Z calibration will run. Otherwise full calibration is executed.
  5009. */
  5010. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  5011. {
  5012. int8_t verbosity_level = 0;
  5013. bool only_Z = code_seen('Z');
  5014. #ifdef SUPPORT_VERBOSITY
  5015. if (code_seen('V'))
  5016. {
  5017. // Just 'V' without a number counts as V1.
  5018. char c = strchr_pointer[1];
  5019. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  5020. }
  5021. #endif //SUPPORT_VERBOSITY
  5022. gcode_M45(only_Z, verbosity_level);
  5023. }
  5024. break;
  5025. /*!
  5026. ### M46 - Show the assigned IP address <a href="https://reprap.org/wiki/G-code#M46:_Show_the_assigned_IP_address">M46: Show the assigned IP address.</a>
  5027. */
  5028. /*
  5029. case 46:
  5030. {
  5031. // M46: Prusa3D: Show the assigned IP address.
  5032. uint8_t ip[4];
  5033. bool hasIP = card.ToshibaFlashAir_GetIP(ip);
  5034. if (hasIP) {
  5035. SERIAL_ECHOPGM("Toshiba FlashAir current IP: ");
  5036. SERIAL_ECHO(int(ip[0]));
  5037. SERIAL_ECHOPGM(".");
  5038. SERIAL_ECHO(int(ip[1]));
  5039. SERIAL_ECHOPGM(".");
  5040. SERIAL_ECHO(int(ip[2]));
  5041. SERIAL_ECHOPGM(".");
  5042. SERIAL_ECHO(int(ip[3]));
  5043. SERIAL_ECHOLNPGM("");
  5044. } else {
  5045. SERIAL_ECHOLNPGM("Toshiba FlashAir GetIP failed");
  5046. }
  5047. break;
  5048. }
  5049. */
  5050. /*!
  5051. ### M47 - Show end stops dialog on the display <a href="https://reprap.org/wiki/G-code#M47:_Show_end_stops_dialog_on_the_display">M47: Show end stops dialog on the display</a>
  5052. */
  5053. case 47:
  5054. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5055. lcd_diag_show_end_stops();
  5056. KEEPALIVE_STATE(IN_HANDLER);
  5057. break;
  5058. #if 0
  5059. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  5060. {
  5061. // Disable the default update procedure of the display. We will do a modal dialog.
  5062. lcd_update_enable(false);
  5063. // Let the planner use the uncorrected coordinates.
  5064. mbl.reset();
  5065. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  5066. // the planner will not perform any adjustments in the XY plane.
  5067. // Wait for the motors to stop and update the current position with the absolute values.
  5068. world2machine_revert_to_uncorrected();
  5069. // Move the print head close to the bed.
  5070. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5071. 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);
  5072. st_synchronize();
  5073. // Home in the XY plane.
  5074. set_destination_to_current();
  5075. int l_feedmultiply = setup_for_endstop_move();
  5076. home_xy();
  5077. int8_t verbosity_level = 0;
  5078. if (code_seen('V')) {
  5079. // Just 'V' without a number counts as V1.
  5080. char c = strchr_pointer[1];
  5081. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  5082. }
  5083. bool success = scan_bed_induction_points(verbosity_level);
  5084. clean_up_after_endstop_move(l_feedmultiply);
  5085. // Print head up.
  5086. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5087. 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);
  5088. st_synchronize();
  5089. lcd_update_enable(true);
  5090. break;
  5091. }
  5092. #endif
  5093. #ifdef ENABLE_AUTO_BED_LEVELING
  5094. #ifdef Z_PROBE_REPEATABILITY_TEST
  5095. /*!
  5096. ### M48 - Z-Probe repeatability measurement function <a href="https://reprap.org/wiki/G-code#M48:_Measure_Z-Probe_repeatability">M48: Measure Z-Probe repeatability</a>
  5097. This function assumes the bed has been homed. Specifically, that a G28 command as been issued prior to invoking the M48 Z-Probe repeatability measurement function. Any information generated by a prior G29 Bed leveling command will be lost and needs to be regenerated.
  5098. The number of samples will default to 10 if not specified. You can use upper or lower case letters for any of the options EXCEPT n. n must be in lower case because Marlin uses a capital N for its communication protocol and will get horribly confused if you send it a capital N.
  5099. @todo Why would you check for both uppercase and lowercase? Seems wasteful.
  5100. #### Usage
  5101. M48 [ n | X | Y | V | L ]
  5102. #### Parameters
  5103. - `n` - Number of samples. Valid values 4-50
  5104. - `X` - X position for samples
  5105. - `Y` - Y position for samples
  5106. - `V` - Verbose level. Valid values 1-4
  5107. - `L` - Legs of movementprior to doing probe. Valid values 1-15
  5108. */
  5109. case 48: // M48 Z-Probe repeatability
  5110. {
  5111. #if Z_MIN_PIN == -1
  5112. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  5113. #endif
  5114. double sum=0.0;
  5115. double mean=0.0;
  5116. double sigma=0.0;
  5117. double sample_set[50];
  5118. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  5119. double X_current, Y_current, Z_current;
  5120. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  5121. if (code_seen('V') || code_seen('v')) {
  5122. verbose_level = code_value();
  5123. if (verbose_level<0 || verbose_level>4 ) {
  5124. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  5125. goto Sigma_Exit;
  5126. }
  5127. }
  5128. if (verbose_level > 0) {
  5129. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  5130. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  5131. }
  5132. if (code_seen('n')) {
  5133. n_samples = code_value();
  5134. if (n_samples<4 || n_samples>50 ) {
  5135. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  5136. goto Sigma_Exit;
  5137. }
  5138. }
  5139. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  5140. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  5141. Z_current = st_get_position_mm(Z_AXIS);
  5142. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5143. ext_position = st_get_position_mm(E_AXIS);
  5144. if (code_seen('X') || code_seen('x') ) {
  5145. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  5146. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  5147. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  5148. goto Sigma_Exit;
  5149. }
  5150. }
  5151. if (code_seen('Y') || code_seen('y') ) {
  5152. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  5153. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  5154. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  5155. goto Sigma_Exit;
  5156. }
  5157. }
  5158. if (code_seen('L') || code_seen('l') ) {
  5159. n_legs = code_value();
  5160. if ( n_legs==1 )
  5161. n_legs = 2;
  5162. if ( n_legs<0 || n_legs>15 ) {
  5163. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  5164. goto Sigma_Exit;
  5165. }
  5166. }
  5167. //
  5168. // Do all the preliminary setup work. First raise the probe.
  5169. //
  5170. st_synchronize();
  5171. plan_bed_level_matrix.set_to_identity();
  5172. plan_buffer_line( X_current, Y_current, Z_start_location,
  5173. ext_position,
  5174. homing_feedrate[Z_AXIS]/60,
  5175. active_extruder);
  5176. st_synchronize();
  5177. //
  5178. // Now get everything to the specified probe point So we can safely do a probe to
  5179. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  5180. // use that as a starting point for each probe.
  5181. //
  5182. if (verbose_level > 2)
  5183. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  5184. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5185. ext_position,
  5186. homing_feedrate[X_AXIS]/60,
  5187. active_extruder);
  5188. st_synchronize();
  5189. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  5190. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  5191. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5192. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  5193. //
  5194. // OK, do the inital probe to get us close to the bed.
  5195. // Then retrace the right amount and use that in subsequent probes
  5196. //
  5197. int l_feedmultiply = setup_for_endstop_move();
  5198. run_z_probe();
  5199. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5200. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5201. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5202. ext_position,
  5203. homing_feedrate[X_AXIS]/60,
  5204. active_extruder);
  5205. st_synchronize();
  5206. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5207. for( n=0; n<n_samples; n++) {
  5208. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  5209. if ( n_legs) {
  5210. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  5211. int rotational_direction, l;
  5212. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  5213. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  5214. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  5215. //SERIAL_ECHOPAIR("starting radius: ",radius);
  5216. //SERIAL_ECHOPAIR(" theta: ",theta);
  5217. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  5218. //SERIAL_PROTOCOLLNPGM("");
  5219. for( l=0; l<n_legs-1; l++) {
  5220. if (rotational_direction==1)
  5221. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5222. else
  5223. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5224. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  5225. if ( radius<0.0 )
  5226. radius = -radius;
  5227. X_current = X_probe_location + cos(theta) * radius;
  5228. Y_current = Y_probe_location + sin(theta) * radius;
  5229. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  5230. X_current = X_MIN_POS;
  5231. if ( X_current>X_MAX_POS)
  5232. X_current = X_MAX_POS;
  5233. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  5234. Y_current = Y_MIN_POS;
  5235. if ( Y_current>Y_MAX_POS)
  5236. Y_current = Y_MAX_POS;
  5237. if (verbose_level>3 ) {
  5238. SERIAL_ECHOPAIR("x: ", X_current);
  5239. SERIAL_ECHOPAIR("y: ", Y_current);
  5240. SERIAL_PROTOCOLLNPGM("");
  5241. }
  5242. do_blocking_move_to( X_current, Y_current, Z_current );
  5243. }
  5244. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5245. }
  5246. int l_feedmultiply = setup_for_endstop_move();
  5247. run_z_probe();
  5248. sample_set[n] = current_position[Z_AXIS];
  5249. //
  5250. // Get the current mean for the data points we have so far
  5251. //
  5252. sum=0.0;
  5253. for( j=0; j<=n; j++) {
  5254. sum = sum + sample_set[j];
  5255. }
  5256. mean = sum / (double (n+1));
  5257. //
  5258. // Now, use that mean to calculate the standard deviation for the
  5259. // data points we have so far
  5260. //
  5261. sum=0.0;
  5262. for( j=0; j<=n; j++) {
  5263. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5264. }
  5265. sigma = sqrt( sum / (double (n+1)) );
  5266. if (verbose_level > 1) {
  5267. SERIAL_PROTOCOL(n+1);
  5268. SERIAL_PROTOCOL(" of ");
  5269. SERIAL_PROTOCOL(n_samples);
  5270. SERIAL_PROTOCOLPGM(" z: ");
  5271. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5272. }
  5273. if (verbose_level > 2) {
  5274. SERIAL_PROTOCOL(" mean: ");
  5275. SERIAL_PROTOCOL_F(mean,6);
  5276. SERIAL_PROTOCOL(" sigma: ");
  5277. SERIAL_PROTOCOL_F(sigma,6);
  5278. }
  5279. if (verbose_level > 0)
  5280. SERIAL_PROTOCOLPGM("\n");
  5281. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5282. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5283. st_synchronize();
  5284. }
  5285. _delay(1000);
  5286. clean_up_after_endstop_move(l_feedmultiply);
  5287. // enable_endstops(true);
  5288. if (verbose_level > 0) {
  5289. SERIAL_PROTOCOLPGM("Mean: ");
  5290. SERIAL_PROTOCOL_F(mean, 6);
  5291. SERIAL_PROTOCOLPGM("\n");
  5292. }
  5293. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5294. SERIAL_PROTOCOL_F(sigma, 6);
  5295. SERIAL_PROTOCOLPGM("\n\n");
  5296. Sigma_Exit:
  5297. break;
  5298. }
  5299. #endif // Z_PROBE_REPEATABILITY_TEST
  5300. #endif // ENABLE_AUTO_BED_LEVELING
  5301. /*!
  5302. ### M73 - Set/get print progress <a href="https://reprap.org/wiki/G-code#M73:_Set.2FGet_build_percentage">M73: Set/Get build percentage</a>
  5303. #### Usage
  5304. M73 [ P | R | Q | S ]
  5305. #### Parameters
  5306. - `P` - Percent in normal mode
  5307. - `R` - Time remaining in normal mode
  5308. - `Q` - Percent in silent mode
  5309. - `S` - Time in silent mode
  5310. */
  5311. case 73: //M73 show percent done and time remaining
  5312. if(code_seen('P')) print_percent_done_normal = code_value();
  5313. if(code_seen('R')) print_time_remaining_normal = code_value();
  5314. if(code_seen('Q')) print_percent_done_silent = code_value();
  5315. if(code_seen('S')) print_time_remaining_silent = code_value();
  5316. {
  5317. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %d; print time remaining in mins: %d\n");
  5318. printf_P(_msg_mode_done_remain, _N("NORMAL"), int(print_percent_done_normal), print_time_remaining_normal);
  5319. printf_P(_msg_mode_done_remain, _N("SILENT"), int(print_percent_done_silent), print_time_remaining_silent);
  5320. }
  5321. break;
  5322. /*!
  5323. ### M104 - Set hotend temperature <a href="https://reprap.org/wiki/G-code#M104:_Set_Extruder_Temperature">M104: Set Extruder Temperature</a>
  5324. #### Usage
  5325. M104 [ S ]
  5326. #### Parameters
  5327. - `S` - Target temperature
  5328. */
  5329. case 104: // M104
  5330. {
  5331. uint8_t extruder;
  5332. if(setTargetedHotend(104,extruder)){
  5333. break;
  5334. }
  5335. if (code_seen('S'))
  5336. {
  5337. setTargetHotendSafe(code_value(), extruder);
  5338. }
  5339. break;
  5340. }
  5341. /*!
  5342. ### M112 - Emergency stop <a href="https://reprap.org/wiki/G-code#M112:_Full_.28Emergency.29_Stop">M112: Full (Emergency) Stop</a>
  5343. It is processed much earlier as to bypass the cmdqueue.
  5344. */
  5345. case 112:
  5346. kill(MSG_M112_KILL, 3);
  5347. break;
  5348. /*!
  5349. ### M140 - Set bed temperature <a href="https://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29">M140: Set Bed Temperature (Fast)</a>
  5350. #### Usage
  5351. M140 [ S ]
  5352. #### Parameters
  5353. - `S` - Target temperature
  5354. */
  5355. case 140:
  5356. if (code_seen('S')) setTargetBed(code_value());
  5357. break;
  5358. /*!
  5359. ### M105 - Report temperatures <a href="https://reprap.org/wiki/G-code#M105:_Get_Extruder_Temperature">M105: Get Extruder Temperature</a>
  5360. Prints temperatures:
  5361. - `T:` - Hotend (actual / target)
  5362. - `B:` - Bed (actual / target)
  5363. - `Tx:` - x Tool (actual / target)
  5364. - `@:` - Hotend power
  5365. - `B@:` - Bed power
  5366. - `P:` - PINDAv2 actual (only MK2.5/s and MK3/s)
  5367. - `A:` - Ambient actual (only MK3/s)
  5368. _Example:_
  5369. ok T:20.2 /0.0 B:19.1 /0.0 T0:20.2 /0.0 @:0 B@:0 P:19.8 A:26.4
  5370. */
  5371. case 105:
  5372. {
  5373. uint8_t extruder;
  5374. if(setTargetedHotend(105, extruder)){
  5375. break;
  5376. }
  5377. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  5378. SERIAL_PROTOCOLPGM("ok T:");
  5379. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  5380. SERIAL_PROTOCOLPGM(" /");
  5381. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  5382. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5383. SERIAL_PROTOCOLPGM(" B:");
  5384. SERIAL_PROTOCOL_F(degBed(),1);
  5385. SERIAL_PROTOCOLPGM(" /");
  5386. SERIAL_PROTOCOL_F(degTargetBed(),1);
  5387. #endif //TEMP_BED_PIN
  5388. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  5389. SERIAL_PROTOCOLPGM(" T");
  5390. SERIAL_PROTOCOL(cur_extruder);
  5391. SERIAL_PROTOCOLPGM(":");
  5392. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  5393. SERIAL_PROTOCOLPGM(" /");
  5394. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  5395. }
  5396. #else
  5397. SERIAL_ERROR_START;
  5398. SERIAL_ERRORLNRPGM(_i("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  5399. #endif
  5400. SERIAL_PROTOCOLPGM(" @:");
  5401. #ifdef EXTRUDER_WATTS
  5402. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  5403. SERIAL_PROTOCOLPGM("W");
  5404. #else
  5405. SERIAL_PROTOCOL(getHeaterPower(extruder));
  5406. #endif
  5407. SERIAL_PROTOCOLPGM(" B@:");
  5408. #ifdef BED_WATTS
  5409. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  5410. SERIAL_PROTOCOLPGM("W");
  5411. #else
  5412. SERIAL_PROTOCOL(getHeaterPower(-1));
  5413. #endif
  5414. #ifdef PINDA_THERMISTOR
  5415. SERIAL_PROTOCOLPGM(" P:");
  5416. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  5417. #endif //PINDA_THERMISTOR
  5418. #ifdef AMBIENT_THERMISTOR
  5419. SERIAL_PROTOCOLPGM(" A:");
  5420. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  5421. #endif //AMBIENT_THERMISTOR
  5422. #ifdef SHOW_TEMP_ADC_VALUES
  5423. {float raw = 0.0;
  5424. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5425. SERIAL_PROTOCOLPGM(" ADC B:");
  5426. SERIAL_PROTOCOL_F(degBed(),1);
  5427. SERIAL_PROTOCOLPGM("C->");
  5428. raw = rawBedTemp();
  5429. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  5430. SERIAL_PROTOCOLPGM(" Rb->");
  5431. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  5432. SERIAL_PROTOCOLPGM(" Rxb->");
  5433. SERIAL_PROTOCOL_F(raw, 5);
  5434. #endif
  5435. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  5436. SERIAL_PROTOCOLPGM(" T");
  5437. SERIAL_PROTOCOL(cur_extruder);
  5438. SERIAL_PROTOCOLPGM(":");
  5439. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  5440. SERIAL_PROTOCOLPGM("C->");
  5441. raw = rawHotendTemp(cur_extruder);
  5442. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  5443. SERIAL_PROTOCOLPGM(" Rt");
  5444. SERIAL_PROTOCOL(cur_extruder);
  5445. SERIAL_PROTOCOLPGM("->");
  5446. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  5447. SERIAL_PROTOCOLPGM(" Rx");
  5448. SERIAL_PROTOCOL(cur_extruder);
  5449. SERIAL_PROTOCOLPGM("->");
  5450. SERIAL_PROTOCOL_F(raw, 5);
  5451. }}
  5452. #endif
  5453. SERIAL_PROTOCOLLN("");
  5454. KEEPALIVE_STATE(NOT_BUSY);
  5455. return;
  5456. break;
  5457. }
  5458. /*!
  5459. ### M109 - Wait for extruder temperature <a href="https://reprap.org/wiki/G-code#M109:_Set_Extruder_Temperature_and_Wait">M109: Set Extruder Temperature and Wait</a>
  5460. #### Usage
  5461. M104 [ B | R | S ]
  5462. #### Parameters (not mandatory)
  5463. - `S` - Set extruder temperature
  5464. - `R` - Set extruder temperature
  5465. - `B` - Set max. extruder temperature, while `S` is min. temperature. Not active in default, only if AUTOTEMP is defined in source code.
  5466. Parameters S and R are treated identically.
  5467. Command always waits for both cool down and heat up.
  5468. If no parameters are supplied waits for previously set extruder temperature.
  5469. */
  5470. case 109:
  5471. {
  5472. uint8_t extruder;
  5473. if(setTargetedHotend(109, extruder)){
  5474. break;
  5475. }
  5476. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5477. heating_status = 1;
  5478. if (farm_mode) { prusa_statistics(1); };
  5479. #ifdef AUTOTEMP
  5480. autotemp_enabled=false;
  5481. #endif
  5482. if (code_seen('S')) {
  5483. setTargetHotendSafe(code_value(), extruder);
  5484. } else if (code_seen('R')) {
  5485. setTargetHotendSafe(code_value(), extruder);
  5486. }
  5487. #ifdef AUTOTEMP
  5488. if (code_seen('S')) autotemp_min=code_value();
  5489. if (code_seen('B')) autotemp_max=code_value();
  5490. if (code_seen('F'))
  5491. {
  5492. autotemp_factor=code_value();
  5493. autotemp_enabled=true;
  5494. }
  5495. #endif
  5496. codenum = _millis();
  5497. /* See if we are heating up or cooling down */
  5498. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5499. KEEPALIVE_STATE(NOT_BUSY);
  5500. cancel_heatup = false;
  5501. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5502. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5503. KEEPALIVE_STATE(IN_HANDLER);
  5504. heating_status = 2;
  5505. if (farm_mode) { prusa_statistics(2); };
  5506. //starttime=_millis();
  5507. previous_millis_cmd = _millis();
  5508. }
  5509. break;
  5510. /*!
  5511. ### M190 - Wait for bed temperature <a href="https://reprap.org/wiki/G-code#M190:_Wait_for_bed_temperature_to_reach_target_temp">M190: Wait for bed temperature to reach target temp</a>
  5512. #### Usage
  5513. M190 [ R | S ]
  5514. #### Parameters (not mandatory)
  5515. - `S` - Set extruder temperature and wait for heating
  5516. - `R` - Set extruder temperature and wait for heating or cooling
  5517. If no parameter is supplied, waits for heating or cooling to previously set temperature.
  5518. */
  5519. case 190:
  5520. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5521. {
  5522. bool CooldownNoWait = false;
  5523. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5524. heating_status = 3;
  5525. if (farm_mode) { prusa_statistics(1); };
  5526. if (code_seen('S'))
  5527. {
  5528. setTargetBed(code_value());
  5529. CooldownNoWait = true;
  5530. }
  5531. else if (code_seen('R'))
  5532. {
  5533. setTargetBed(code_value());
  5534. }
  5535. codenum = _millis();
  5536. cancel_heatup = false;
  5537. target_direction = isHeatingBed(); // true if heating, false if cooling
  5538. KEEPALIVE_STATE(NOT_BUSY);
  5539. while ( (target_direction)&&(!cancel_heatup) ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false)) )
  5540. {
  5541. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5542. {
  5543. if (!farm_mode) {
  5544. float tt = degHotend(active_extruder);
  5545. SERIAL_PROTOCOLPGM("T:");
  5546. SERIAL_PROTOCOL(tt);
  5547. SERIAL_PROTOCOLPGM(" E:");
  5548. SERIAL_PROTOCOL((int)active_extruder);
  5549. SERIAL_PROTOCOLPGM(" B:");
  5550. SERIAL_PROTOCOL_F(degBed(), 1);
  5551. SERIAL_PROTOCOLLN("");
  5552. }
  5553. codenum = _millis();
  5554. }
  5555. manage_heater();
  5556. manage_inactivity();
  5557. lcd_update(0);
  5558. }
  5559. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5560. KEEPALIVE_STATE(IN_HANDLER);
  5561. heating_status = 4;
  5562. previous_millis_cmd = _millis();
  5563. }
  5564. #endif
  5565. break;
  5566. #if defined(FAN_PIN) && FAN_PIN > -1
  5567. /*!
  5568. ### M106 - Set fan speed <a href="https://reprap.org/wiki/G-code#M106:_Fan_On">M106: Fan On</a>
  5569. #### Usage
  5570. M106 [ S ]
  5571. #### Parameters
  5572. - `S` - Specifies the duty cycle of the print fan. Allowed values are 0-255. If it's omitted, a value of 255 is used.
  5573. */
  5574. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5575. if (code_seen('S')){
  5576. fanSpeed=constrain(code_value(),0,255);
  5577. }
  5578. else {
  5579. fanSpeed=255;
  5580. }
  5581. break;
  5582. /*!
  5583. ### M107 - Fan off <a href="https://reprap.org/wiki/G-code#M107:_Fan_Off">M107: Fan Off</a>
  5584. */
  5585. case 107:
  5586. fanSpeed = 0;
  5587. break;
  5588. #endif //FAN_PIN
  5589. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5590. /*!
  5591. ### M80 - Turn on the Power Supply <a href="https://reprap.org/wiki/G-code#M80:_ATX_Power_On">M80: ATX Power On</a>
  5592. Only works if the firmware is compiled with PS_ON_PIN defined.
  5593. */
  5594. case 80:
  5595. SET_OUTPUT(PS_ON_PIN); //GND
  5596. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5597. // If you have a switch on suicide pin, this is useful
  5598. // if you want to start another print with suicide feature after
  5599. // a print without suicide...
  5600. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5601. SET_OUTPUT(SUICIDE_PIN);
  5602. WRITE(SUICIDE_PIN, HIGH);
  5603. #endif
  5604. powersupply = true;
  5605. LCD_MESSAGERPGM(_T(WELCOME_MSG));
  5606. lcd_update(0);
  5607. break;
  5608. /*!
  5609. ### M81 - Turn off Power Supply <a href="https://reprap.org/wiki/G-code#M81:_ATX_Power_Off">M81: ATX Power Off</a>
  5610. Only works if the firmware is compiled with PS_ON_PIN defined.
  5611. */
  5612. case 81:
  5613. disable_heater();
  5614. st_synchronize();
  5615. disable_e0();
  5616. disable_e1();
  5617. disable_e2();
  5618. finishAndDisableSteppers();
  5619. fanSpeed = 0;
  5620. _delay(1000); // Wait a little before to switch off
  5621. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5622. st_synchronize();
  5623. suicide();
  5624. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5625. SET_OUTPUT(PS_ON_PIN);
  5626. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5627. #endif
  5628. powersupply = false;
  5629. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5630. lcd_update(0);
  5631. break;
  5632. #endif
  5633. /*!
  5634. ### M82 - Set E axis to absolute mode <a href="https://reprap.org/wiki/G-code#M82:_Set_extruder_to_absolute_mode">M82: Set extruder to absolute mode</a>
  5635. Makes the extruder interpret extrusion as absolute positions.
  5636. */
  5637. case 82:
  5638. axis_relative_modes[E_AXIS] = false;
  5639. break;
  5640. /*!
  5641. ### M83 - Set E axis to relative mode <a href="https://reprap.org/wiki/G-code#M83:_Set_extruder_to_relative_mode">M83: Set extruder to relative mode</a>
  5642. Makes the extruder interpret extrusion values as relative positions.
  5643. */
  5644. case 83:
  5645. axis_relative_modes[E_AXIS] = true;
  5646. break;
  5647. /*!
  5648. ### M84 - Disable steppers <a href="https://reprap.org/wiki/G-code#M84:_Stop_idle_hold">M84: Stop idle hold</a>
  5649. This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5650. This command can be used without any additional parameters. In that case all steppers are disabled.
  5651. The file completeness check uses this parameter to detect an incomplete file. It has to be present at the end of a file with no parameters.
  5652. M84 [ S | X | Y | Z | E ]
  5653. - `S` - Seconds
  5654. - `X` - X axis
  5655. - `Y` - Y axis
  5656. - `Z` - Z axis
  5657. - `E` - Exruder
  5658. ### M18 - Disable steppers <a href="https://reprap.org/wiki/G-code#M18:_Disable_all_stepper_motors">M18: Disable all stepper motors</a>
  5659. Equal to M84 (compatibility)
  5660. */
  5661. case 18: //compatibility
  5662. case 84: // M84
  5663. if(code_seen('S')){
  5664. stepper_inactive_time = code_value() * 1000;
  5665. }
  5666. else
  5667. {
  5668. 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])));
  5669. if(all_axis)
  5670. {
  5671. st_synchronize();
  5672. disable_e0();
  5673. disable_e1();
  5674. disable_e2();
  5675. finishAndDisableSteppers();
  5676. }
  5677. else
  5678. {
  5679. st_synchronize();
  5680. if (code_seen('X')) disable_x();
  5681. if (code_seen('Y')) disable_y();
  5682. if (code_seen('Z')) disable_z();
  5683. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5684. if (code_seen('E')) {
  5685. disable_e0();
  5686. disable_e1();
  5687. disable_e2();
  5688. }
  5689. #endif
  5690. }
  5691. }
  5692. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  5693. print_time_remaining_init();
  5694. snmm_filaments_used = 0;
  5695. break;
  5696. /*!
  5697. ### M85 - Set max inactive time <a href="https://reprap.org/wiki/G-code#M85:_Set_Inactivity_Shutdown_Timer">M85: Set Inactivity Shutdown Timer</a>
  5698. #### Usage
  5699. M85 [ S ]
  5700. #### Parameters
  5701. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5702. */
  5703. case 85: // M85
  5704. if(code_seen('S')) {
  5705. max_inactive_time = code_value() * 1000;
  5706. }
  5707. break;
  5708. #ifdef SAFETYTIMER
  5709. /*!
  5710. ### M86 - Set safety timer expiration time <a href="https://reprap.org/wiki/G-code#M86:_Set_Safety_Timer_expiration_time">M86: Set Safety Timer expiration time</a>
  5711. When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5712. #### Usage
  5713. M86 [ S ]
  5714. #### Parameters
  5715. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5716. */
  5717. case 86:
  5718. if (code_seen('S')) {
  5719. safetytimer_inactive_time = code_value() * 1000;
  5720. safetyTimer.start();
  5721. }
  5722. break;
  5723. #endif
  5724. /*!
  5725. ### M92 Set Axis steps-per-unit <a href="https://reprap.org/wiki/G-code#M92:_Set_axis_steps_per_unit">M92: Set axis_steps_per_unit</a>
  5726. Allows programming of steps per unit (usually mm) for motor drives. These values are reset to firmware defaults on power on, unless saved to EEPROM if available (M500 in Marlin)
  5727. #### Usage
  5728. M92 [ X | Y | Z | E ]
  5729. #### Parameters
  5730. - `X` - Steps per unit for the X drive
  5731. - `Y` - Steps per unit for the Y drive
  5732. - `Z` - Steps per unit for the Z drive
  5733. - `E` - Steps per unit for the extruder drive
  5734. */
  5735. case 92:
  5736. for(int8_t i=0; i < NUM_AXIS; i++)
  5737. {
  5738. if(code_seen(axis_codes[i]))
  5739. {
  5740. if(i == E_AXIS) { // E
  5741. float value = code_value();
  5742. if(value < 20.0) {
  5743. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5744. cs.max_jerk[E_AXIS] *= factor;
  5745. max_feedrate[i] *= factor;
  5746. axis_steps_per_sqr_second[i] *= factor;
  5747. }
  5748. cs.axis_steps_per_unit[i] = value;
  5749. fsensor_set_axis_steps_per_unit(value);
  5750. }
  5751. else {
  5752. cs.axis_steps_per_unit[i] = code_value();
  5753. }
  5754. }
  5755. }
  5756. break;
  5757. /*!
  5758. ### M110 - Set Line number <a href="https://reprap.org/wiki/G-code#M110:_Set_Current_Line_Number">M110: Set Current Line Number</a>
  5759. Sets the line number in G-code
  5760. #### Usage
  5761. M110 [ N ]
  5762. #### Parameters
  5763. - `N` - Line number
  5764. */
  5765. case 110:
  5766. if (code_seen('N'))
  5767. gcode_LastN = code_value_long();
  5768. break;
  5769. /*!
  5770. ### M113 - Get or set host keep-alive interval <a href="https://reprap.org/wiki/G-code#M113:_Host_Keepalive">M113: Host Keepalive</a>
  5771. During some lengthy processes, such as G29, Marlin may appear to the host to have “gone away.” The “host keepalive” feature will send messages to the host when Marlin is busy or waiting for user response so the host won’t try to reconnect (or disconnect).
  5772. #### Usage
  5773. M113 [ S ]
  5774. #### Parameters
  5775. - `S` - Seconds. Default is 2 seconds between "busy" messages
  5776. */
  5777. case 113:
  5778. if (code_seen('S')) {
  5779. host_keepalive_interval = (uint8_t)code_value_short();
  5780. // NOMORE(host_keepalive_interval, 60);
  5781. }
  5782. else {
  5783. SERIAL_ECHO_START;
  5784. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5785. SERIAL_PROTOCOLLN("");
  5786. }
  5787. break;
  5788. /*!
  5789. ### M115 - Firmware info <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities">M115: Get Firmware Version and Capabilities</a>
  5790. Print the firmware info and capabilities
  5791. Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5792. `M115 U` Checks the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware, it will pause the print for 30s and ask the user to upgrade the firmware.
  5793. _Examples:_
  5794. `M115` results:
  5795. `FIRMWARE_NAME:Prusa-Firmware 3.8.1 based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:1.0 MACHINE_TYPE:Prusa i3 MK3S EXTRUDER_COUNT:1 UUID:00000000-0000-0000-0000-000000000000`
  5796. `M115 V` results:
  5797. `3.8.1`
  5798. `M115 U3.8.2-RC1` results on LCD display for 30s or user interaction:
  5799. `New firmware version available: 3.8.2-RC1 Please upgrade.`
  5800. #### Usage
  5801. M115 [ V | U ]
  5802. #### Parameters
  5803. - V - Report current installed firmware version
  5804. - U - Firmware version provided by G-code to be compared to current one.
  5805. */
  5806. case 115: // M115
  5807. if (code_seen('V')) {
  5808. // Report the Prusa version number.
  5809. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5810. } else if (code_seen('U')) {
  5811. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5812. // pause the print for 30s and ask the user to upgrade the firmware.
  5813. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5814. } else {
  5815. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5816. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5817. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5818. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5819. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5820. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5821. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5822. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5823. SERIAL_ECHOPGM(" UUID:");
  5824. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5825. }
  5826. break;
  5827. /*!
  5828. ### M114 - Get current position <a href="https://reprap.org/wiki/G-code#M114:_Get_Current_Position">M114: Get Current Position</a>
  5829. */
  5830. case 114:
  5831. gcode_M114();
  5832. break;
  5833. /*
  5834. M117 moved up to get the high priority
  5835. case 117: // M117 display message
  5836. starpos = (strchr(strchr_pointer + 5,'*'));
  5837. if(starpos!=NULL)
  5838. *(starpos)='\0';
  5839. lcd_setstatus(strchr_pointer + 5);
  5840. break;*/
  5841. /*!
  5842. ### M120 - Enable endstops <a href="https://reprap.org/wiki/G-code#M120:_Enable_endstop_detection">M120: Enable endstop detection</a>
  5843. */
  5844. case 120:
  5845. enable_endstops(false) ;
  5846. break;
  5847. /*!
  5848. ### M121 - Disable endstops <a href="https://reprap.org/wiki/G-code#M121:_Disable_endstop_detection">M121: Disable endstop detection</a>
  5849. */
  5850. case 121:
  5851. enable_endstops(true) ;
  5852. break;
  5853. /*!
  5854. ### M119 - Get endstop states <a href="https://reprap.org/wiki/G-code#M119:_Get_Endstop_Status">M119: Get Endstop Status</a>
  5855. Returns the current state of the configured X, Y, Z endstops. Takes into account any 'inverted endstop' settings, so one can confirm that the machine is interpreting the endstops correctly.
  5856. */
  5857. case 119:
  5858. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5859. SERIAL_PROTOCOLLN("");
  5860. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5861. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5862. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5863. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5864. }else{
  5865. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5866. }
  5867. SERIAL_PROTOCOLLN("");
  5868. #endif
  5869. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5870. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5871. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5872. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5873. }else{
  5874. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5875. }
  5876. SERIAL_PROTOCOLLN("");
  5877. #endif
  5878. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5879. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5880. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5881. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5882. }else{
  5883. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5884. }
  5885. SERIAL_PROTOCOLLN("");
  5886. #endif
  5887. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5888. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5889. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5890. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5891. }else{
  5892. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5893. }
  5894. SERIAL_PROTOCOLLN("");
  5895. #endif
  5896. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5897. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5898. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5899. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5900. }else{
  5901. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5902. }
  5903. SERIAL_PROTOCOLLN("");
  5904. #endif
  5905. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5906. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5907. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5908. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5909. }else{
  5910. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5911. }
  5912. SERIAL_PROTOCOLLN("");
  5913. #endif
  5914. break;
  5915. //!@todo update for all axes, use for loop
  5916. #ifdef BLINKM
  5917. /*!
  5918. ### M150 - Set RGB(W) Color <a href="https://reprap.org/wiki/G-code#M150:_Set_LED_color">M150: Set LED color</a>
  5919. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code by defining BLINKM and its dependencies.
  5920. #### Usage
  5921. M150 [ R | U | B ]
  5922. #### Parameters
  5923. - `R` - Red color value
  5924. - `U` - Green color value. It is NOT `G`!
  5925. - `B` - Blue color value
  5926. */
  5927. case 150:
  5928. {
  5929. byte red;
  5930. byte grn;
  5931. byte blu;
  5932. if(code_seen('R')) red = code_value();
  5933. if(code_seen('U')) grn = code_value();
  5934. if(code_seen('B')) blu = code_value();
  5935. SendColors(red,grn,blu);
  5936. }
  5937. break;
  5938. #endif //BLINKM
  5939. /*!
  5940. ### M200 - Set filament diameter <a href="https://reprap.org/wiki/G-code#M200:_Set_filament_diameter">M200: Set filament diameter</a>
  5941. #### Usage
  5942. M200 [ D | T ]
  5943. #### Parameters
  5944. - `D` - Diameter in mm
  5945. - `T` - Number of extruder (MMUs)
  5946. */
  5947. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5948. {
  5949. uint8_t extruder = active_extruder;
  5950. if(code_seen('T')) {
  5951. extruder = code_value();
  5952. if(extruder >= EXTRUDERS) {
  5953. SERIAL_ECHO_START;
  5954. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  5955. break;
  5956. }
  5957. }
  5958. if(code_seen('D')) {
  5959. float diameter = (float)code_value();
  5960. if (diameter == 0.0) {
  5961. // setting any extruder filament size disables volumetric on the assumption that
  5962. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5963. // for all extruders
  5964. cs.volumetric_enabled = false;
  5965. } else {
  5966. cs.filament_size[extruder] = (float)code_value();
  5967. // make sure all extruders have some sane value for the filament size
  5968. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5969. #if EXTRUDERS > 1
  5970. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5971. #if EXTRUDERS > 2
  5972. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5973. #endif
  5974. #endif
  5975. cs.volumetric_enabled = true;
  5976. }
  5977. } else {
  5978. //reserved for setting filament diameter via UFID or filament measuring device
  5979. break;
  5980. }
  5981. calculate_extruder_multipliers();
  5982. }
  5983. break;
  5984. /*!
  5985. ### M201 - Set Print Max Acceleration <a href="https://reprap.org/wiki/G-code#M201:_Set_max_printing_acceleration">M201: Set max printing acceleration</a>
  5986. For each axis individually.
  5987. */
  5988. case 201:
  5989. for (int8_t i = 0; i < NUM_AXIS; i++)
  5990. {
  5991. if (code_seen(axis_codes[i]))
  5992. {
  5993. unsigned long val = code_value();
  5994. #ifdef TMC2130
  5995. unsigned long val_silent = val;
  5996. if ((i == X_AXIS) || (i == Y_AXIS))
  5997. {
  5998. if (val > NORMAL_MAX_ACCEL_XY)
  5999. val = NORMAL_MAX_ACCEL_XY;
  6000. if (val_silent > SILENT_MAX_ACCEL_XY)
  6001. val_silent = SILENT_MAX_ACCEL_XY;
  6002. }
  6003. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  6004. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  6005. #else //TMC2130
  6006. max_acceleration_units_per_sq_second[i] = val;
  6007. #endif //TMC2130
  6008. }
  6009. }
  6010. // 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)
  6011. reset_acceleration_rates();
  6012. break;
  6013. #if 0 // Not used for Sprinter/grbl gen6
  6014. case 202: // M202
  6015. for(int8_t i=0; i < NUM_AXIS; i++) {
  6016. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  6017. }
  6018. break;
  6019. #endif
  6020. /*!
  6021. ### M203 - Set Max Feedrate <a href="https://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate">M203: Set maximum feedrate</a>
  6022. For each axis individually.
  6023. */
  6024. case 203: // M203 max feedrate mm/sec
  6025. for (int8_t i = 0; i < NUM_AXIS; i++)
  6026. {
  6027. if (code_seen(axis_codes[i]))
  6028. {
  6029. float val = code_value();
  6030. #ifdef TMC2130
  6031. float val_silent = val;
  6032. if ((i == X_AXIS) || (i == Y_AXIS))
  6033. {
  6034. if (val > NORMAL_MAX_FEEDRATE_XY)
  6035. val = NORMAL_MAX_FEEDRATE_XY;
  6036. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  6037. val_silent = SILENT_MAX_FEEDRATE_XY;
  6038. }
  6039. cs.max_feedrate_normal[i] = val;
  6040. cs.max_feedrate_silent[i] = val_silent;
  6041. #else //TMC2130
  6042. max_feedrate[i] = val;
  6043. #endif //TMC2130
  6044. }
  6045. }
  6046. break;
  6047. /*!
  6048. ### M204 - Acceleration settings <a href="https://reprap.org/wiki/G-code#M204:_Set_default_acceleration">M204: Set default acceleration</a>
  6049. #### Old format:
  6050. ##### Usage
  6051. M204 [ S | T ]
  6052. ##### Parameters
  6053. - `S` - normal moves
  6054. - `T` - filmanent only moves
  6055. #### New format:
  6056. ##### Usage
  6057. M204 [ P | R | T ]
  6058. ##### Parameters
  6059. - `P` - printing moves
  6060. - `R` - filmanent only moves
  6061. - `T` - travel moves (as of now T is ignored)
  6062. */
  6063. case 204:
  6064. {
  6065. if(code_seen('S')) {
  6066. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  6067. // and it is also generated by Slic3r to control acceleration per extrusion type
  6068. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  6069. cs.acceleration = code_value();
  6070. // Interpret the T value as retract acceleration in the old Marlin format.
  6071. if(code_seen('T'))
  6072. cs.retract_acceleration = code_value();
  6073. } else {
  6074. // New acceleration format, compatible with the upstream Marlin.
  6075. if(code_seen('P'))
  6076. cs.acceleration = code_value();
  6077. if(code_seen('R'))
  6078. cs.retract_acceleration = code_value();
  6079. if(code_seen('T')) {
  6080. // Interpret the T value as the travel acceleration in the new Marlin format.
  6081. /*!
  6082. @todo Prusa3D firmware currently does not support travel acceleration value independent from the extruding acceleration value.
  6083. */
  6084. // travel_acceleration = code_value();
  6085. }
  6086. }
  6087. }
  6088. break;
  6089. /*!
  6090. ### M205 - Set advanced settings <a href="https://reprap.org/wiki/G-code#M205:_Advanced_settings">M205: Advanced settings</a>
  6091. Set some advanced settings related to movement.
  6092. #### Usage
  6093. M205 [ S | T | B | X | Y | Z | E ]
  6094. #### Parameters
  6095. - `S` - Minimum feedrate for print moves (unit/s)
  6096. - `T` - Minimum feedrate for travel moves (units/s)
  6097. - `B` - Minimum segment time (us)
  6098. - `X` - Maximum X jerk (units/s)
  6099. - `Y` - Maximum Y jerk (units/s)
  6100. - `Z` - Maximum Z jerk (units/s)
  6101. - `E` - Maximum E jerk (units/s)
  6102. */
  6103. case 205:
  6104. {
  6105. if(code_seen('S')) cs.minimumfeedrate = code_value();
  6106. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  6107. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  6108. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  6109. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  6110. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  6111. if(code_seen('E'))
  6112. {
  6113. float e = code_value();
  6114. #ifndef LA_NOCOMPAT
  6115. e = la10c_jerk(e);
  6116. #endif
  6117. cs.max_jerk[E_AXIS] = e;
  6118. }
  6119. if (cs.max_jerk[X_AXIS] > DEFAULT_XJERK) cs.max_jerk[X_AXIS] = DEFAULT_XJERK;
  6120. if (cs.max_jerk[Y_AXIS] > DEFAULT_YJERK) cs.max_jerk[Y_AXIS] = DEFAULT_YJERK;
  6121. }
  6122. break;
  6123. /*!
  6124. ### M206 - Set additional homing offsets <a href="https://reprap.org/wiki/G-code#M206:_Offset_axes">M206: Offset axes</a>
  6125. #### Usage
  6126. M206 [ X | Y | Z ]
  6127. #### Parameters
  6128. - `X` - X axis offset
  6129. - `Y` - Y axis offset
  6130. - `Z` - Z axis offset
  6131. */
  6132. case 206:
  6133. for(int8_t i=0; i < 3; i++)
  6134. {
  6135. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  6136. }
  6137. break;
  6138. #ifdef FWRETRACT
  6139. /*!
  6140. ### M207 - Set firmware retraction <a href="https://reprap.org/wiki/G-code#M207:_Set_retract_length">M207: Set retract length</a>
  6141. #### Usage
  6142. M207 [ S | F | Z ]
  6143. #### Parameters
  6144. - `S` - positive length to retract, in mm
  6145. - `F` - retraction feedrate, in mm/min
  6146. - `Z` - additional zlift/hop
  6147. */
  6148. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  6149. {
  6150. if(code_seen('S'))
  6151. {
  6152. cs.retract_length = code_value() ;
  6153. }
  6154. if(code_seen('F'))
  6155. {
  6156. cs.retract_feedrate = code_value()/60 ;
  6157. }
  6158. if(code_seen('Z'))
  6159. {
  6160. cs.retract_zlift = code_value() ;
  6161. }
  6162. }break;
  6163. /*!
  6164. ### M208 - Set retract recover length <a href="https://reprap.org/wiki/G-code#M208:_Set_unretract_length">M208: Set unretract length</a>
  6165. #### Usage
  6166. M208 [ S | F ]
  6167. #### Parameters
  6168. - `S` - positive length surplus to the M207 Snnn, in mm
  6169. - `F` - feedrate, in mm/sec
  6170. */
  6171. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  6172. {
  6173. if(code_seen('S'))
  6174. {
  6175. cs.retract_recover_length = code_value() ;
  6176. }
  6177. if(code_seen('F'))
  6178. {
  6179. cs.retract_recover_feedrate = code_value()/60 ;
  6180. }
  6181. }break;
  6182. /*!
  6183. ### M209 - Enable/disable automatict retract <a href="https://reprap.org/wiki/G-code#M209:_Enable_automatic_retract">M209: Enable automatic retract</a>
  6184. This boolean value S 1=true or 0=false enables automatic retract detect if the slicer did not support G10/G11: every normal extrude-only move will be classified as retract depending on the direction.
  6185. #### Usage
  6186. M209 [ S ]
  6187. #### Parameters
  6188. - `S` - 1=true or 0=false
  6189. */
  6190. 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.
  6191. {
  6192. if(code_seen('S'))
  6193. {
  6194. int t= code_value() ;
  6195. switch(t)
  6196. {
  6197. case 0:
  6198. {
  6199. cs.autoretract_enabled=false;
  6200. retracted[0]=false;
  6201. #if EXTRUDERS > 1
  6202. retracted[1]=false;
  6203. #endif
  6204. #if EXTRUDERS > 2
  6205. retracted[2]=false;
  6206. #endif
  6207. }break;
  6208. case 1:
  6209. {
  6210. cs.autoretract_enabled=true;
  6211. retracted[0]=false;
  6212. #if EXTRUDERS > 1
  6213. retracted[1]=false;
  6214. #endif
  6215. #if EXTRUDERS > 2
  6216. retracted[2]=false;
  6217. #endif
  6218. }break;
  6219. default:
  6220. SERIAL_ECHO_START;
  6221. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6222. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6223. SERIAL_ECHOLNPGM("\"(1)");
  6224. }
  6225. }
  6226. }break;
  6227. #endif // FWRETRACT
  6228. #if EXTRUDERS > 1
  6229. /*!
  6230. ### M218 - Set hotend offset <a href="https://reprap.org/wiki/G-code#M218:_Set_Hotend_Offset">M218: Set Hotend Offset</a>
  6231. In Prusa Firmware this G-code is only active if `EXTRUDERS` is higher then 1 in the source code. On Original i3 Prusa MK2/s MK2.5/s MK3/s it is not active.
  6232. #### Usage
  6233. M218 [ X | Y ]
  6234. #### Parameters
  6235. - `X` - X offset
  6236. - `Y` - Y offset
  6237. */
  6238. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  6239. {
  6240. uint8_t extruder;
  6241. if(setTargetedHotend(218, extruder)){
  6242. break;
  6243. }
  6244. if(code_seen('X'))
  6245. {
  6246. extruder_offset[X_AXIS][extruder] = code_value();
  6247. }
  6248. if(code_seen('Y'))
  6249. {
  6250. extruder_offset[Y_AXIS][extruder] = code_value();
  6251. }
  6252. SERIAL_ECHO_START;
  6253. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  6254. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  6255. {
  6256. SERIAL_ECHO(" ");
  6257. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  6258. SERIAL_ECHO(",");
  6259. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  6260. }
  6261. SERIAL_ECHOLN("");
  6262. }break;
  6263. #endif
  6264. /*!
  6265. ### M220 Set feedrate percentage <a href="https://reprap.org/wiki/G-code#M220:_Set_speed_factor_override_percentage">M220: Set speed factor override percentage</a>
  6266. #### Usage
  6267. M220 [ B | S | R ]
  6268. #### Parameters
  6269. - `B` - Backup current speed factor
  6270. - `S` - Speed factor override percentage (0..100 or higher)
  6271. - `R` - Restore previous speed factor
  6272. */
  6273. case 220: // M220 S<factor in percent>- set speed factor override percentage
  6274. {
  6275. if (code_seen('B')) //backup current speed factor
  6276. {
  6277. saved_feedmultiply_mm = feedmultiply;
  6278. }
  6279. if(code_seen('S'))
  6280. {
  6281. feedmultiply = code_value() ;
  6282. }
  6283. if (code_seen('R')) { //restore previous feedmultiply
  6284. feedmultiply = saved_feedmultiply_mm;
  6285. }
  6286. }
  6287. break;
  6288. /*!
  6289. ### M221 - Set extrude factor override percentage <a href="https://reprap.org/wiki/G-code#M221:_Set_extrude_factor_override_percentage">M221: Set extrude factor override percentage</a>
  6290. #### Usage
  6291. M221 [ S | T ]
  6292. #### Parameters
  6293. - `S` - Extrude factor override percentage (0..100 or higher), default 100%
  6294. - `T` - Extruder drive number (Prusa Firmware only), default 0 if not set.
  6295. */
  6296. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  6297. {
  6298. if(code_seen('S'))
  6299. {
  6300. int tmp_code = code_value();
  6301. if (code_seen('T'))
  6302. {
  6303. uint8_t extruder;
  6304. if(setTargetedHotend(221, extruder)){
  6305. break;
  6306. }
  6307. extruder_multiply[extruder] = tmp_code;
  6308. }
  6309. else
  6310. {
  6311. extrudemultiply = tmp_code ;
  6312. }
  6313. }
  6314. calculate_extruder_multipliers();
  6315. }
  6316. break;
  6317. /*!
  6318. ### M226 - Wait for Pin state <a href="https://reprap.org/wiki/G-code#M226:_Wait_for_pin_state">M226: Wait for pin state</a>
  6319. Wait until the specified pin reaches the state required
  6320. #### Usage
  6321. M226 [ P | S ]
  6322. #### Parameters
  6323. - `P` - pin number
  6324. - `S` - pin state
  6325. */
  6326. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  6327. {
  6328. if(code_seen('P')){
  6329. int pin_number = code_value(); // pin number
  6330. int pin_state = -1; // required pin state - default is inverted
  6331. if(code_seen('S')) pin_state = code_value(); // required pin state
  6332. if(pin_state >= -1 && pin_state <= 1){
  6333. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  6334. {
  6335. if (sensitive_pins[i] == pin_number)
  6336. {
  6337. pin_number = -1;
  6338. break;
  6339. }
  6340. }
  6341. if (pin_number > -1)
  6342. {
  6343. int target = LOW;
  6344. st_synchronize();
  6345. pinMode(pin_number, INPUT);
  6346. switch(pin_state){
  6347. case 1:
  6348. target = HIGH;
  6349. break;
  6350. case 0:
  6351. target = LOW;
  6352. break;
  6353. case -1:
  6354. target = !digitalRead(pin_number);
  6355. break;
  6356. }
  6357. while(digitalRead(pin_number) != target){
  6358. manage_heater();
  6359. manage_inactivity();
  6360. lcd_update(0);
  6361. }
  6362. }
  6363. }
  6364. }
  6365. }
  6366. break;
  6367. #if NUM_SERVOS > 0
  6368. /*!
  6369. ### M280 - Set/Get servo position <a href="https://reprap.org/wiki/G-code#M280:_Set_servo_position">M280: Set servo position</a>
  6370. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6371. #### Usage
  6372. M280 [ P | S ]
  6373. #### Parameters
  6374. - `P` - Servo index (id)
  6375. - `S` - Target position
  6376. */
  6377. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6378. {
  6379. int servo_index = -1;
  6380. int servo_position = 0;
  6381. if (code_seen('P'))
  6382. servo_index = code_value();
  6383. if (code_seen('S')) {
  6384. servo_position = code_value();
  6385. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  6386. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6387. servos[servo_index].attach(0);
  6388. #endif
  6389. servos[servo_index].write(servo_position);
  6390. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6391. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  6392. servos[servo_index].detach();
  6393. #endif
  6394. }
  6395. else {
  6396. SERIAL_ECHO_START;
  6397. SERIAL_ECHO("Servo ");
  6398. SERIAL_ECHO(servo_index);
  6399. SERIAL_ECHOLN(" out of range");
  6400. }
  6401. }
  6402. else if (servo_index >= 0) {
  6403. SERIAL_PROTOCOL(MSG_OK);
  6404. SERIAL_PROTOCOL(" Servo ");
  6405. SERIAL_PROTOCOL(servo_index);
  6406. SERIAL_PROTOCOL(": ");
  6407. SERIAL_PROTOCOL(servos[servo_index].read());
  6408. SERIAL_PROTOCOLLN("");
  6409. }
  6410. }
  6411. break;
  6412. #endif // NUM_SERVOS > 0
  6413. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  6414. /*!
  6415. ### M300 - Play tone <a href="https://reprap.org/wiki/G-code#M300:_Play_beep_sound">M300: Play beep sound</a>
  6416. In Prusa Firmware the defaults are `100Hz` and `1000ms`, so that `M300` without parameters will beep for a second.
  6417. #### Usage
  6418. M300 [ S | P ]
  6419. #### Parameters
  6420. - `S` - frequency in Hz. Not all firmware versions support this parameter
  6421. - `P` - duration in milliseconds
  6422. */
  6423. case 300: // M300
  6424. {
  6425. int beepS = code_seen('S') ? code_value() : 110;
  6426. int beepP = code_seen('P') ? code_value() : 1000;
  6427. if (beepS > 0)
  6428. {
  6429. #if BEEPER > 0
  6430. Sound_MakeCustom(beepP,beepS,false);
  6431. #endif
  6432. }
  6433. else
  6434. {
  6435. _delay(beepP);
  6436. }
  6437. }
  6438. break;
  6439. #endif // M300
  6440. #ifdef PIDTEMP
  6441. /*!
  6442. ### M301 - Set hotend PID <a href="https://reprap.org/wiki/G-code#M301:_Set_PID_parameters">M301: Set PID parameters</a>
  6443. Sets Proportional (P), Integral (I) and Derivative (D) values for hot end.
  6444. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6445. #### Usage
  6446. M301 [ P | I | D | C ]
  6447. #### Parameters
  6448. - `P` - proportional (Kp)
  6449. - `I` - integral (Ki)
  6450. - `D` - derivative (Kd)
  6451. - `C` - heating power=Kc*(e_speed0)
  6452. */
  6453. case 301:
  6454. {
  6455. if(code_seen('P')) cs.Kp = code_value();
  6456. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  6457. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6458. #ifdef PID_ADD_EXTRUSION_RATE
  6459. if(code_seen('C')) Kc = code_value();
  6460. #endif
  6461. updatePID();
  6462. SERIAL_PROTOCOLRPGM(MSG_OK);
  6463. SERIAL_PROTOCOL(" p:");
  6464. SERIAL_PROTOCOL(cs.Kp);
  6465. SERIAL_PROTOCOL(" i:");
  6466. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6467. SERIAL_PROTOCOL(" d:");
  6468. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6469. #ifdef PID_ADD_EXTRUSION_RATE
  6470. SERIAL_PROTOCOL(" c:");
  6471. //Kc does not have scaling applied above, or in resetting defaults
  6472. SERIAL_PROTOCOL(Kc);
  6473. #endif
  6474. SERIAL_PROTOCOLLN("");
  6475. }
  6476. break;
  6477. #endif //PIDTEMP
  6478. #ifdef PIDTEMPBED
  6479. /*!
  6480. ### M304 - Set bed PID <a href="https://reprap.org/wiki/G-code#M304:_Set_PID_parameters_-_Bed">M304: Set PID parameters - Bed</a>
  6481. Sets Proportional (P), Integral (I) and Derivative (D) values for bed.
  6482. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6483. #### Usage
  6484. M304 [ P | I | D ]
  6485. #### Parameters
  6486. - `P` - proportional (Kp)
  6487. - `I` - integral (Ki)
  6488. - `D` - derivative (Kd)
  6489. */
  6490. case 304:
  6491. {
  6492. if(code_seen('P')) cs.bedKp = code_value();
  6493. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6494. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6495. updatePID();
  6496. SERIAL_PROTOCOLRPGM(MSG_OK);
  6497. SERIAL_PROTOCOL(" p:");
  6498. SERIAL_PROTOCOL(cs.bedKp);
  6499. SERIAL_PROTOCOL(" i:");
  6500. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6501. SERIAL_PROTOCOL(" d:");
  6502. SERIAL_PROTOCOL(unscalePID_d(cs.bedKd));
  6503. SERIAL_PROTOCOLLN("");
  6504. }
  6505. break;
  6506. #endif //PIDTEMP
  6507. /*!
  6508. ### M240 - Trigger camera <a href="https://reprap.org/wiki/G-code#M240:_Trigger_camera">M240: Trigger camera</a>
  6509. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6510. You need to (re)define and assign `CHDK` or `PHOTOGRAPH_PIN` the correct pin number to be able to use the feature.
  6511. */
  6512. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6513. {
  6514. #ifdef CHDK
  6515. SET_OUTPUT(CHDK);
  6516. WRITE(CHDK, HIGH);
  6517. chdkHigh = _millis();
  6518. chdkActive = true;
  6519. #else
  6520. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6521. const uint8_t NUM_PULSES=16;
  6522. const float PULSE_LENGTH=0.01524;
  6523. for(int i=0; i < NUM_PULSES; i++) {
  6524. WRITE(PHOTOGRAPH_PIN, HIGH);
  6525. _delay_ms(PULSE_LENGTH);
  6526. WRITE(PHOTOGRAPH_PIN, LOW);
  6527. _delay_ms(PULSE_LENGTH);
  6528. }
  6529. _delay(7.33);
  6530. for(int i=0; i < NUM_PULSES; i++) {
  6531. WRITE(PHOTOGRAPH_PIN, HIGH);
  6532. _delay_ms(PULSE_LENGTH);
  6533. WRITE(PHOTOGRAPH_PIN, LOW);
  6534. _delay_ms(PULSE_LENGTH);
  6535. }
  6536. #endif
  6537. #endif //chdk end if
  6538. }
  6539. break;
  6540. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6541. /*!
  6542. ### M302 - Allow cold extrude, or set minimum extrude temperature <a href="https://reprap.org/wiki/G-code#M302:_Allow_cold_extrudes">M302: Allow cold extrudes</a>
  6543. This tells the printer to allow movement of the extruder motor above a certain temperature, or if disabled, to allow extruder movement when the hotend is below a safe printing temperature.
  6544. #### Usage
  6545. M302 [ S ]
  6546. #### Parameters
  6547. - `S` - Cold extrude minimum temperature
  6548. */
  6549. case 302:
  6550. {
  6551. float temp = .0;
  6552. if (code_seen('S')) temp=code_value();
  6553. set_extrude_min_temp(temp);
  6554. }
  6555. break;
  6556. #endif
  6557. /*!
  6558. ### M303 - PID autotune <a href="https://reprap.org/wiki/G-code#M303:_Run_PID_tuning">M303: Run PID tuning</a>
  6559. PID Tuning refers to a control algorithm used in some repraps to tune heating behavior for hot ends and heated beds. This command generates Proportional (Kp), Integral (Ki), and Derivative (Kd) values for the hotend or bed. Send the appropriate code and wait for the output to update the firmware values.
  6560. #### Usage
  6561. M303 [ E | S | C ]
  6562. #### Parameters
  6563. - `E` - Extruder, default `E0`. Use `E-1` to calibrate the bed PID
  6564. - `S` - Target temperature, default `210°C` for hotend, 70 for bed
  6565. - `C` - Cycles, default `5`
  6566. */
  6567. case 303:
  6568. {
  6569. float temp = 150.0;
  6570. int e=0;
  6571. int c=5;
  6572. if (code_seen('E')) e=code_value();
  6573. if (e<0)
  6574. temp=70;
  6575. if (code_seen('S')) temp=code_value();
  6576. if (code_seen('C')) c=code_value();
  6577. PID_autotune(temp, e, c);
  6578. }
  6579. break;
  6580. /*!
  6581. ### M400 - Wait for all moves to finish <a href="https://reprap.org/wiki/G-code#M400:_Wait_for_current_moves_to_finish">M400: Wait for current moves to finish</a>
  6582. Finishes all current moves and and thus clears the buffer.
  6583. Equivalent to `G4` with no parameters.
  6584. */
  6585. case 400:
  6586. {
  6587. st_synchronize();
  6588. }
  6589. break;
  6590. /*!
  6591. ### M403 - Set filament type (material) for particular extruder and notify the MMU <a href="https://reprap.org/wiki/G-code#M403:_Set_filament_type_.28material.29_for_particular_extruder_and_notify_the_MMU.">M403 - Set filament type (material) for particular extruder and notify the MMU</a>
  6592. Currently three different materials are needed (default, flex and PVA).
  6593. And storing this information for different load/unload profiles etc. in the future firmware does not have to wait for "ok" from MMU.
  6594. #### Usage
  6595. M403 [ E | F ]
  6596. #### Parameters
  6597. - `E` - Extruder number. 0-indexed.
  6598. - `F` - Filament type
  6599. */
  6600. case 403:
  6601. {
  6602. // currently three different materials are needed (default, flex and PVA)
  6603. // add storing this information for different load/unload profiles etc. in the future
  6604. // firmware does not wait for "ok" from mmu
  6605. if (mmu_enabled)
  6606. {
  6607. uint8_t extruder = 255;
  6608. uint8_t filament = FILAMENT_UNDEFINED;
  6609. if(code_seen('E')) extruder = code_value();
  6610. if(code_seen('F')) filament = code_value();
  6611. mmu_set_filament_type(extruder, filament);
  6612. }
  6613. }
  6614. break;
  6615. /*!
  6616. ### M500 - Store settings in EEPROM <a href="https://reprap.org/wiki/G-code#M500:_Store_parameters_in_non-volatile_storage">M500: Store parameters in non-volatile storage</a>
  6617. Save current parameters to EEPROM.
  6618. */
  6619. case 500:
  6620. {
  6621. Config_StoreSettings();
  6622. }
  6623. break;
  6624. /*!
  6625. ### M501 - Read settings from EEPROM <a href="https://reprap.org/wiki/G-code#M501:_Read_parameters_from_EEPROM">M501: Read parameters from EEPROM</a>
  6626. Set the active parameters to those stored in the EEPROM. This is useful to revert parameters after experimenting with them.
  6627. */
  6628. case 501:
  6629. {
  6630. Config_RetrieveSettings();
  6631. }
  6632. break;
  6633. /*!
  6634. ### M502 - Revert all settings to factory default <a href="https://reprap.org/wiki/G-code#M502:_Restore_Default_Settings">M502: Restore Default Settings</a>
  6635. This command resets all tunable parameters to their default values, as set in the firmware's configuration files. This doesn't reset any parameters stored in the EEPROM, so it must be followed by M500 to write the default settings.
  6636. */
  6637. case 502:
  6638. {
  6639. Config_ResetDefault();
  6640. }
  6641. break;
  6642. /*!
  6643. ### M503 - Repport all settings currently in memory <a href="https://reprap.org/wiki/G-code#M503:_Report_Current_Settings">M503: Report Current Settings</a>
  6644. This command asks the firmware to reply with the current print settings as set in memory. Settings will differ from EEPROM contents if changed since the last load / save. The reply output includes the G-Code commands to produce each setting. For example, Steps-Per-Unit values are displayed as an M92 command.
  6645. */
  6646. case 503:
  6647. {
  6648. Config_PrintSettings();
  6649. }
  6650. break;
  6651. /*!
  6652. ### M509 - Force language selection <a href="https://reprap.org/wiki/G-code#M509:_Force_language_selection">M509: Force language selection</a>
  6653. Resets the language to English.
  6654. Only on Original Prusa i3 MK2.5/s and MK3/s with multiple languages.
  6655. */
  6656. case 509:
  6657. {
  6658. lang_reset();
  6659. SERIAL_ECHO_START;
  6660. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6661. }
  6662. break;
  6663. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6664. /*!
  6665. ### M540 - Abort print on endstop hit (enable/disable) <a href="https://reprap.org/wiki/G-code#M540_in_Marlin:_Enable.2FDisable_.22Stop_SD_Print_on_Endstop_Hit.22">M540 in Marlin: Enable/Disable "Stop SD Print on Endstop Hit"</a>
  6666. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. You must define `ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED`.
  6667. #### Usage
  6668. M540 [ S ]
  6669. #### Parameters
  6670. - `S` - disabled=0, enabled=1
  6671. */
  6672. case 540:
  6673. {
  6674. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6675. }
  6676. break;
  6677. #endif
  6678. /*!
  6679. ### M851 - Set Z-Probe Offset <a href="https://reprap.org/wiki/G-code#M851:_Set_Z-Probe_Offset">M851: Set Z-Probe Offset"</a>
  6680. Sets the Z-probe Z offset. This offset is used to determine the actual Z position of the nozzle when using a probe to home Z with G28. This value may also be used by G81 (Prusa) / G29 (Marlin) to apply correction to the Z position.
  6681. This value represents the distance from nozzle to the bed surface at the point where the probe is triggered. This value will be negative for typical switch probes, inductive probes, and setups where the nozzle makes a circuit with a raised metal contact. This setting will be greater than zero on machines where the nozzle itself is used as the probe, pressing down on the bed to press a switch. (This is a common setup on delta machines.)
  6682. #### Usage
  6683. M851 [ Z ]
  6684. #### Parameters
  6685. - `Z` - Z offset probe to nozzle.
  6686. */
  6687. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6688. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6689. {
  6690. float value;
  6691. if (code_seen('Z'))
  6692. {
  6693. value = code_value();
  6694. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6695. {
  6696. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6697. SERIAL_ECHO_START;
  6698. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6699. SERIAL_PROTOCOLLN("");
  6700. }
  6701. else
  6702. {
  6703. SERIAL_ECHO_START;
  6704. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6705. SERIAL_ECHORPGM(MSG_Z_MIN);
  6706. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6707. SERIAL_ECHORPGM(MSG_Z_MAX);
  6708. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6709. SERIAL_PROTOCOLLN("");
  6710. }
  6711. }
  6712. else
  6713. {
  6714. SERIAL_ECHO_START;
  6715. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6716. SERIAL_ECHO(-cs.zprobe_zoffset);
  6717. SERIAL_PROTOCOLLN("");
  6718. }
  6719. break;
  6720. }
  6721. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6722. #ifdef FILAMENTCHANGEENABLE
  6723. /*!
  6724. ### M600 - Initiate Filament change procedure <a href="https://reprap.org/wiki/G-code#M600:_Filament_change_pause">M600: Filament change pause</a>
  6725. Initiates Filament change, it is also used during Filament Runout Sensor process.
  6726. If the `M600` is triggered under 25mm it will do a Z-lift of 25mm to prevent a filament blob.
  6727. #### Usage
  6728. M600 [ X | Y | Z | E | L | AUTO ]
  6729. - `X` - X position, default 211
  6730. - `Y` - Y position, default 0
  6731. - `Z` - relative lift Z, default 2.
  6732. - `E` - initial retract, default -2
  6733. - `L` - later retract distance for removal, default -80
  6734. - `AUTO` - Automatically (only with MMU)
  6735. */
  6736. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6737. {
  6738. st_synchronize();
  6739. float x_position = current_position[X_AXIS];
  6740. float y_position = current_position[Y_AXIS];
  6741. float z_shift = 0; // is it necessary to be a float?
  6742. float e_shift_init = 0;
  6743. float e_shift_late = 0;
  6744. bool automatic = false;
  6745. //Retract extruder
  6746. if(code_seen('E'))
  6747. {
  6748. e_shift_init = code_value();
  6749. }
  6750. else
  6751. {
  6752. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6753. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6754. #endif
  6755. }
  6756. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6757. if (code_seen('L'))
  6758. {
  6759. e_shift_late = code_value();
  6760. }
  6761. else
  6762. {
  6763. #ifdef FILAMENTCHANGE_FINALRETRACT
  6764. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6765. #endif
  6766. }
  6767. //Lift Z
  6768. if(code_seen('Z'))
  6769. {
  6770. z_shift = code_value();
  6771. }
  6772. else
  6773. {
  6774. z_shift = gcode_M600_filament_change_z_shift<uint8_t>();
  6775. }
  6776. //Move XY to side
  6777. if(code_seen('X'))
  6778. {
  6779. x_position = code_value();
  6780. }
  6781. else
  6782. {
  6783. #ifdef FILAMENTCHANGE_XPOS
  6784. x_position = FILAMENTCHANGE_XPOS;
  6785. #endif
  6786. }
  6787. if(code_seen('Y'))
  6788. {
  6789. y_position = code_value();
  6790. }
  6791. else
  6792. {
  6793. #ifdef FILAMENTCHANGE_YPOS
  6794. y_position = FILAMENTCHANGE_YPOS ;
  6795. #endif
  6796. }
  6797. if (mmu_enabled && code_seen("AUTO"))
  6798. automatic = true;
  6799. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6800. }
  6801. break;
  6802. #endif //FILAMENTCHANGEENABLE
  6803. /*!
  6804. ### M601 - Pause print <a href="https://reprap.org/wiki/G-code#M601:_Pause_print">M601: Pause print</a>
  6805. */
  6806. /*!
  6807. ### M125 - Pause print (TODO: not implemented)
  6808. */
  6809. /*!
  6810. ### M25 - Pause SD print <a href="https://reprap.org/wiki/G-code#M25:_Pause_SD_print">M25: Pause SD print</a>
  6811. */
  6812. case 25:
  6813. case 601:
  6814. {
  6815. if (!isPrintPaused)
  6816. {
  6817. st_synchronize();
  6818. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  6819. lcd_pause_print();
  6820. }
  6821. }
  6822. break;
  6823. /*!
  6824. ### M602 - Resume print <a href="https://reprap.org/wiki/G-code#M602:_Resume_print">M602: Resume print</a>
  6825. */
  6826. case 602: {
  6827. if (isPrintPaused)
  6828. lcd_resume_print();
  6829. }
  6830. break;
  6831. /*!
  6832. ### M603 - Stop print <a href="https://reprap.org/wiki/G-code#M603:_Stop_print">M603: Stop print</a>
  6833. */
  6834. case 603: {
  6835. lcd_print_stop();
  6836. }
  6837. break;
  6838. #ifdef PINDA_THERMISTOR
  6839. /*!
  6840. ### M860 - Wait for extruder temperature (PINDA) <a href="https://reprap.org/wiki/G-code#M860_Wait_for_Probe_Temperature">M860 Wait for Probe Temperature</a>
  6841. Wait for PINDA thermistor to reach target temperature
  6842. #### Usage
  6843. M860 [ S ]
  6844. #### Parameters
  6845. - `S` - Target temperature
  6846. */
  6847. case 860:
  6848. {
  6849. int set_target_pinda = 0;
  6850. if (code_seen('S')) {
  6851. set_target_pinda = code_value();
  6852. }
  6853. else {
  6854. break;
  6855. }
  6856. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  6857. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  6858. SERIAL_PROTOCOL(set_target_pinda);
  6859. SERIAL_PROTOCOLLN("");
  6860. codenum = _millis();
  6861. cancel_heatup = false;
  6862. bool is_pinda_cooling = false;
  6863. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  6864. is_pinda_cooling = true;
  6865. }
  6866. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  6867. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  6868. {
  6869. SERIAL_PROTOCOLPGM("P:");
  6870. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  6871. SERIAL_PROTOCOLPGM("/");
  6872. SERIAL_PROTOCOL(set_target_pinda);
  6873. SERIAL_PROTOCOLLN("");
  6874. codenum = _millis();
  6875. }
  6876. manage_heater();
  6877. manage_inactivity();
  6878. lcd_update(0);
  6879. }
  6880. LCD_MESSAGERPGM(MSG_OK);
  6881. break;
  6882. }
  6883. /*!
  6884. ### M861 - Set/Get PINDA temperature compensation offsets <a href="https://reprap.org/wiki/G-code#M861_Set_Probe_Thermal_Compensation">M861 Set Probe Thermal Compensation</a>
  6885. Set compensation ustep value `S` for compensation table index `I`.
  6886. #### Usage
  6887. M861 [ ? | ! | Z | S | I ]
  6888. #### Parameters
  6889. - `?` - Print current EEPROM offset values
  6890. - `!` - Set factory default values
  6891. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6892. - `S` - Microsteps
  6893. - `I` - Table index
  6894. */
  6895. case 861:
  6896. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  6897. uint8_t cal_status = calibration_status_pinda();
  6898. int16_t usteps = 0;
  6899. cal_status ? SERIAL_PROTOCOLLN("PINDA cal status: 1") : SERIAL_PROTOCOLLN("PINDA cal status: 0");
  6900. SERIAL_PROTOCOLLN("index, temp, ustep, um");
  6901. for (uint8_t i = 0; i < 6; i++)
  6902. {
  6903. if(i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i-1) * 2, &usteps);
  6904. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6905. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6906. SERIAL_PROTOCOLPGM(", ");
  6907. SERIAL_PROTOCOL(35 + (i * 5));
  6908. SERIAL_PROTOCOLPGM(", ");
  6909. SERIAL_PROTOCOL(usteps);
  6910. SERIAL_PROTOCOLPGM(", ");
  6911. SERIAL_PROTOCOL(mm * 1000);
  6912. SERIAL_PROTOCOLLN("");
  6913. }
  6914. }
  6915. else if (code_seen('!')) { // ! - Set factory default values
  6916. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6917. int16_t z_shift = 8; //40C - 20um - 8usteps
  6918. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT, &z_shift);
  6919. z_shift = 24; //45C - 60um - 24usteps
  6920. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 2, &z_shift);
  6921. z_shift = 48; //50C - 120um - 48usteps
  6922. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 4, &z_shift);
  6923. z_shift = 80; //55C - 200um - 80usteps
  6924. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 6, &z_shift);
  6925. z_shift = 120; //60C - 300um - 120usteps
  6926. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 8, &z_shift);
  6927. SERIAL_PROTOCOLLN("factory restored");
  6928. }
  6929. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6930. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6931. int16_t z_shift = 0;
  6932. for (uint8_t i = 0; i < 5; i++) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  6933. SERIAL_PROTOCOLLN("zerorized");
  6934. }
  6935. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  6936. int16_t usteps = code_value();
  6937. if (code_seen('I')) {
  6938. uint8_t index = code_value();
  6939. if (index < 5) {
  6940. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + index * 2, &usteps);
  6941. SERIAL_PROTOCOLLN("OK");
  6942. SERIAL_PROTOCOLLN("index, temp, ustep, um");
  6943. for (uint8_t i = 0; i < 6; i++)
  6944. {
  6945. usteps = 0;
  6946. if (i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i - 1) * 2, &usteps);
  6947. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6948. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6949. SERIAL_PROTOCOLPGM(", ");
  6950. SERIAL_PROTOCOL(35 + (i * 5));
  6951. SERIAL_PROTOCOLPGM(", ");
  6952. SERIAL_PROTOCOL(usteps);
  6953. SERIAL_PROTOCOLPGM(", ");
  6954. SERIAL_PROTOCOL(mm * 1000);
  6955. SERIAL_PROTOCOLLN("");
  6956. }
  6957. }
  6958. }
  6959. }
  6960. else {
  6961. SERIAL_PROTOCOLPGM("no valid command");
  6962. }
  6963. break;
  6964. #endif //PINDA_THERMISTOR
  6965. /*!
  6966. ### M862 - Print checking <a href="https://reprap.org/wiki/G-code#M862:_Print_checking">M862: Print checking</a>
  6967. Checks the parameters of the printer and gcode and performs compatibility check
  6968. - M862.1 { P<nozzle_diameter> | Q } 0.25/0.40/0.60
  6969. - M862.2 { P<model_code> | Q }
  6970. - M862.3 { P"<model_name>" | Q }
  6971. - M862.4 { P<fw_version> | Q }
  6972. - M862.5 { P<gcode_level> | Q }
  6973. When run with P<> argument, the check is performed against the input value.
  6974. When run with Q argument, the current value is shown.
  6975. M862.3 accepts text identifiers of printer types too.
  6976. The syntax of M862.3 is (note the quotes around the type):
  6977. M862.3 P "MK3S"
  6978. Accepted printer type identifiers and their numeric counterparts:
  6979. - MK1 (100)
  6980. - MK2 (200)
  6981. - MK2MM (201)
  6982. - MK2S (202)
  6983. - MK2SMM (203)
  6984. - MK2.5 (250)
  6985. - MK2.5MMU2 (20250)
  6986. - MK2.5S (252)
  6987. - MK2.5SMMU2S (20252)
  6988. - MK3 (300)
  6989. - MK3MMU2 (20300)
  6990. - MK3S (302)
  6991. - MK3SMMU2S (20302)
  6992. */
  6993. case 862: // M862: print checking
  6994. float nDummy;
  6995. uint8_t nCommand;
  6996. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  6997. switch((ClPrintChecking)nCommand)
  6998. {
  6999. case ClPrintChecking::_Nozzle: // ~ .1
  7000. uint16_t nDiameter;
  7001. if(code_seen('P'))
  7002. {
  7003. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  7004. nozzle_diameter_check(nDiameter);
  7005. }
  7006. /*
  7007. else if(code_seen('S')&&farm_mode)
  7008. {
  7009. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  7010. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  7011. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  7012. }
  7013. */
  7014. else if(code_seen('Q'))
  7015. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  7016. break;
  7017. case ClPrintChecking::_Model: // ~ .2
  7018. if(code_seen('P'))
  7019. {
  7020. uint16_t nPrinterModel;
  7021. nPrinterModel=(uint16_t)code_value_long();
  7022. printer_model_check(nPrinterModel);
  7023. }
  7024. else if(code_seen('Q'))
  7025. SERIAL_PROTOCOLLN(nPrinterType);
  7026. break;
  7027. case ClPrintChecking::_Smodel: // ~ .3
  7028. if(code_seen('P'))
  7029. printer_smodel_check(strchr_pointer);
  7030. else if(code_seen('Q'))
  7031. SERIAL_PROTOCOLLNRPGM(sPrinterName);
  7032. break;
  7033. case ClPrintChecking::_Version: // ~ .4
  7034. if(code_seen('P'))
  7035. fw_version_check(++strchr_pointer);
  7036. else if(code_seen('Q'))
  7037. SERIAL_PROTOCOLLN(FW_VERSION);
  7038. break;
  7039. case ClPrintChecking::_Gcode: // ~ .5
  7040. if(code_seen('P'))
  7041. {
  7042. uint16_t nGcodeLevel;
  7043. nGcodeLevel=(uint16_t)code_value_long();
  7044. gcode_level_check(nGcodeLevel);
  7045. }
  7046. else if(code_seen('Q'))
  7047. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  7048. break;
  7049. }
  7050. break;
  7051. #ifdef LIN_ADVANCE
  7052. /*!
  7053. ### M900 - Set Linear advance options <a href="https://reprap.org/wiki/G-code#M900_Set_Linear_Advance_Scaling_Factors">M900 Set Linear Advance Scaling Factors</a>
  7054. Sets the advance extrusion factors for Linear Advance. If any of the R, W, H, or D parameters are set to zero the ratio will be computed dynamically during printing.
  7055. #### Usage
  7056. M900 [ K | R | W | H | D]
  7057. #### Parameters
  7058. - `K` - Advance K factor
  7059. - `R` - Set ratio directly (overrides WH/D)
  7060. - `W` - Width
  7061. - `H` - Height
  7062. - `D` - Diameter Set ratio from WH/D
  7063. */
  7064. case 900:
  7065. gcode_M900();
  7066. break;
  7067. #endif
  7068. /*!
  7069. ### M907 - Set digital trimpot motor current in mA using axis codes <a href="https://reprap.org/wiki/G-code#M907:_Set_digital_trimpot_motor">M907: Set digital trimpot motor</a>
  7070. Set digital trimpot motor current using axis codes (X, Y, Z, E, B, S).
  7071. #### Usage
  7072. M907 [ X | Y | Z | E | B | S ]
  7073. #### Parameters
  7074. - `X` - X motor driver
  7075. - `Y` - Y motor driver
  7076. - `Z` - Z motor driver
  7077. - `E` - Extruder motor driver
  7078. - `B` - Second Extruder motor driver
  7079. - `S` - All motors
  7080. */
  7081. case 907:
  7082. {
  7083. #ifdef TMC2130
  7084. // See tmc2130_cur2val() for translation to 0 .. 63 range
  7085. for (int i = 0; i < NUM_AXIS; i++)
  7086. if(code_seen(axis_codes[i]))
  7087. {
  7088. long cur_mA = code_value_long();
  7089. uint8_t val = tmc2130_cur2val(cur_mA);
  7090. tmc2130_set_current_h(i, val);
  7091. tmc2130_set_current_r(i, val);
  7092. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  7093. }
  7094. #else //TMC2130
  7095. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7096. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  7097. if(code_seen('B')) st_current_set(4,code_value());
  7098. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  7099. #endif
  7100. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  7101. if(code_seen('X')) st_current_set(0, code_value());
  7102. #endif
  7103. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  7104. if(code_seen('Z')) st_current_set(1, code_value());
  7105. #endif
  7106. #ifdef MOTOR_CURRENT_PWM_E_PIN
  7107. if(code_seen('E')) st_current_set(2, code_value());
  7108. #endif
  7109. #endif //TMC2130
  7110. }
  7111. break;
  7112. /*!
  7113. ### M908 - Control digital trimpot directly <a href="https://reprap.org/wiki/G-code#M908:_Control_digital_trimpot_directly">M908: Control digital trimpot directly</a>
  7114. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. Not usable on Prusa printers.
  7115. #### Usage
  7116. M908 [ P | S ]
  7117. #### Parameters
  7118. - `P` - channel
  7119. - `S` - current
  7120. */
  7121. case 908:
  7122. {
  7123. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7124. uint8_t channel,current;
  7125. if(code_seen('P')) channel=code_value();
  7126. if(code_seen('S')) current=code_value();
  7127. digitalPotWrite(channel, current);
  7128. #endif
  7129. }
  7130. break;
  7131. #ifdef TMC2130_SERVICE_CODES_M910_M918
  7132. /*!
  7133. ### M910 - TMC2130 init <a href="https://reprap.org/wiki/G-code#M910:_TMC2130_init">M910: TMC2130 init</a>
  7134. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7135. */
  7136. case 910:
  7137. {
  7138. tmc2130_init();
  7139. }
  7140. break;
  7141. /*!
  7142. ### M911 - Set TMC2130 holding currents <a href="https://reprap.org/wiki/G-code#M911:_Set_TMC2130_holding_currents">M911: Set TMC2130 holding currents</a>
  7143. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7144. #### Usage
  7145. M911 [ X | Y | Z | E ]
  7146. #### Parameters
  7147. - `X` - X stepper driver holding current value
  7148. - `Y` - Y stepper driver holding current value
  7149. - `Z` - Z stepper driver holding current value
  7150. - `E` - Extruder stepper driver holding current value
  7151. */
  7152. case 911:
  7153. {
  7154. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  7155. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  7156. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  7157. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  7158. }
  7159. break;
  7160. /*!
  7161. ### M912 - Set TMC2130 running currents <a href="https://reprap.org/wiki/G-code#M912:_Set_TMC2130_running_currents">M912: Set TMC2130 running currents</a>
  7162. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7163. #### Usage
  7164. M912 [ X | Y | Z | E ]
  7165. #### Parameters
  7166. - `X` - X stepper driver running current value
  7167. - `Y` - Y stepper driver running current value
  7168. - `Z` - Z stepper driver running current value
  7169. - `E` - Extruder stepper driver running current value
  7170. */
  7171. case 912:
  7172. {
  7173. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  7174. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  7175. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  7176. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  7177. }
  7178. break;
  7179. /*!
  7180. ### M913 - Print TMC2130 currents <a href="https://reprap.org/wiki/G-code#M913:_Print_TMC2130_currents">M913: Print TMC2130 currents</a>
  7181. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7182. Shows TMC2130 currents.
  7183. */
  7184. case 913:
  7185. {
  7186. tmc2130_print_currents();
  7187. }
  7188. break;
  7189. /*!
  7190. ### M914 - Set TMC2130 normal mode <a href="https://reprap.org/wiki/G-code#M914:_Set_TMC2130_normal_mode">M914: Set TMC2130 normal mode</a>
  7191. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7192. */
  7193. case 914:
  7194. {
  7195. tmc2130_mode = TMC2130_MODE_NORMAL;
  7196. update_mode_profile();
  7197. tmc2130_init();
  7198. }
  7199. break;
  7200. /*!
  7201. ### M915 - Set TMC2130 silent mode <a href="https://reprap.org/wiki/G-code#M915:_Set_TMC2130_silent_mode">M915: Set TMC2130 silent mode</a>
  7202. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7203. */
  7204. case 915:
  7205. {
  7206. tmc2130_mode = TMC2130_MODE_SILENT;
  7207. update_mode_profile();
  7208. tmc2130_init();
  7209. }
  7210. break;
  7211. /*!
  7212. ### M916 - Set TMC2130 Stallguard sensitivity threshold <a href="https://reprap.org/wiki/G-code#M916:_Set_TMC2130_Stallguard_sensitivity_threshold">M916: Set TMC2130 Stallguard sensitivity threshold</a>
  7213. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7214. #### Usage
  7215. M916 [ X | Y | Z | E ]
  7216. #### Parameters
  7217. - `X` - X stepper driver stallguard sensitivity threshold value
  7218. - `Y` - Y stepper driver stallguard sensitivity threshold value
  7219. - `Z` - Z stepper driver stallguard sensitivity threshold value
  7220. - `E` - Extruder stepper driver stallguard sensitivity threshold value
  7221. */
  7222. case 916:
  7223. {
  7224. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  7225. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  7226. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  7227. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  7228. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  7229. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  7230. }
  7231. break;
  7232. /*!
  7233. ### M917 - Set TMC2130 PWM amplitude offset (pwm_ampl) <a href="https://reprap.org/wiki/G-code#M917:_Set_TMC2130_PWM_amplitude_offset_.28pwm_ampl.29">M917: Set TMC2130 PWM amplitude offset (pwm_ampl)</a>
  7234. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7235. #### Usage
  7236. M917 [ X | Y | Z | E ]
  7237. #### Parameters
  7238. - `X` - X stepper driver PWM amplitude offset value
  7239. - `Y` - Y stepper driver PWM amplitude offset value
  7240. - `Z` - Z stepper driver PWM amplitude offset value
  7241. - `E` - Extruder stepper driver PWM amplitude offset value
  7242. */
  7243. case 917:
  7244. {
  7245. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  7246. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  7247. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  7248. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  7249. }
  7250. break;
  7251. /*!
  7252. ### M918 - Set TMC2130 PWM amplitude gradient (pwm_grad) <a href="https://reprap.org/wiki/G-code#M918:_Set_TMC2130_PWM_amplitude_gradient_.28pwm_grad.29">M918: Set TMC2130 PWM amplitude gradient (pwm_grad)</a>
  7253. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7254. #### Usage
  7255. M918 [ X | Y | Z | E ]
  7256. #### Parameters
  7257. - `X` - X stepper driver PWM amplitude gradient value
  7258. - `Y` - Y stepper driver PWM amplitude gradient value
  7259. - `Z` - Z stepper driver PWM amplitude gradient value
  7260. - `E` - Extruder stepper driver PWM amplitude gradient value
  7261. */
  7262. case 918:
  7263. {
  7264. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  7265. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  7266. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  7267. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  7268. }
  7269. break;
  7270. #endif //TMC2130_SERVICE_CODES_M910_M918
  7271. /*!
  7272. ### M350 - Set microstepping mode <a href="https://reprap.org/wiki/G-code#M350:_Set_microstepping_mode">M350: Set microstepping mode</a>
  7273. Printers with TMC2130 drivers have `X`, `Y`, `Z` and `E` as options. The steps-per-unit value is updated accordingly. Not all resolutions are valid!
  7274. Printers without TMC2130 drivers also have `B` and `S` options. In this case, the steps-per-unit value in not changed!
  7275. #### Usage
  7276. M350 [ X | Y | Z | E | B | S ]
  7277. #### Parameters
  7278. - `X` - X new resolution
  7279. - `Y` - Y new resolution
  7280. - `Z` - Z new resolution
  7281. - `E` - E new resolution
  7282. Only valid for MK2.5(S) or printers without TMC2130 drivers
  7283. - `B` - Second extruder new resolution
  7284. - `S` - All axes new resolution
  7285. */
  7286. case 350:
  7287. {
  7288. #ifdef TMC2130
  7289. for (int i=0; i<NUM_AXIS; i++)
  7290. {
  7291. if(code_seen(axis_codes[i]))
  7292. {
  7293. uint16_t res_new = code_value();
  7294. bool res_valid = (res_new == 8) || (res_new == 16) || (res_new == 32); // resolutions valid for all axis
  7295. res_valid |= (i != E_AXIS) && ((res_new == 1) || (res_new == 2) || (res_new == 4)); // resolutions valid for X Y Z only
  7296. res_valid |= (i == E_AXIS) && ((res_new == 64) || (res_new == 128)); // resolutions valid for E only
  7297. if (res_valid)
  7298. {
  7299. st_synchronize();
  7300. uint16_t res = tmc2130_get_res(i);
  7301. tmc2130_set_res(i, res_new);
  7302. cs.axis_ustep_resolution[i] = res_new;
  7303. if (res_new > res)
  7304. {
  7305. uint16_t fac = (res_new / res);
  7306. cs.axis_steps_per_unit[i] *= fac;
  7307. position[i] *= fac;
  7308. }
  7309. else
  7310. {
  7311. uint16_t fac = (res / res_new);
  7312. cs.axis_steps_per_unit[i] /= fac;
  7313. position[i] /= fac;
  7314. }
  7315. if (i == E_AXIS)
  7316. fsensor_set_axis_steps_per_unit(cs.axis_steps_per_unit[i]);
  7317. }
  7318. }
  7319. }
  7320. #else //TMC2130
  7321. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7322. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  7323. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  7324. if(code_seen('B')) microstep_mode(4,code_value());
  7325. microstep_readings();
  7326. #endif
  7327. #endif //TMC2130
  7328. }
  7329. break;
  7330. /*!
  7331. ### M351 - Toggle Microstep Pins <a href="https://reprap.org/wiki/G-code#M351:_Toggle_MS1_MS2_pins_directly">M351: Toggle MS1 MS2 pins directly</a>
  7332. Toggle MS1 MS2 pins directly.
  7333. #### Usage
  7334. M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  7335. #### Parameters
  7336. - `X` - Update X axis
  7337. - `Y` - Update Y axis
  7338. - `Z` - Update Z axis
  7339. - `E` - Update E axis
  7340. - `S` - which MSx pin to toggle
  7341. - `B` - new pin value
  7342. */
  7343. case 351:
  7344. {
  7345. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7346. if(code_seen('S')) switch((int)code_value())
  7347. {
  7348. case 1:
  7349. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  7350. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  7351. break;
  7352. case 2:
  7353. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  7354. if(code_seen('B')) microstep_ms(4,-1,code_value());
  7355. break;
  7356. }
  7357. microstep_readings();
  7358. #endif
  7359. }
  7360. break;
  7361. /*!
  7362. ### M701 - Load filament <a href="https://reprap.org/wiki/G-code#M701:_Load_filament">M701: Load filament</a>
  7363. */
  7364. case 701:
  7365. {
  7366. if (mmu_enabled && code_seen('E'))
  7367. tmp_extruder = code_value();
  7368. gcode_M701();
  7369. }
  7370. break;
  7371. /*!
  7372. ### M702 - Unload filament <a href="https://reprap.org/wiki/G-code#M702:_Unload_filament">G32: Undock Z Probe sled</a>
  7373. #### Usage
  7374. M702 [ U | C ]
  7375. #### Parameters
  7376. - `U` - Unload all filaments used in current print
  7377. - `C` - Unload just current filament
  7378. - without any parameters unload all filaments
  7379. */
  7380. case 702:
  7381. {
  7382. #ifdef SNMM
  7383. if (code_seen('U'))
  7384. extr_unload_used(); //! if "U" unload all filaments which were used in current print
  7385. else if (code_seen('C'))
  7386. extr_unload(); //! if "C" unload just current filament
  7387. else
  7388. extr_unload_all(); //! otherwise unload all filaments
  7389. #else
  7390. if (code_seen('C')) {
  7391. if(mmu_enabled) extr_unload(); //! if "C" unload current filament; if mmu is not present no action is performed
  7392. }
  7393. else {
  7394. if(mmu_enabled) extr_unload(); //! unload current filament
  7395. else unload_filament();
  7396. }
  7397. #endif //SNMM
  7398. }
  7399. break;
  7400. /*!
  7401. ### M999 - Restart after being stopped <a href="https://reprap.org/wiki/G-code#M999:_Restart_after_being_stopped_by_error">M999: Restart after being stopped by error</a>
  7402. @todo Usually doesn't work. Should be fixed or removed. Most of the time, if `Stopped` it set, the print fails and is unrecoverable.
  7403. */
  7404. case 999:
  7405. Stopped = false;
  7406. lcd_reset_alert_level();
  7407. gcode_LastN = Stopped_gcode_LastN;
  7408. FlushSerialRequestResend();
  7409. break;
  7410. /*!
  7411. #### End of M-Commands
  7412. */
  7413. default:
  7414. printf_P(PSTR("Unknown M code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  7415. }
  7416. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  7417. mcode_in_progress = 0;
  7418. }
  7419. }
  7420. // end if(code_seen('M')) (end of M codes)
  7421. /*!
  7422. -----------------------------------------------------------------------------------------
  7423. # T Codes
  7424. T<extruder nr.> - select extruder in case of multi extruder printer. select filament in case of MMU_V2.
  7425. #### For MMU_V2:
  7426. T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  7427. @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  7428. @n Tx Same as T?, except nozzle doesn't have to be preheated. Tc must be placed after extruder nozzle is preheated to finish filament load.
  7429. @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  7430. */
  7431. else if(code_seen('T'))
  7432. {
  7433. int index;
  7434. bool load_to_nozzle = false;
  7435. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  7436. *(strchr_pointer + index) = tolower(*(strchr_pointer + index));
  7437. if ((*(strchr_pointer + index) < '0' || *(strchr_pointer + index) > '4') && *(strchr_pointer + index) != '?' && *(strchr_pointer + index) != 'x' && *(strchr_pointer + index) != 'c') {
  7438. SERIAL_ECHOLNPGM("Invalid T code.");
  7439. }
  7440. else if (*(strchr_pointer + index) == 'x'){ //load to bondtech gears; if mmu is not present do nothing
  7441. if (mmu_enabled)
  7442. {
  7443. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_FILAMENT), _T(MSG_FILAMENT));
  7444. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  7445. {
  7446. printf_P(PSTR("Duplicate T-code ignored.\n"));
  7447. }
  7448. else
  7449. {
  7450. st_synchronize();
  7451. mmu_command(MmuCmd::T0 + tmp_extruder);
  7452. manage_response(true, true, MMU_TCODE_MOVE);
  7453. }
  7454. }
  7455. }
  7456. else if (*(strchr_pointer + index) == 'c') { //load to from bondtech gears to nozzle (nozzle should be preheated)
  7457. if (mmu_enabled)
  7458. {
  7459. st_synchronize();
  7460. mmu_continue_loading(is_usb_printing || (lcd_commands_type == LcdCommands::Layer1Cal));
  7461. mmu_extruder = tmp_extruder; //filament change is finished
  7462. mmu_load_to_nozzle();
  7463. }
  7464. }
  7465. else {
  7466. if (*(strchr_pointer + index) == '?')
  7467. {
  7468. if(mmu_enabled)
  7469. {
  7470. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_FILAMENT), _T(MSG_FILAMENT));
  7471. load_to_nozzle = true;
  7472. } else
  7473. {
  7474. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_EXTRUDER), _T(MSG_EXTRUDER));
  7475. }
  7476. }
  7477. else {
  7478. tmp_extruder = code_value();
  7479. if (mmu_enabled && lcd_autoDepleteEnabled())
  7480. {
  7481. tmp_extruder = ad_getAlternative(tmp_extruder);
  7482. }
  7483. }
  7484. st_synchronize();
  7485. snmm_filaments_used |= (1 << tmp_extruder); //for stop print
  7486. if (mmu_enabled)
  7487. {
  7488. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  7489. {
  7490. printf_P(PSTR("Duplicate T-code ignored.\n"));
  7491. }
  7492. else
  7493. {
  7494. #if defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  7495. if (EEPROM_MMU_CUTTER_ENABLED_always == eeprom_read_byte((uint8_t*)EEPROM_MMU_CUTTER_ENABLED))
  7496. {
  7497. mmu_command(MmuCmd::K0 + tmp_extruder);
  7498. manage_response(true, true, MMU_UNLOAD_MOVE);
  7499. }
  7500. #endif //defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  7501. mmu_command(MmuCmd::T0 + tmp_extruder);
  7502. manage_response(true, true, MMU_TCODE_MOVE);
  7503. mmu_continue_loading(is_usb_printing || (lcd_commands_type == LcdCommands::Layer1Cal));
  7504. mmu_extruder = tmp_extruder; //filament change is finished
  7505. if (load_to_nozzle)// for single material usage with mmu
  7506. {
  7507. mmu_load_to_nozzle();
  7508. }
  7509. }
  7510. }
  7511. else
  7512. {
  7513. #ifdef SNMM
  7514. mmu_extruder = tmp_extruder;
  7515. _delay(100);
  7516. disable_e0();
  7517. disable_e1();
  7518. disable_e2();
  7519. pinMode(E_MUX0_PIN, OUTPUT);
  7520. pinMode(E_MUX1_PIN, OUTPUT);
  7521. _delay(100);
  7522. SERIAL_ECHO_START;
  7523. SERIAL_ECHO("T:");
  7524. SERIAL_ECHOLN((int)tmp_extruder);
  7525. switch (tmp_extruder) {
  7526. case 1:
  7527. WRITE(E_MUX0_PIN, HIGH);
  7528. WRITE(E_MUX1_PIN, LOW);
  7529. break;
  7530. case 2:
  7531. WRITE(E_MUX0_PIN, LOW);
  7532. WRITE(E_MUX1_PIN, HIGH);
  7533. break;
  7534. case 3:
  7535. WRITE(E_MUX0_PIN, HIGH);
  7536. WRITE(E_MUX1_PIN, HIGH);
  7537. break;
  7538. default:
  7539. WRITE(E_MUX0_PIN, LOW);
  7540. WRITE(E_MUX1_PIN, LOW);
  7541. break;
  7542. }
  7543. _delay(100);
  7544. #else //SNMM
  7545. if (tmp_extruder >= EXTRUDERS) {
  7546. SERIAL_ECHO_START;
  7547. SERIAL_ECHOPGM("T");
  7548. SERIAL_PROTOCOLLN((int)tmp_extruder);
  7549. SERIAL_ECHOLNRPGM(_n("Invalid extruder"));////MSG_INVALID_EXTRUDER
  7550. }
  7551. else {
  7552. #if EXTRUDERS > 1
  7553. boolean make_move = false;
  7554. #endif
  7555. if (code_seen('F')) {
  7556. #if EXTRUDERS > 1
  7557. make_move = true;
  7558. #endif
  7559. next_feedrate = code_value();
  7560. if (next_feedrate > 0.0) {
  7561. feedrate = next_feedrate;
  7562. }
  7563. }
  7564. #if EXTRUDERS > 1
  7565. if (tmp_extruder != active_extruder) {
  7566. // Save current position to return to after applying extruder offset
  7567. memcpy(destination, current_position, sizeof(destination));
  7568. // Offset extruder (only by XY)
  7569. int i;
  7570. for (i = 0; i < 2; i++) {
  7571. current_position[i] = current_position[i] -
  7572. extruder_offset[i][active_extruder] +
  7573. extruder_offset[i][tmp_extruder];
  7574. }
  7575. // Set the new active extruder and position
  7576. active_extruder = tmp_extruder;
  7577. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  7578. // Move to the old position if 'F' was in the parameters
  7579. if (make_move && Stopped == false) {
  7580. prepare_move();
  7581. }
  7582. }
  7583. #endif
  7584. SERIAL_ECHO_START;
  7585. SERIAL_ECHORPGM(_n("Active Extruder: "));////MSG_ACTIVE_EXTRUDER
  7586. SERIAL_PROTOCOLLN((int)active_extruder);
  7587. }
  7588. #endif //SNMM
  7589. }
  7590. }
  7591. } // end if(code_seen('T')) (end of T codes)
  7592. /*!
  7593. #### End of T-Codes
  7594. */
  7595. /**
  7596. *---------------------------------------------------------------------------------
  7597. *# D codes
  7598. */
  7599. else if (code_seen('D')) // D codes (debug)
  7600. {
  7601. switch((int)code_value())
  7602. {
  7603. /*!
  7604. ### D-1 - Endless Loop <a href="https://reprap.org/wiki/G-code#D-1:_Endless_Loop">D-1: Endless Loop</a>
  7605. */
  7606. case -1:
  7607. dcode__1(); break;
  7608. #ifdef DEBUG_DCODES
  7609. /*!
  7610. ### D0 - Reset <a href="https://reprap.org/wiki/G-code#D0:_Reset">D0: Reset</a>
  7611. #### Usage
  7612. D0 [ B ]
  7613. #### Parameters
  7614. - `B` - Bootloader
  7615. */
  7616. case 0:
  7617. dcode_0(); break;
  7618. /*!
  7619. *
  7620. ### D1 - Clear EEPROM and RESET <a href="https://reprap.org/wiki/G-code#D1:_Clear_EEPROM_and_RESET">D1: Clear EEPROM and RESET</a>
  7621. D1
  7622. *
  7623. */
  7624. case 1:
  7625. dcode_1(); break;
  7626. /*!
  7627. ### D2 - Read/Write RAM <a href="https://reprap.org/wiki/G-code#D2:_Read.2FWrite_RAM">D3: Read/Write RAM</a>
  7628. This command can be used without any additional parameters. It will read the entire RAM.
  7629. #### Usage
  7630. D3 [ A | C | X ]
  7631. #### Parameters
  7632. - `A` - Address (0x0000-0x1fff)
  7633. - `C` - Count (0x0001-0x2000)
  7634. - `X` - Data
  7635. */
  7636. case 2:
  7637. dcode_2(); break;
  7638. #endif //DEBUG_DCODES
  7639. #ifdef DEBUG_DCODE3
  7640. /*!
  7641. ### D3 - Read/Write EEPROM <a href="https://reprap.org/wiki/G-code#D3:_Read.2FWrite_EEPROM">D3: Read/Write EEPROM</a>
  7642. This command can be used without any additional parameters. It will read the entire eeprom.
  7643. #### Usage
  7644. D3 [ A | C | X ]
  7645. #### Parameters
  7646. - `A` - Address (0x0000-0x0fff)
  7647. - `C` - Count (0x0001-0x1000)
  7648. - `X` - Data
  7649. */
  7650. case 3:
  7651. dcode_3(); break;
  7652. #endif //DEBUG_DCODE3
  7653. #ifdef DEBUG_DCODES
  7654. /*!
  7655. ### D4 - Read/Write PIN <a href="https://reprap.org/wiki/G-code#D4:_Read.2FWrite_PIN">D4: Read/Write PIN</a>
  7656. To read the digital value of a pin you need only to define the pin number.
  7657. #### Usage
  7658. D4 [ P | F | V ]
  7659. #### Parameters
  7660. - `P` - Pin (0-255)
  7661. - `F` - Function in/out (0/1)
  7662. - `V` - Value (0/1)
  7663. */
  7664. case 4:
  7665. dcode_4(); break;
  7666. #endif //DEBUG_DCODES
  7667. #ifdef DEBUG_DCODE5
  7668. /*!
  7669. ### D5 - Read/Write FLASH <a href="https://reprap.org/wiki/G-code#D5:_Read.2FWrite_FLASH">D5: Read/Write Flash</a>
  7670. This command can be used without any additional parameters. It will read the 1kb FLASH.
  7671. #### Usage
  7672. D3 [ A | C | X | E ]
  7673. #### Parameters
  7674. - `A` - Address (0x00000-0x3ffff)
  7675. - `C` - Count (0x0001-0x2000)
  7676. - `X` - Data
  7677. - `E` - Erase
  7678. */
  7679. case 5:
  7680. dcode_5(); break;
  7681. break;
  7682. #endif //DEBUG_DCODE5
  7683. #ifdef DEBUG_DCODES
  7684. /*!
  7685. ### D6 - Read/Write external FLASH <a href="https://reprap.org/wiki/G-code#D6:_Read.2FWrite_external_FLASH">D6: Read/Write external Flash</a>
  7686. Reserved
  7687. */
  7688. case 6:
  7689. dcode_6(); break;
  7690. /*!
  7691. ### D7 - Read/Write Bootloader <a href="https://reprap.org/wiki/G-code#D7:_Read.2FWrite_Bootloader">D7: Read/Write Bootloader</a>
  7692. Reserved
  7693. */
  7694. case 7:
  7695. dcode_7(); break;
  7696. /*!
  7697. ### D8 - Read/Write PINDA <a href="https://reprap.org/wiki/G-code#D8:_Read.2FWrite_PINDA">D8: Read/Write PINDA</a>
  7698. #### Usage
  7699. D8 [ ? | ! | P | Z ]
  7700. #### Parameters
  7701. - `?` - Read PINDA temperature shift values
  7702. - `!` - Reset PINDA temperature shift values to default
  7703. - `P` - Pinda temperature [C]
  7704. - `Z` - Z Offset [mm]
  7705. */
  7706. case 8:
  7707. dcode_8(); break;
  7708. /*!
  7709. ### D9 - Read ADC <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9: Read ADC</a>
  7710. #### Usage
  7711. D9 [ I | V ]
  7712. #### Parameters
  7713. - `I` - ADC channel index
  7714. - `0` - Heater 0 temperature
  7715. - `1` - Heater 1 temperature
  7716. - `2` - Bed temperature
  7717. - `3` - PINDA temperature
  7718. - `4` - PWR voltage
  7719. - `5` - Ambient temperature
  7720. - `6` - BED voltage
  7721. - `V` Value to be written as simulated
  7722. */
  7723. case 9:
  7724. dcode_9(); break;
  7725. /*!
  7726. ### D10 - Set XYZ calibration = OK <a href="https://reprap.org/wiki/G-code#D10:_Set_XYZ_calibration_.3D_OK">D10: Set XYZ calibration = OK</a>
  7727. */
  7728. case 10:
  7729. dcode_10(); break;
  7730. /*!
  7731. ### D12 - Time <a href="https://reprap.org/wiki/G-code#D12:_Time">D12: Time</a>
  7732. Writes the actual time in the log file.
  7733. */
  7734. #endif //DEBUG_DCODES
  7735. #ifdef HEATBED_ANALYSIS
  7736. /*!
  7737. ### D80 - Bed check <a href="https://reprap.org/wiki/G-code#D80:_Bed_check">D80: Bed check</a>
  7738. This command will log data to SD card file "mesh.txt".
  7739. #### Usage
  7740. D80 [ E | F | G | H | I | J ]
  7741. #### Parameters
  7742. - `E` - Dimension X (default 40)
  7743. - `F` - Dimention Y (default 40)
  7744. - `G` - Points X (default 40)
  7745. - `H` - Points Y (default 40)
  7746. - `I` - Offset X (default 74)
  7747. - `J` - Offset Y (default 34)
  7748. */
  7749. case 80:
  7750. {
  7751. float dimension_x = 40;
  7752. float dimension_y = 40;
  7753. int points_x = 40;
  7754. int points_y = 40;
  7755. float offset_x = 74;
  7756. float offset_y = 33;
  7757. if (code_seen('E')) dimension_x = code_value();
  7758. if (code_seen('F')) dimension_y = code_value();
  7759. if (code_seen('G')) {points_x = code_value(); }
  7760. if (code_seen('H')) {points_y = code_value(); }
  7761. if (code_seen('I')) {offset_x = code_value(); }
  7762. if (code_seen('J')) {offset_y = code_value(); }
  7763. printf_P(PSTR("DIM X: %f\n"), dimension_x);
  7764. printf_P(PSTR("DIM Y: %f\n"), dimension_y);
  7765. printf_P(PSTR("POINTS X: %d\n"), points_x);
  7766. printf_P(PSTR("POINTS Y: %d\n"), points_y);
  7767. printf_P(PSTR("OFFSET X: %f\n"), offset_x);
  7768. printf_P(PSTR("OFFSET Y: %f\n"), offset_y);
  7769. bed_check(dimension_x,dimension_y,points_x,points_y,offset_x,offset_y);
  7770. }break;
  7771. /*!
  7772. ### D81 - Bed analysis <a href="https://reprap.org/wiki/G-code#D81:_Bed_analysis">D80: Bed analysis</a>
  7773. This command will log data to SD card file "wldsd.txt".
  7774. #### Usage
  7775. D81 [ E | F | G | H | I | J ]
  7776. #### Parameters
  7777. - `E` - Dimension X (default 40)
  7778. - `F` - Dimention Y (default 40)
  7779. - `G` - Points X (default 40)
  7780. - `H` - Points Y (default 40)
  7781. - `I` - Offset X (default 74)
  7782. - `J` - Offset Y (default 34)
  7783. */
  7784. case 81:
  7785. {
  7786. float dimension_x = 40;
  7787. float dimension_y = 40;
  7788. int points_x = 40;
  7789. int points_y = 40;
  7790. float offset_x = 74;
  7791. float offset_y = 33;
  7792. if (code_seen('E')) dimension_x = code_value();
  7793. if (code_seen('F')) dimension_y = code_value();
  7794. if (code_seen("G")) { strchr_pointer+=1; points_x = code_value(); }
  7795. if (code_seen("H")) { strchr_pointer+=1; points_y = code_value(); }
  7796. if (code_seen("I")) { strchr_pointer+=1; offset_x = code_value(); }
  7797. if (code_seen("J")) { strchr_pointer+=1; offset_y = code_value(); }
  7798. bed_analysis(dimension_x,dimension_y,points_x,points_y,offset_x,offset_y);
  7799. } break;
  7800. #endif //HEATBED_ANALYSIS
  7801. #ifdef DEBUG_DCODES
  7802. /*!
  7803. ### D106 - Print measured fan speed for different pwm values <a href="https://reprap.org/wiki/G-code#D106:_Print_measured_fan_speed_for_different_pwm_values">D106: Print measured fan speed for different pwm values</a>
  7804. */
  7805. case 106:
  7806. {
  7807. for (int i = 255; i > 0; i = i - 5) {
  7808. fanSpeed = i;
  7809. //delay_keep_alive(2000);
  7810. for (int j = 0; j < 100; j++) {
  7811. delay_keep_alive(100);
  7812. }
  7813. printf_P(_N("%d: %d\n"), i, fan_speed[1]);
  7814. }
  7815. }break;
  7816. #ifdef TMC2130
  7817. /*!
  7818. ### D2130 - Trinamic stepper controller <a href="https://reprap.org/wiki/G-code#D2130:_Trinamic_stepper_controller">D2130: Trinamic stepper controller</a>
  7819. @todo Please review by owner of the code. RepRap Wiki Gcode needs to be updated after review of owner as well.
  7820. #### Usage
  7821. D2130 [ Axis | Command | Subcommand | Value ]
  7822. #### Parameters
  7823. - Axis
  7824. - `X` - X stepper driver
  7825. - `Y` - Y stepper driver
  7826. - `Z` - Z stepper driver
  7827. - `E` - Extruder stepper driver
  7828. - Commands
  7829. - `0` - Current off
  7830. - `1` - Current on
  7831. - `+` - Single step
  7832. - `-` - Single step oposite direction
  7833. - `NNN` - Value sereval steps
  7834. - `?` - Read register
  7835. - Subcommands for read register
  7836. - `mres` - Micro step resolution. More information in datasheet '5.5.2 CHOPCONF – Chopper Configuration'
  7837. - `step` - Step
  7838. - `mscnt` - Microstep counter. More information in datasheet '5.5 Motor Driver Registers'
  7839. - `mscuract` - Actual microstep current for motor. More information in datasheet '5.5 Motor Driver Registers'
  7840. - `wave` - Microstep linearity compensation curve
  7841. - `!` - Set register
  7842. - Subcommands for set register
  7843. - `mres` - Micro step resolution
  7844. - `step` - Step
  7845. - `wave` - Microstep linearity compensation curve
  7846. - Values for set register
  7847. - `0, 180 --> 250` - Off
  7848. - `0.9 --> 1.25` - Valid values (recommended is 1.1)
  7849. - `@` - Home calibrate axis
  7850. Examples:
  7851. D2130E?wave
  7852. Print extruder microstep linearity compensation curve
  7853. D2130E!wave0
  7854. Disable extruder linearity compensation curve, (sine curve is used)
  7855. D2130E!wave220
  7856. (sin(x))^1.1 extruder microstep compensation curve used
  7857. Notes:
  7858. For more information see https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC2130_datasheet.pdf
  7859. *
  7860. */
  7861. case 2130:
  7862. dcode_2130(); break;
  7863. #endif //TMC2130
  7864. #if (defined (FILAMENT_SENSOR) && defined(PAT9125))
  7865. /*!
  7866. ### D9125 - PAT9125 filament sensor <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9125: PAT9125 filament sensor</a>
  7867. #### Usage
  7868. D9125 [ ? | ! | R | X | Y | L ]
  7869. #### Parameters
  7870. - `?` - Print values
  7871. - `!` - Print values
  7872. - `R` - Resolution. Not active in code
  7873. - `X` - X values
  7874. - `Y` - Y values
  7875. - `L` - Activate filament sensor log
  7876. */
  7877. case 9125:
  7878. dcode_9125(); break;
  7879. #endif //FILAMENT_SENSOR
  7880. #endif //DEBUG_DCODES
  7881. }
  7882. }
  7883. else
  7884. {
  7885. SERIAL_ECHO_START;
  7886. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  7887. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  7888. SERIAL_ECHOLNPGM("\"(2)");
  7889. }
  7890. KEEPALIVE_STATE(NOT_BUSY);
  7891. ClearToSend();
  7892. }
  7893. /*!
  7894. #### End of D-Codes
  7895. */
  7896. /** @defgroup GCodes G-Code List
  7897. */
  7898. // ---------------------------------------------------
  7899. void FlushSerialRequestResend()
  7900. {
  7901. //char cmdbuffer[bufindr][100]="Resend:";
  7902. MYSERIAL.flush();
  7903. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  7904. }
  7905. // Confirm the execution of a command, if sent from a serial line.
  7906. // Execution of a command from a SD card will not be confirmed.
  7907. void ClearToSend()
  7908. {
  7909. previous_millis_cmd = _millis();
  7910. if ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR))
  7911. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7912. }
  7913. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7914. void update_currents() {
  7915. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  7916. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  7917. float tmp_motor[3];
  7918. //SERIAL_ECHOLNPGM("Currents updated: ");
  7919. if (destination[Z_AXIS] < Z_SILENT) {
  7920. //SERIAL_ECHOLNPGM("LOW");
  7921. for (uint8_t i = 0; i < 3; i++) {
  7922. st_current_set(i, current_low[i]);
  7923. /*MYSERIAL.print(int(i));
  7924. SERIAL_ECHOPGM(": ");
  7925. MYSERIAL.println(current_low[i]);*/
  7926. }
  7927. }
  7928. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  7929. //SERIAL_ECHOLNPGM("HIGH");
  7930. for (uint8_t i = 0; i < 3; i++) {
  7931. st_current_set(i, current_high[i]);
  7932. /*MYSERIAL.print(int(i));
  7933. SERIAL_ECHOPGM(": ");
  7934. MYSERIAL.println(current_high[i]);*/
  7935. }
  7936. }
  7937. else {
  7938. for (uint8_t i = 0; i < 3; i++) {
  7939. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  7940. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  7941. st_current_set(i, tmp_motor[i]);
  7942. /*MYSERIAL.print(int(i));
  7943. SERIAL_ECHOPGM(": ");
  7944. MYSERIAL.println(tmp_motor[i]);*/
  7945. }
  7946. }
  7947. }
  7948. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7949. void get_coordinates()
  7950. {
  7951. bool seen[4]={false,false,false,false};
  7952. for(int8_t i=0; i < NUM_AXIS; i++) {
  7953. if(code_seen(axis_codes[i]))
  7954. {
  7955. bool relative = axis_relative_modes[i];
  7956. destination[i] = (float)code_value();
  7957. if (i == E_AXIS) {
  7958. float emult = extruder_multiplier[active_extruder];
  7959. if (emult != 1.) {
  7960. if (! relative) {
  7961. destination[i] -= current_position[i];
  7962. relative = true;
  7963. }
  7964. destination[i] *= emult;
  7965. }
  7966. }
  7967. if (relative)
  7968. destination[i] += current_position[i];
  7969. seen[i]=true;
  7970. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7971. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  7972. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7973. }
  7974. else destination[i] = current_position[i]; //Are these else lines really needed?
  7975. }
  7976. if(code_seen('F')) {
  7977. next_feedrate = code_value();
  7978. #ifdef MAX_SILENT_FEEDRATE
  7979. if (tmc2130_mode == TMC2130_MODE_SILENT)
  7980. if (next_feedrate > MAX_SILENT_FEEDRATE) next_feedrate = MAX_SILENT_FEEDRATE;
  7981. #endif //MAX_SILENT_FEEDRATE
  7982. if(next_feedrate > 0.0) feedrate = next_feedrate;
  7983. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  7984. {
  7985. // float e_max_speed =
  7986. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  7987. }
  7988. }
  7989. }
  7990. void get_arc_coordinates()
  7991. {
  7992. #ifdef SF_ARC_FIX
  7993. bool relative_mode_backup = relative_mode;
  7994. relative_mode = true;
  7995. #endif
  7996. get_coordinates();
  7997. #ifdef SF_ARC_FIX
  7998. relative_mode=relative_mode_backup;
  7999. #endif
  8000. if(code_seen('I')) {
  8001. offset[0] = code_value();
  8002. }
  8003. else {
  8004. offset[0] = 0.0;
  8005. }
  8006. if(code_seen('J')) {
  8007. offset[1] = code_value();
  8008. }
  8009. else {
  8010. offset[1] = 0.0;
  8011. }
  8012. }
  8013. void clamp_to_software_endstops(float target[3])
  8014. {
  8015. #ifdef DEBUG_DISABLE_SWLIMITS
  8016. return;
  8017. #endif //DEBUG_DISABLE_SWLIMITS
  8018. world2machine_clamp(target[0], target[1]);
  8019. // Clamp the Z coordinate.
  8020. if (min_software_endstops) {
  8021. float negative_z_offset = 0;
  8022. #ifdef ENABLE_AUTO_BED_LEVELING
  8023. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  8024. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  8025. #endif
  8026. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  8027. }
  8028. if (max_software_endstops) {
  8029. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  8030. }
  8031. }
  8032. #ifdef MESH_BED_LEVELING
  8033. 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) {
  8034. float dx = x - current_position[X_AXIS];
  8035. float dy = y - current_position[Y_AXIS];
  8036. int n_segments = 0;
  8037. if (mbl.active) {
  8038. float len = abs(dx) + abs(dy);
  8039. if (len > 0)
  8040. // Split to 3cm segments or shorter.
  8041. n_segments = int(ceil(len / 30.f));
  8042. }
  8043. if (n_segments > 1) {
  8044. // In a multi-segment move explicitly set the final target in the plan
  8045. // as the move will be recalculated in it's entirety
  8046. float gcode_target[NUM_AXIS];
  8047. gcode_target[X_AXIS] = x;
  8048. gcode_target[Y_AXIS] = y;
  8049. gcode_target[Z_AXIS] = z;
  8050. gcode_target[E_AXIS] = e;
  8051. float dz = z - current_position[Z_AXIS];
  8052. float de = e - current_position[E_AXIS];
  8053. for (int i = 1; i < n_segments; ++ i) {
  8054. float t = float(i) / float(n_segments);
  8055. plan_buffer_line(current_position[X_AXIS] + t * dx,
  8056. current_position[Y_AXIS] + t * dy,
  8057. current_position[Z_AXIS] + t * dz,
  8058. current_position[E_AXIS] + t * de,
  8059. feed_rate, extruder, gcode_target);
  8060. if (waiting_inside_plan_buffer_line_print_aborted)
  8061. return;
  8062. }
  8063. }
  8064. // The rest of the path.
  8065. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  8066. }
  8067. #endif // MESH_BED_LEVELING
  8068. void prepare_move()
  8069. {
  8070. clamp_to_software_endstops(destination);
  8071. previous_millis_cmd = _millis();
  8072. // Do not use feedmultiply for E or Z only moves
  8073. if( (current_position[X_AXIS] == destination [X_AXIS]) && (current_position[Y_AXIS] == destination [Y_AXIS])) {
  8074. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  8075. }
  8076. else {
  8077. #ifdef MESH_BED_LEVELING
  8078. 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);
  8079. #else
  8080. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate*feedmultiply*(1./(60.f*100.f)), active_extruder);
  8081. #endif
  8082. }
  8083. set_current_to_destination();
  8084. }
  8085. void prepare_arc_move(char isclockwise) {
  8086. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  8087. // Trace the arc
  8088. mc_arc(current_position, destination, offset, X_AXIS, Y_AXIS, Z_AXIS, feedrate*feedmultiply/60/100.0, r, isclockwise, active_extruder);
  8089. // As far as the parser is concerned, the position is now == target. In reality the
  8090. // motion control system might still be processing the action and the real tool position
  8091. // in any intermediate location.
  8092. for(int8_t i=0; i < NUM_AXIS; i++) {
  8093. current_position[i] = destination[i];
  8094. }
  8095. previous_millis_cmd = _millis();
  8096. }
  8097. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8098. #if defined(FAN_PIN)
  8099. #if CONTROLLERFAN_PIN == FAN_PIN
  8100. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  8101. #endif
  8102. #endif
  8103. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  8104. unsigned long lastMotorCheck = 0;
  8105. void controllerFan()
  8106. {
  8107. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  8108. {
  8109. lastMotorCheck = _millis();
  8110. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  8111. #if EXTRUDERS > 2
  8112. || !READ(E2_ENABLE_PIN)
  8113. #endif
  8114. #if EXTRUDER > 1
  8115. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  8116. || !READ(X2_ENABLE_PIN)
  8117. #endif
  8118. || !READ(E1_ENABLE_PIN)
  8119. #endif
  8120. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  8121. {
  8122. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  8123. }
  8124. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  8125. {
  8126. digitalWrite(CONTROLLERFAN_PIN, 0);
  8127. analogWrite(CONTROLLERFAN_PIN, 0);
  8128. }
  8129. else
  8130. {
  8131. // allows digital or PWM fan output to be used (see M42 handling)
  8132. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8133. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8134. }
  8135. }
  8136. }
  8137. #endif
  8138. #ifdef TEMP_STAT_LEDS
  8139. static bool blue_led = false;
  8140. static bool red_led = false;
  8141. static uint32_t stat_update = 0;
  8142. void handle_status_leds(void) {
  8143. float max_temp = 0.0;
  8144. if(_millis() > stat_update) {
  8145. stat_update += 500; // Update every 0.5s
  8146. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  8147. max_temp = max(max_temp, degHotend(cur_extruder));
  8148. max_temp = max(max_temp, degTargetHotend(cur_extruder));
  8149. }
  8150. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  8151. max_temp = max(max_temp, degTargetBed());
  8152. max_temp = max(max_temp, degBed());
  8153. #endif
  8154. if((max_temp > 55.0) && (red_led == false)) {
  8155. digitalWrite(STAT_LED_RED, 1);
  8156. digitalWrite(STAT_LED_BLUE, 0);
  8157. red_led = true;
  8158. blue_led = false;
  8159. }
  8160. if((max_temp < 54.0) && (blue_led == false)) {
  8161. digitalWrite(STAT_LED_RED, 0);
  8162. digitalWrite(STAT_LED_BLUE, 1);
  8163. red_led = false;
  8164. blue_led = true;
  8165. }
  8166. }
  8167. }
  8168. #endif
  8169. #ifdef SAFETYTIMER
  8170. /**
  8171. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  8172. *
  8173. * Full screen blocking notification message is shown after heater turning off.
  8174. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  8175. * damage print.
  8176. *
  8177. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  8178. */
  8179. static void handleSafetyTimer()
  8180. {
  8181. #if (EXTRUDERS > 1)
  8182. #error Implemented only for one extruder.
  8183. #endif //(EXTRUDERS > 1)
  8184. if ((PRINTER_ACTIVE) || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  8185. {
  8186. safetyTimer.stop();
  8187. }
  8188. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  8189. {
  8190. safetyTimer.start();
  8191. }
  8192. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  8193. {
  8194. setTargetBed(0);
  8195. setAllTargetHotends(0);
  8196. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED
  8197. }
  8198. }
  8199. #endif //SAFETYTIMER
  8200. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  8201. {
  8202. bool bInhibitFlag;
  8203. #ifdef FILAMENT_SENSOR
  8204. if (mmu_enabled == false)
  8205. {
  8206. //-// if (mcode_in_progress != 600) //M600 not in progress
  8207. #ifdef PAT9125
  8208. bInhibitFlag=(menu_menu==lcd_menu_extruder_info); // Support::ExtruderInfo menu active
  8209. #endif // PAT9125
  8210. #ifdef IR_SENSOR
  8211. bInhibitFlag=(menu_menu==lcd_menu_show_sensors_state); // Support::SensorInfo menu active
  8212. #endif // IR_SENSOR
  8213. if ((mcode_in_progress != 600) && (eFilamentAction != FilamentAction::AutoLoad) && (!bInhibitFlag)) //M600 not in progress, preHeat @ autoLoad menu not active, Support::ExtruderInfo/SensorInfo menu not active
  8214. {
  8215. if (!moves_planned() && !IS_SD_PRINTING && !is_usb_printing && (lcd_commands_type != LcdCommands::Layer1Cal) && ! eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE))
  8216. {
  8217. if (fsensor_check_autoload())
  8218. {
  8219. #ifdef PAT9125
  8220. fsensor_autoload_check_stop();
  8221. #endif //PAT9125
  8222. //-// if (degHotend0() > EXTRUDE_MINTEMP)
  8223. if(0)
  8224. {
  8225. Sound_MakeCustom(50,1000,false);
  8226. loading_flag = true;
  8227. enquecommand_front_P((PSTR("M701")));
  8228. }
  8229. else
  8230. {
  8231. /*
  8232. lcd_update_enable(false);
  8233. show_preheat_nozzle_warning();
  8234. lcd_update_enable(true);
  8235. */
  8236. eFilamentAction=FilamentAction::AutoLoad;
  8237. bFilamentFirstRun=false;
  8238. if(target_temperature[0]>=EXTRUDE_MINTEMP)
  8239. {
  8240. bFilamentPreheatState=true;
  8241. // mFilamentItem(target_temperature[0],target_temperature_bed);
  8242. menu_submenu(mFilamentItemForce);
  8243. }
  8244. else
  8245. {
  8246. menu_submenu(lcd_generic_preheat_menu);
  8247. lcd_timeoutToStatus.start();
  8248. }
  8249. }
  8250. }
  8251. }
  8252. else
  8253. {
  8254. #ifdef PAT9125
  8255. fsensor_autoload_check_stop();
  8256. #endif //PAT9125
  8257. if (fsensor_enabled && !saved_printing)
  8258. fsensor_update();
  8259. }
  8260. }
  8261. }
  8262. #endif //FILAMENT_SENSOR
  8263. #ifdef SAFETYTIMER
  8264. handleSafetyTimer();
  8265. #endif //SAFETYTIMER
  8266. #if defined(KILL_PIN) && KILL_PIN > -1
  8267. static int killCount = 0; // make the inactivity button a bit less responsive
  8268. const int KILL_DELAY = 10000;
  8269. #endif
  8270. if(buflen < (BUFSIZE-1)){
  8271. get_command();
  8272. }
  8273. if( (_millis() - previous_millis_cmd) > max_inactive_time )
  8274. if(max_inactive_time)
  8275. kill(_n("Inactivity Shutdown"), 4);
  8276. if(stepper_inactive_time) {
  8277. if( (_millis() - previous_millis_cmd) > stepper_inactive_time )
  8278. {
  8279. if(blocks_queued() == false && ignore_stepper_queue == false) {
  8280. disable_x();
  8281. disable_y();
  8282. disable_z();
  8283. disable_e0();
  8284. disable_e1();
  8285. disable_e2();
  8286. }
  8287. }
  8288. }
  8289. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  8290. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  8291. {
  8292. chdkActive = false;
  8293. WRITE(CHDK, LOW);
  8294. }
  8295. #endif
  8296. #if defined(KILL_PIN) && KILL_PIN > -1
  8297. // Check if the kill button was pressed and wait just in case it was an accidental
  8298. // key kill key press
  8299. // -------------------------------------------------------------------------------
  8300. if( 0 == READ(KILL_PIN) )
  8301. {
  8302. killCount++;
  8303. }
  8304. else if (killCount > 0)
  8305. {
  8306. killCount--;
  8307. }
  8308. // Exceeded threshold and we can confirm that it was not accidental
  8309. // KILL the machine
  8310. // ----------------------------------------------------------------
  8311. if ( killCount >= KILL_DELAY)
  8312. {
  8313. kill(NULL, 5);
  8314. }
  8315. #endif
  8316. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8317. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  8318. #endif
  8319. #ifdef EXTRUDER_RUNOUT_PREVENT
  8320. if( (_millis() - previous_millis_cmd) > EXTRUDER_RUNOUT_SECONDS*1000 )
  8321. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  8322. {
  8323. bool oldstatus=READ(E0_ENABLE_PIN);
  8324. enable_e0();
  8325. float oldepos=current_position[E_AXIS];
  8326. float oldedes=destination[E_AXIS];
  8327. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  8328. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  8329. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  8330. current_position[E_AXIS]=oldepos;
  8331. destination[E_AXIS]=oldedes;
  8332. plan_set_e_position(oldepos);
  8333. previous_millis_cmd=_millis();
  8334. st_synchronize();
  8335. WRITE(E0_ENABLE_PIN,oldstatus);
  8336. }
  8337. #endif
  8338. #ifdef TEMP_STAT_LEDS
  8339. handle_status_leds();
  8340. #endif
  8341. check_axes_activity();
  8342. mmu_loop();
  8343. }
  8344. void kill(const char *full_screen_message, unsigned char id)
  8345. {
  8346. printf_P(_N("KILL: %d\n"), id);
  8347. //return;
  8348. cli(); // Stop interrupts
  8349. disable_heater();
  8350. disable_x();
  8351. // SERIAL_ECHOLNPGM("kill - disable Y");
  8352. disable_y();
  8353. poweroff_z();
  8354. disable_e0();
  8355. disable_e1();
  8356. disable_e2();
  8357. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  8358. pinMode(PS_ON_PIN,INPUT);
  8359. #endif
  8360. SERIAL_ERROR_START;
  8361. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  8362. if (full_screen_message != NULL) {
  8363. SERIAL_ERRORLNRPGM(full_screen_message);
  8364. lcd_display_message_fullscreen_P(full_screen_message);
  8365. } else {
  8366. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  8367. }
  8368. // FMC small patch to update the LCD before ending
  8369. sei(); // enable interrupts
  8370. for ( int i=5; i--; lcd_update(0))
  8371. {
  8372. _delay(200);
  8373. }
  8374. cli(); // disable interrupts
  8375. suicide();
  8376. while(1)
  8377. {
  8378. #ifdef WATCHDOG
  8379. wdt_reset();
  8380. #endif //WATCHDOG
  8381. /* Intentionally left empty */
  8382. } // Wait for reset
  8383. }
  8384. // Stop: Emergency stop used by overtemp functions which allows recovery
  8385. //
  8386. // In addition to stopping the print, this prevents subsequent G[0-3] commands to be
  8387. // processed via USB (using "Stopped") until the print is resumed via M999 or
  8388. // manually started from scratch with the LCD.
  8389. //
  8390. // Note that the current instruction is completely discarded, so resuming from Stop()
  8391. // will introduce either over/under extrusion on the current segment, and will not
  8392. // survive a power panic. Switching Stop() to use the pause machinery instead (with
  8393. // the addition of disabling the headers) could allow true recovery in the future.
  8394. void Stop()
  8395. {
  8396. disable_heater();
  8397. if(Stopped == false) {
  8398. Stopped = true;
  8399. lcd_print_stop();
  8400. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  8401. SERIAL_ERROR_START;
  8402. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  8403. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  8404. }
  8405. }
  8406. bool IsStopped() { return Stopped; };
  8407. #ifdef FAST_PWM_FAN
  8408. void setPwmFrequency(uint8_t pin, int val)
  8409. {
  8410. val &= 0x07;
  8411. switch(digitalPinToTimer(pin))
  8412. {
  8413. #if defined(TCCR0A)
  8414. case TIMER0A:
  8415. case TIMER0B:
  8416. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8417. // TCCR0B |= val;
  8418. break;
  8419. #endif
  8420. #if defined(TCCR1A)
  8421. case TIMER1A:
  8422. case TIMER1B:
  8423. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8424. // TCCR1B |= val;
  8425. break;
  8426. #endif
  8427. #if defined(TCCR2)
  8428. case TIMER2:
  8429. case TIMER2:
  8430. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8431. TCCR2 |= val;
  8432. break;
  8433. #endif
  8434. #if defined(TCCR2A)
  8435. case TIMER2A:
  8436. case TIMER2B:
  8437. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8438. TCCR2B |= val;
  8439. break;
  8440. #endif
  8441. #if defined(TCCR3A)
  8442. case TIMER3A:
  8443. case TIMER3B:
  8444. case TIMER3C:
  8445. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8446. TCCR3B |= val;
  8447. break;
  8448. #endif
  8449. #if defined(TCCR4A)
  8450. case TIMER4A:
  8451. case TIMER4B:
  8452. case TIMER4C:
  8453. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8454. TCCR4B |= val;
  8455. break;
  8456. #endif
  8457. #if defined(TCCR5A)
  8458. case TIMER5A:
  8459. case TIMER5B:
  8460. case TIMER5C:
  8461. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8462. TCCR5B |= val;
  8463. break;
  8464. #endif
  8465. }
  8466. }
  8467. #endif //FAST_PWM_FAN
  8468. //! @brief Get and validate extruder number
  8469. //!
  8470. //! If it is not specified, active_extruder is returned in parameter extruder.
  8471. //! @param [in] code M code number
  8472. //! @param [out] extruder
  8473. //! @return error
  8474. //! @retval true Invalid extruder specified in T code
  8475. //! @retval false Valid extruder specified in T code, or not specifiead
  8476. bool setTargetedHotend(int code, uint8_t &extruder)
  8477. {
  8478. extruder = active_extruder;
  8479. if(code_seen('T')) {
  8480. extruder = code_value();
  8481. if(extruder >= EXTRUDERS) {
  8482. SERIAL_ECHO_START;
  8483. switch(code){
  8484. case 104:
  8485. SERIAL_ECHORPGM(_n("M104 Invalid extruder "));////MSG_M104_INVALID_EXTRUDER
  8486. break;
  8487. case 105:
  8488. SERIAL_ECHO(_n("M105 Invalid extruder "));////MSG_M105_INVALID_EXTRUDER
  8489. break;
  8490. case 109:
  8491. SERIAL_ECHO(_n("M109 Invalid extruder "));////MSG_M109_INVALID_EXTRUDER
  8492. break;
  8493. case 218:
  8494. SERIAL_ECHO(_n("M218 Invalid extruder "));////MSG_M218_INVALID_EXTRUDER
  8495. break;
  8496. case 221:
  8497. SERIAL_ECHO(_n("M221 Invalid extruder "));////MSG_M221_INVALID_EXTRUDER
  8498. break;
  8499. }
  8500. SERIAL_PROTOCOLLN((int)extruder);
  8501. return true;
  8502. }
  8503. }
  8504. return false;
  8505. }
  8506. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  8507. {
  8508. 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)
  8509. {
  8510. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  8511. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  8512. }
  8513. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  8514. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  8515. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  8516. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  8517. total_filament_used = 0;
  8518. }
  8519. float calculate_extruder_multiplier(float diameter) {
  8520. float out = 1.f;
  8521. if (cs.volumetric_enabled && diameter > 0.f) {
  8522. float area = M_PI * diameter * diameter * 0.25;
  8523. out = 1.f / area;
  8524. }
  8525. if (extrudemultiply != 100)
  8526. out *= float(extrudemultiply) * 0.01f;
  8527. return out;
  8528. }
  8529. void calculate_extruder_multipliers() {
  8530. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  8531. #if EXTRUDERS > 1
  8532. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  8533. #if EXTRUDERS > 2
  8534. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  8535. #endif
  8536. #endif
  8537. }
  8538. void delay_keep_alive(unsigned int ms)
  8539. {
  8540. for (;;) {
  8541. manage_heater();
  8542. // Manage inactivity, but don't disable steppers on timeout.
  8543. manage_inactivity(true);
  8544. lcd_update(0);
  8545. if (ms == 0)
  8546. break;
  8547. else if (ms >= 50) {
  8548. _delay(50);
  8549. ms -= 50;
  8550. } else {
  8551. _delay(ms);
  8552. ms = 0;
  8553. }
  8554. }
  8555. }
  8556. static void wait_for_heater(long codenum, uint8_t extruder) {
  8557. if (!degTargetHotend(extruder))
  8558. return;
  8559. #ifdef TEMP_RESIDENCY_TIME
  8560. long residencyStart;
  8561. residencyStart = -1;
  8562. /* continue to loop until we have reached the target temp
  8563. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  8564. cancel_heatup = false;
  8565. while ((!cancel_heatup) && ((residencyStart == -1) ||
  8566. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  8567. #else
  8568. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  8569. #endif //TEMP_RESIDENCY_TIME
  8570. if ((_millis() - codenum) > 1000UL)
  8571. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  8572. if (!farm_mode) {
  8573. SERIAL_PROTOCOLPGM("T:");
  8574. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  8575. SERIAL_PROTOCOLPGM(" E:");
  8576. SERIAL_PROTOCOL((int)extruder);
  8577. #ifdef TEMP_RESIDENCY_TIME
  8578. SERIAL_PROTOCOLPGM(" W:");
  8579. if (residencyStart > -1)
  8580. {
  8581. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  8582. SERIAL_PROTOCOLLN(codenum);
  8583. }
  8584. else
  8585. {
  8586. SERIAL_PROTOCOLLN("?");
  8587. }
  8588. }
  8589. #else
  8590. SERIAL_PROTOCOLLN("");
  8591. #endif
  8592. codenum = _millis();
  8593. }
  8594. manage_heater();
  8595. manage_inactivity(true); //do not disable steppers
  8596. lcd_update(0);
  8597. #ifdef TEMP_RESIDENCY_TIME
  8598. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  8599. or when current temp falls outside the hysteresis after target temp was reached */
  8600. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  8601. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  8602. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  8603. {
  8604. residencyStart = _millis();
  8605. }
  8606. #endif //TEMP_RESIDENCY_TIME
  8607. }
  8608. }
  8609. void check_babystep()
  8610. {
  8611. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8612. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  8613. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  8614. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  8615. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  8616. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8617. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  8618. babystep_z);
  8619. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  8620. lcd_update_enable(true);
  8621. }
  8622. }
  8623. #ifdef HEATBED_ANALYSIS
  8624. void d_setup()
  8625. {
  8626. pinMode(D_DATACLOCK, INPUT_PULLUP);
  8627. pinMode(D_DATA, INPUT_PULLUP);
  8628. pinMode(D_REQUIRE, OUTPUT);
  8629. digitalWrite(D_REQUIRE, HIGH);
  8630. }
  8631. float d_ReadData()
  8632. {
  8633. int digit[13];
  8634. String mergeOutput;
  8635. float output;
  8636. digitalWrite(D_REQUIRE, HIGH);
  8637. for (int i = 0; i<13; i++)
  8638. {
  8639. for (int j = 0; j < 4; j++)
  8640. {
  8641. while (digitalRead(D_DATACLOCK) == LOW) {}
  8642. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8643. bitWrite(digit[i], j, digitalRead(D_DATA));
  8644. }
  8645. }
  8646. digitalWrite(D_REQUIRE, LOW);
  8647. mergeOutput = "";
  8648. output = 0;
  8649. for (int r = 5; r <= 10; r++) //Merge digits
  8650. {
  8651. mergeOutput += digit[r];
  8652. }
  8653. output = mergeOutput.toFloat();
  8654. if (digit[4] == 8) //Handle sign
  8655. {
  8656. output *= -1;
  8657. }
  8658. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8659. {
  8660. output /= 10;
  8661. }
  8662. return output;
  8663. }
  8664. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8665. int t1 = 0;
  8666. int t_delay = 0;
  8667. int digit[13];
  8668. int m;
  8669. char str[3];
  8670. //String mergeOutput;
  8671. char mergeOutput[15];
  8672. float output;
  8673. int mesh_point = 0; //index number of calibration point
  8674. 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
  8675. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8676. float mesh_home_z_search = 4;
  8677. float measure_z_height = 0.2f;
  8678. float row[x_points_num];
  8679. int ix = 0;
  8680. int iy = 0;
  8681. const char* filename_wldsd = "mesh.txt";
  8682. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  8683. char numb_wldsd[8]; // (" -A.BCD" + null)
  8684. #ifdef MICROMETER_LOGGING
  8685. d_setup();
  8686. #endif //MICROMETER_LOGGING
  8687. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8688. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8689. unsigned int custom_message_type_old = custom_message_type;
  8690. unsigned int custom_message_state_old = custom_message_state;
  8691. custom_message_type = CustomMsg::MeshBedLeveling;
  8692. custom_message_state = (x_points_num * y_points_num) + 10;
  8693. lcd_update(1);
  8694. //mbl.reset();
  8695. babystep_undo();
  8696. card.openFile(filename_wldsd, false);
  8697. /*destination[Z_AXIS] = mesh_home_z_search;
  8698. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8699. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  8700. for(int8_t i=0; i < NUM_AXIS; i++) {
  8701. current_position[i] = destination[i];
  8702. }
  8703. st_synchronize();
  8704. */
  8705. destination[Z_AXIS] = measure_z_height;
  8706. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  8707. for(int8_t i=0; i < NUM_AXIS; i++) {
  8708. current_position[i] = destination[i];
  8709. }
  8710. st_synchronize();
  8711. /*int l_feedmultiply = */setup_for_endstop_move(false);
  8712. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8713. SERIAL_PROTOCOL(x_points_num);
  8714. SERIAL_PROTOCOLPGM(",");
  8715. SERIAL_PROTOCOL(y_points_num);
  8716. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8717. SERIAL_PROTOCOL(mesh_home_z_search);
  8718. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8719. SERIAL_PROTOCOL(x_dimension);
  8720. SERIAL_PROTOCOLPGM(",");
  8721. SERIAL_PROTOCOL(y_dimension);
  8722. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8723. while (mesh_point != x_points_num * y_points_num) {
  8724. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8725. iy = mesh_point / x_points_num;
  8726. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8727. float z0 = 0.f;
  8728. /*destination[Z_AXIS] = mesh_home_z_search;
  8729. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8730. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  8731. for(int8_t i=0; i < NUM_AXIS; i++) {
  8732. current_position[i] = destination[i];
  8733. }
  8734. st_synchronize();*/
  8735. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8736. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8737. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  8738. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  8739. mesh_plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], XY_AXIS_FEEDRATE/6, active_extruder);
  8740. set_current_to_destination();
  8741. st_synchronize();
  8742. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  8743. delay_keep_alive(1000);
  8744. #ifdef MICROMETER_LOGGING
  8745. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8746. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8747. //strcat(data_wldsd, numb_wldsd);
  8748. //MYSERIAL.println(data_wldsd);
  8749. //delay(1000);
  8750. //delay(3000);
  8751. //t1 = millis();
  8752. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8753. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8754. memset(digit, 0, sizeof(digit));
  8755. //cli();
  8756. digitalWrite(D_REQUIRE, LOW);
  8757. for (int i = 0; i<13; i++)
  8758. {
  8759. //t1 = millis();
  8760. for (int j = 0; j < 4; j++)
  8761. {
  8762. while (digitalRead(D_DATACLOCK) == LOW) {}
  8763. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8764. //printf_P(PSTR("Done %d\n"), j);
  8765. bitWrite(digit[i], j, digitalRead(D_DATA));
  8766. }
  8767. //t_delay = (millis() - t1);
  8768. //SERIAL_PROTOCOLPGM(" ");
  8769. //SERIAL_PROTOCOL_F(t_delay, 5);
  8770. //SERIAL_PROTOCOLPGM(" ");
  8771. }
  8772. //sei();
  8773. digitalWrite(D_REQUIRE, HIGH);
  8774. mergeOutput[0] = '\0';
  8775. output = 0;
  8776. for (int r = 5; r <= 10; r++) //Merge digits
  8777. {
  8778. sprintf(str, "%d", digit[r]);
  8779. strcat(mergeOutput, str);
  8780. }
  8781. output = atof(mergeOutput);
  8782. if (digit[4] == 8) //Handle sign
  8783. {
  8784. output *= -1;
  8785. }
  8786. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8787. {
  8788. output *= 0.1;
  8789. }
  8790. //output = d_ReadData();
  8791. //row[ix] = current_position[Z_AXIS];
  8792. //row[ix] = d_ReadData();
  8793. row[ix] = output;
  8794. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8795. memset(data_wldsd, 0, sizeof(data_wldsd));
  8796. for (int i = 0; i < x_points_num; i++) {
  8797. SERIAL_PROTOCOLPGM(" ");
  8798. SERIAL_PROTOCOL_F(row[i], 5);
  8799. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8800. dtostrf(row[i], 7, 3, numb_wldsd);
  8801. strcat(data_wldsd, numb_wldsd);
  8802. }
  8803. card.write_command(data_wldsd);
  8804. SERIAL_PROTOCOLPGM("\n");
  8805. }
  8806. custom_message_state--;
  8807. mesh_point++;
  8808. lcd_update(1);
  8809. }
  8810. #endif //MICROMETER_LOGGING
  8811. card.closefile();
  8812. //clean_up_after_endstop_move(l_feedmultiply);
  8813. }
  8814. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8815. int t1 = 0;
  8816. int t_delay = 0;
  8817. int digit[13];
  8818. int m;
  8819. char str[3];
  8820. //String mergeOutput;
  8821. char mergeOutput[15];
  8822. float output;
  8823. int mesh_point = 0; //index number of calibration point
  8824. 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
  8825. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8826. float mesh_home_z_search = 4;
  8827. float row[x_points_num];
  8828. int ix = 0;
  8829. int iy = 0;
  8830. const char* filename_wldsd = "wldsd.txt";
  8831. char data_wldsd[70];
  8832. char numb_wldsd[10];
  8833. d_setup();
  8834. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  8835. // We don't know where we are! HOME!
  8836. // Push the commands to the front of the message queue in the reverse order!
  8837. // There shall be always enough space reserved for these commands.
  8838. repeatcommand_front(); // repeat G80 with all its parameters
  8839. enquecommand_front_P((PSTR("G28 W0")));
  8840. enquecommand_front_P((PSTR("G1 Z5")));
  8841. return;
  8842. }
  8843. unsigned int custom_message_type_old = custom_message_type;
  8844. unsigned int custom_message_state_old = custom_message_state;
  8845. custom_message_type = CustomMsg::MeshBedLeveling;
  8846. custom_message_state = (x_points_num * y_points_num) + 10;
  8847. lcd_update(1);
  8848. mbl.reset();
  8849. babystep_undo();
  8850. card.openFile(filename_wldsd, false);
  8851. current_position[Z_AXIS] = mesh_home_z_search;
  8852. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  8853. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8854. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8855. int l_feedmultiply = setup_for_endstop_move(false);
  8856. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8857. SERIAL_PROTOCOL(x_points_num);
  8858. SERIAL_PROTOCOLPGM(",");
  8859. SERIAL_PROTOCOL(y_points_num);
  8860. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8861. SERIAL_PROTOCOL(mesh_home_z_search);
  8862. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8863. SERIAL_PROTOCOL(x_dimension);
  8864. SERIAL_PROTOCOLPGM(",");
  8865. SERIAL_PROTOCOL(y_dimension);
  8866. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8867. while (mesh_point != x_points_num * y_points_num) {
  8868. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8869. iy = mesh_point / x_points_num;
  8870. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8871. float z0 = 0.f;
  8872. current_position[Z_AXIS] = mesh_home_z_search;
  8873. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8874. st_synchronize();
  8875. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8876. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8877. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  8878. st_synchronize();
  8879. 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
  8880. break;
  8881. card.closefile();
  8882. }
  8883. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8884. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8885. //strcat(data_wldsd, numb_wldsd);
  8886. //MYSERIAL.println(data_wldsd);
  8887. //_delay(1000);
  8888. //_delay(3000);
  8889. //t1 = _millis();
  8890. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8891. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8892. memset(digit, 0, sizeof(digit));
  8893. //cli();
  8894. digitalWrite(D_REQUIRE, LOW);
  8895. for (int i = 0; i<13; i++)
  8896. {
  8897. //t1 = _millis();
  8898. for (int j = 0; j < 4; j++)
  8899. {
  8900. while (digitalRead(D_DATACLOCK) == LOW) {}
  8901. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8902. bitWrite(digit[i], j, digitalRead(D_DATA));
  8903. }
  8904. //t_delay = (_millis() - t1);
  8905. //SERIAL_PROTOCOLPGM(" ");
  8906. //SERIAL_PROTOCOL_F(t_delay, 5);
  8907. //SERIAL_PROTOCOLPGM(" ");
  8908. }
  8909. //sei();
  8910. digitalWrite(D_REQUIRE, HIGH);
  8911. mergeOutput[0] = '\0';
  8912. output = 0;
  8913. for (int r = 5; r <= 10; r++) //Merge digits
  8914. {
  8915. sprintf(str, "%d", digit[r]);
  8916. strcat(mergeOutput, str);
  8917. }
  8918. output = atof(mergeOutput);
  8919. if (digit[4] == 8) //Handle sign
  8920. {
  8921. output *= -1;
  8922. }
  8923. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8924. {
  8925. output *= 0.1;
  8926. }
  8927. //output = d_ReadData();
  8928. //row[ix] = current_position[Z_AXIS];
  8929. memset(data_wldsd, 0, sizeof(data_wldsd));
  8930. for (int i = 0; i <3; i++) {
  8931. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8932. dtostrf(current_position[i], 8, 5, numb_wldsd);
  8933. strcat(data_wldsd, numb_wldsd);
  8934. strcat(data_wldsd, ";");
  8935. }
  8936. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8937. dtostrf(output, 8, 5, numb_wldsd);
  8938. strcat(data_wldsd, numb_wldsd);
  8939. //strcat(data_wldsd, ";");
  8940. card.write_command(data_wldsd);
  8941. //row[ix] = d_ReadData();
  8942. row[ix] = output; // current_position[Z_AXIS];
  8943. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8944. for (int i = 0; i < x_points_num; i++) {
  8945. SERIAL_PROTOCOLPGM(" ");
  8946. SERIAL_PROTOCOL_F(row[i], 5);
  8947. }
  8948. SERIAL_PROTOCOLPGM("\n");
  8949. }
  8950. custom_message_state--;
  8951. mesh_point++;
  8952. lcd_update(1);
  8953. }
  8954. card.closefile();
  8955. clean_up_after_endstop_move(l_feedmultiply);
  8956. }
  8957. #endif //HEATBED_ANALYSIS
  8958. #ifndef PINDA_THERMISTOR
  8959. static void temp_compensation_start() {
  8960. custom_message_type = CustomMsg::TempCompPreheat;
  8961. custom_message_state = PINDA_HEAT_T + 1;
  8962. lcd_update(2);
  8963. if (degHotend(active_extruder) > EXTRUDE_MINTEMP) {
  8964. current_position[E_AXIS] -= default_retraction;
  8965. }
  8966. plan_buffer_line_curposXYZE(400, active_extruder);
  8967. current_position[X_AXIS] = PINDA_PREHEAT_X;
  8968. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  8969. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  8970. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  8971. st_synchronize();
  8972. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  8973. for (int i = 0; i < PINDA_HEAT_T; i++) {
  8974. delay_keep_alive(1000);
  8975. custom_message_state = PINDA_HEAT_T - i;
  8976. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  8977. else lcd_update(1);
  8978. }
  8979. custom_message_type = CustomMsg::Status;
  8980. custom_message_state = 0;
  8981. }
  8982. static void temp_compensation_apply() {
  8983. int i_add;
  8984. int z_shift = 0;
  8985. float z_shift_mm;
  8986. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  8987. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  8988. i_add = (target_temperature_bed - 60) / 10;
  8989. EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + i_add * 2, &z_shift);
  8990. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  8991. }else {
  8992. //interpolation
  8993. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  8994. }
  8995. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  8996. 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);
  8997. st_synchronize();
  8998. plan_set_z_position(current_position[Z_AXIS]);
  8999. }
  9000. else {
  9001. //we have no temp compensation data
  9002. }
  9003. }
  9004. #endif //ndef PINDA_THERMISTOR
  9005. float temp_comp_interpolation(float inp_temperature) {
  9006. //cubic spline interpolation
  9007. int n, i, j;
  9008. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  9009. int shift[10];
  9010. int temp_C[10];
  9011. n = 6; //number of measured points
  9012. shift[0] = 0;
  9013. for (i = 0; i < n; i++) {
  9014. if (i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i-1) * 2, &shift[i]); //read shift in steps from EEPROM
  9015. temp_C[i] = 50 + i * 10; //temperature in C
  9016. #ifdef PINDA_THERMISTOR
  9017. temp_C[i] = 35 + i * 5; //temperature in C
  9018. #else
  9019. temp_C[i] = 50 + i * 10; //temperature in C
  9020. #endif
  9021. x[i] = (float)temp_C[i];
  9022. f[i] = (float)shift[i];
  9023. }
  9024. if (inp_temperature < x[0]) return 0;
  9025. for (i = n - 1; i>0; i--) {
  9026. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  9027. h[i - 1] = x[i] - x[i - 1];
  9028. }
  9029. //*********** formation of h, s , f matrix **************
  9030. for (i = 1; i<n - 1; i++) {
  9031. m[i][i] = 2 * (h[i - 1] + h[i]);
  9032. if (i != 1) {
  9033. m[i][i - 1] = h[i - 1];
  9034. m[i - 1][i] = h[i - 1];
  9035. }
  9036. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  9037. }
  9038. //*********** forward elimination **************
  9039. for (i = 1; i<n - 2; i++) {
  9040. temp = (m[i + 1][i] / m[i][i]);
  9041. for (j = 1; j <= n - 1; j++)
  9042. m[i + 1][j] -= temp*m[i][j];
  9043. }
  9044. //*********** backward substitution *********
  9045. for (i = n - 2; i>0; i--) {
  9046. sum = 0;
  9047. for (j = i; j <= n - 2; j++)
  9048. sum += m[i][j] * s[j];
  9049. s[i] = (m[i][n - 1] - sum) / m[i][i];
  9050. }
  9051. for (i = 0; i<n - 1; i++)
  9052. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  9053. a = (s[i + 1] - s[i]) / (6 * h[i]);
  9054. b = s[i] / 2;
  9055. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  9056. d = f[i];
  9057. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  9058. }
  9059. return sum;
  9060. }
  9061. #ifdef PINDA_THERMISTOR
  9062. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  9063. {
  9064. if (!temp_cal_active) return 0;
  9065. if (!calibration_status_pinda()) return 0;
  9066. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  9067. }
  9068. #endif //PINDA_THERMISTOR
  9069. void long_pause() //long pause print
  9070. {
  9071. st_synchronize();
  9072. start_pause_print = _millis();
  9073. // Stop heaters
  9074. setAllTargetHotends(0);
  9075. //lift z
  9076. current_position[Z_AXIS] += Z_PAUSE_LIFT;
  9077. if (current_position[Z_AXIS] > Z_MAX_POS) current_position[Z_AXIS] = Z_MAX_POS;
  9078. plan_buffer_line_curposXYZE(15, active_extruder);
  9079. //Move XY to side
  9080. current_position[X_AXIS] = X_PAUSE_POS;
  9081. current_position[Y_AXIS] = Y_PAUSE_POS;
  9082. plan_buffer_line_curposXYZE(50, active_extruder);
  9083. // Turn off the print fan
  9084. fanSpeed = 0;
  9085. }
  9086. void serialecho_temperatures() {
  9087. float tt = degHotend(active_extruder);
  9088. SERIAL_PROTOCOLPGM("T:");
  9089. SERIAL_PROTOCOL(tt);
  9090. SERIAL_PROTOCOLPGM(" E:");
  9091. SERIAL_PROTOCOL((int)active_extruder);
  9092. SERIAL_PROTOCOLPGM(" B:");
  9093. SERIAL_PROTOCOL_F(degBed(), 1);
  9094. SERIAL_PROTOCOLLN("");
  9095. }
  9096. #ifdef UVLO_SUPPORT
  9097. void uvlo_drain_reset()
  9098. {
  9099. // burn all that residual power
  9100. wdt_enable(WDTO_1S);
  9101. WRITE(BEEPER,HIGH);
  9102. lcd_clear();
  9103. lcd_puts_at_P(0, 1, MSG_POWERPANIC_DETECTED);
  9104. while(1);
  9105. }
  9106. void uvlo_()
  9107. {
  9108. unsigned long time_start = _millis();
  9109. bool sd_print = card.sdprinting;
  9110. // Conserve power as soon as possible.
  9111. #ifdef LCD_BL_PIN
  9112. backlightMode = BACKLIGHT_MODE_DIM;
  9113. backlightLevel_LOW = 0;
  9114. backlight_update();
  9115. #endif //LCD_BL_PIN
  9116. disable_x();
  9117. disable_y();
  9118. #ifdef TMC2130
  9119. tmc2130_set_current_h(Z_AXIS, 20);
  9120. tmc2130_set_current_r(Z_AXIS, 20);
  9121. tmc2130_set_current_h(E_AXIS, 20);
  9122. tmc2130_set_current_r(E_AXIS, 20);
  9123. #endif //TMC2130
  9124. // Stop all heaters
  9125. uint8_t saved_target_temperature_bed = target_temperature_bed;
  9126. uint16_t saved_target_temperature_ext = target_temperature[active_extruder];
  9127. setAllTargetHotends(0);
  9128. setTargetBed(0);
  9129. // Calculate the file position, from which to resume this print.
  9130. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  9131. {
  9132. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9133. sd_position -= sdlen_planner;
  9134. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9135. sd_position -= sdlen_cmdqueue;
  9136. if (sd_position < 0) sd_position = 0;
  9137. }
  9138. // save the global state at planning time
  9139. uint16_t feedrate_bckp;
  9140. if (current_block)
  9141. {
  9142. memcpy(saved_target, current_block->gcode_target, sizeof(saved_target));
  9143. feedrate_bckp = current_block->gcode_feedrate;
  9144. }
  9145. else
  9146. {
  9147. saved_target[0] = SAVED_TARGET_UNSET;
  9148. feedrate_bckp = feedrate;
  9149. }
  9150. // From this point on and up to the print recovery, Z should not move during X/Y travels and
  9151. // should be controlled precisely. Reset the MBL status before planner_abort_hard in order to
  9152. // get the physical Z for further manipulation.
  9153. bool mbl_was_active = mbl.active;
  9154. mbl.active = false;
  9155. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  9156. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  9157. // are in action.
  9158. planner_abort_hard();
  9159. // Store the print logical Z position, which we need to recover (a slight error here would be
  9160. // recovered on the next Gcode instruction, while a physical location error would not)
  9161. float logical_z = current_position[Z_AXIS];
  9162. if(mbl_was_active) logical_z -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  9163. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z, logical_z);
  9164. // Store the print E position before we lose track
  9165. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), current_position[E_AXIS]);
  9166. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, axis_relative_modes[3]?0:1);
  9167. // Clean the input command queue, inhibit serial processing using saved_printing
  9168. cmdqueue_reset();
  9169. card.sdprinting = false;
  9170. saved_printing = true;
  9171. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9172. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9173. sei();
  9174. // Retract
  9175. current_position[E_AXIS] -= default_retraction;
  9176. plan_buffer_line_curposXYZE(95, active_extruder);
  9177. st_synchronize();
  9178. disable_e0();
  9179. // Read out the current Z motor microstep counter to move the axis up towards
  9180. // a full step before powering off. NOTE: we need to ensure to schedule more
  9181. // than "dropsegments" steps in order to move (this is always the case here
  9182. // due to UVLO_Z_AXIS_SHIFT being used)
  9183. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9184. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9185. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9186. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9187. + UVLO_Z_AXIS_SHIFT;
  9188. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60, active_extruder);
  9189. st_synchronize();
  9190. poweroff_z();
  9191. // Write the file position.
  9192. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  9193. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9194. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9195. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9196. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9197. // Scale the z value to 1u resolution.
  9198. int16_t v = mbl_was_active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  9199. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  9200. }
  9201. // Write the _final_ Z position and motor microstep counter (unused).
  9202. eeprom_update_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z, current_position[Z_AXIS]);
  9203. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9204. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9205. // Store the current position.
  9206. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  9207. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  9208. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  9209. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDRATE, feedrate_bckp);
  9210. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY, feedmultiply);
  9211. eeprom_update_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND, saved_target_temperature_ext);
  9212. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, saved_target_temperature_bed);
  9213. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  9214. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  9215. #if EXTRUDERS > 1
  9216. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  9217. #if EXTRUDERS > 2
  9218. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  9219. #endif
  9220. #endif
  9221. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  9222. // Store the saved target
  9223. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+0*4), saved_target[X_AXIS]);
  9224. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+1*4), saved_target[Y_AXIS]);
  9225. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+2*4), saved_target[Z_AXIS]);
  9226. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+3*4), saved_target[E_AXIS]);
  9227. #ifdef LIN_ADVANCE
  9228. eeprom_update_float((float*)(EEPROM_UVLO_LA_K), extruder_advance_K);
  9229. #endif
  9230. // Finaly store the "power outage" flag.
  9231. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  9232. // Increment power failure counter
  9233. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9234. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9235. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  9236. WRITE(BEEPER,HIGH);
  9237. // All is set: with all the juice left, try to move extruder away to detach the nozzle completely from the print
  9238. poweron_z();
  9239. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  9240. plan_buffer_line_curposXYZE(500, active_extruder);
  9241. st_synchronize();
  9242. wdt_enable(WDTO_1S);
  9243. while(1);
  9244. }
  9245. void uvlo_tiny()
  9246. {
  9247. unsigned long time_start = _millis();
  9248. // Conserve power as soon as possible.
  9249. disable_x();
  9250. disable_y();
  9251. disable_e0();
  9252. #ifdef TMC2130
  9253. tmc2130_set_current_h(Z_AXIS, 20);
  9254. tmc2130_set_current_r(Z_AXIS, 20);
  9255. #endif //TMC2130
  9256. // Stop all heaters
  9257. setAllTargetHotends(0);
  9258. setTargetBed(0);
  9259. // When power is interrupted on the _first_ recovery an attempt can be made to raise the
  9260. // extruder, causing the Z position to change. Similarly, when recovering, the Z position is
  9261. // lowered. In such cases we cannot just save Z, we need to re-align the steppers to a fullstep.
  9262. // Disable MBL (if not already) to work with physical coordinates.
  9263. mbl.active = false;
  9264. planner_abort_hard();
  9265. // Allow for small roundoffs to be ignored
  9266. if(abs(current_position[Z_AXIS] - eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z))) >= 1.f/cs.axis_steps_per_unit[Z_AXIS])
  9267. {
  9268. // Clean the input command queue, inhibit serial processing using saved_printing
  9269. cmdqueue_reset();
  9270. card.sdprinting = false;
  9271. saved_printing = true;
  9272. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9273. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9274. sei();
  9275. // The axis was moved: adjust Z as done on a regular UVLO.
  9276. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9277. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9278. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9279. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9280. + UVLO_TINY_Z_AXIS_SHIFT;
  9281. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60, active_extruder);
  9282. st_synchronize();
  9283. poweroff_z();
  9284. // Update Z position
  9285. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  9286. // Update the _final_ Z motor microstep counter (unused).
  9287. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9288. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9289. }
  9290. // Update the the "power outage" flag.
  9291. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  9292. // Increment power failure counter
  9293. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9294. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9295. printf_P(_N("UVLO_TINY - end %d\n"), _millis() - time_start);
  9296. uvlo_drain_reset();
  9297. }
  9298. #endif //UVLO_SUPPORT
  9299. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  9300. void setup_fan_interrupt() {
  9301. //INT7
  9302. DDRE &= ~(1 << 7); //input pin
  9303. PORTE &= ~(1 << 7); //no internal pull-up
  9304. //start with sensing rising edge
  9305. EICRB &= ~(1 << 6);
  9306. EICRB |= (1 << 7);
  9307. //enable INT7 interrupt
  9308. EIMSK |= (1 << 7);
  9309. }
  9310. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  9311. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  9312. ISR(INT7_vect) {
  9313. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  9314. #ifdef FAN_SOFT_PWM
  9315. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  9316. #else //FAN_SOFT_PWM
  9317. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  9318. #endif //FAN_SOFT_PWM
  9319. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  9320. t_fan_rising_edge = millis_nc();
  9321. }
  9322. else { //interrupt was triggered by falling edge
  9323. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  9324. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  9325. }
  9326. }
  9327. EICRB ^= (1 << 6); //change edge
  9328. }
  9329. #endif
  9330. #ifdef UVLO_SUPPORT
  9331. void setup_uvlo_interrupt() {
  9332. DDRE &= ~(1 << 4); //input pin
  9333. PORTE &= ~(1 << 4); //no internal pull-up
  9334. // sensing falling edge
  9335. EICRB |= (1 << 0);
  9336. EICRB &= ~(1 << 1);
  9337. // enable INT4 interrupt
  9338. EIMSK |= (1 << 4);
  9339. // check if power was lost before we armed the interrupt
  9340. if(!(PINE & (1 << 4)) && eeprom_read_byte((uint8_t*)EEPROM_UVLO))
  9341. {
  9342. SERIAL_ECHOLNPGM("INT4");
  9343. uvlo_drain_reset();
  9344. }
  9345. }
  9346. ISR(INT4_vect) {
  9347. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  9348. SERIAL_ECHOLNPGM("INT4");
  9349. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  9350. if(PRINTER_ACTIVE && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  9351. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  9352. }
  9353. void recover_print(uint8_t automatic) {
  9354. char cmd[30];
  9355. lcd_update_enable(true);
  9356. lcd_update(2);
  9357. lcd_setstatuspgm(_i("Recovering print "));////MSG_RECOVERING_PRINT c=20 r=1
  9358. // Recover position, temperatures and extrude_multipliers
  9359. bool mbl_was_active = recover_machine_state_after_power_panic();
  9360. // Lift the print head 25mm, first to avoid collisions with oozed material with the print,
  9361. // and second also so one may remove the excess priming material.
  9362. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 1)
  9363. {
  9364. sprintf_P(cmd, PSTR("G1 Z%.3f F800"), current_position[Z_AXIS] + 25);
  9365. enquecommand(cmd);
  9366. }
  9367. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine
  9368. // transformation status. G28 will not touch Z when MBL is off.
  9369. enquecommand_P(PSTR("G28 X Y"));
  9370. // Set the target bed and nozzle temperatures and wait.
  9371. sprintf_P(cmd, PSTR("M104 S%d"), target_temperature[active_extruder]);
  9372. enquecommand(cmd);
  9373. sprintf_P(cmd, PSTR("M190 S%d"), target_temperature_bed);
  9374. enquecommand(cmd);
  9375. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  9376. enquecommand(cmd);
  9377. enquecommand_P(PSTR("M83")); //E axis relative mode
  9378. // If not automatically recoreverd (long power loss)
  9379. if(automatic == 0){
  9380. //Extrude some filament to stabilize the pressure
  9381. enquecommand_P(PSTR("G1 E5 F120"));
  9382. // Retract to be consistent with a short pause
  9383. sprintf_P(cmd, PSTR("G1 E%-0.3f F2700"), default_retraction);
  9384. enquecommand(cmd);
  9385. }
  9386. printf_P(_N("After waiting for temp:\nCurrent pos X_AXIS:%.3f\nCurrent pos Y_AXIS:%.3f\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  9387. // Restart the print.
  9388. restore_print_from_eeprom(mbl_was_active);
  9389. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  9390. }
  9391. bool recover_machine_state_after_power_panic()
  9392. {
  9393. // 1) Preset some dummy values for the XY axes
  9394. current_position[X_AXIS] = 0;
  9395. current_position[Y_AXIS] = 0;
  9396. // 2) Restore the mesh bed leveling offsets, but not the MBL status.
  9397. // This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9398. bool mbl_was_active = false;
  9399. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9400. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9401. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9402. // Scale the z value to 10u resolution.
  9403. int16_t v;
  9404. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  9405. if (v != 0)
  9406. mbl_was_active = true;
  9407. mbl.z_values[iy][ix] = float(v) * 0.001f;
  9408. }
  9409. // Recover the physical coordinate of the Z axis at the time of the power panic.
  9410. // The current position after power panic is moved to the next closest 0th full step.
  9411. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z));
  9412. // Recover last E axis position
  9413. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9414. memcpy(destination, current_position, sizeof(destination));
  9415. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9416. print_world_coordinates();
  9417. // 3) Initialize the logical to physical coordinate system transformation.
  9418. world2machine_initialize();
  9419. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9420. // print_mesh_bed_leveling_table();
  9421. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  9422. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  9423. babystep_load();
  9424. // 5) Set the physical positions from the logical positions using the world2machine transformation
  9425. // This is only done to inizialize Z/E axes with physical locations, since X/Y are unknown.
  9426. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  9427. // 6) Power up the Z motors, mark their positions as known.
  9428. axis_known_position[Z_AXIS] = true;
  9429. enable_z();
  9430. // 7) Recover the target temperatures.
  9431. target_temperature[active_extruder] = eeprom_read_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND);
  9432. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  9433. // 8) Recover extruder multipilers
  9434. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  9435. #if EXTRUDERS > 1
  9436. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  9437. #if EXTRUDERS > 2
  9438. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  9439. #endif
  9440. #endif
  9441. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  9442. // 9) Recover the saved target
  9443. saved_target[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+0*4));
  9444. saved_target[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+1*4));
  9445. saved_target[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+2*4));
  9446. saved_target[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+3*4));
  9447. #ifdef LIN_ADVANCE
  9448. extruder_advance_K = eeprom_read_float((float*)EEPROM_UVLO_LA_K);
  9449. #endif
  9450. return mbl_was_active;
  9451. }
  9452. void restore_print_from_eeprom(bool mbl_was_active) {
  9453. int feedrate_rec;
  9454. int feedmultiply_rec;
  9455. uint8_t fan_speed_rec;
  9456. char cmd[30];
  9457. char filename[13];
  9458. uint8_t depth = 0;
  9459. char dir_name[9];
  9460. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  9461. feedrate_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDRATE);
  9462. feedmultiply_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY);
  9463. SERIAL_ECHOPGM("Feedrate:");
  9464. MYSERIAL.print(feedrate_rec);
  9465. SERIAL_ECHOPGM(", feedmultiply:");
  9466. MYSERIAL.println(feedmultiply_rec);
  9467. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  9468. MYSERIAL.println(int(depth));
  9469. for (int i = 0; i < depth; i++) {
  9470. for (int j = 0; j < 8; j++) {
  9471. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  9472. }
  9473. dir_name[8] = '\0';
  9474. MYSERIAL.println(dir_name);
  9475. strcpy(dir_names[i], dir_name);
  9476. card.chdir(dir_name);
  9477. }
  9478. for (int i = 0; i < 8; i++) {
  9479. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  9480. }
  9481. filename[8] = '\0';
  9482. MYSERIAL.print(filename);
  9483. strcat_P(filename, PSTR(".gco"));
  9484. sprintf_P(cmd, PSTR("M23 %s"), filename);
  9485. enquecommand(cmd);
  9486. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  9487. SERIAL_ECHOPGM("Position read from eeprom:");
  9488. MYSERIAL.println(position);
  9489. // Move to the XY print position in logical coordinates, where the print has been killed, but
  9490. // without shifting Z along the way. This requires performing the move without mbl.
  9491. sprintf_P(cmd, PSTR("G1 X%f Y%f F3000"),
  9492. eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0)),
  9493. eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4)));
  9494. enquecommand(cmd);
  9495. // Enable MBL and switch to logical positioning
  9496. if (mbl_was_active)
  9497. enquecommand_P(PSTR("PRUSA MBL V1"));
  9498. // Move the Z axis down to the print, in logical coordinates.
  9499. sprintf_P(cmd, PSTR("G1 Z%f"), eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)));
  9500. enquecommand(cmd);
  9501. // Unretract.
  9502. sprintf_P(cmd, PSTR("G1 E%0.3f F2700"), default_retraction);
  9503. enquecommand(cmd);
  9504. // Recover final E axis position and mode
  9505. float pos_e = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9506. sprintf_P(cmd, PSTR("G92 E"));
  9507. dtostrf(pos_e, 6, 3, cmd + strlen(cmd));
  9508. enquecommand(cmd);
  9509. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  9510. enquecommand_P(PSTR("M82")); //E axis abslute mode
  9511. // Set the feedrates saved at the power panic.
  9512. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  9513. enquecommand(cmd);
  9514. sprintf_P(cmd, PSTR("M220 S%d"), feedmultiply_rec);
  9515. enquecommand(cmd);
  9516. // Set the fan speed saved at the power panic.
  9517. strcpy_P(cmd, PSTR("M106 S"));
  9518. strcat(cmd, itostr3(int(fan_speed_rec)));
  9519. enquecommand(cmd);
  9520. // Set a position in the file.
  9521. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  9522. enquecommand(cmd);
  9523. enquecommand_P(PSTR("G4 S0"));
  9524. enquecommand_P(PSTR("PRUSA uvlo"));
  9525. }
  9526. #endif //UVLO_SUPPORT
  9527. //! @brief Immediately stop print moves
  9528. //!
  9529. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  9530. //! If printing from sd card, position in file is saved.
  9531. //! If printing from USB, line number is saved.
  9532. //!
  9533. //! @param z_move
  9534. //! @param e_move
  9535. void stop_and_save_print_to_ram(float z_move, float e_move)
  9536. {
  9537. if (saved_printing) return;
  9538. #if 0
  9539. unsigned char nplanner_blocks;
  9540. #endif
  9541. unsigned char nlines;
  9542. uint16_t sdlen_planner;
  9543. uint16_t sdlen_cmdqueue;
  9544. cli();
  9545. if (card.sdprinting) {
  9546. #if 0
  9547. nplanner_blocks = number_of_blocks();
  9548. #endif
  9549. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  9550. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9551. saved_sdpos -= sdlen_planner;
  9552. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9553. saved_sdpos -= sdlen_cmdqueue;
  9554. saved_printing_type = PRINTING_TYPE_SD;
  9555. }
  9556. else if (is_usb_printing) { //reuse saved_sdpos for storing line number
  9557. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  9558. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  9559. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  9560. saved_sdpos -= nlines;
  9561. saved_sdpos -= buflen; //number of blocks in cmd buffer
  9562. saved_printing_type = PRINTING_TYPE_USB;
  9563. }
  9564. else {
  9565. saved_printing_type = PRINTING_TYPE_NONE;
  9566. //not sd printing nor usb printing
  9567. }
  9568. #if 0
  9569. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  9570. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  9571. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  9572. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  9573. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  9574. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  9575. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  9576. {
  9577. card.setIndex(saved_sdpos);
  9578. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  9579. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  9580. MYSERIAL.print(char(card.get()));
  9581. SERIAL_ECHOLNPGM("Content of command buffer: ");
  9582. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  9583. MYSERIAL.print(char(card.get()));
  9584. SERIAL_ECHOLNPGM("End of command buffer");
  9585. }
  9586. {
  9587. // Print the content of the planner buffer, line by line:
  9588. card.setIndex(saved_sdpos);
  9589. int8_t iline = 0;
  9590. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  9591. SERIAL_ECHOPGM("Planner line (from file): ");
  9592. MYSERIAL.print(int(iline), DEC);
  9593. SERIAL_ECHOPGM(", length: ");
  9594. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  9595. SERIAL_ECHOPGM(", steps: (");
  9596. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  9597. SERIAL_ECHOPGM(",");
  9598. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  9599. SERIAL_ECHOPGM(",");
  9600. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  9601. SERIAL_ECHOPGM(",");
  9602. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  9603. SERIAL_ECHOPGM("), events: ");
  9604. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  9605. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  9606. MYSERIAL.print(char(card.get()));
  9607. }
  9608. }
  9609. {
  9610. // Print the content of the command buffer, line by line:
  9611. int8_t iline = 0;
  9612. union {
  9613. struct {
  9614. char lo;
  9615. char hi;
  9616. } lohi;
  9617. uint16_t value;
  9618. } sdlen_single;
  9619. int _bufindr = bufindr;
  9620. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  9621. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  9622. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  9623. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  9624. }
  9625. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  9626. MYSERIAL.print(int(iline), DEC);
  9627. SERIAL_ECHOPGM(", type: ");
  9628. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  9629. SERIAL_ECHOPGM(", len: ");
  9630. MYSERIAL.println(sdlen_single.value, DEC);
  9631. // Print the content of the buffer line.
  9632. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  9633. SERIAL_ECHOPGM("Buffer line (from file): ");
  9634. MYSERIAL.println(int(iline), DEC);
  9635. for (; sdlen_single.value > 0; -- sdlen_single.value)
  9636. MYSERIAL.print(char(card.get()));
  9637. if (-- _buflen == 0)
  9638. break;
  9639. // First skip the current command ID and iterate up to the end of the string.
  9640. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  9641. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  9642. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9643. // If the end of the buffer was empty,
  9644. if (_bufindr == sizeof(cmdbuffer)) {
  9645. // skip to the start and find the nonzero command.
  9646. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9647. }
  9648. }
  9649. }
  9650. #endif
  9651. // save the global state at planning time
  9652. if (current_block)
  9653. {
  9654. memcpy(saved_target, current_block->gcode_target, sizeof(saved_target));
  9655. saved_feedrate2 = current_block->gcode_feedrate;
  9656. }
  9657. else
  9658. {
  9659. saved_target[0] = SAVED_TARGET_UNSET;
  9660. saved_feedrate2 = feedrate;
  9661. }
  9662. planner_abort_hard(); //abort printing
  9663. memcpy(saved_pos, current_position, sizeof(saved_pos));
  9664. saved_feedmultiply2 = feedmultiply; //save feedmultiply
  9665. saved_active_extruder = active_extruder; //save active_extruder
  9666. saved_extruder_temperature = degTargetHotend(active_extruder);
  9667. saved_extruder_relative_mode = axis_relative_modes[E_AXIS];
  9668. saved_fanSpeed = fanSpeed;
  9669. cmdqueue_reset(); //empty cmdqueue
  9670. card.sdprinting = false;
  9671. // card.closefile();
  9672. saved_printing = true;
  9673. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  9674. st_reset_timer();
  9675. sei();
  9676. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  9677. #if 1
  9678. // Rather than calling plan_buffer_line directly, push the move into the command queue so that
  9679. // the caller can continue processing. This is used during powerpanic to save the state as we
  9680. // move away from the print.
  9681. char buf[48];
  9682. if(e_move)
  9683. {
  9684. // First unretract (relative extrusion)
  9685. if(!saved_extruder_relative_mode){
  9686. enquecommand(PSTR("M83"), true);
  9687. }
  9688. //retract 45mm/s
  9689. // A single sprintf may not be faster, but is definitely 20B shorter
  9690. // than a sequence of commands building the string piece by piece
  9691. // A snprintf would have been a safer call, but since it is not used
  9692. // in the whole program, its implementation would bring more bytes to the total size
  9693. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  9694. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  9695. enquecommand(buf, false);
  9696. }
  9697. if(z_move)
  9698. {
  9699. // Then lift Z axis
  9700. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  9701. enquecommand(buf, false);
  9702. }
  9703. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  9704. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  9705. repeatcommand_front();
  9706. #else
  9707. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS] + z_move, saved_pos[E_AXIS] + e_move, homing_feedrate[Z_AXIS], active_extruder);
  9708. st_synchronize(); //wait moving
  9709. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9710. memcpy(destination, current_position, sizeof(destination));
  9711. #endif
  9712. waiting_inside_plan_buffer_line_print_aborted = true; //unroll the stack
  9713. }
  9714. }
  9715. //! @brief Restore print from ram
  9716. //!
  9717. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  9718. //! print fan speed, waits for extruder temperature restore, then restores
  9719. //! position and continues print moves.
  9720. //!
  9721. //! Internally lcd_update() is called by wait_for_heater().
  9722. //!
  9723. //! @param e_move
  9724. void restore_print_from_ram_and_continue(float e_move)
  9725. {
  9726. if (!saved_printing) return;
  9727. #ifdef FANCHECK
  9728. // Do not allow resume printing if fans are still not ok
  9729. if ((fan_check_error != EFCE_OK) && (fan_check_error != EFCE_FIXED)) return;
  9730. if (fan_check_error == EFCE_FIXED) fan_check_error = EFCE_OK; //reenable serial stream processing if printing from usb
  9731. #endif
  9732. // for (int axis = X_AXIS; axis <= E_AXIS; axis++)
  9733. // current_position[axis] = st_get_position_mm(axis);
  9734. active_extruder = saved_active_extruder; //restore active_extruder
  9735. fanSpeed = saved_fanSpeed;
  9736. if (degTargetHotend(saved_active_extruder) != saved_extruder_temperature)
  9737. {
  9738. setTargetHotendSafe(saved_extruder_temperature, saved_active_extruder);
  9739. heating_status = 1;
  9740. wait_for_heater(_millis(), saved_active_extruder);
  9741. heating_status = 2;
  9742. }
  9743. axis_relative_modes[E_AXIS] = saved_extruder_relative_mode;
  9744. float e = saved_pos[E_AXIS] - e_move;
  9745. plan_set_e_position(e);
  9746. #ifdef FANCHECK
  9747. fans_check_enabled = false;
  9748. #endif
  9749. //first move print head in XY to the saved position:
  9750. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], current_position[Z_AXIS], saved_pos[E_AXIS] - e_move, homing_feedrate[Z_AXIS]/13, active_extruder);
  9751. //then move Z
  9752. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS] - e_move, homing_feedrate[Z_AXIS]/13, active_extruder);
  9753. //and finaly unretract (35mm/s)
  9754. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  9755. st_synchronize();
  9756. #ifdef FANCHECK
  9757. fans_check_enabled = true;
  9758. #endif
  9759. // restore original feedrate/feedmultiply _after_ restoring the extruder position
  9760. feedrate = saved_feedrate2;
  9761. feedmultiply = saved_feedmultiply2;
  9762. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9763. memcpy(destination, current_position, sizeof(destination));
  9764. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  9765. card.setIndex(saved_sdpos);
  9766. sdpos_atomic = saved_sdpos;
  9767. card.sdprinting = true;
  9768. }
  9769. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  9770. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  9771. serial_count = 0;
  9772. FlushSerialRequestResend();
  9773. }
  9774. else {
  9775. //not sd printing nor usb printing
  9776. }
  9777. SERIAL_PROTOCOLLNRPGM(MSG_OK); //dummy response because of octoprint is waiting for this
  9778. lcd_setstatuspgm(_T(WELCOME_MSG));
  9779. saved_printing_type = PRINTING_TYPE_NONE;
  9780. saved_printing = false;
  9781. waiting_inside_plan_buffer_line_print_aborted = true; //unroll the stack
  9782. }
  9783. // Cancel the state related to a currently saved print
  9784. void cancel_saved_printing()
  9785. {
  9786. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  9787. saved_target[0] = SAVED_TARGET_UNSET;
  9788. saved_printing_type = PRINTING_TYPE_NONE;
  9789. saved_printing = false;
  9790. }
  9791. void print_world_coordinates()
  9792. {
  9793. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  9794. }
  9795. void print_physical_coordinates()
  9796. {
  9797. printf_P(_N("physical coordinates: (%.3f, %.3f, %.3f)\n"), st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS), st_get_position_mm(Z_AXIS));
  9798. }
  9799. void print_mesh_bed_leveling_table()
  9800. {
  9801. SERIAL_ECHOPGM("mesh bed leveling: ");
  9802. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  9803. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  9804. MYSERIAL.print(mbl.z_values[y][x], 3);
  9805. SERIAL_ECHOPGM(" ");
  9806. }
  9807. SERIAL_ECHOLNPGM("");
  9808. }
  9809. uint16_t print_time_remaining() {
  9810. uint16_t print_t = PRINT_TIME_REMAINING_INIT;
  9811. #ifdef TMC2130
  9812. if (SilentModeMenu == SILENT_MODE_OFF) print_t = print_time_remaining_normal;
  9813. else print_t = print_time_remaining_silent;
  9814. #else
  9815. print_t = print_time_remaining_normal;
  9816. #endif //TMC2130
  9817. if ((print_t != PRINT_TIME_REMAINING_INIT) && (feedmultiply != 0)) print_t = 100ul * print_t / feedmultiply;
  9818. return print_t;
  9819. }
  9820. uint8_t calc_percent_done()
  9821. {
  9822. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  9823. uint8_t percent_done = 0;
  9824. #ifdef TMC2130
  9825. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100) {
  9826. percent_done = print_percent_done_normal;
  9827. }
  9828. else if (print_percent_done_silent <= 100) {
  9829. percent_done = print_percent_done_silent;
  9830. }
  9831. #else
  9832. if (print_percent_done_normal <= 100) {
  9833. percent_done = print_percent_done_normal;
  9834. }
  9835. #endif //TMC2130
  9836. else {
  9837. percent_done = card.percentDone();
  9838. }
  9839. return percent_done;
  9840. }
  9841. static void print_time_remaining_init()
  9842. {
  9843. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  9844. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  9845. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  9846. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  9847. }
  9848. void load_filament_final_feed()
  9849. {
  9850. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  9851. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FINAL, active_extruder);
  9852. }
  9853. //! @brief Wait for user to check the state
  9854. //! @par nozzle_temp nozzle temperature to load filament
  9855. void M600_check_state(float nozzle_temp)
  9856. {
  9857. lcd_change_fil_state = 0;
  9858. while (lcd_change_fil_state != 1)
  9859. {
  9860. lcd_change_fil_state = 0;
  9861. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9862. lcd_alright();
  9863. KEEPALIVE_STATE(IN_HANDLER);
  9864. switch(lcd_change_fil_state)
  9865. {
  9866. // Filament failed to load so load it again
  9867. case 2:
  9868. if (mmu_enabled)
  9869. mmu_M600_load_filament(false, nozzle_temp); //nonautomatic load; change to "wrong filament loaded" option?
  9870. else
  9871. M600_load_filament_movements();
  9872. break;
  9873. // Filament loaded properly but color is not clear
  9874. case 3:
  9875. st_synchronize();
  9876. load_filament_final_feed();
  9877. lcd_loading_color();
  9878. st_synchronize();
  9879. break;
  9880. // Everything good
  9881. default:
  9882. lcd_change_success();
  9883. break;
  9884. }
  9885. }
  9886. }
  9887. //! @brief Wait for user action
  9888. //!
  9889. //! Beep, manage nozzle heater and wait for user to start unload filament
  9890. //! If times out, active extruder temperature is set to 0.
  9891. //!
  9892. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  9893. void M600_wait_for_user(float HotendTempBckp) {
  9894. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9895. int counterBeep = 0;
  9896. unsigned long waiting_start_time = _millis();
  9897. uint8_t wait_for_user_state = 0;
  9898. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9899. bool bFirst=true;
  9900. while (!(wait_for_user_state == 0 && lcd_clicked())){
  9901. manage_heater();
  9902. manage_inactivity(true);
  9903. #if BEEPER > 0
  9904. if (counterBeep == 500) {
  9905. counterBeep = 0;
  9906. }
  9907. SET_OUTPUT(BEEPER);
  9908. if (counterBeep == 0) {
  9909. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  9910. {
  9911. bFirst=false;
  9912. WRITE(BEEPER, HIGH);
  9913. }
  9914. }
  9915. if (counterBeep == 20) {
  9916. WRITE(BEEPER, LOW);
  9917. }
  9918. counterBeep++;
  9919. #endif //BEEPER > 0
  9920. switch (wait_for_user_state) {
  9921. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  9922. delay_keep_alive(4);
  9923. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  9924. lcd_display_message_fullscreen_P(_i("Press knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  9925. wait_for_user_state = 1;
  9926. setAllTargetHotends(0);
  9927. st_synchronize();
  9928. disable_e0();
  9929. disable_e1();
  9930. disable_e2();
  9931. }
  9932. break;
  9933. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  9934. delay_keep_alive(4);
  9935. if (lcd_clicked()) {
  9936. setTargetHotend(HotendTempBckp, active_extruder);
  9937. lcd_wait_for_heater();
  9938. wait_for_user_state = 2;
  9939. }
  9940. break;
  9941. case 2: //waiting for nozzle to reach target temperature
  9942. if (abs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  9943. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9944. waiting_start_time = _millis();
  9945. wait_for_user_state = 0;
  9946. }
  9947. else {
  9948. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  9949. lcd_set_cursor(1, 4);
  9950. lcd_print(ftostr3(degHotend(active_extruder)));
  9951. }
  9952. break;
  9953. }
  9954. }
  9955. WRITE(BEEPER, LOW);
  9956. }
  9957. void M600_load_filament_movements()
  9958. {
  9959. #ifdef SNMM
  9960. display_loading();
  9961. do
  9962. {
  9963. current_position[E_AXIS] += 0.002;
  9964. plan_buffer_line_curposXYZE(500, active_extruder);
  9965. delay_keep_alive(2);
  9966. }
  9967. while (!lcd_clicked());
  9968. st_synchronize();
  9969. current_position[E_AXIS] += bowden_length[mmu_extruder];
  9970. plan_buffer_line_curposXYZE(3000, active_extruder);
  9971. current_position[E_AXIS] += FIL_LOAD_LENGTH - 60;
  9972. plan_buffer_line_curposXYZE(1400, active_extruder);
  9973. current_position[E_AXIS] += 40;
  9974. plan_buffer_line_curposXYZE(400, active_extruder);
  9975. current_position[E_AXIS] += 10;
  9976. plan_buffer_line_curposXYZE(50, active_extruder);
  9977. #else
  9978. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  9979. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST, active_extruder);
  9980. #endif
  9981. load_filament_final_feed();
  9982. lcd_loading_filament();
  9983. st_synchronize();
  9984. }
  9985. void M600_load_filament() {
  9986. //load filament for single material and SNMM
  9987. lcd_wait_interact();
  9988. //load_filament_time = _millis();
  9989. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9990. #ifdef PAT9125
  9991. fsensor_autoload_check_start();
  9992. #endif //PAT9125
  9993. while(!lcd_clicked())
  9994. {
  9995. manage_heater();
  9996. manage_inactivity(true);
  9997. #ifdef FILAMENT_SENSOR
  9998. if (fsensor_check_autoload())
  9999. {
  10000. Sound_MakeCustom(50,1000,false);
  10001. break;
  10002. }
  10003. #endif //FILAMENT_SENSOR
  10004. }
  10005. #ifdef PAT9125
  10006. fsensor_autoload_check_stop();
  10007. #endif //PAT9125
  10008. KEEPALIVE_STATE(IN_HANDLER);
  10009. #ifdef FSENSOR_QUALITY
  10010. fsensor_oq_meassure_start(70);
  10011. #endif //FSENSOR_QUALITY
  10012. M600_load_filament_movements();
  10013. Sound_MakeCustom(50,1000,false);
  10014. #ifdef FSENSOR_QUALITY
  10015. fsensor_oq_meassure_stop();
  10016. if (!fsensor_oq_result())
  10017. {
  10018. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Fil. sensor response is poor, disable it?"), false, true);
  10019. lcd_update_enable(true);
  10020. lcd_update(2);
  10021. if (disable)
  10022. fsensor_disable();
  10023. }
  10024. #endif //FSENSOR_QUALITY
  10025. lcd_update_enable(false);
  10026. }
  10027. //! @brief Wait for click
  10028. //!
  10029. //! Set
  10030. void marlin_wait_for_click()
  10031. {
  10032. int8_t busy_state_backup = busy_state;
  10033. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10034. lcd_consume_click();
  10035. while(!lcd_clicked())
  10036. {
  10037. manage_heater();
  10038. manage_inactivity(true);
  10039. lcd_update(0);
  10040. }
  10041. KEEPALIVE_STATE(busy_state_backup);
  10042. }
  10043. #define FIL_LOAD_LENGTH 60
  10044. #ifdef PSU_Delta
  10045. bool bEnableForce_z;
  10046. void init_force_z()
  10047. {
  10048. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  10049. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  10050. disable_force_z();
  10051. }
  10052. void check_force_z()
  10053. {
  10054. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  10055. init_force_z(); // causes enforced switching into disable-state
  10056. }
  10057. void disable_force_z()
  10058. {
  10059. if(!bEnableForce_z) return; // motor already disabled (may be ;-p )
  10060. bEnableForce_z=false;
  10061. // switching to silent mode
  10062. #ifdef TMC2130
  10063. tmc2130_mode=TMC2130_MODE_SILENT;
  10064. update_mode_profile();
  10065. tmc2130_init(true);
  10066. #endif // TMC2130
  10067. }
  10068. void enable_force_z()
  10069. {
  10070. if(bEnableForce_z)
  10071. return; // motor already enabled (may be ;-p )
  10072. bEnableForce_z=true;
  10073. // mode recovering
  10074. #ifdef TMC2130
  10075. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  10076. update_mode_profile();
  10077. tmc2130_init(true);
  10078. #endif // TMC2130
  10079. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  10080. }
  10081. #endif // PSU_Delta