Marlin_main.cpp 385 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482
  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. #include "config.h"
  48. #include "macros.h"
  49. #ifdef ENABLE_AUTO_BED_LEVELING
  50. #include "vector_3.h"
  51. #ifdef AUTO_BED_LEVELING_GRID
  52. #include "qr_solve.h"
  53. #endif
  54. #endif // ENABLE_AUTO_BED_LEVELING
  55. #ifdef MESH_BED_LEVELING
  56. #include "mesh_bed_leveling.h"
  57. #include "mesh_bed_calibration.h"
  58. #endif
  59. #include "printers.h"
  60. #include "menu.h"
  61. #include "ultralcd.h"
  62. #include "conv2str.h"
  63. #include "backlight.h"
  64. #include "planner.h"
  65. #include "stepper.h"
  66. #include "temperature.h"
  67. #include "fancheck.h"
  68. #include "motion_control.h"
  69. #include "cardreader.h"
  70. #include "ConfigurationStore.h"
  71. #include "language.h"
  72. #include "pins_arduino.h"
  73. #include "math.h"
  74. #include "util.h"
  75. #include "Timer.h"
  76. #include "Prusa_farm.h"
  77. #include <avr/wdt.h>
  78. #include <avr/pgmspace.h>
  79. #include "Tcodes.h"
  80. #include "Dcodes.h"
  81. #include "AutoDeplete.h"
  82. #ifndef LA_NOCOMPAT
  83. #include "la10compat.h"
  84. #endif
  85. #include "spi.h"
  86. #include "Filament_sensor.h"
  87. #ifdef TMC2130
  88. #include "tmc2130.h"
  89. #endif //TMC2130
  90. #ifdef XFLASH
  91. #include "xflash.h"
  92. #include "optiboot_xflash.h"
  93. #endif //XFLASH
  94. #include "xflash_dump.h"
  95. #ifdef BLINKM
  96. #include "BlinkM.h"
  97. #include "Wire.h"
  98. #endif
  99. #ifdef ULTRALCD
  100. #include "ultralcd.h"
  101. #endif
  102. #if NUM_SERVOS > 0
  103. #include "Servo.h"
  104. #endif
  105. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  106. #include <SPI.h>
  107. #endif
  108. #include "mmu2.h"
  109. #define VERSION_STRING "1.0.2"
  110. #include "ultralcd.h"
  111. #include "sound.h"
  112. #include "cmdqueue.h"
  113. //Macro for print fan speed
  114. #define FAN_PULSE_WIDTH_LIMIT ((fanSpeed > 100) ? 3 : 4) //time in ms
  115. //filament types
  116. #define FILAMENT_DEFAULT 0
  117. #define FILAMENT_FLEX 1
  118. #define FILAMENT_PVA 2
  119. #define FILAMENT_UNDEFINED 255
  120. //Stepper Movement Variables
  121. //===========================================================================
  122. //=============================imported variables============================
  123. //===========================================================================
  124. //===========================================================================
  125. //=============================public variables=============================
  126. //===========================================================================
  127. #ifdef SDSUPPORT
  128. CardReader card;
  129. #endif
  130. uint8_t mbl_z_probe_nr = 3; //numer of Z measurements for each point in mesh bed leveling calibration
  131. //used for PINDA temp calibration and pause print
  132. #define DEFAULT_RETRACTION 1
  133. #define DEFAULT_RETRACTION_MM 4 //MM
  134. float default_retraction = DEFAULT_RETRACTION;
  135. float homing_feedrate[] = HOMING_FEEDRATE;
  136. //Although this flag and many others like this could be represented with a struct/bitfield for each axis (more readable and efficient code), the implementation
  137. //would not be standard across all platforms. That being said, the code will continue to use bitmasks for independent axis.
  138. //Moreover, according to C/C++ standard, the ordering of bits is platform/compiler dependent and the compiler is allowed to align the bits arbitrarily,
  139. //thus bit operations like shifting and masking may stop working and will be very hard to fix.
  140. uint8_t axis_relative_modes = 0;
  141. int feedmultiply=100; //100->1 200->2
  142. int extrudemultiply=100; //100->1 200->2
  143. int extruder_multiply[EXTRUDERS] = {100
  144. #if EXTRUDERS > 1
  145. , 100
  146. #if EXTRUDERS > 2
  147. , 100
  148. #endif
  149. #endif
  150. };
  151. bool homing_flag = false;
  152. int8_t lcd_change_fil_state = 0;
  153. unsigned long pause_time = 0;
  154. unsigned long start_pause_print = _millis();
  155. unsigned long t_fan_rising_edge = _millis();
  156. LongTimer safetyTimer;
  157. static LongTimer crashDetTimer;
  158. //unsigned long load_filament_time;
  159. bool mesh_bed_leveling_flag = false;
  160. unsigned long total_filament_used;
  161. HeatingStatus heating_status;
  162. uint8_t heating_status_counter;
  163. bool loading_flag = false;
  164. #define XY_NO_RESTORE_FLAG (mesh_bed_leveling_flag || homing_flag)
  165. bool fan_state[2];
  166. int fan_edge_counter[2];
  167. int fan_speed[2];
  168. float extruder_multiplier[EXTRUDERS] = {1.0
  169. #if EXTRUDERS > 1
  170. , 1.0
  171. #if EXTRUDERS > 2
  172. , 1.0
  173. #endif
  174. #endif
  175. };
  176. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  177. //shortcuts for more readable code
  178. #define _x current_position[X_AXIS]
  179. #define _y current_position[Y_AXIS]
  180. #define _z current_position[Z_AXIS]
  181. #define _e current_position[E_AXIS]
  182. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  183. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  184. bool axis_known_position[3] = {false, false, false};
  185. // Extruder offset
  186. #if EXTRUDERS > 1
  187. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  188. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  189. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  190. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  191. #endif
  192. };
  193. #endif
  194. uint8_t active_extruder = 0;
  195. int fanSpeed=0;
  196. uint8_t newFanSpeed = 0;
  197. #ifdef FWRETRACT
  198. bool retracted[EXTRUDERS]={false
  199. #if EXTRUDERS > 1
  200. , false
  201. #if EXTRUDERS > 2
  202. , false
  203. #endif
  204. #endif
  205. };
  206. bool retracted_swap[EXTRUDERS]={false
  207. #if EXTRUDERS > 1
  208. , false
  209. #if EXTRUDERS > 2
  210. , false
  211. #endif
  212. #endif
  213. };
  214. float retract_length_swap = RETRACT_LENGTH_SWAP;
  215. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  216. #endif
  217. #ifdef PS_DEFAULT_OFF
  218. bool powersupply = false;
  219. #else
  220. bool powersupply = true;
  221. #endif
  222. bool cancel_heatup = false;
  223. int8_t busy_state = NOT_BUSY;
  224. static long prev_busy_signal_ms = -1;
  225. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  226. const char errormagic[] PROGMEM = "Error:";
  227. const char echomagic[] PROGMEM = "echo:";
  228. const char G28W0[] PROGMEM = "G28 W0";
  229. // Define some coordinates outside the clamp limits (making them invalid past the parsing stage) so
  230. // that they can be used later for various logical checks
  231. #define X_COORD_INVALID (X_MIN_POS-1)
  232. #define SAVED_START_POSITION_UNSET X_COORD_INVALID
  233. float saved_start_position[NUM_AXIS] = {SAVED_START_POSITION_UNSET, 0, 0, 0};
  234. uint16_t saved_segment_idx = 0;
  235. // save/restore printing in case that mmu was not responding
  236. bool mmu_print_saved = false;
  237. // storing estimated time to end of print counted by slicer
  238. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  239. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  240. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  241. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  242. uint16_t print_time_to_change_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  243. uint16_t print_time_to_change_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  244. uint32_t IP_address = 0;
  245. //===========================================================================
  246. //=============================Private Variables=============================
  247. //===========================================================================
  248. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  249. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  250. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  251. // For tracing an arc
  252. static float offset[3] = {0.0, 0.0, 0.0};
  253. // Current feedrate
  254. float feedrate = 1500.0;
  255. // Feedrate for the next move
  256. static float next_feedrate;
  257. // Original feedrate saved during homing moves
  258. static float saved_feedrate;
  259. const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS; // Sensitive pin list for M42
  260. //static float tt = 0;
  261. //static float bt = 0;
  262. //Inactivity shutdown variables
  263. static LongTimer previous_millis_cmd;
  264. unsigned long max_inactive_time = 0;
  265. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  266. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  267. unsigned long starttime=0;
  268. unsigned long stoptime=0;
  269. ShortTimer usb_timer;
  270. bool Stopped=false;
  271. #if NUM_SERVOS > 0
  272. Servo servos[NUM_SERVOS];
  273. #endif
  274. bool target_direction;
  275. //Insert variables if CHDK is defined
  276. #ifdef CHDK
  277. unsigned long chdkHigh = 0;
  278. bool chdkActive = false;
  279. #endif
  280. //! @name RAM save/restore printing
  281. //! @{
  282. bool saved_printing = false; //!< Print is paused and saved in RAM
  283. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  284. uint8_t saved_printing_type = PRINTING_TYPE_SD;
  285. static float saved_pos[4] = { X_COORD_INVALID, 0, 0, 0 };
  286. static uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
  287. static int saved_feedmultiply2 = 0;
  288. static uint8_t saved_active_extruder = 0;
  289. float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  290. float saved_bed_temperature = 0.0; //!< Bed temperature
  291. static bool saved_extruder_relative_mode = false;
  292. int saved_fan_speed = 0; //!< Print fan speed
  293. //! @}
  294. static int saved_feedmultiply_mm = 100;
  295. class AutoReportFeatures {
  296. union {
  297. struct {
  298. uint8_t temp : 1; //Temperature flag
  299. uint8_t fans : 1; //Fans flag
  300. uint8_t pos: 1; //Position flag
  301. uint8_t ar4 : 1; //Unused
  302. uint8_t ar5 : 1; //Unused
  303. uint8_t ar6 : 1; //Unused
  304. uint8_t ar7 : 1; //Unused
  305. } __attribute__((packed)) bits;
  306. uint8_t byte;
  307. } arFunctionsActive;
  308. uint8_t auto_report_period;
  309. public:
  310. LongTimer auto_report_timer;
  311. AutoReportFeatures():auto_report_period(0){
  312. #if defined(AUTO_REPORT)
  313. arFunctionsActive.byte = 0xff;
  314. #else
  315. arFunctionsActive.byte = 0;
  316. #endif //AUTO_REPORT
  317. }
  318. inline bool Temp()const { return arFunctionsActive.bits.temp != 0; }
  319. inline void SetTemp(uint8_t v){ arFunctionsActive.bits.temp = v; }
  320. inline bool Fans()const { return arFunctionsActive.bits.fans != 0; }
  321. inline void SetFans(uint8_t v){ arFunctionsActive.bits.fans = v; }
  322. inline bool Pos()const { return arFunctionsActive.bits.pos != 0; }
  323. inline void SetPos(uint8_t v){ arFunctionsActive.bits.pos = v; }
  324. inline void SetMask(uint8_t mask){ arFunctionsActive.byte = mask; }
  325. /// sets the autoreporting timer's period
  326. /// setting it to zero stops the timer
  327. void SetPeriod(uint8_t p){
  328. auto_report_period = p;
  329. if (auto_report_period != 0){
  330. auto_report_timer.start();
  331. } else{
  332. auto_report_timer.stop();
  333. }
  334. }
  335. inline void TimerStart() { auto_report_timer.start(); }
  336. inline bool TimerRunning()const { return auto_report_timer.running(); }
  337. inline bool TimerExpired() { return auto_report_timer.expired(auto_report_period * 1000ul); }
  338. };
  339. AutoReportFeatures autoReportFeatures;
  340. //===========================================================================
  341. //=============================Routines======================================
  342. //===========================================================================
  343. static bool setTargetedHotend(int code, uint8_t &extruder);
  344. static void print_time_remaining_init();
  345. static void wait_for_heater(long codenum, uint8_t extruder);
  346. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
  347. static void gcode_M105(uint8_t extruder);
  348. #ifndef PINDA_THERMISTOR
  349. static void temp_compensation_start();
  350. static void temp_compensation_apply();
  351. #endif
  352. #ifdef PRUSA_SN_SUPPORT
  353. static uint8_t get_PRUSA_SN(char* SN);
  354. #endif //PRUSA_SN_SUPPORT
  355. uint16_t gcode_in_progress = 0;
  356. uint16_t mcode_in_progress = 0;
  357. void serial_echopair_P(const char *s_P, float v)
  358. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  359. void serial_echopair_P(const char *s_P, double v)
  360. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  361. void serial_echopair_P(const char *s_P, unsigned long v)
  362. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  363. void serialprintPGM(const char *str) {
  364. while(uint8_t ch = pgm_read_byte(str)) {
  365. MYSERIAL.write((char)ch);
  366. ++str;
  367. }
  368. }
  369. void serialprintlnPGM(const char *str) {
  370. serialprintPGM(str);
  371. MYSERIAL.println();
  372. }
  373. #ifdef SDSUPPORT
  374. #include "SdFatUtil.h"
  375. int freeMemory() { return SdFatUtil::FreeRam(); }
  376. #else
  377. extern "C" {
  378. extern unsigned int __bss_end;
  379. extern unsigned int __heap_start;
  380. extern void *__brkval;
  381. int freeMemory() {
  382. int free_memory;
  383. if ((int)__brkval == 0)
  384. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  385. else
  386. free_memory = ((int)&free_memory) - ((int)__brkval);
  387. return free_memory;
  388. }
  389. }
  390. #endif //!SDSUPPORT
  391. void setup_killpin()
  392. {
  393. #if defined(KILL_PIN) && KILL_PIN > -1
  394. SET_INPUT(KILL_PIN);
  395. WRITE(KILL_PIN,HIGH);
  396. #endif
  397. }
  398. // Set home pin
  399. void setup_homepin(void)
  400. {
  401. #if defined(HOME_PIN) && HOME_PIN > -1
  402. SET_INPUT(HOME_PIN);
  403. WRITE(HOME_PIN,HIGH);
  404. #endif
  405. }
  406. void setup_photpin()
  407. {
  408. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  409. SET_OUTPUT(PHOTOGRAPH_PIN);
  410. WRITE(PHOTOGRAPH_PIN, LOW);
  411. #endif
  412. }
  413. void setup_powerhold()
  414. {
  415. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  416. SET_OUTPUT(SUICIDE_PIN);
  417. WRITE(SUICIDE_PIN, HIGH);
  418. #endif
  419. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  420. SET_OUTPUT(PS_ON_PIN);
  421. #if defined(PS_DEFAULT_OFF)
  422. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  423. #else
  424. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  425. #endif
  426. #endif
  427. }
  428. void suicide()
  429. {
  430. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  431. SET_OUTPUT(SUICIDE_PIN);
  432. WRITE(SUICIDE_PIN, LOW);
  433. #endif
  434. }
  435. void servo_init()
  436. {
  437. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  438. servos[0].attach(SERVO0_PIN);
  439. #endif
  440. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  441. servos[1].attach(SERVO1_PIN);
  442. #endif
  443. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  444. servos[2].attach(SERVO2_PIN);
  445. #endif
  446. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  447. servos[3].attach(SERVO3_PIN);
  448. #endif
  449. #if (NUM_SERVOS >= 5)
  450. #error "TODO: enter initalisation code for more servos"
  451. #endif
  452. }
  453. bool __attribute__((noinline)) printer_active() {
  454. return IS_SD_PRINTING
  455. || usb_timer.running()
  456. || isPrintPaused
  457. || (custom_message_type == CustomMsg::TempCal)
  458. || saved_printing
  459. || (lcd_commands_type == LcdCommands::Layer1Cal)
  460. || mmu_print_saved
  461. || homing_flag
  462. || mesh_bed_leveling_flag;
  463. }
  464. bool fans_check_enabled = true;
  465. #ifdef TMC2130
  466. void crashdet_stop_and_save_print()
  467. {
  468. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  469. }
  470. void crashdet_restore_print_and_continue()
  471. {
  472. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  473. // babystep_apply();
  474. }
  475. void crashdet_fmt_error(char* buf, uint8_t mask)
  476. {
  477. if(mask & X_AXIS_MASK) *buf++ = axis_codes[X_AXIS];
  478. if(mask & Y_AXIS_MASK) *buf++ = axis_codes[Y_AXIS];
  479. *buf++ = ' ';
  480. strcpy_P(buf, _T(MSG_CRASH_DETECTED));
  481. }
  482. void crashdet_detected(uint8_t mask)
  483. {
  484. st_synchronize();
  485. static uint8_t crashDet_counter = 0;
  486. static uint8_t crashDet_axes = 0;
  487. bool automatic_recovery_after_crash = true;
  488. char msg[LCD_WIDTH+1] = "";
  489. if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)) {
  490. crashDet_counter = 0;
  491. }
  492. if(++crashDet_counter >= CRASHDET_COUNTER_MAX) {
  493. automatic_recovery_after_crash = false;
  494. }
  495. crashDetTimer.start();
  496. crashDet_axes |= mask;
  497. lcd_update_enable(true);
  498. lcd_clear();
  499. lcd_update(2);
  500. if (mask & X_AXIS_MASK)
  501. {
  502. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_X, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_X) + 1);
  503. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT) + 1);
  504. }
  505. if (mask & Y_AXIS_MASK)
  506. {
  507. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_Y, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_Y) + 1);
  508. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT) + 1);
  509. }
  510. lcd_update_enable(true);
  511. lcd_update(2);
  512. // prepare the status message with the _current_ axes status
  513. crashdet_fmt_error(msg, mask);
  514. lcd_setstatus(msg);
  515. gcode_G28(true, true, false); //home X and Y
  516. if (automatic_recovery_after_crash) {
  517. enquecommand_P(PSTR("CRASH_RECOVER"));
  518. }else{
  519. setTargetHotend(0, active_extruder);
  520. // notify the user of *all* the axes previously affected, not just the last one
  521. lcd_update_enable(false);
  522. lcd_clear();
  523. crashdet_fmt_error(msg, crashDet_axes);
  524. crashDet_axes = 0;
  525. lcd_print(msg);
  526. // ask whether to resume printing
  527. lcd_set_cursor(0, 1);
  528. lcd_puts_P(_T(MSG_RESUME_PRINT));
  529. lcd_putc('?');
  530. bool yesno = lcd_show_yes_no_and_wait(false);
  531. lcd_update_enable(true);
  532. if (yesno)
  533. {
  534. enquecommand_P(PSTR("CRASH_RECOVER"));
  535. }
  536. else
  537. {
  538. enquecommand_P(PSTR("CRASH_CANCEL"));
  539. }
  540. }
  541. }
  542. void crashdet_recover()
  543. {
  544. crashdet_restore_print_and_continue();
  545. if (lcd_crash_detect_enabled()) tmc2130_sg_stop_on_crash = true;
  546. }
  547. void crashdet_cancel()
  548. {
  549. saved_printing = false;
  550. tmc2130_sg_stop_on_crash = true;
  551. if (saved_printing_type == PRINTING_TYPE_SD) {
  552. lcd_print_stop();
  553. }else if(saved_printing_type == PRINTING_TYPE_USB){
  554. SERIAL_ECHOLNRPGM(MSG_OCTOPRINT_CANCEL); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  555. cmdqueue_reset();
  556. }
  557. }
  558. #endif //TMC2130
  559. void failstats_reset_print()
  560. {
  561. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  562. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  563. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  564. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  565. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  566. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  567. }
  568. void softReset()
  569. {
  570. cli();
  571. wdt_enable(WDTO_15MS);
  572. while(1);
  573. }
  574. #ifdef MESH_BED_LEVELING
  575. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  576. #endif
  577. static void factory_reset_stats(){
  578. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  579. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  580. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  581. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  582. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  583. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  584. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  585. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  586. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  587. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  588. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  589. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  590. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  591. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  592. }
  593. // Factory reset function
  594. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  595. // Level input parameter sets depth of reset
  596. static void factory_reset(char level)
  597. {
  598. lcd_clear();
  599. Sound_MakeCustom(100,0,false);
  600. switch (level) {
  601. case 0: // Level 0: Language reset
  602. lang_reset();
  603. break;
  604. case 1: //Level 1: Reset statistics
  605. factory_reset_stats();
  606. lcd_menu_statistics();
  607. break;
  608. case 2: // Level 2: Prepare for shipping
  609. factory_reset_stats();
  610. // FALLTHRU
  611. case 3: // Level 3: Preparation after being serviced
  612. // Force language selection at the next boot up.
  613. lang_reset();
  614. // Force the "Follow calibration flow" message at the next boot up.
  615. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  616. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 2); //run wizard
  617. farm_disable();
  618. #ifdef FILAMENT_SENSOR
  619. fsensor.setEnabled(true);
  620. fsensor.setAutoLoadEnabled(true, true);
  621. fsensor.setRunoutEnabled(true, true);
  622. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  623. fsensor.setJamDetectionEnabled(true, true);
  624. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  625. #endif //FILAMENT_SENSOR
  626. break;
  627. case 4:
  628. menu_progressbar_init(EEPROM_TOP, PSTR("ERASING all data"));
  629. // Erase EEPROM
  630. for (uint16_t i = 0; i < EEPROM_TOP; i++) {
  631. eeprom_update_byte((uint8_t*)i, 0xFF);
  632. menu_progressbar_update(i);
  633. }
  634. menu_progressbar_finish();
  635. softReset();
  636. break;
  637. default:
  638. break;
  639. }
  640. }
  641. extern "C" {
  642. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  643. }
  644. int uart_putchar(char c, FILE *)
  645. {
  646. MYSERIAL.write(c);
  647. return 0;
  648. }
  649. void lcd_splash()
  650. {
  651. lcd_clear(); // clears display and homes screen
  652. lcd_puts_P(PSTR("\n Original Prusa i3\n Prusa Research"));
  653. }
  654. void factory_reset()
  655. {
  656. KEEPALIVE_STATE(PAUSED_FOR_USER);
  657. if (!READ(BTN_ENC))
  658. {
  659. _delay_ms(1000);
  660. if (!READ(BTN_ENC))
  661. {
  662. lcd_clear();
  663. lcd_puts_P(PSTR("Factory RESET"));
  664. SET_OUTPUT(BEEPER);
  665. if(eSoundMode!=e_SOUND_MODE_SILENT)
  666. WRITE(BEEPER, HIGH);
  667. while (!READ(BTN_ENC));
  668. WRITE(BEEPER, LOW);
  669. _delay_ms(2000);
  670. char level = reset_menu();
  671. factory_reset(level);
  672. switch (level) {
  673. case 0:
  674. case 1:
  675. case 2:
  676. case 3:
  677. case 4: _delay_ms(0); break;
  678. }
  679. }
  680. }
  681. KEEPALIVE_STATE(IN_HANDLER);
  682. }
  683. void show_fw_version_warnings() {
  684. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  685. switch (FW_DEV_VERSION) {
  686. 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
  687. 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
  688. case(FW_VERSION_DEVEL):
  689. case(FW_VERSION_DEBUG):
  690. lcd_update_enable(false);
  691. lcd_clear();
  692. #if FW_DEV_VERSION == FW_VERSION_DEVEL
  693. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  694. #else
  695. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  696. #endif
  697. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  698. lcd_puts_at_P(0, 2, PSTR("ver ")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  699. lcd_puts_at_P(0, 3, PSTR(FW_REPOSITORY));
  700. lcd_wait_for_click();
  701. break;
  702. // 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
  703. }
  704. lcd_update_enable(true);
  705. }
  706. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  707. //! @brief try to check if firmware is on right type of printer
  708. static void check_if_fw_is_on_right_printer() {
  709. if (fsensor.probeOtherType()) {
  710. lcd_show_fullscreen_message_and_wait_P(_i(PRINTER_NAME " firmware detected on " PRINTER_NAME_ALTERNATE " printer"));////c=20 r=4
  711. }
  712. }
  713. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  714. uint8_t check_printer_version()
  715. {
  716. uint8_t version_changed = 0;
  717. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  718. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  719. if (printer_type != PRINTER_TYPE) {
  720. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  721. else version_changed |= 0b10;
  722. }
  723. if (motherboard != MOTHERBOARD) {
  724. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  725. else version_changed |= 0b01;
  726. }
  727. return version_changed;
  728. }
  729. #ifdef BOOTAPP
  730. #include "bootapp.h" //bootloader support
  731. #endif //BOOTAPP
  732. #if (LANG_MODE != 0) //secondary language support
  733. #ifdef XFLASH
  734. // language update from external flash
  735. #define LANGBOOT_BLOCKSIZE 0x1000u
  736. #define LANGBOOT_RAMBUFFER 0x0800
  737. void update_sec_lang_from_external_flash()
  738. {
  739. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  740. {
  741. uint8_t lang = boot_reserved >> 3;
  742. uint8_t state = boot_reserved & 0x07;
  743. lang_table_header_t header;
  744. uint32_t src_addr;
  745. if (lang_get_header(lang, &header, &src_addr))
  746. {
  747. lcd_puts_at_P(1,3,PSTR("Language update."));
  748. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  749. _delay(100);
  750. boot_reserved = (boot_reserved & 0xF8) | ((state + 1) & 0x07);
  751. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  752. {
  753. cli();
  754. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  755. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  756. xflash_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  757. if (state == 0)
  758. {
  759. //TODO - check header integrity
  760. }
  761. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  762. }
  763. else
  764. {
  765. //TODO - check sec lang data integrity
  766. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  767. }
  768. }
  769. }
  770. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  771. }
  772. #ifdef DEBUG_XFLASH
  773. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  774. {
  775. lang_table_header_t header;
  776. uint8_t count = 0;
  777. uint32_t addr = 0x00000;
  778. while (1)
  779. {
  780. printf_P(_n("LANGTABLE%d:"), count);
  781. xflash_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  782. if (header.magic != LANG_MAGIC)
  783. {
  784. puts_P(_n("NG!"));
  785. break;
  786. }
  787. puts_P(_n("OK"));
  788. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  789. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  790. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  791. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  792. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  793. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  794. addr += header.size;
  795. codes[count] = header.code;
  796. count ++;
  797. }
  798. return count;
  799. }
  800. void list_sec_lang_from_external_flash()
  801. {
  802. uint16_t codes[8];
  803. uint8_t count = lang_xflash_enum_codes(codes);
  804. printf_P(_n("XFlash lang count = %hhd\n"), count);
  805. }
  806. #endif //DEBUG_XFLASH
  807. #endif //XFLASH
  808. #endif //(LANG_MODE != 0)
  809. static void fw_crash_init()
  810. {
  811. #ifdef XFLASH_DUMP
  812. dump_crash_reason crash_reason;
  813. if(xfdump_check_state(&crash_reason))
  814. {
  815. // always signal to the host that a dump is available for retrieval
  816. puts_P(_N("// action:dump_available"));
  817. #ifdef EMERGENCY_DUMP
  818. if(crash_reason != dump_crash_reason::manual &&
  819. eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG) != 0xFF)
  820. {
  821. lcd_show_fullscreen_message_and_wait_P(
  822. _n("FW crash detected! "
  823. "You can continue printing. "
  824. "Debug data available for analysis. "
  825. "Contact support to submit details."));
  826. }
  827. #endif
  828. }
  829. #else //XFLASH_DUMP
  830. dump_crash_reason crash_reason = (dump_crash_reason)eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG);
  831. if(crash_reason != dump_crash_reason::manual && (uint8_t)crash_reason != 0xFF)
  832. {
  833. lcd_beeper_quick_feedback();
  834. lcd_clear();
  835. lcd_puts_P(_n("FIRMWARE CRASH!\nCrash reason:\n"));
  836. switch(crash_reason)
  837. {
  838. case dump_crash_reason::stack_error:
  839. lcd_puts_P(_n("Static memory has\nbeen overwritten"));
  840. break;
  841. case dump_crash_reason::watchdog:
  842. lcd_puts_P(_n("Watchdog timeout"));
  843. break;
  844. case dump_crash_reason::bad_isr:
  845. lcd_puts_P(_n("Bad interrupt"));
  846. break;
  847. default:
  848. lcd_print((uint8_t)crash_reason);
  849. break;
  850. }
  851. lcd_wait_for_click();
  852. }
  853. #endif //XFLASH_DUMP
  854. // prevent crash prompts to reappear once acknowledged
  855. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, 0xFF);
  856. }
  857. static void xflash_err_msg()
  858. {
  859. puts_P(_n("XFLASH not responding."));
  860. lcd_show_fullscreen_message_and_wait_P(_n("External SPI flash\nXFLASH is not res-\nponding. Language\nswitch unavailable."));
  861. }
  862. // "Setup" function is called by the Arduino framework on startup.
  863. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  864. // are initialized by the main() routine provided by the Arduino framework.
  865. void setup()
  866. {
  867. timer2_init(); // enables functional millis
  868. MMU2::mmu2.Start();
  869. ultralcd_init();
  870. spi_init();
  871. lcd_splash();
  872. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  873. selectedSerialPort = eeprom_read_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE);
  874. if (selectedSerialPort == 0xFF) selectedSerialPort = 0;
  875. eeprom_update_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE, selectedSerialPort);
  876. MYSERIAL.begin(BAUDRATE);
  877. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  878. stdout = uartout;
  879. #ifdef XFLASH
  880. bool xflash_success = xflash_init();
  881. uint8_t optiboot_status = 1;
  882. if (xflash_success)
  883. {
  884. optiboot_status = optiboot_xflash_enter();
  885. #if (LANG_MODE != 0) //secondary language support
  886. update_sec_lang_from_external_flash();
  887. #endif //(LANG_MODE != 0)
  888. }
  889. #else
  890. const bool xflash_success = true;
  891. #endif //XFLASH
  892. setup_killpin();
  893. setup_powerhold();
  894. farm_mode_init();
  895. #ifdef TMC2130
  896. if( FarmOrUserECool() ){
  897. //increased extruder current (PFW363)
  898. tmc2130_current_h[E_AXIS] = TMC2130_CURRENTS_FARM;
  899. tmc2130_current_r[E_AXIS] = TMC2130_CURRENTS_FARM;
  900. }
  901. #endif //TMC2130
  902. #ifdef PRUSA_SN_SUPPORT
  903. //Check for valid SN in EEPROM. Try to retrieve it in case it's invalid.
  904. //SN is valid only if it is NULL terminated and starts with "CZPX".
  905. {
  906. char SN[20];
  907. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  908. if (SN[19] || strncmp_P(SN, PSTR("CZPX"), 4))
  909. {
  910. if (!get_PRUSA_SN(SN))
  911. {
  912. eeprom_update_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  913. puts_P(PSTR("SN updated"));
  914. }
  915. else
  916. puts_P(PSTR("SN update failed"));
  917. }
  918. }
  919. #endif //PRUSA_SN_SUPPORT
  920. #ifndef XFLASH
  921. SERIAL_PROTOCOLLNPGM("start");
  922. #else
  923. if ((optiboot_status != 0) || (selectedSerialPort != 0))
  924. SERIAL_PROTOCOLLNPGM("start");
  925. #endif
  926. SERIAL_ECHO_START;
  927. puts_P(PSTR(" " FW_VERSION_FULL));
  928. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  929. #ifdef DEBUG_SEC_LANG
  930. lang_table_header_t header;
  931. uint32_t src_addr = 0x00000;
  932. if (lang_get_header(1, &header, &src_addr))
  933. {
  934. printf_P(
  935. _n(
  936. " _src_addr = 0x%08lx\n"
  937. " _lt_magic = 0x%08lx %S\n"
  938. " _lt_size = 0x%04x (%d)\n"
  939. " _lt_count = 0x%04x (%d)\n"
  940. " _lt_chsum = 0x%04x\n"
  941. " _lt_code = 0x%04x (%c%c)\n"
  942. " _lt_resv1 = 0x%08lx\n"
  943. ),
  944. src_addr,
  945. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  946. header.size, header.size,
  947. header.count, header.count,
  948. header.checksum,
  949. header.code, header.code >> 8, header.code & 0xff,
  950. header.signature
  951. );
  952. #if 0
  953. xflash_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  954. for (uint16_t i = 0; i < 1024; i++)
  955. {
  956. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  957. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  958. if ((i % 16) == 15) putchar('\n');
  959. }
  960. #endif
  961. uint16_t sum = 0;
  962. for (uint16_t i = 0; i < header.size; i++)
  963. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  964. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  965. sum -= header.checksum; //subtract checksum
  966. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  967. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  968. if (sum == header.checksum)
  969. puts_P(_n("Checksum OK"));
  970. else
  971. puts_P(_n("Checksum NG"));
  972. }
  973. else
  974. puts_P(_n("lang_get_header failed!"));
  975. #if 0
  976. for (uint16_t i = 0; i < 1024*10; i++)
  977. {
  978. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  979. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  980. if ((i % 16) == 15) putchar('\n');
  981. }
  982. #endif
  983. #if 0
  984. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  985. for (int i = 0; i < 4096; ++i) {
  986. int b = eeprom_read_byte((unsigned char*)i);
  987. if (b != 255) {
  988. SERIAL_ECHO(i);
  989. SERIAL_ECHO(":");
  990. SERIAL_ECHO(b);
  991. SERIAL_ECHOLN("");
  992. }
  993. }
  994. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  995. #endif
  996. #endif //DEBUG_SEC_LANG
  997. // Check startup - does nothing if bootloader sets MCUSR to 0
  998. byte mcu = MCUSR;
  999. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  1000. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  1001. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  1002. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  1003. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  1004. if (mcu & 1) puts_P(MSG_POWERUP);
  1005. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  1006. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  1007. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  1008. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  1009. MCUSR = 0;
  1010. //SERIAL_ECHORPGM(MSG_MARLIN);
  1011. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  1012. #ifdef STRING_VERSION_CONFIG_H
  1013. #ifdef STRING_CONFIG_H_AUTHOR
  1014. SERIAL_ECHO_START;
  1015. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  1016. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  1017. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  1018. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  1019. SERIAL_ECHOPGM("Compiled: ");
  1020. SERIAL_ECHOLNPGM(__DATE__);
  1021. #endif
  1022. #endif
  1023. SERIAL_ECHO_START;
  1024. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1025. SERIAL_ECHO(freeMemory());
  1026. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1027. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1028. //lcd_update_enable(false); // why do we need this?? - andre
  1029. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1030. bool previous_settings_retrieved = false;
  1031. uint8_t hw_changed = check_printer_version();
  1032. 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
  1033. previous_settings_retrieved = Config_RetrieveSettings();
  1034. }
  1035. else { //printer version was changed so use default settings
  1036. Config_ResetDefault();
  1037. }
  1038. // writes a magic number at the end of static variables to monitor against incorrect overwriting
  1039. // of static memory by stack (this needs to be done before soft_pwm_init, since the check is
  1040. // performed inside the soft_pwm_isr)
  1041. SdFatUtil::set_stack_guard();
  1042. // Initialize pwm/temperature loops
  1043. soft_pwm_init();
  1044. temp_mgr_init();
  1045. #ifdef EXTRUDER_ALTFAN_DETECT
  1046. SERIAL_ECHORPGM(_n("Extruder fan type: "));
  1047. if (extruder_altfan_detect())
  1048. SERIAL_ECHOLNRPGM(PSTR("ALTFAN"));
  1049. else
  1050. SERIAL_ECHOLNRPGM(PSTR("NOCTUA"));
  1051. #endif //EXTRUDER_ALTFAN_DETECT
  1052. plan_init(); // Initialize planner;
  1053. factory_reset();
  1054. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  1055. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff)
  1056. {
  1057. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  1058. // where all the EEPROM entries are set to 0x0ff.
  1059. // Once a firmware boots up, it forces at least a language selection, which changes
  1060. // EEPROM_LANG to number lower than 0x0ff.
  1061. // 1) Set a high power mode.
  1062. eeprom_update_byte((uint8_t*)EEPROM_SILENT, SILENT_MODE_OFF);
  1063. #ifdef TMC2130
  1064. tmc2130_mode = TMC2130_MODE_NORMAL;
  1065. #endif //TMC2130
  1066. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  1067. }
  1068. lcd_encoder_diff=0;
  1069. #ifdef TMC2130
  1070. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1071. if (silentMode == 0xff) silentMode = 0;
  1072. tmc2130_mode = TMC2130_MODE_NORMAL;
  1073. if (lcd_crash_detect_enabled() && !farm_mode)
  1074. {
  1075. lcd_crash_detect_enable();
  1076. puts_P(_N("CrashDetect ENABLED!"));
  1077. }
  1078. else
  1079. {
  1080. lcd_crash_detect_disable();
  1081. puts_P(_N("CrashDetect DISABLED"));
  1082. }
  1083. #ifdef TMC2130_LINEARITY_CORRECTION
  1084. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1085. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1086. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1087. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1088. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1089. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1090. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1091. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1092. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1093. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1094. #endif //TMC2130_LINEARITY_CORRECTION
  1095. #ifdef TMC2130_VARIABLE_RESOLUTION
  1096. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1097. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1098. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1099. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1100. #else //TMC2130_VARIABLE_RESOLUTION
  1101. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1102. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1103. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1104. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1105. #endif //TMC2130_VARIABLE_RESOLUTION
  1106. #endif //TMC2130
  1107. st_init(); // Initialize stepper, this enables interrupts!
  1108. #ifdef TMC2130
  1109. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1110. update_mode_profile();
  1111. tmc2130_init(TMCInitParams(false, FarmOrUserECool() ));
  1112. #endif //TMC2130
  1113. #ifdef PSU_Delta
  1114. init_force_z(); // ! important for correct Z-axis initialization
  1115. #endif // PSU_Delta
  1116. setup_photpin();
  1117. #if 0
  1118. servo_init();
  1119. #endif
  1120. // Reset the machine correction matrix.
  1121. // It does not make sense to load the correction matrix until the machine is homed.
  1122. world2machine_reset();
  1123. // Initialize current_position accounting for software endstops to
  1124. // avoid unexpected initial shifts on the first move
  1125. clamp_to_software_endstops(current_position);
  1126. plan_set_position_curposXYZE();
  1127. // Show the xflash error message now that serial, lcd and encoder are available
  1128. if (!xflash_success)
  1129. xflash_err_msg();
  1130. #ifdef FILAMENT_SENSOR
  1131. fsensor.init();
  1132. #endif //FILAMENT_SENSOR
  1133. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1134. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1135. #endif
  1136. setup_homepin();
  1137. #if defined(Z_AXIS_ALWAYS_ON)
  1138. enable_z();
  1139. #endif
  1140. // The farm monitoring SW may accidentally expect
  1141. // 2 messages of "printer started" to consider a printer working.
  1142. prusa_statistics(8);
  1143. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1144. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1145. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1146. // but this times out if a blocking dialog is shown in setup().
  1147. card.initsd();
  1148. #ifdef DEBUG_SD_SPEED_TEST
  1149. if (card.cardOK)
  1150. {
  1151. uint8_t* buff = (uint8_t*)block_buffer;
  1152. uint32_t block = 0;
  1153. uint32_t sumr = 0;
  1154. uint32_t sumw = 0;
  1155. for (int i = 0; i < 1024; i++)
  1156. {
  1157. uint32_t u = _micros();
  1158. bool res = card.card.readBlock(i, buff);
  1159. u = _micros() - u;
  1160. if (res)
  1161. {
  1162. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1163. sumr += u;
  1164. u = _micros();
  1165. res = card.card.writeBlock(i, buff);
  1166. u = _micros() - u;
  1167. if (res)
  1168. {
  1169. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1170. sumw += u;
  1171. }
  1172. else
  1173. {
  1174. printf_P(PSTR("writeBlock %4d error\n"), i);
  1175. break;
  1176. }
  1177. }
  1178. else
  1179. {
  1180. printf_P(PSTR("readBlock %4d error\n"), i);
  1181. break;
  1182. }
  1183. }
  1184. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1185. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1186. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1187. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1188. }
  1189. else
  1190. printf_P(PSTR("Card NG!\n"));
  1191. #endif //DEBUG_SD_SPEED_TEST
  1192. eeprom_init();
  1193. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1194. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1195. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1196. #if (LANG_MODE != 0) //secondary language support
  1197. #ifdef DEBUG_XFLASH
  1198. XFLASH_SPI_ENTER();
  1199. uint8_t uid[8]; // 64bit unique id
  1200. xflash_rd_uid(uid);
  1201. puts_P(_n("XFLASH UID="));
  1202. for (uint8_t i = 0; i < 8; i ++)
  1203. printf_P(PSTR("%02x"), uid[i]);
  1204. putchar('\n');
  1205. list_sec_lang_from_external_flash();
  1206. #endif //DEBUG_XFLASH
  1207. // lang_reset();
  1208. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1209. lcd_language();
  1210. #ifdef DEBUG_SEC_LANG
  1211. uint16_t sec_lang_code = lang_get_code(1);
  1212. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1213. 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);
  1214. lang_print_sec_lang(uartout);
  1215. #endif //DEBUG_SEC_LANG
  1216. #endif //(LANG_MODE != 0)
  1217. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  1218. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1219. }
  1220. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1221. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1222. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1223. int16_t z_shift = 0;
  1224. for (uint8_t i = 0; i < 5; i++) {
  1225. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  1226. }
  1227. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1228. }
  1229. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 255) {
  1230. eeprom_write_byte((uint8_t*)EEPROM_UVLO, 0);
  1231. }
  1232. if (eeprom_read_byte((uint8_t*)EEPROM_SD_SORT) == 255) {
  1233. eeprom_write_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1234. }
  1235. //mbl_mode_init();
  1236. mbl_settings_init();
  1237. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1238. if (SilentModeMenu_MMU == 255) {
  1239. SilentModeMenu_MMU = 1;
  1240. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1241. }
  1242. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1243. setup_fan_interrupt();
  1244. #endif //DEBUG_DISABLE_FANCHECK
  1245. #ifndef DEBUG_DISABLE_STARTMSGS
  1246. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1247. if (!farm_mode) {
  1248. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1249. check_if_fw_is_on_right_printer();
  1250. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1251. show_fw_version_warnings();
  1252. }
  1253. switch (hw_changed) {
  1254. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1255. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1256. case(0b01):
  1257. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1258. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1259. break;
  1260. case(0b10):
  1261. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1262. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1263. break;
  1264. case(0b11):
  1265. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1266. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1267. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1268. break;
  1269. default: break; //no change, show no message
  1270. }
  1271. if (!previous_settings_retrieved) {
  1272. 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=6
  1273. Config_StoreSettings();
  1274. }
  1275. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) >= 1) {
  1276. lcd_wizard(WizState::Run);
  1277. }
  1278. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1279. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1280. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1281. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1282. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1283. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  1284. // Show the message.
  1285. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1286. }
  1287. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1288. // Show the message.
  1289. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1290. lcd_update_enable(true);
  1291. }
  1292. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == false) {
  1293. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1294. lcd_update_enable(true);
  1295. }
  1296. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1297. // Show the message.
  1298. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1299. }
  1300. }
  1301. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1302. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1303. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1304. update_current_firmware_version_to_eeprom();
  1305. lcd_selftest();
  1306. }
  1307. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1308. KEEPALIVE_STATE(IN_PROCESS);
  1309. #endif //DEBUG_DISABLE_STARTMSGS
  1310. lcd_update_enable(true);
  1311. lcd_clear();
  1312. lcd_update(2);
  1313. // Store the currently running firmware into an eeprom,
  1314. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1315. update_current_firmware_version_to_eeprom();
  1316. #ifdef TMC2130
  1317. tmc2130_home_origin[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN);
  1318. tmc2130_home_bsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS);
  1319. tmc2130_home_fsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS);
  1320. if (tmc2130_home_origin[X_AXIS] == 0xff) tmc2130_home_origin[X_AXIS] = 0;
  1321. if (tmc2130_home_bsteps[X_AXIS] == 0xff) tmc2130_home_bsteps[X_AXIS] = 48;
  1322. if (tmc2130_home_fsteps[X_AXIS] == 0xff) tmc2130_home_fsteps[X_AXIS] = 48;
  1323. tmc2130_home_origin[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN);
  1324. tmc2130_home_bsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS);
  1325. tmc2130_home_fsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS);
  1326. if (tmc2130_home_origin[Y_AXIS] == 0xff) tmc2130_home_origin[Y_AXIS] = 0;
  1327. if (tmc2130_home_bsteps[Y_AXIS] == 0xff) tmc2130_home_bsteps[Y_AXIS] = 48;
  1328. if (tmc2130_home_fsteps[Y_AXIS] == 0xff) tmc2130_home_fsteps[Y_AXIS] = 48;
  1329. tmc2130_home_enabled = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED);
  1330. if (tmc2130_home_enabled == 0xff) tmc2130_home_enabled = 0;
  1331. #endif //TMC2130
  1332. // report crash failures
  1333. fw_crash_init();
  1334. #ifdef UVLO_SUPPORT
  1335. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1336. /*
  1337. if (lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1338. else {
  1339. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1340. lcd_update_enable(true);
  1341. lcd_update(2);
  1342. lcd_setstatuspgm(MSG_WELCOME);
  1343. }
  1344. */
  1345. manage_heater(); // Update temperatures
  1346. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1347. 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));
  1348. #endif
  1349. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1350. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1351. puts_P(_N("Automatic recovery!"));
  1352. #endif
  1353. recover_print(1);
  1354. }
  1355. else{
  1356. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1357. puts_P(_N("Normal recovery!"));
  1358. #endif
  1359. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) ) recover_print(0);
  1360. else {
  1361. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1362. lcd_update_enable(true);
  1363. lcd_update(2);
  1364. lcd_setstatuspgm(MSG_WELCOME);
  1365. }
  1366. }
  1367. }
  1368. // Only arm the uvlo interrupt _after_ a recovering print has been initialized and
  1369. // the entire state machine initialized.
  1370. setup_uvlo_interrupt();
  1371. #endif //UVLO_SUPPORT
  1372. fCheckModeInit();
  1373. fSetMmuMode(MMU2::mmu2.Enabled());
  1374. KEEPALIVE_STATE(NOT_BUSY);
  1375. #ifdef WATCHDOG
  1376. wdt_enable(WDTO_4S);
  1377. #ifdef EMERGENCY_HANDLERS
  1378. WDTCSR |= (1 << WDIE);
  1379. #endif //EMERGENCY_HANDLERS
  1380. #endif //WATCHDOG
  1381. }
  1382. static inline void crash_and_burn(dump_crash_reason reason)
  1383. {
  1384. WRITE(BEEPER, HIGH);
  1385. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, (uint8_t)reason);
  1386. #ifdef EMERGENCY_DUMP
  1387. xfdump_full_dump_and_reset(reason);
  1388. #elif defined(EMERGENCY_SERIAL_DUMP)
  1389. if(emergency_serial_dump)
  1390. serial_dump_and_reset(reason);
  1391. #endif
  1392. softReset();
  1393. }
  1394. #ifdef EMERGENCY_HANDLERS
  1395. #ifdef WATCHDOG
  1396. ISR(WDT_vect)
  1397. {
  1398. crash_and_burn(dump_crash_reason::watchdog);
  1399. }
  1400. #endif
  1401. ISR(BADISR_vect)
  1402. {
  1403. crash_and_burn(dump_crash_reason::bad_isr);
  1404. }
  1405. #endif //EMERGENCY_HANDLERS
  1406. void stack_error() {
  1407. crash_and_burn(dump_crash_reason::stack_error);
  1408. }
  1409. /**
  1410. * Output autoreport values according to features requested in M155
  1411. */
  1412. #if defined(AUTO_REPORT)
  1413. void host_autoreport()
  1414. {
  1415. if (autoReportFeatures.TimerExpired())
  1416. {
  1417. if(autoReportFeatures.Temp()){
  1418. gcode_M105(active_extruder);
  1419. }
  1420. if(autoReportFeatures.Pos()){
  1421. gcode_M114();
  1422. }
  1423. #if defined(AUTO_REPORT) && (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  1424. if(autoReportFeatures.Fans()){
  1425. gcode_M123();
  1426. }
  1427. #endif //AUTO_REPORT and (FANCHECK and TACH_0 or TACH_1)
  1428. autoReportFeatures.TimerStart();
  1429. }
  1430. }
  1431. #endif //AUTO_REPORT
  1432. /**
  1433. * Output a "busy" message at regular intervals
  1434. * while the machine is not accepting commands.
  1435. */
  1436. void host_keepalive() {
  1437. #ifndef HOST_KEEPALIVE_FEATURE
  1438. return;
  1439. #endif //HOST_KEEPALIVE_FEATURE
  1440. if (farm_mode) return;
  1441. long ms = _millis();
  1442. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1443. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1444. switch (busy_state) {
  1445. case IN_HANDLER:
  1446. case IN_PROCESS:
  1447. SERIAL_ECHO_START;
  1448. SERIAL_ECHOLNPGM("busy: processing");
  1449. break;
  1450. case PAUSED_FOR_USER:
  1451. SERIAL_ECHO_START;
  1452. SERIAL_ECHOLNPGM("busy: paused for user");
  1453. break;
  1454. case PAUSED_FOR_INPUT:
  1455. SERIAL_ECHO_START;
  1456. SERIAL_ECHOLNPGM("busy: paused for input");
  1457. break;
  1458. default:
  1459. break;
  1460. }
  1461. }
  1462. prev_busy_signal_ms = ms;
  1463. }
  1464. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1465. // Before loop(), the setup() function is called by the main() routine.
  1466. void loop()
  1467. {
  1468. // Reset a previously aborted command, we can now start processing motion again
  1469. planner_aborted = false;
  1470. if(Stopped) {
  1471. // Currently Stopped (possibly due to an error) and not accepting new serial commands.
  1472. // Signal to the host that we're currently busy waiting for supervision.
  1473. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1474. } else {
  1475. // Printer is available for processing, reset state
  1476. KEEPALIVE_STATE(NOT_BUSY);
  1477. }
  1478. if (isPrintPaused && saved_printing_type == PRINTING_TYPE_USB) { //keep believing that usb is being printed. Prevents accessing dangerous menus while pausing.
  1479. usb_timer.start();
  1480. }
  1481. else if (usb_timer.expired(10000)) { //just need to check if it expired. Nothing else is needed to be done.
  1482. ;
  1483. }
  1484. #ifdef PRUSA_M28
  1485. if (prusa_sd_card_upload)
  1486. {
  1487. //we read byte-by byte
  1488. serial_read_stream();
  1489. }
  1490. else
  1491. #endif
  1492. {
  1493. get_command();
  1494. #ifdef SDSUPPORT
  1495. card.checkautostart(false);
  1496. #endif
  1497. if(buflen)
  1498. {
  1499. cmdbuffer_front_already_processed = false;
  1500. #ifdef SDSUPPORT
  1501. if(card.saving)
  1502. {
  1503. // Saving a G-code file onto an SD-card is in progress.
  1504. // Saving starts with M28, saving until M29 is seen.
  1505. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1506. card.write_command(CMDBUFFER_CURRENT_STRING);
  1507. if(card.logging)
  1508. process_commands();
  1509. else
  1510. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1511. } else {
  1512. card.closefile();
  1513. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1514. }
  1515. } else {
  1516. process_commands();
  1517. }
  1518. #else
  1519. process_commands();
  1520. #endif //SDSUPPORT
  1521. if (! cmdbuffer_front_already_processed && buflen)
  1522. {
  1523. // ptr points to the start of the block currently being processed.
  1524. // The first character in the block is the block type.
  1525. char *ptr = cmdbuffer + bufindr;
  1526. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1527. // To support power panic, move the lenght of the command on the SD card to a planner buffer.
  1528. union {
  1529. struct {
  1530. char lo;
  1531. char hi;
  1532. } lohi;
  1533. uint16_t value;
  1534. } sdlen;
  1535. sdlen.value = 0;
  1536. {
  1537. // This block locks the interrupts globally for 3.25 us,
  1538. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1539. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1540. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1541. cli();
  1542. // Reset the command to something, which will be ignored by the power panic routine,
  1543. // so this buffer length will not be counted twice.
  1544. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1545. // Extract the current buffer length.
  1546. sdlen.lohi.lo = *ptr ++;
  1547. sdlen.lohi.hi = *ptr;
  1548. // and pass it to the planner queue.
  1549. planner_add_sd_length(sdlen.value);
  1550. sei();
  1551. }
  1552. }
  1553. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1554. cli();
  1555. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1556. // and one for each command to previous block in the planner queue.
  1557. planner_add_sd_length(1);
  1558. sei();
  1559. }
  1560. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1561. // this block's SD card length will not be counted twice as its command type has been replaced
  1562. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1563. cmdqueue_pop_front();
  1564. }
  1565. host_keepalive();
  1566. }
  1567. }
  1568. //check heater every n milliseconds
  1569. manage_heater();
  1570. manage_inactivity(isPrintPaused);
  1571. checkHitEndstops();
  1572. lcd_update(0);
  1573. #ifdef TMC2130
  1574. tmc2130_check_overtemp();
  1575. if (tmc2130_sg_crash)
  1576. {
  1577. uint8_t crash = tmc2130_sg_crash;
  1578. tmc2130_sg_crash = 0;
  1579. // crashdet_stop_and_save_print();
  1580. switch (crash)
  1581. {
  1582. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1583. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1584. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1585. }
  1586. }
  1587. #endif //TMC2130
  1588. MMU2::mmu2.mmu_loop();
  1589. }
  1590. #define DEFINE_PGM_READ_ANY(type, reader) \
  1591. static inline type pgm_read_any(const type *p) \
  1592. { return pgm_read_##reader##_near(p); }
  1593. DEFINE_PGM_READ_ANY(float, float);
  1594. DEFINE_PGM_READ_ANY(signed char, byte);
  1595. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1596. static const PROGMEM type array##_P[3] = \
  1597. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1598. static inline type array(uint8_t axis) \
  1599. { return pgm_read_any(&array##_P[axis]); } \
  1600. type array##_ext(uint8_t axis) \
  1601. { return pgm_read_any(&array##_P[axis]); }
  1602. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1603. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1604. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1605. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1606. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1607. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1608. static void axis_is_at_home(uint8_t axis) {
  1609. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1610. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1611. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1612. }
  1613. //! @return original feedmultiply
  1614. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1615. saved_feedrate = feedrate;
  1616. int l_feedmultiply = feedmultiply;
  1617. feedmultiply = 100;
  1618. previous_millis_cmd.start();
  1619. enable_endstops(enable_endstops_now);
  1620. return l_feedmultiply;
  1621. }
  1622. //! @param original_feedmultiply feedmultiply to restore
  1623. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1624. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1625. enable_endstops(false);
  1626. #endif
  1627. feedrate = saved_feedrate;
  1628. feedmultiply = original_feedmultiply;
  1629. previous_millis_cmd.start();
  1630. }
  1631. #ifdef ENABLE_AUTO_BED_LEVELING
  1632. #ifdef AUTO_BED_LEVELING_GRID
  1633. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1634. {
  1635. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1636. planeNormal.debug("planeNormal");
  1637. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1638. //bedLevel.debug("bedLevel");
  1639. //plan_bed_level_matrix.debug("bed level before");
  1640. //vector_3 uncorrected_position = plan_get_position_mm();
  1641. //uncorrected_position.debug("position before");
  1642. vector_3 corrected_position = plan_get_position();
  1643. // corrected_position.debug("position after");
  1644. current_position[X_AXIS] = corrected_position.x;
  1645. current_position[Y_AXIS] = corrected_position.y;
  1646. current_position[Z_AXIS] = corrected_position.z;
  1647. // put the bed at 0 so we don't go below it.
  1648. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1649. plan_set_position_curposXYZE();
  1650. }
  1651. #else // not AUTO_BED_LEVELING_GRID
  1652. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1653. plan_bed_level_matrix.set_to_identity();
  1654. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1655. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1656. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1657. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1658. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1659. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1660. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1661. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1662. vector_3 corrected_position = plan_get_position();
  1663. current_position[X_AXIS] = corrected_position.x;
  1664. current_position[Y_AXIS] = corrected_position.y;
  1665. current_position[Z_AXIS] = corrected_position.z;
  1666. // put the bed at 0 so we don't go below it.
  1667. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1668. plan_set_position_curposXYZE();
  1669. }
  1670. #endif // AUTO_BED_LEVELING_GRID
  1671. static void run_z_probe() {
  1672. plan_bed_level_matrix.set_to_identity();
  1673. feedrate = homing_feedrate[Z_AXIS];
  1674. // move down until you find the bed
  1675. float zPosition = -10;
  1676. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1677. st_synchronize();
  1678. // we have to let the planner know where we are right now as it is not where we said to go.
  1679. zPosition = st_get_position_mm(Z_AXIS);
  1680. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1681. // move up the retract distance
  1682. zPosition += home_retract_mm(Z_AXIS);
  1683. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1684. st_synchronize();
  1685. // move back down slowly to find bed
  1686. feedrate = homing_feedrate[Z_AXIS]/4;
  1687. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1688. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1689. st_synchronize();
  1690. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1691. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1692. plan_set_position_curposXYZE();
  1693. }
  1694. static void do_blocking_move_to(float x, float y, float z) {
  1695. float oldFeedRate = feedrate;
  1696. feedrate = homing_feedrate[Z_AXIS];
  1697. current_position[Z_AXIS] = z;
  1698. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1699. st_synchronize();
  1700. feedrate = XY_TRAVEL_SPEED;
  1701. current_position[X_AXIS] = x;
  1702. current_position[Y_AXIS] = y;
  1703. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1704. st_synchronize();
  1705. feedrate = oldFeedRate;
  1706. }
  1707. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1708. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1709. }
  1710. /// Probe bed height at position (x,y), returns the measured z value
  1711. static float probe_pt(float x, float y, float z_before) {
  1712. // move to right place
  1713. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1714. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1715. run_z_probe();
  1716. float measured_z = current_position[Z_AXIS];
  1717. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1718. SERIAL_PROTOCOLPGM(" x: ");
  1719. SERIAL_PROTOCOL(x);
  1720. SERIAL_PROTOCOLPGM(" y: ");
  1721. SERIAL_PROTOCOL(y);
  1722. SERIAL_PROTOCOLPGM(" z: ");
  1723. SERIAL_PROTOCOL(measured_z);
  1724. SERIAL_PROTOCOLPGM("\n");
  1725. return measured_z;
  1726. }
  1727. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1728. #ifdef LIN_ADVANCE
  1729. /**
  1730. * M900: Set and/or Get advance K factor
  1731. *
  1732. * K<factor> Set advance K factor
  1733. */
  1734. inline void gcode_M900() {
  1735. float newK = code_seen('K') ? code_value_float() : -2;
  1736. #ifdef LA_NOCOMPAT
  1737. if (newK >= 0 && newK < LA_K_MAX)
  1738. extruder_advance_K = newK;
  1739. else
  1740. SERIAL_ECHOLNPGM("K out of allowed range!");
  1741. #else
  1742. if (newK == 0)
  1743. {
  1744. extruder_advance_K = 0;
  1745. la10c_reset();
  1746. }
  1747. else
  1748. {
  1749. newK = la10c_value(newK);
  1750. if (newK < 0)
  1751. SERIAL_ECHOLNPGM("K out of allowed range!");
  1752. else
  1753. extruder_advance_K = newK;
  1754. }
  1755. #endif
  1756. SERIAL_ECHO_START;
  1757. SERIAL_ECHOPGM("Advance K=");
  1758. SERIAL_ECHOLN(extruder_advance_K);
  1759. }
  1760. #endif // LIN_ADVANCE
  1761. bool check_commands() {
  1762. bool end_command_found = false;
  1763. while (buflen)
  1764. {
  1765. if ((code_seen_P(PSTR("M84"))) || (code_seen_P(PSTR("M 84")))) end_command_found = true;
  1766. if (!cmdbuffer_front_already_processed)
  1767. cmdqueue_pop_front();
  1768. cmdbuffer_front_already_processed = false;
  1769. }
  1770. return end_command_found;
  1771. }
  1772. // raise_z_above: slowly raise Z to the requested height
  1773. //
  1774. // contrarily to a simple move, this function will carefully plan a move
  1775. // when the current Z position is unknown. In such cases, stallguard is
  1776. // enabled and will prevent prolonged pushing against the Z tops
  1777. void raise_z_above(float target, bool plan)
  1778. {
  1779. if (current_position[Z_AXIS] >= target)
  1780. return;
  1781. // Z needs raising
  1782. current_position[Z_AXIS] = target;
  1783. clamp_to_software_endstops(current_position);
  1784. #if defined(Z_MIN_PIN) && (Z_MIN_PIN > -1) && !defined(DEBUG_DISABLE_ZMINLIMIT)
  1785. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1786. #else
  1787. bool z_min_endstop = false;
  1788. #endif
  1789. if (axis_known_position[Z_AXIS] || z_min_endstop)
  1790. {
  1791. // current position is known or very low, it's safe to raise Z
  1792. if(plan) plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1793. return;
  1794. }
  1795. // ensure Z is powered in normal mode to overcome initial load
  1796. enable_z();
  1797. st_synchronize();
  1798. // rely on crashguard to limit damage
  1799. bool z_endstop_enabled = enable_z_endstop(true);
  1800. #ifdef TMC2130
  1801. tmc2130_home_enter(Z_AXIS_MASK);
  1802. #endif //TMC2130
  1803. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  1804. st_synchronize();
  1805. #ifdef TMC2130
  1806. if (endstop_z_hit_on_purpose())
  1807. {
  1808. // not necessarily exact, but will avoid further vertical moves
  1809. current_position[Z_AXIS] = max_pos[Z_AXIS];
  1810. plan_set_position_curposXYZE();
  1811. }
  1812. tmc2130_home_exit();
  1813. #endif //TMC2130
  1814. enable_z_endstop(z_endstop_enabled);
  1815. }
  1816. #ifdef TMC2130
  1817. bool calibrate_z_auto()
  1818. {
  1819. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1820. lcd_clear();
  1821. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1822. bool endstops_enabled = enable_endstops(true);
  1823. int axis_up_dir = -home_dir(Z_AXIS);
  1824. tmc2130_home_enter(Z_AXIS_MASK);
  1825. current_position[Z_AXIS] = 0;
  1826. plan_set_position_curposXYZE();
  1827. set_destination_to_current();
  1828. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1829. feedrate = homing_feedrate[Z_AXIS];
  1830. plan_buffer_line_destinationXYZE(feedrate / 60);
  1831. st_synchronize();
  1832. // current_position[axis] = 0;
  1833. // plan_set_position_curposXYZE();
  1834. tmc2130_home_exit();
  1835. enable_endstops(false);
  1836. current_position[Z_AXIS] = 0;
  1837. plan_set_position_curposXYZE();
  1838. set_destination_to_current();
  1839. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1840. feedrate = homing_feedrate[Z_AXIS] / 2;
  1841. plan_buffer_line_destinationXYZE(feedrate / 60);
  1842. st_synchronize();
  1843. enable_endstops(endstops_enabled);
  1844. if (PRINTER_TYPE == PRINTER_MK3) {
  1845. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1846. }
  1847. else {
  1848. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1849. }
  1850. plan_set_position_curposXYZE();
  1851. return true;
  1852. }
  1853. #endif //TMC2130
  1854. #ifdef TMC2130
  1855. static void check_Z_crash(void)
  1856. {
  1857. if (!READ(Z_TMC2130_DIAG)) { //Z crash
  1858. FORCE_HIGH_POWER_END;
  1859. current_position[Z_AXIS] = 0;
  1860. plan_set_position_curposXYZE();
  1861. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  1862. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1863. st_synchronize();
  1864. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1865. }
  1866. }
  1867. #endif //TMC2130
  1868. #ifdef TMC2130
  1869. void homeaxis(uint8_t axis, uint8_t cnt, uint8_t* pstep)
  1870. #else
  1871. void homeaxis(uint8_t axis, uint8_t cnt)
  1872. #endif //TMC2130
  1873. {
  1874. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1875. #define HOMEAXIS_DO(LETTER) \
  1876. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1877. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1878. {
  1879. int axis_home_dir = home_dir(axis);
  1880. feedrate = homing_feedrate[axis];
  1881. #ifdef TMC2130
  1882. tmc2130_home_enter(X_AXIS_MASK << axis);
  1883. #endif //TMC2130
  1884. // Move away a bit, so that the print head does not touch the end position,
  1885. // and the following movement to endstop has a chance to achieve the required velocity
  1886. // for the stall guard to work.
  1887. current_position[axis] = 0;
  1888. plan_set_position_curposXYZE();
  1889. set_destination_to_current();
  1890. // destination[axis] = 11.f;
  1891. destination[axis] = -3.f * axis_home_dir;
  1892. plan_buffer_line_destinationXYZE(feedrate/60);
  1893. st_synchronize();
  1894. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1895. endstops_hit_on_purpose();
  1896. enable_endstops(false);
  1897. current_position[axis] = 0;
  1898. plan_set_position_curposXYZE();
  1899. destination[axis] = 1. * axis_home_dir;
  1900. plan_buffer_line_destinationXYZE(feedrate/60);
  1901. st_synchronize();
  1902. // Now continue to move up to the left end stop with the collision detection enabled.
  1903. enable_endstops(true);
  1904. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1905. plan_buffer_line_destinationXYZE(feedrate/60);
  1906. st_synchronize();
  1907. for (uint8_t i = 0; i < cnt; i++)
  1908. {
  1909. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1910. endstops_hit_on_purpose();
  1911. enable_endstops(false);
  1912. current_position[axis] = 0;
  1913. plan_set_position_curposXYZE();
  1914. destination[axis] = -10.f * axis_home_dir;
  1915. plan_buffer_line_destinationXYZE(feedrate/60);
  1916. st_synchronize();
  1917. endstops_hit_on_purpose();
  1918. // Now move left up to the collision, this time with a repeatable velocity.
  1919. enable_endstops(true);
  1920. destination[axis] = 11.f * axis_home_dir;
  1921. #ifdef TMC2130
  1922. feedrate = homing_feedrate[axis];
  1923. #else //TMC2130
  1924. feedrate = homing_feedrate[axis] / 2;
  1925. #endif //TMC2130
  1926. plan_buffer_line_destinationXYZE(feedrate/60);
  1927. st_synchronize();
  1928. #ifdef TMC2130
  1929. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1930. if (pstep) pstep[i] = mscnt >> 4;
  1931. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1932. #endif //TMC2130
  1933. }
  1934. endstops_hit_on_purpose();
  1935. enable_endstops(false);
  1936. #ifdef TMC2130
  1937. uint8_t orig = tmc2130_home_origin[axis];
  1938. uint8_t back = tmc2130_home_bsteps[axis];
  1939. if (tmc2130_home_enabled && (orig <= 63))
  1940. {
  1941. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1942. if (back > 0)
  1943. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1944. }
  1945. else
  1946. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1947. tmc2130_home_exit();
  1948. #endif //TMC2130
  1949. axis_is_at_home(axis);
  1950. axis_known_position[axis] = true;
  1951. // Move from minimum
  1952. #ifdef TMC2130
  1953. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1954. #else //TMC2130
  1955. float dist = - axis_home_dir * 0.01f * 64;
  1956. #endif //TMC2130
  1957. current_position[axis] -= dist;
  1958. plan_set_position_curposXYZE();
  1959. current_position[axis] += dist;
  1960. destination[axis] = current_position[axis];
  1961. plan_buffer_line_destinationXYZE(0.5f*feedrate/60);
  1962. st_synchronize();
  1963. feedrate = 0.0;
  1964. }
  1965. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1966. {
  1967. #ifdef TMC2130
  1968. FORCE_HIGH_POWER_START;
  1969. #endif
  1970. int axis_home_dir = home_dir(axis);
  1971. current_position[axis] = 0;
  1972. plan_set_position_curposXYZE();
  1973. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1974. feedrate = homing_feedrate[axis];
  1975. plan_buffer_line_destinationXYZE(feedrate/60);
  1976. st_synchronize();
  1977. #ifdef TMC2130
  1978. check_Z_crash();
  1979. #endif //TMC2130
  1980. current_position[axis] = 0;
  1981. plan_set_position_curposXYZE();
  1982. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1983. plan_buffer_line_destinationXYZE(feedrate/60);
  1984. st_synchronize();
  1985. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1986. feedrate = homing_feedrate[axis]/2 ;
  1987. plan_buffer_line_destinationXYZE(feedrate/60);
  1988. st_synchronize();
  1989. #ifdef TMC2130
  1990. check_Z_crash();
  1991. #endif //TMC2130
  1992. axis_is_at_home(axis);
  1993. destination[axis] = current_position[axis];
  1994. feedrate = 0.0;
  1995. endstops_hit_on_purpose();
  1996. axis_known_position[axis] = true;
  1997. #ifdef TMC2130
  1998. FORCE_HIGH_POWER_END;
  1999. #endif
  2000. }
  2001. enable_endstops(endstops_enabled);
  2002. }
  2003. /**/
  2004. void home_xy()
  2005. {
  2006. set_destination_to_current();
  2007. homeaxis(X_AXIS);
  2008. homeaxis(Y_AXIS);
  2009. plan_set_position_curposXYZE();
  2010. endstops_hit_on_purpose();
  2011. }
  2012. void refresh_cmd_timeout(void)
  2013. {
  2014. previous_millis_cmd.start();
  2015. }
  2016. #ifdef FWRETRACT
  2017. void retract(bool retracting, bool swapretract = false) {
  2018. // Perform FW retraction, just if needed, but behave as if the move has never took place in
  2019. // order to keep E/Z coordinates unchanged. This is done by manipulating the internal planner
  2020. // position, which requires a sync
  2021. if(retracting && !retracted[active_extruder]) {
  2022. st_synchronize();
  2023. set_destination_to_current();
  2024. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  2025. plan_set_e_position(current_position[E_AXIS]);
  2026. float oldFeedrate = feedrate;
  2027. feedrate=cs.retract_feedrate*60;
  2028. retracted[active_extruder]=true;
  2029. prepare_move();
  2030. if(cs.retract_zlift) {
  2031. st_synchronize();
  2032. current_position[Z_AXIS]-=cs.retract_zlift;
  2033. plan_set_position_curposXYZE();
  2034. prepare_move();
  2035. }
  2036. feedrate = oldFeedrate;
  2037. } else if(!retracting && retracted[active_extruder]) {
  2038. st_synchronize();
  2039. set_destination_to_current();
  2040. float oldFeedrate = feedrate;
  2041. feedrate=cs.retract_recover_feedrate*60;
  2042. if(cs.retract_zlift) {
  2043. current_position[Z_AXIS]+=cs.retract_zlift;
  2044. plan_set_position_curposXYZE();
  2045. prepare_move();
  2046. st_synchronize();
  2047. }
  2048. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  2049. plan_set_e_position(current_position[E_AXIS]);
  2050. retracted[active_extruder]=false;
  2051. prepare_move();
  2052. feedrate = oldFeedrate;
  2053. }
  2054. } //retract
  2055. #endif //FWRETRACT
  2056. #ifdef TMC2130
  2057. void force_high_power_mode(bool start_high_power_section) {
  2058. #ifdef PSU_Delta
  2059. if (start_high_power_section == true) enable_force_z();
  2060. #endif //PSU_Delta
  2061. uint8_t silent;
  2062. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2063. if (silent == 1) {
  2064. //we are in silent mode, set to normal mode to enable crash detection
  2065. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2066. st_synchronize();
  2067. cli();
  2068. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2069. update_mode_profile();
  2070. tmc2130_init(TMCInitParams(FarmOrUserECool()));
  2071. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2072. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2073. st_reset_timer();
  2074. sei();
  2075. }
  2076. }
  2077. #endif //TMC2130
  2078. void gcode_M105(uint8_t extruder)
  2079. {
  2080. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  2081. SERIAL_PROTOCOLPGM("T:");
  2082. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  2083. SERIAL_PROTOCOLPGM(" /");
  2084. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  2085. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2086. SERIAL_PROTOCOLPGM(" B:");
  2087. SERIAL_PROTOCOL_F(degBed(),1);
  2088. SERIAL_PROTOCOLPGM(" /");
  2089. SERIAL_PROTOCOL_F(degTargetBed(),1);
  2090. #endif //TEMP_BED_PIN
  2091. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2092. SERIAL_PROTOCOLPGM(" T");
  2093. SERIAL_PROTOCOL(cur_extruder);
  2094. SERIAL_PROTOCOL(':');
  2095. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2096. SERIAL_PROTOCOLPGM(" /");
  2097. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  2098. }
  2099. #else
  2100. SERIAL_ERROR_START;
  2101. SERIAL_ERRORLNRPGM(_n("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  2102. #endif
  2103. SERIAL_PROTOCOLPGM(" @:");
  2104. #ifdef EXTRUDER_WATTS
  2105. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  2106. SERIAL_PROTOCOLPGM("W");
  2107. #else
  2108. SERIAL_PROTOCOL(getHeaterPower(extruder));
  2109. #endif
  2110. SERIAL_PROTOCOLPGM(" B@:");
  2111. #ifdef BED_WATTS
  2112. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  2113. SERIAL_PROTOCOLPGM("W");
  2114. #else
  2115. SERIAL_PROTOCOL(getHeaterPower(-1));
  2116. #endif
  2117. #ifdef PINDA_THERMISTOR
  2118. SERIAL_PROTOCOLPGM(" P:");
  2119. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  2120. #endif //PINDA_THERMISTOR
  2121. #ifdef AMBIENT_THERMISTOR
  2122. SERIAL_PROTOCOLPGM(" A:");
  2123. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  2124. #endif //AMBIENT_THERMISTOR
  2125. #ifdef SHOW_TEMP_ADC_VALUES
  2126. {
  2127. float raw = 0.0;
  2128. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2129. SERIAL_PROTOCOLPGM(" ADC B:");
  2130. SERIAL_PROTOCOL_F(degBed(),1);
  2131. SERIAL_PROTOCOLPGM("C->");
  2132. raw = rawBedTemp();
  2133. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2134. SERIAL_PROTOCOLPGM(" Rb->");
  2135. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2136. SERIAL_PROTOCOLPGM(" Rxb->");
  2137. SERIAL_PROTOCOL_F(raw, 5);
  2138. #endif
  2139. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2140. SERIAL_PROTOCOLPGM(" T");
  2141. SERIAL_PROTOCOL(cur_extruder);
  2142. SERIAL_PROTOCOLPGM(":");
  2143. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2144. SERIAL_PROTOCOLPGM("C->");
  2145. raw = rawHotendTemp(cur_extruder);
  2146. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2147. SERIAL_PROTOCOLPGM(" Rt");
  2148. SERIAL_PROTOCOL(cur_extruder);
  2149. SERIAL_PROTOCOLPGM("->");
  2150. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2151. SERIAL_PROTOCOLPGM(" Rx");
  2152. SERIAL_PROTOCOL(cur_extruder);
  2153. SERIAL_PROTOCOLPGM("->");
  2154. SERIAL_PROTOCOL_F(raw, 5);
  2155. }
  2156. }
  2157. #endif
  2158. SERIAL_PROTOCOLLN();
  2159. }
  2160. #ifdef TMC2130
  2161. 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)
  2162. #else
  2163. 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)
  2164. #endif //TMC2130
  2165. {
  2166. // Flag for the display update routine and to disable the print cancelation during homing.
  2167. st_synchronize();
  2168. homing_flag = true;
  2169. #if 0
  2170. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2171. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2172. #endif
  2173. // Which axes should be homed?
  2174. bool home_x = home_x_axis;
  2175. bool home_y = home_y_axis;
  2176. bool home_z = home_z_axis;
  2177. // Either all X,Y,Z codes are present, or none of them.
  2178. bool home_all_axes = home_x == home_y && home_x == home_z;
  2179. if (home_all_axes)
  2180. // No X/Y/Z code provided means to home all axes.
  2181. home_x = home_y = home_z = true;
  2182. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2183. if (home_all_axes) {
  2184. raise_z_above(MESH_HOME_Z_SEARCH);
  2185. st_synchronize();
  2186. }
  2187. #ifdef ENABLE_AUTO_BED_LEVELING
  2188. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2189. #endif //ENABLE_AUTO_BED_LEVELING
  2190. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2191. // the planner will not perform any adjustments in the XY plane.
  2192. // Wait for the motors to stop and update the current position with the absolute values.
  2193. world2machine_revert_to_uncorrected();
  2194. // For mesh bed leveling deactivate the matrix temporarily.
  2195. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2196. // in a single axis only.
  2197. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2198. #ifdef MESH_BED_LEVELING
  2199. uint8_t mbl_was_active = mbl.active;
  2200. mbl.active = 0;
  2201. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2202. #endif
  2203. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2204. if (home_z)
  2205. babystep_undo();
  2206. int l_feedmultiply = setup_for_endstop_move();
  2207. set_destination_to_current();
  2208. feedrate = 0.0;
  2209. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2210. if(home_z)
  2211. homeaxis(Z_AXIS);
  2212. #endif
  2213. #ifdef QUICK_HOME
  2214. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2215. if(home_x && home_y) //first diagonal move
  2216. {
  2217. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2218. uint8_t x_axis_home_dir = home_dir(X_AXIS);
  2219. plan_set_position_curposXYZE();
  2220. 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);
  2221. feedrate = homing_feedrate[X_AXIS];
  2222. if(homing_feedrate[Y_AXIS]<feedrate)
  2223. feedrate = homing_feedrate[Y_AXIS];
  2224. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2225. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2226. } else {
  2227. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2228. }
  2229. plan_buffer_line_destinationXYZE(feedrate/60);
  2230. st_synchronize();
  2231. axis_is_at_home(X_AXIS);
  2232. axis_is_at_home(Y_AXIS);
  2233. plan_set_position_curposXYZE();
  2234. destination[X_AXIS] = current_position[X_AXIS];
  2235. destination[Y_AXIS] = current_position[Y_AXIS];
  2236. plan_buffer_line_destinationXYZE(feedrate/60);
  2237. feedrate = 0.0;
  2238. st_synchronize();
  2239. endstops_hit_on_purpose();
  2240. current_position[X_AXIS] = destination[X_AXIS];
  2241. current_position[Y_AXIS] = destination[Y_AXIS];
  2242. current_position[Z_AXIS] = destination[Z_AXIS];
  2243. }
  2244. #endif /* QUICK_HOME */
  2245. #ifdef TMC2130
  2246. if(home_x)
  2247. {
  2248. if (!calib)
  2249. homeaxis(X_AXIS);
  2250. else
  2251. tmc2130_home_calibrate(X_AXIS);
  2252. }
  2253. if(home_y)
  2254. {
  2255. if (!calib)
  2256. homeaxis(Y_AXIS);
  2257. else
  2258. tmc2130_home_calibrate(Y_AXIS);
  2259. }
  2260. #else //TMC2130
  2261. if(home_x) homeaxis(X_AXIS);
  2262. if(home_y) homeaxis(Y_AXIS);
  2263. #endif //TMC2130
  2264. if(home_x_axis && home_x_value != 0)
  2265. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2266. if(home_y_axis && home_y_value != 0)
  2267. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2268. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2269. #ifndef Z_SAFE_HOMING
  2270. if(home_z) {
  2271. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2272. raise_z_above(Z_RAISE_BEFORE_HOMING);
  2273. st_synchronize();
  2274. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2275. #ifdef MESH_BED_LEVELING // If Mesh bed leveling, move X&Y to safe position for home
  2276. raise_z_above(MESH_HOME_Z_SEARCH);
  2277. st_synchronize();
  2278. if (!axis_known_position[X_AXIS]) homeaxis(X_AXIS);
  2279. if (!axis_known_position[Y_AXIS]) homeaxis(Y_AXIS);
  2280. // 1st mesh bed leveling measurement point, corrected.
  2281. world2machine_initialize();
  2282. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2283. world2machine_reset();
  2284. if (destination[Y_AXIS] < Y_MIN_POS)
  2285. destination[Y_AXIS] = Y_MIN_POS;
  2286. feedrate = homing_feedrate[X_AXIS] / 20;
  2287. enable_endstops(false);
  2288. #ifdef DEBUG_BUILD
  2289. SERIAL_ECHOLNPGM("plan_set_position()");
  2290. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2291. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2292. #endif
  2293. plan_set_position_curposXYZE();
  2294. #ifdef DEBUG_BUILD
  2295. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2296. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2297. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2298. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2299. #endif
  2300. plan_buffer_line_destinationXYZE(feedrate);
  2301. st_synchronize();
  2302. current_position[X_AXIS] = destination[X_AXIS];
  2303. current_position[Y_AXIS] = destination[Y_AXIS];
  2304. enable_endstops(true);
  2305. endstops_hit_on_purpose();
  2306. homeaxis(Z_AXIS);
  2307. #else // MESH_BED_LEVELING
  2308. homeaxis(Z_AXIS);
  2309. #endif // MESH_BED_LEVELING
  2310. }
  2311. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2312. if(home_all_axes) {
  2313. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2314. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2315. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2316. feedrate = XY_TRAVEL_SPEED/60;
  2317. current_position[Z_AXIS] = 0;
  2318. plan_set_position_curposXYZE();
  2319. plan_buffer_line_destinationXYZE(feedrate);
  2320. st_synchronize();
  2321. current_position[X_AXIS] = destination[X_AXIS];
  2322. current_position[Y_AXIS] = destination[Y_AXIS];
  2323. homeaxis(Z_AXIS);
  2324. }
  2325. // Let's see if X and Y are homed and probe is inside bed area.
  2326. if(home_z) {
  2327. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2328. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2329. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2330. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2331. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2332. current_position[Z_AXIS] = 0;
  2333. plan_set_position_curposXYZE();
  2334. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2335. feedrate = max_feedrate[Z_AXIS];
  2336. plan_buffer_line_destinationXYZE(feedrate);
  2337. st_synchronize();
  2338. homeaxis(Z_AXIS);
  2339. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2340. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2341. SERIAL_ECHO_START;
  2342. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2343. } else {
  2344. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2345. SERIAL_ECHO_START;
  2346. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2347. }
  2348. }
  2349. #endif // Z_SAFE_HOMING
  2350. #endif // Z_HOME_DIR < 0
  2351. if(home_z_axis && home_z_value != 0)
  2352. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2353. #ifdef ENABLE_AUTO_BED_LEVELING
  2354. if(home_z)
  2355. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2356. #endif
  2357. // Set the planner and stepper routine positions.
  2358. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2359. // contains the machine coordinates.
  2360. plan_set_position_curposXYZE();
  2361. clean_up_after_endstop_move(l_feedmultiply);
  2362. endstops_hit_on_purpose();
  2363. #ifndef MESH_BED_LEVELING
  2364. //-// Oct 2019 :: this part of code is (from) now probably un-compilable
  2365. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  2366. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  2367. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  2368. lcd_adjust_z();
  2369. #endif
  2370. // Load the machine correction matrix
  2371. world2machine_initialize();
  2372. // and correct the current_position XY axes to match the transformed coordinate system.
  2373. world2machine_update_current();
  2374. #ifdef MESH_BED_LEVELING
  2375. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2376. {
  2377. if (! home_z && mbl_was_active) {
  2378. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2379. mbl.active = true;
  2380. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2381. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2382. }
  2383. }
  2384. #endif
  2385. prusa_statistics(20);
  2386. st_synchronize();
  2387. homing_flag = false;
  2388. #if 0
  2389. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2390. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2391. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2392. #endif
  2393. }
  2394. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2395. {
  2396. #ifdef TMC2130
  2397. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2398. #else
  2399. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2400. #endif //TMC2130
  2401. }
  2402. // G80 - Automatic mesh bed leveling
  2403. static void gcode_G80()
  2404. {
  2405. st_synchronize();
  2406. if (planner_aborted)
  2407. return;
  2408. mesh_bed_leveling_flag = true;
  2409. #ifndef PINDA_THERMISTOR
  2410. static bool run = false; // thermistor-less PINDA temperature compensation is running
  2411. #endif // ndef PINDA_THERMISTOR
  2412. #ifdef SUPPORT_VERBOSITY
  2413. int8_t verbosity_level = 0;
  2414. if (code_seen('V')) {
  2415. // Just 'V' without a number counts as V1.
  2416. char c = strchr_pointer[1];
  2417. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  2418. }
  2419. #endif //SUPPORT_VERBOSITY
  2420. // Firstly check if we know where we are
  2421. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2422. // We don't know where we are! HOME!
  2423. // Push the commands to the front of the message queue in the reverse order!
  2424. // There shall be always enough space reserved for these commands.
  2425. repeatcommand_front(); // repeat G80 with all its parameters
  2426. enquecommand_front_P(G28W0);
  2427. return;
  2428. }
  2429. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  2430. if (code_seen('N')) {
  2431. nMeasPoints = code_value_uint8();
  2432. if (nMeasPoints != 7) {
  2433. nMeasPoints = 3;
  2434. }
  2435. }
  2436. else {
  2437. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  2438. }
  2439. uint8_t nProbeRetry = 3;
  2440. if (code_seen('R')) {
  2441. nProbeRetry = code_value_uint8();
  2442. if (nProbeRetry > 10) {
  2443. nProbeRetry = 10;
  2444. }
  2445. }
  2446. else {
  2447. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  2448. }
  2449. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  2450. #ifndef PINDA_THERMISTOR
  2451. if (run == false && eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true && target_temperature_bed >= 50)
  2452. {
  2453. temp_compensation_start();
  2454. run = true;
  2455. repeatcommand_front(); // repeat G80 with all its parameters
  2456. enquecommand_front_P(G28W0);
  2457. break;
  2458. }
  2459. run = false;
  2460. #endif //PINDA_THERMISTOR
  2461. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  2462. CustomMsg custom_message_type_old = custom_message_type;
  2463. uint8_t custom_message_state_old = custom_message_state;
  2464. custom_message_type = CustomMsg::MeshBedLeveling;
  2465. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  2466. lcd_update(1);
  2467. mbl.reset(); //reset mesh bed leveling
  2468. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2469. babystep_undo();
  2470. // Cycle through all points and probe them
  2471. // First move up. During this first movement, the babystepping will be reverted.
  2472. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2473. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  2474. // The move to the first calibration point.
  2475. current_position[X_AXIS] = BED_X0;
  2476. current_position[Y_AXIS] = BED_Y0;
  2477. #ifdef SUPPORT_VERBOSITY
  2478. if (verbosity_level >= 1)
  2479. {
  2480. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2481. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  2482. }
  2483. #else //SUPPORT_VERBOSITY
  2484. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2485. #endif //SUPPORT_VERBOSITY
  2486. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  2487. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2488. // Wait until the move is finished.
  2489. st_synchronize();
  2490. if (planner_aborted)
  2491. {
  2492. custom_message_type = custom_message_type_old;
  2493. custom_message_state = custom_message_state_old;
  2494. return;
  2495. }
  2496. uint8_t mesh_point = 0; //index number of calibration point
  2497. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  2498. 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)
  2499. #ifdef SUPPORT_VERBOSITY
  2500. if (verbosity_level >= 1) {
  2501. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  2502. }
  2503. #endif // SUPPORT_VERBOSITY
  2504. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  2505. while (mesh_point != nMeasPoints * nMeasPoints) {
  2506. // Get coords of a measuring point.
  2507. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  2508. uint8_t iy = mesh_point / nMeasPoints;
  2509. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  2510. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  2511. custom_message_state--;
  2512. mesh_point++;
  2513. continue; //skip
  2514. }*/
  2515. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  2516. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  2517. {
  2518. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  2519. }
  2520. float z0 = 0.f;
  2521. if (has_z && (mesh_point > 0)) {
  2522. uint16_t z_offset_u = 0;
  2523. if (nMeasPoints == 7) {
  2524. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  2525. }
  2526. else {
  2527. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  2528. }
  2529. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  2530. #ifdef SUPPORT_VERBOSITY
  2531. if (verbosity_level >= 1) {
  2532. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  2533. }
  2534. #endif // SUPPORT_VERBOSITY
  2535. }
  2536. // Move Z up to MESH_HOME_Z_SEARCH.
  2537. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2538. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  2539. float init_z_bckp = current_position[Z_AXIS];
  2540. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2541. st_synchronize();
  2542. // Move to XY position of the sensor point.
  2543. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  2544. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  2545. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2546. #ifdef SUPPORT_VERBOSITY
  2547. if (verbosity_level >= 1) {
  2548. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2549. SERIAL_PROTOCOL(mesh_point);
  2550. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  2551. }
  2552. #else //SUPPORT_VERBOSITY
  2553. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2554. #endif // SUPPORT_VERBOSITY
  2555. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2556. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2557. st_synchronize();
  2558. if (planner_aborted)
  2559. {
  2560. custom_message_type = custom_message_type_old;
  2561. custom_message_state = custom_message_state_old;
  2562. return;
  2563. }
  2564. // Go down until endstop is hit
  2565. const float Z_CALIBRATION_THRESHOLD = 1.f;
  2566. 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
  2567. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2568. break;
  2569. }
  2570. 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.
  2571. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  2572. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2573. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2574. st_synchronize();
  2575. 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
  2576. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2577. break;
  2578. }
  2579. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  2580. puts_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken."));
  2581. break;
  2582. }
  2583. }
  2584. 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
  2585. puts_P(PSTR("Bed leveling failed. Sensor triggered too high."));
  2586. break;
  2587. }
  2588. #ifdef SUPPORT_VERBOSITY
  2589. if (verbosity_level >= 10) {
  2590. SERIAL_ECHOPGM("X: ");
  2591. MYSERIAL.print(current_position[X_AXIS], 5);
  2592. SERIAL_ECHOLNPGM("");
  2593. SERIAL_ECHOPGM("Y: ");
  2594. MYSERIAL.print(current_position[Y_AXIS], 5);
  2595. SERIAL_PROTOCOLPGM("\n");
  2596. }
  2597. #endif // SUPPORT_VERBOSITY
  2598. float offset_z = 0;
  2599. #ifdef PINDA_THERMISTOR
  2600. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  2601. #endif //PINDA_THERMISTOR
  2602. // #ifdef SUPPORT_VERBOSITY
  2603. /* if (verbosity_level >= 1)
  2604. {
  2605. SERIAL_ECHOPGM("mesh bed leveling: ");
  2606. MYSERIAL.print(current_position[Z_AXIS], 5);
  2607. SERIAL_ECHOPGM(" offset: ");
  2608. MYSERIAL.print(offset_z, 5);
  2609. SERIAL_ECHOLNPGM("");
  2610. }*/
  2611. // #endif // SUPPORT_VERBOSITY
  2612. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  2613. custom_message_state--;
  2614. mesh_point++;
  2615. lcd_update(1);
  2616. }
  2617. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2618. #ifdef SUPPORT_VERBOSITY
  2619. if (verbosity_level >= 20) {
  2620. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  2621. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  2622. MYSERIAL.print(current_position[Z_AXIS], 5);
  2623. }
  2624. #endif // SUPPORT_VERBOSITY
  2625. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2626. st_synchronize();
  2627. if (mesh_point != nMeasPoints * nMeasPoints) {
  2628. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  2629. bool bState;
  2630. do { // repeat until Z-leveling o.k.
  2631. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ...")); ////MSG_ZLEVELING_ENFORCED c=20 r=4
  2632. #ifdef TMC2130
  2633. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  2634. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  2635. #else // TMC2130
  2636. lcd_wait_for_click_delay(0); // ~ no timeout
  2637. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  2638. #endif // TMC2130
  2639. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  2640. bState=enable_z_endstop(false);
  2641. current_position[Z_AXIS] -= 1;
  2642. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2643. st_synchronize();
  2644. enable_z_endstop(true);
  2645. #ifdef TMC2130
  2646. tmc2130_home_enter(Z_AXIS_MASK);
  2647. #endif // TMC2130
  2648. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2649. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2650. st_synchronize();
  2651. #ifdef TMC2130
  2652. tmc2130_home_exit();
  2653. #endif // TMC2130
  2654. enable_z_endstop(bState);
  2655. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  2656. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  2657. custom_message_type = custom_message_type_old;
  2658. custom_message_state = custom_message_state_old;
  2659. lcd_update_enable(true); // display / status-line recovery
  2660. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  2661. repeatcommand_front(); // re-run (i.e. of "G80")
  2662. return;
  2663. }
  2664. clean_up_after_endstop_move(l_feedmultiply);
  2665. // SERIAL_ECHOLNPGM("clean up finished ");
  2666. #ifndef PINDA_THERMISTOR
  2667. if(eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  2668. #endif
  2669. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  2670. // SERIAL_ECHOLNPGM("babystep applied");
  2671. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  2672. #ifdef SUPPORT_VERBOSITY
  2673. if (verbosity_level >= 1) {
  2674. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  2675. }
  2676. #endif // SUPPORT_VERBOSITY
  2677. for (uint8_t i = 0; i < 4; ++i) {
  2678. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  2679. long correction = 0;
  2680. if (code_seen(codes[i]))
  2681. correction = code_value_long();
  2682. else if (eeprom_bed_correction_valid) {
  2683. unsigned char *addr = (i < 2) ?
  2684. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  2685. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  2686. correction = eeprom_read_int8(addr);
  2687. }
  2688. if (correction == 0)
  2689. continue;
  2690. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  2691. SERIAL_ERROR_START;
  2692. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  2693. SERIAL_ECHO(correction);
  2694. SERIAL_ECHOLNPGM(" microns");
  2695. }
  2696. else {
  2697. float offset = float(correction) * 0.001f;
  2698. switch (i) {
  2699. case 0:
  2700. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2701. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  2702. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  2703. }
  2704. }
  2705. break;
  2706. case 1:
  2707. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2708. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  2709. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  2710. }
  2711. }
  2712. break;
  2713. case 2:
  2714. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2715. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2716. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  2717. }
  2718. }
  2719. break;
  2720. case 3:
  2721. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2722. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  2723. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  2724. }
  2725. }
  2726. break;
  2727. }
  2728. }
  2729. }
  2730. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  2731. if (nMeasPoints == 3) {
  2732. 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)
  2733. }
  2734. /*
  2735. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2736. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2737. SERIAL_PROTOCOLPGM(",");
  2738. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2739. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2740. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2741. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2742. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2743. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2744. SERIAL_PROTOCOLPGM(" ");
  2745. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2746. }
  2747. SERIAL_PROTOCOLPGM("\n");
  2748. }
  2749. */
  2750. if (nMeasPoints == 7 && magnet_elimination) {
  2751. mbl_interpolation(nMeasPoints);
  2752. }
  2753. /*
  2754. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2755. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2756. SERIAL_PROTOCOLPGM(",");
  2757. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2758. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2759. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2760. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2761. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2762. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2763. SERIAL_PROTOCOLPGM(" ");
  2764. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2765. }
  2766. SERIAL_PROTOCOLPGM("\n");
  2767. }
  2768. */
  2769. // SERIAL_ECHOLNPGM("Upsample finished");
  2770. mbl.active = 1; //activate mesh bed leveling
  2771. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  2772. go_home_with_z_lift();
  2773. // SERIAL_ECHOLNPGM("Go home finished");
  2774. //unretract (after PINDA preheat retraction)
  2775. if (((int)degHotend(active_extruder) > extrude_min_temp) && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() && (target_temperature_bed >= 50)) {
  2776. current_position[E_AXIS] += default_retraction;
  2777. plan_buffer_line_curposXYZE(400);
  2778. }
  2779. KEEPALIVE_STATE(NOT_BUSY);
  2780. // Restore custom message state
  2781. lcd_setstatuspgm(MSG_WELCOME);
  2782. custom_message_type = custom_message_type_old;
  2783. custom_message_state = custom_message_state_old;
  2784. lcd_update(2);
  2785. st_synchronize();
  2786. mesh_bed_leveling_flag = false;
  2787. }
  2788. void adjust_bed_reset()
  2789. {
  2790. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2791. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2792. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2793. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2794. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2795. }
  2796. //! @brief Calibrate XYZ
  2797. //! @param onlyZ if true, calibrate only Z axis
  2798. //! @param verbosity_level
  2799. //! @retval true Succeeded
  2800. //! @retval false Failed
  2801. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2802. {
  2803. bool final_result = false;
  2804. #ifdef TMC2130
  2805. FORCE_HIGH_POWER_START;
  2806. #endif // TMC2130
  2807. FORCE_BL_ON_START;
  2808. // Only Z calibration?
  2809. if (!onlyZ)
  2810. {
  2811. setTargetBed(0);
  2812. setAllTargetHotends(0);
  2813. adjust_bed_reset(); //reset bed level correction
  2814. }
  2815. // Disable the default update procedure of the display. We will do a modal dialog.
  2816. lcd_update_enable(false);
  2817. // Let the planner use the uncorrected coordinates.
  2818. mbl.reset();
  2819. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2820. // the planner will not perform any adjustments in the XY plane.
  2821. // Wait for the motors to stop and update the current position with the absolute values.
  2822. world2machine_revert_to_uncorrected();
  2823. // Reset the baby step value applied without moving the axes.
  2824. babystep_reset();
  2825. // Mark all axes as in a need for homing.
  2826. memset(axis_known_position, 0, sizeof(axis_known_position));
  2827. // Home in the XY plane.
  2828. //set_destination_to_current();
  2829. int l_feedmultiply = setup_for_endstop_move();
  2830. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2831. raise_z_above(MESH_HOME_Z_SEARCH);
  2832. st_synchronize();
  2833. home_xy();
  2834. enable_endstops(false);
  2835. current_position[X_AXIS] += 5;
  2836. current_position[Y_AXIS] += 5;
  2837. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2838. st_synchronize();
  2839. // Let the user move the Z axes up to the end stoppers.
  2840. #ifdef TMC2130
  2841. if (calibrate_z_auto())
  2842. {
  2843. #else //TMC2130
  2844. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2845. {
  2846. #endif //TMC2130
  2847. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2848. if(onlyZ){
  2849. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2850. lcd_puts_at_P(0,3,_n("1/9"));
  2851. }else{
  2852. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2853. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2854. lcd_puts_at_P(0,3,_n("1/4"));
  2855. }
  2856. refresh_cmd_timeout();
  2857. #ifndef STEEL_SHEET
  2858. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2859. {
  2860. lcd_wait_for_cool_down();
  2861. }
  2862. #endif //STEEL_SHEET
  2863. if(!onlyZ)
  2864. {
  2865. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2866. #ifdef STEEL_SHEET
  2867. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  2868. if(result) lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2869. #endif //STEEL_SHEET
  2870. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2871. KEEPALIVE_STATE(IN_HANDLER);
  2872. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2873. lcd_puts_at_P(0,3,_n("1/4"));
  2874. }
  2875. bool endstops_enabled = enable_endstops(false);
  2876. current_position[Z_AXIS] -= 1; //move 1mm down with disabled endstop
  2877. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2878. st_synchronize();
  2879. // Move the print head close to the bed.
  2880. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2881. enable_endstops(true);
  2882. #ifdef TMC2130
  2883. tmc2130_home_enter(Z_AXIS_MASK);
  2884. #endif //TMC2130
  2885. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2886. st_synchronize();
  2887. #ifdef TMC2130
  2888. tmc2130_home_exit();
  2889. #endif //TMC2130
  2890. enable_endstops(endstops_enabled);
  2891. if ((st_get_position_mm(Z_AXIS) <= (MESH_HOME_Z_SEARCH + HOME_Z_SEARCH_THRESHOLD)) &&
  2892. (st_get_position_mm(Z_AXIS) >= (MESH_HOME_Z_SEARCH - HOME_Z_SEARCH_THRESHOLD)))
  2893. {
  2894. if (onlyZ)
  2895. {
  2896. clean_up_after_endstop_move(l_feedmultiply);
  2897. // Z only calibration.
  2898. // Load the machine correction matrix
  2899. world2machine_initialize();
  2900. // and correct the current_position to match the transformed coordinate system.
  2901. world2machine_update_current();
  2902. //FIXME
  2903. bool result = sample_mesh_and_store_reference();
  2904. if (result)
  2905. {
  2906. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2907. {
  2908. // Shipped, the nozzle height has been set already. The user can start printing now.
  2909. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2910. }
  2911. final_result = true;
  2912. // babystep_apply();
  2913. }
  2914. }
  2915. else
  2916. {
  2917. // Reset the baby step value and the baby step applied flag.
  2918. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2919. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  2920. // Complete XYZ calibration.
  2921. uint8_t point_too_far_mask = 0;
  2922. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2923. clean_up_after_endstop_move(l_feedmultiply);
  2924. // Print head up.
  2925. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2926. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2927. st_synchronize();
  2928. //#ifndef NEW_XYZCAL
  2929. if (result >= 0)
  2930. {
  2931. #ifdef HEATBED_V2
  2932. sample_z();
  2933. #else //HEATBED_V2
  2934. point_too_far_mask = 0;
  2935. // Second half: The fine adjustment.
  2936. // Let the planner use the uncorrected coordinates.
  2937. mbl.reset();
  2938. world2machine_reset();
  2939. // Home in the XY plane.
  2940. int l_feedmultiply = setup_for_endstop_move();
  2941. home_xy();
  2942. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2943. clean_up_after_endstop_move(l_feedmultiply);
  2944. // Print head up.
  2945. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2946. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2947. st_synchronize();
  2948. // if (result >= 0) babystep_apply();
  2949. #endif //HEATBED_V2
  2950. }
  2951. //#endif //NEW_XYZCAL
  2952. lcd_update_enable(true);
  2953. lcd_update(2);
  2954. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2955. if (result >= 0)
  2956. {
  2957. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2958. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2959. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2960. final_result = true;
  2961. }
  2962. }
  2963. #ifdef TMC2130
  2964. tmc2130_home_exit();
  2965. #endif
  2966. }
  2967. else
  2968. {
  2969. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2970. final_result = false;
  2971. }
  2972. }
  2973. else
  2974. {
  2975. // Timeouted.
  2976. }
  2977. lcd_update_enable(true);
  2978. #ifdef TMC2130
  2979. FORCE_HIGH_POWER_END;
  2980. #endif // TMC2130
  2981. FORCE_BL_ON_END;
  2982. return final_result;
  2983. }
  2984. void gcode_M114()
  2985. {
  2986. SERIAL_PROTOCOLPGM("X:");
  2987. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2988. SERIAL_PROTOCOLPGM(" Y:");
  2989. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2990. SERIAL_PROTOCOLPGM(" Z:");
  2991. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2992. SERIAL_PROTOCOLPGM(" E:");
  2993. SERIAL_PROTOCOL(current_position[E_AXIS]);
  2994. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  2995. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  2996. SERIAL_PROTOCOLPGM(" Y:");
  2997. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  2998. SERIAL_PROTOCOLPGM(" Z:");
  2999. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  3000. SERIAL_PROTOCOLPGM(" E:");
  3001. SERIAL_PROTOCOLLN(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  3002. }
  3003. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3004. void gcode_M123()
  3005. {
  3006. printf_P(_N("E0:%d RPM PRN1:%d RPM E0@:%u PRN1@:%d\n"), 60*fan_speed[active_extruder], 60*fan_speed[1], newFanSpeed, fanSpeed);
  3007. }
  3008. #endif //FANCHECK and TACH_0 or TACH_1
  3009. //! extracted code to compute z_shift for M600 in case of filament change operation
  3010. //! requested from fsensors.
  3011. //! The function ensures, that the printhead lifts to at least 25mm above the heat bed
  3012. //! unlike the previous implementation, which was adding 25mm even when the head was
  3013. //! printing at e.g. 24mm height.
  3014. //! A safety margin of FILAMENTCHANGE_ZADD is added in all cases to avoid touching
  3015. //! the printout.
  3016. //! This function is templated to enable fast change of computation data type.
  3017. //! @return new z_shift value
  3018. template<typename T>
  3019. static T gcode_M600_filament_change_z_shift()
  3020. {
  3021. #ifdef FILAMENTCHANGE_ZADD
  3022. static_assert(Z_MAX_POS < (255 - FILAMENTCHANGE_ZADD), "Z-range too high, change the T type from uint8_t to uint16_t");
  3023. // avoid floating point arithmetics when not necessary - results in shorter code
  3024. T z_shift = T(FILAMENTCHANGE_ZADD); // always move above printout
  3025. T ztmp = T( current_position[Z_AXIS] );
  3026. if((ztmp + z_shift) < T(MIN_Z_FOR_SWAP)){
  3027. z_shift = T(MIN_Z_FOR_SWAP) - ztmp; // make sure to be at least 25mm above the heat bed
  3028. }
  3029. return z_shift;
  3030. #else
  3031. return T(0);
  3032. #endif
  3033. }
  3034. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/) {
  3035. st_synchronize();
  3036. float lastpos[4];
  3037. prusa_statistics(22);
  3038. //First backup current position and settings
  3039. int feedmultiplyBckp = feedmultiply;
  3040. float HotendTempBckp = degTargetHotend(active_extruder);
  3041. int fanSpeedBckp = fanSpeed;
  3042. lastpos[X_AXIS] = current_position[X_AXIS];
  3043. lastpos[Y_AXIS] = current_position[Y_AXIS];
  3044. lastpos[Z_AXIS] = current_position[Z_AXIS];
  3045. lastpos[E_AXIS] = current_position[E_AXIS];
  3046. // Retract E
  3047. current_position[E_AXIS] += e_shift;
  3048. plan_buffer_line_curposXYZE(FILAMENTCHANGE_RFEED);
  3049. st_synchronize();
  3050. // Lift Z
  3051. current_position[Z_AXIS] += z_shift;
  3052. clamp_to_software_endstops(current_position);
  3053. plan_buffer_line_curposXYZE(FILAMENTCHANGE_ZFEED);
  3054. st_synchronize();
  3055. // Move XY to side
  3056. current_position[X_AXIS] = x_position;
  3057. current_position[Y_AXIS] = y_position;
  3058. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3059. st_synchronize();
  3060. // Beep, manage nozzle heater and wait for user to start unload filament
  3061. if (!MMU2::mmu2.Enabled())
  3062. M600_wait_for_user(HotendTempBckp);
  3063. lcd_change_fil_state = 0;
  3064. // Unload filament
  3065. if (MMU2::mmu2.Enabled())
  3066. MMU2::mmu2.unload(); // unload just current filament for multimaterial printers (used also in M702)
  3067. else
  3068. unload_filament(true); // unload filament for single material (used also in M702)
  3069. st_synchronize(); // finish moves
  3070. #ifdef FILAMENT_SENSOR
  3071. fsensor.setRunoutEnabled(false); //suppress filament runouts while loading filament.
  3072. fsensor.setAutoLoadEnabled(false); //suppress filament autoloads while loading filament.
  3073. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  3074. fsensor.setJamDetectionEnabled(false); //suppress filament jam detection while loading filament.
  3075. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  3076. #endif
  3077. if (!MMU2::mmu2.Enabled()) {
  3078. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3079. lcd_change_fil_state =
  3080. lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Was filament unload successful?"), false, true); ////MSG_UNLOAD_SUCCESSFUL c=20 r=2
  3081. if (lcd_change_fil_state == 0) {
  3082. lcd_clear();
  3083. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3084. current_position[X_AXIS] -= 100;
  3085. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3086. st_synchronize();
  3087. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually."));////MSG_CHECK_IDLER c=20 r=5
  3088. }
  3089. }
  3090. if (MMU2::mmu2.Enabled()) {
  3091. if (!automatic) {
  3092. if (saved_printing){
  3093. // if M600 was invoked by filament senzor (FINDA) eject filament so user can easily remove it
  3094. MMU2::mmu2.eject_filament(MMU2::mmu2.get_current_tool(), false);
  3095. }
  3096. //@@TODO mmu_M600_wait_and_beep();
  3097. if (saved_printing) {
  3098. lcd_clear();
  3099. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3100. //@@TODO mmu_command(MmuCmd::R0);
  3101. // manage_response(false, false);
  3102. }
  3103. }
  3104. //@@TODO mmu_M600_load_filament(automatic, HotendTempBckp);
  3105. } else
  3106. M600_load_filament();
  3107. if (!automatic)
  3108. M600_check_state(HotendTempBckp);
  3109. lcd_update_enable(true);
  3110. // Not let's go back to print
  3111. fanSpeed = fanSpeedBckp;
  3112. // Feed a little of filament to stabilize pressure
  3113. if (!automatic) {
  3114. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  3115. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EXFEED);
  3116. }
  3117. // Move XY back
  3118. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  3119. st_synchronize();
  3120. // Move Z back
  3121. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  3122. st_synchronize();
  3123. // Set E position to original
  3124. plan_set_e_position(lastpos[E_AXIS]);
  3125. memcpy(current_position, lastpos, sizeof(lastpos));
  3126. set_destination_to_current();
  3127. // Recover feed rate
  3128. feedmultiply = feedmultiplyBckp;
  3129. char cmd[9];
  3130. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3131. enquecommand(cmd);
  3132. #ifdef FILAMENT_SENSOR
  3133. fsensor.settings_init();
  3134. #endif
  3135. lcd_setstatuspgm(MSG_WELCOME);
  3136. custom_message_type = CustomMsg::Status;
  3137. }
  3138. void gcode_M701(uint8_t mmuSlotIndex){
  3139. printf_P(PSTR("gcode_M701 begin\n"));
  3140. #ifdef FILAMENT_SENSOR
  3141. fsensor.setRunoutEnabled(false); // suppress filament runouts while loading filament.
  3142. fsensor.setAutoLoadEnabled(false); // suppress filament autoloads while loading filament.
  3143. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  3144. fsensor.setJamDetectionEnabled(false); // suppress filament jam detection while loading filament.
  3145. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  3146. #endif
  3147. prusa_statistics(22);
  3148. }
  3149. if (MMU2::mmu2.Enabled() && mmuSlotIndex < MMU_FILAMENT_COUNT) {
  3150. MMU2::mmu2.load_filament(mmuSlotIndex); // loads current extruder
  3151. // mmu_extruder = mmuSlotIndex; // @@TODO shall load filament set current tool to some specific index? We don't do that anymore.
  3152. } else {
  3153. enable_z();
  3154. custom_message_type = CustomMsg::FilamentLoading;
  3155. const int feed_mm_before_raising = 30;
  3156. static_assert(feed_mm_before_raising <= FILAMENTCHANGE_FIRSTFEED);
  3157. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  3158. current_position[E_AXIS] += FILAMENTCHANGE_FIRSTFEED - feed_mm_before_raising;
  3159. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST); //fast sequence
  3160. st_synchronize();
  3161. raise_z_above(MIN_Z_FOR_LOAD, false);
  3162. current_position[E_AXIS] += feed_mm_before_raising;
  3163. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST); //fast sequence
  3164. load_filament_final_feed(); // slow sequence
  3165. st_synchronize();
  3166. Sound_MakeCustom(50, 500, false);
  3167. if (!farm_mode && loading_flag) {
  3168. lcd_load_filament_color_check();
  3169. }
  3170. lcd_update_enable(true);
  3171. lcd_update(2);
  3172. lcd_setstatuspgm(MSG_WELCOME);
  3173. disable_z();
  3174. loading_flag = false;
  3175. custom_message_type = CustomMsg::Status;
  3176. }
  3177. eFilamentAction = FilamentAction::None;
  3178. #ifdef FILAMENT_SENSOR
  3179. fsensor.settings_init(); // restore filament runout state.
  3180. #endif
  3181. }
  3182. /**
  3183. * @brief Get serial number from 32U2 processor
  3184. *
  3185. * Typical format of S/N is:CZPX0917X003XC13518
  3186. *
  3187. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  3188. * reply is stored in *SN.
  3189. * Operation takes typically 23 ms. If no valid SN can be retrieved within the 250ms window, the function aborts
  3190. * and returns a general failure flag.
  3191. * The command will fail if the 32U2 processor is unpowered via USB since it is isolated from the rest of the electronics.
  3192. * In that case the value that is stored in the EEPROM should be used instead.
  3193. *
  3194. * @return 0 on success
  3195. * @return 1 on general failure
  3196. */
  3197. #ifdef PRUSA_SN_SUPPORT
  3198. static uint8_t get_PRUSA_SN(char* SN)
  3199. {
  3200. uint8_t selectedSerialPort_bak = selectedSerialPort;
  3201. uint8_t rxIndex;
  3202. bool SN_valid = false;
  3203. ShortTimer timeout;
  3204. selectedSerialPort = 0;
  3205. timeout.start();
  3206. while (!SN_valid)
  3207. {
  3208. rxIndex = 0;
  3209. _delay(50);
  3210. MYSERIAL.flush(); //clear RX buffer
  3211. SERIAL_ECHOLNRPGM(PSTR(";S"));
  3212. while (rxIndex < 19)
  3213. {
  3214. if (timeout.expired(250u))
  3215. goto exit;
  3216. if (MYSERIAL.available() > 0)
  3217. {
  3218. SN[rxIndex] = MYSERIAL.read();
  3219. rxIndex++;
  3220. }
  3221. }
  3222. SN[rxIndex] = 0;
  3223. // printf_P(PSTR("SN:%s\n"), SN);
  3224. SN_valid = (strncmp_P(SN, PSTR("CZPX"), 4) == 0);
  3225. }
  3226. exit:
  3227. selectedSerialPort = selectedSerialPort_bak;
  3228. return !SN_valid;
  3229. }
  3230. #endif //PRUSA_SN_SUPPORT
  3231. //! Detection of faulty RAMBo 1.1b boards equipped with bigger capacitors
  3232. //! at the TACH_1 pin, which causes bad detection of print fan speed.
  3233. //! Warning: This function is not to be used by ordinary users, it is here only for automated testing purposes,
  3234. //! it may even interfere with other functions of the printer! You have been warned!
  3235. //! The test idea is to measure the time necessary to charge the capacitor.
  3236. //! So the algorithm is as follows:
  3237. //! 1. Set TACH_1 pin to INPUT mode and LOW
  3238. //! 2. Wait a few ms
  3239. //! 3. disable interrupts and measure the time until the TACH_1 pin reaches HIGH
  3240. //! Repeat 1.-3. several times
  3241. //! Good RAMBo's times are in the range of approx. 260-320 us
  3242. //! Bad RAMBo's times are approx. 260-1200 us
  3243. //! So basically we are interested in maximum time, the minima are mostly the same.
  3244. //! May be that's why the bad RAMBo's still produce some fan RPM reading, but not corresponding to reality
  3245. static void gcode_PRUSA_BadRAMBoFanTest(){
  3246. //printf_P(PSTR("Enter fan pin test\n"));
  3247. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  3248. fan_measuring = false; // prevent EXTINT7 breaking into the measurement
  3249. unsigned long tach1max = 0;
  3250. uint8_t tach1cntr = 0;
  3251. for( /* nothing */; tach1cntr < 100; ++tach1cntr){
  3252. //printf_P(PSTR("TACH_1: %d\n"), tach1cntr);
  3253. SET_OUTPUT(TACH_1);
  3254. WRITE(TACH_1, LOW);
  3255. _delay(20); // the delay may be lower
  3256. unsigned long tachMeasure = _micros();
  3257. cli();
  3258. SET_INPUT(TACH_1);
  3259. // just wait brutally in an endless cycle until we reach HIGH
  3260. // if this becomes a problem it may be improved to non-endless cycle
  3261. while( READ(TACH_1) == 0 ) ;
  3262. sei();
  3263. tachMeasure = _micros() - tachMeasure;
  3264. if( tach1max < tachMeasure )
  3265. tach1max = tachMeasure;
  3266. //printf_P(PSTR("TACH_1: %d: capacitor check time=%lu us\n"), (int)tach1cntr, tachMeasure);
  3267. }
  3268. //printf_P(PSTR("TACH_1: max=%lu us\n"), tach1max);
  3269. SERIAL_PROTOCOLPGM("RAMBo FAN ");
  3270. if( tach1max > 500 ){
  3271. // bad RAMBo
  3272. SERIAL_PROTOCOLLNPGM("BAD");
  3273. } else {
  3274. SERIAL_PROTOCOLLNPGM("OK");
  3275. }
  3276. // cleanup after the test function
  3277. SET_INPUT(TACH_1);
  3278. WRITE(TACH_1, HIGH);
  3279. #endif
  3280. }
  3281. // G92 - Set current position to coordinates given
  3282. static void gcode_G92()
  3283. {
  3284. bool codes[NUM_AXIS];
  3285. float values[NUM_AXIS];
  3286. // Check which axes need to be set
  3287. for(uint8_t i = 0; i < NUM_AXIS; ++i)
  3288. {
  3289. codes[i] = code_seen(axis_codes[i]);
  3290. if(codes[i])
  3291. values[i] = code_value();
  3292. }
  3293. if((codes[E_AXIS] && values[E_AXIS] == 0) &&
  3294. (!codes[X_AXIS] && !codes[Y_AXIS] && !codes[Z_AXIS]))
  3295. {
  3296. // As a special optimization, when _just_ clearing the E position
  3297. // we schedule a flag asynchronously along with the next block to
  3298. // reset the starting E position instead of stopping the planner
  3299. current_position[E_AXIS] = 0;
  3300. plan_reset_next_e();
  3301. }
  3302. else
  3303. {
  3304. // In any other case we're forced to synchronize
  3305. st_synchronize();
  3306. for(uint8_t i = 0; i < 3; ++i)
  3307. {
  3308. if(codes[i])
  3309. current_position[i] = values[i] + cs.add_homing[i];
  3310. }
  3311. if(codes[E_AXIS])
  3312. current_position[E_AXIS] = values[E_AXIS];
  3313. // Set all at once
  3314. plan_set_position_curposXYZE();
  3315. }
  3316. }
  3317. #ifdef EXTENDED_CAPABILITIES_REPORT
  3318. static void cap_line(const char* name, bool ena = false) {
  3319. printf_P(PSTR("Cap:%S:%c\n"), name, (char)ena + '0');
  3320. }
  3321. static void extended_capabilities_report()
  3322. {
  3323. // AUTOREPORT_TEMP (M155)
  3324. cap_line(PSTR("AUTOREPORT_TEMP"), ENABLED(AUTO_REPORT));
  3325. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3326. // AUTOREPORT_FANS (M123)
  3327. cap_line(PSTR("AUTOREPORT_FANS"), ENABLED(AUTO_REPORT));
  3328. #endif //FANCHECK and TACH_0 or TACH_1
  3329. // AUTOREPORT_POSITION (M114)
  3330. cap_line(PSTR("AUTOREPORT_POSITION"), ENABLED(AUTO_REPORT));
  3331. // EXTENDED_M20 (support for L and T parameters)
  3332. cap_line(PSTR("EXTENDED_M20"), 1);
  3333. cap_line(PSTR("PRUSA_MMU2"), 1); //this will soon change to ENABLED(PRUSA_MMU2_SUPPORT)
  3334. }
  3335. #endif //EXTENDED_CAPABILITIES_REPORT
  3336. #ifdef BACKLASH_X
  3337. extern uint8_t st_backlash_x;
  3338. #endif //BACKLASH_X
  3339. #ifdef BACKLASH_Y
  3340. extern uint8_t st_backlash_y;
  3341. #endif //BACKLASH_Y
  3342. //! \ingroup marlin_main
  3343. //! @brief Parse and process commands
  3344. //!
  3345. //! look here for descriptions of G-codes: https://reprap.org/wiki/G-code
  3346. //!
  3347. //!
  3348. //! Implemented Codes
  3349. //! -------------------
  3350. //!
  3351. //! * _This list is not updated. Current documentation is maintained inside the process_cmd function._
  3352. //!
  3353. //!@n PRUSA CODES
  3354. //!@n P F - Returns FW versions
  3355. //!@n P R - Returns revision of printer
  3356. //!
  3357. //!@n G0 -> G1
  3358. //!@n G1 - Coordinated Movement X Y Z E
  3359. //!@n G2 - CW ARC
  3360. //!@n G3 - CCW ARC
  3361. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  3362. //!@n G10 - retract filament according to settings of M207
  3363. //!@n G11 - retract recover filament according to settings of M208
  3364. //!@n G28 - Home all Axes
  3365. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  3366. //!@n G30 - Single Z Probe, probes bed at current XY location.
  3367. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  3368. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  3369. //!@n G80 - Automatic mesh bed leveling
  3370. //!@n G81 - Print bed profile
  3371. //!@n G90 - Use Absolute Coordinates
  3372. //!@n G91 - Use Relative Coordinates
  3373. //!@n G92 - Set current position to coordinates given
  3374. //!
  3375. //!@n M Codes
  3376. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  3377. //!@n M1 - Same as M0
  3378. //!@n M17 - Enable/Power all stepper motors
  3379. //!@n M18 - Disable all stepper motors; same as M84
  3380. //!@n M20 - List SD card
  3381. //!@n M21 - Init SD card
  3382. //!@n M22 - Release SD card
  3383. //!@n M23 - Select SD file (M23 filename.g)
  3384. //!@n M24 - Start/resume SD print
  3385. //!@n M25 - Pause SD print
  3386. //!@n M26 - Set SD position in bytes (M26 S12345)
  3387. //!@n M27 - Report SD print status
  3388. //!@n M28 - Start SD write (M28 filename.g)
  3389. //!@n M29 - Stop SD write
  3390. //!@n M30 - Delete file from SD (M30 filename.g)
  3391. //!@n M31 - Output time since last M109 or SD card start to serial
  3392. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  3393. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  3394. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  3395. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  3396. //!@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.
  3397. //!@n M73 - Show percent done and print time remaining
  3398. //!@n M80 - Turn on Power Supply
  3399. //!@n M81 - Turn off Power Supply
  3400. //!@n M82 - Set E codes absolute (default)
  3401. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  3402. //!@n M84 - Disable steppers until next move,
  3403. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  3404. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3405. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  3406. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  3407. //!@n M104 - Set extruder target temp
  3408. //!@n M105 - Read current temp
  3409. //!@n M106 - Fan on
  3410. //!@n M107 - Fan off
  3411. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  3412. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  3413. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  3414. //!@n M112 - Emergency stop
  3415. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  3416. //!@n M114 - Output current position to serial port
  3417. //!@n M115 - Capabilities string
  3418. //!@n M117 - display message
  3419. //!@n M119 - Output Endstop status to serial port
  3420. //!@n M123 - Tachometer value
  3421. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  3422. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  3423. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3424. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3425. //!@n M140 - Set bed target temp
  3426. //!@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.
  3427. //!@n M155 - Automatically send temperatures, fan speeds, position
  3428. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3429. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3430. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3431. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3432. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  3433. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3434. //!@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
  3435. //!@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
  3436. //!@n M206 - set additional homing offset
  3437. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  3438. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  3439. //!@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.
  3440. //!@n M214 - Set Arc Parameters (Use M500 to store in eeprom) P<MM_PER_ARC_SEGMENT> S<MIN_MM_PER_ARC_SEGMENT> R<MIN_ARC_SEGMENTS> F<ARC_SEGMENTS_PER_SEC>
  3441. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3442. //!@n M220 S<factor in percent>- set speed factor override percentage
  3443. //!@n M221 S<factor in percent>- set extrude factor override percentage
  3444. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3445. //!@n M240 - Trigger a camera to take a photograph
  3446. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  3447. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3448. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  3449. //!@n M301 - Set PID parameters P I and D
  3450. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  3451. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  3452. //!@n M304 - Set bed PID parameters P I and D
  3453. //!@n M310 - Temperature model settings
  3454. //!@n M400 - Finish all moves
  3455. //!@n M401 - Lower z-probe if present
  3456. //!@n M402 - Raise z-probe if present
  3457. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  3458. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  3459. //!@n M406 - Turn off Filament Sensor extrusion control
  3460. //!@n M407 - Displays measured filament diameter
  3461. //!@n M500 - stores parameters in EEPROM
  3462. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  3463. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  3464. //!@n M503 - print the current settings (from memory not from EEPROM)
  3465. //!@n M509 - force language selection on next restart
  3466. //!@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)
  3467. //!@n M552 - Set IP address
  3468. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3469. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  3470. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  3471. //!@n M861 - Set / Read PINDA temperature compensation offsets
  3472. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  3473. //!@n M907 - Set digital trimpot motor current using axis codes.
  3474. //!@n M908 - Control digital trimpot directly.
  3475. //!@n M350 - Set microstepping mode.
  3476. //!@n M351 - Toggle MS1 MS2 pins directly.
  3477. //!
  3478. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  3479. //!@n M999 - Restart after being stopped by error
  3480. //! <br><br>
  3481. /** @defgroup marlin_main Marlin main */
  3482. /** \ingroup GCodes */
  3483. //! _This is a list of currently implemented G Codes in Prusa firmware (dynamically generated from doxygen)._
  3484. /**
  3485. They are shown in order of appearance in the code.
  3486. There are reasons why some G Codes aren't in numerical order.
  3487. */
  3488. void process_commands()
  3489. {
  3490. if (!buflen) return; //empty command
  3491. #ifdef CMDBUFFER_DEBUG
  3492. SERIAL_ECHOPGM("Processing a GCODE command: ");
  3493. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  3494. SERIAL_ECHOLNPGM("");
  3495. SERIAL_ECHOPGM("In cmdqueue: ");
  3496. SERIAL_ECHO(buflen);
  3497. SERIAL_ECHOLNPGM("");
  3498. #endif /* CMDBUFFER_DEBUG */
  3499. unsigned long codenum; //throw away variable
  3500. char *starpos = NULL;
  3501. #ifdef ENABLE_AUTO_BED_LEVELING
  3502. float x_tmp, y_tmp, z_tmp, real_z;
  3503. #endif
  3504. // PRUSA GCODES
  3505. KEEPALIVE_STATE(IN_HANDLER);
  3506. /*!
  3507. ---------------------------------------------------------------------------------
  3508. ### M117 - Display Message <a href="https://reprap.org/wiki/G-code#M117:_Display_Message">M117: Display Message</a>
  3509. This causes the given message to be shown in the status line on an attached LCD.
  3510. It is processed early as to allow printing messages that contain G, M, N or T.
  3511. ---------------------------------------------------------------------------------
  3512. ### Special internal commands
  3513. These are used by internal functions to process certain actions in the right order. Some of these are also usable by the user.
  3514. They are processed early as the commands are complex (strings).
  3515. These are only available on the MK3(S) as these require TMC2130 drivers:
  3516. - CRASH DETECTED
  3517. - CRASH RECOVER
  3518. - CRASH_CANCEL
  3519. - TMC_SET_WAVE
  3520. - TMC_SET_STEP
  3521. - TMC_SET_CHOP
  3522. */
  3523. if (code_seen_P(PSTR("M117"))) //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  3524. {
  3525. starpos = (strchr(strchr_pointer + 5, '*'));
  3526. if (starpos != NULL)
  3527. *(starpos) = '\0';
  3528. lcd_setstatus(strchr_pointer + 5);
  3529. custom_message_type = CustomMsg::M117;
  3530. }
  3531. /*!
  3532. ### M0, M1 - Stop the printer <a href="https://reprap.org/wiki/G-code#M0:_Stop_or_Unconditional_stop">M0: Stop or Unconditional stop</a>
  3533. #### Usage
  3534. M0 [P<ms<] [S<sec>] [string]
  3535. M1 [P<ms>] [S<sec>] [string]
  3536. #### Parameters
  3537. - `P<ms>` - Expire time, in milliseconds
  3538. - `S<sec>` - Expire time, in seconds
  3539. - `string` - Must for M1 and optional for M0 message to display on the LCD
  3540. */
  3541. else if (code_seen_P(PSTR("M0")) || code_seen_P(PSTR("M1 "))) {// M0 and M1 - (Un)conditional stop - Wait for user button press on LCD
  3542. const char *src = strchr_pointer + 2;
  3543. codenum = 0;
  3544. bool hasP = false, hasS = false;
  3545. if (code_seen('P')) {
  3546. codenum = code_value_long(); // milliseconds to wait
  3547. hasP = codenum > 0;
  3548. }
  3549. if (code_seen('S')) {
  3550. codenum = code_value_long() * 1000; // seconds to wait
  3551. hasS = codenum > 0;
  3552. }
  3553. starpos = strchr(src, '*');
  3554. if (starpos != NULL) *(starpos) = '\0';
  3555. while (*src == ' ') ++src;
  3556. custom_message_type = CustomMsg::M0Wait;
  3557. if (!hasP && !hasS && *src != '\0') {
  3558. lcd_setstatus(src);
  3559. } else {
  3560. // farmers want to abuse a bug from the previous firmware releases
  3561. // - they need to see the filename on the status screen instead of "Wait for user..."
  3562. // So we won't update the message in farm mode...
  3563. if( ! farm_mode){
  3564. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT c=20
  3565. } else {
  3566. custom_message_type = CustomMsg::Status; // let the lcd display the name of the printed G-code file in farm mode
  3567. }
  3568. }
  3569. lcd_ignore_click(); //call lcd_ignore_click also for else ???
  3570. st_synchronize();
  3571. previous_millis_cmd.start();
  3572. if (codenum > 0 ) {
  3573. codenum += _millis(); // keep track of when we started waiting
  3574. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3575. while(_millis() < codenum && !lcd_clicked()) {
  3576. manage_heater();
  3577. manage_inactivity(true);
  3578. lcd_update(0);
  3579. }
  3580. KEEPALIVE_STATE(IN_HANDLER);
  3581. lcd_ignore_click(false);
  3582. } else {
  3583. marlin_wait_for_click();
  3584. }
  3585. if (IS_SD_PRINTING)
  3586. custom_message_type = CustomMsg::Status;
  3587. else
  3588. LCD_MESSAGERPGM(MSG_WELCOME);
  3589. }
  3590. #ifdef TMC2130
  3591. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  3592. {
  3593. // ### CRASH_DETECTED - TMC2130
  3594. // ---------------------------------
  3595. if(code_seen_P(PSTR("CRASH_DETECTED")))
  3596. {
  3597. uint8_t mask = 0;
  3598. if (code_seen('X')) mask |= X_AXIS_MASK;
  3599. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  3600. crashdet_detected(mask);
  3601. }
  3602. // ### CRASH_RECOVER - TMC2130
  3603. // ----------------------------------
  3604. else if(code_seen_P(PSTR("CRASH_RECOVER")))
  3605. crashdet_recover();
  3606. // ### CRASH_CANCEL - TMC2130
  3607. // ----------------------------------
  3608. else if(code_seen_P(PSTR("CRASH_CANCEL")))
  3609. crashdet_cancel();
  3610. }
  3611. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3612. {
  3613. // ### TMC_SET_WAVE_
  3614. // --------------------
  3615. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0)
  3616. {
  3617. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3618. axis = (axis == 'E')?3:(axis - 'X');
  3619. if (axis < 4)
  3620. {
  3621. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3622. tmc2130_set_wave(axis, 247, fac);
  3623. }
  3624. }
  3625. // ### TMC_SET_STEP_
  3626. // ------------------
  3627. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0)
  3628. {
  3629. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3630. axis = (axis == 'E')?3:(axis - 'X');
  3631. if (axis < 4)
  3632. {
  3633. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3634. uint16_t res = tmc2130_get_res(axis);
  3635. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3636. }
  3637. }
  3638. // ### TMC_SET_CHOP_
  3639. // -------------------
  3640. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0)
  3641. {
  3642. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3643. axis = (axis == 'E')?3:(axis - 'X');
  3644. if (axis < 4)
  3645. {
  3646. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  3647. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3648. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3649. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3650. char* str_end = 0;
  3651. if (CMDBUFFER_CURRENT_STRING[14])
  3652. {
  3653. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3654. if (str_end && *str_end)
  3655. {
  3656. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3657. if (str_end && *str_end)
  3658. {
  3659. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3660. if (str_end && *str_end)
  3661. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3662. }
  3663. }
  3664. }
  3665. tmc2130_chopper_config[axis].toff = chop0;
  3666. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3667. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3668. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3669. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3670. //printf_P(_N("TMC_SET_CHOP_%c %d %d %d %d\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3671. }
  3672. }
  3673. }
  3674. #ifdef BACKLASH_X
  3675. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3676. {
  3677. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3678. st_backlash_x = bl;
  3679. printf_P(_N("st_backlash_x = %d\n"), st_backlash_x);
  3680. }
  3681. #endif //BACKLASH_X
  3682. #ifdef BACKLASH_Y
  3683. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3684. {
  3685. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3686. st_backlash_y = bl;
  3687. printf_P(_N("st_backlash_y = %d\n"), st_backlash_y);
  3688. }
  3689. #endif //BACKLASH_Y
  3690. #endif //TMC2130
  3691. else if(code_seen_P(PSTR("PRUSA"))){
  3692. /*!
  3693. ---------------------------------------------------------------------------------
  3694. ### PRUSA - Internal command set <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode - Notes</a>
  3695. Set of internal PRUSA commands
  3696. #### Usage
  3697. PRUSA [ PRN | FAN | thx | uvlo | MMURES | RESET | fv | M28 | SN | Fir | Rev | Lang | Lz | FR ]
  3698. #### Parameters
  3699. - `PRN` - Prints revision of the printer
  3700. - `FAN` - Prints fan details
  3701. - `thx`
  3702. - `uvlo`
  3703. - `MMURES` - Reset MMU
  3704. - `RESET` - (Careful!)
  3705. - `fv` - ?
  3706. - `M28`
  3707. - `SN`
  3708. - `Fir` - Prints firmware version
  3709. - `Rev`- Prints filament size, elelectronics, nozzle type
  3710. - `Lang` - Reset the language
  3711. - `Lz`
  3712. - `FR` - Full factory reset
  3713. - `nozzle set <diameter>` - set nozzle diameter (farm mode only), e.g. `PRUSA nozzle set 0.4`
  3714. - `nozzle D<diameter>` - check the nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle D0.4`
  3715. - `nozzle` - prints nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle`
  3716. */
  3717. if (farm_prusa_code_seen()) {}
  3718. else if(code_seen_P(PSTR("FANPINTST"))) {
  3719. gcode_PRUSA_BadRAMBoFanTest();
  3720. }
  3721. else if (code_seen_P(PSTR("FAN"))) { // PRUSA FAN
  3722. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3723. }
  3724. else if (code_seen_P(PSTR("uvlo"))) { // PRUSA uvlo
  3725. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3726. enquecommand_P(PSTR("M24"));
  3727. }
  3728. else if (code_seen_P(PSTR("MMURES"))) // PRUSA MMURES
  3729. {
  3730. MMU2::mmu2.Reset(MMU2::MMU2::Software);
  3731. }
  3732. else if (code_seen_P(PSTR("RESET"))) { // PRUSA RESET
  3733. #ifdef WATCHDOG
  3734. #if defined(XFLASH) && defined(BOOTAPP)
  3735. boot_app_magic = BOOT_APP_MAGIC;
  3736. boot_app_flags = BOOT_APP_FLG_RUN;
  3737. #endif //defined(XFLASH) && defined(BOOTAPP)
  3738. softReset();
  3739. #elif defined(BOOTAPP) //this is a safety precaution. This is because the new bootloader turns off the heaters, but the old one doesn't. The watchdog should be used most of the time.
  3740. asm volatile("jmp 0x3E000");
  3741. #endif
  3742. }
  3743. #ifdef PRUSA_SN_SUPPORT
  3744. else if (code_seen_P(PSTR("SN"))) { // PRUSA SN
  3745. char SN[20];
  3746. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  3747. if (SN[19])
  3748. puts_P(PSTR("SN invalid"));
  3749. else
  3750. puts(SN);
  3751. }
  3752. #endif //PRUSA_SN_SUPPORT
  3753. else if(code_seen_P(PSTR("Fir"))){ // PRUSA Fir
  3754. SERIAL_PROTOCOLLN(FW_VERSION_FULL);
  3755. } else if(code_seen_P(PSTR("Rev"))){ // PRUSA Rev
  3756. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3757. } else if(code_seen_P(PSTR("Lang"))) { // PRUSA Lang
  3758. lang_reset();
  3759. } else if(code_seen_P(PSTR("Lz"))) { // PRUSA Lz
  3760. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  3761. } else if(code_seen_P(PSTR("FR"))) { // PRUSA FR
  3762. // Factory full reset
  3763. factory_reset(0);
  3764. } else if(code_seen_P(PSTR("MBL"))) { // PRUSA MBL
  3765. // Change the MBL status without changing the logical Z position.
  3766. if(code_seen('V')) {
  3767. bool value = code_value_short();
  3768. st_synchronize();
  3769. if(value != mbl.active) {
  3770. mbl.active = value;
  3771. // Use plan_set_z_position to reset the physical values
  3772. plan_set_z_position(current_position[Z_AXIS]);
  3773. }
  3774. }
  3775. //-//
  3776. /*
  3777. } else if(code_seen("rrr")) {
  3778. MYSERIAL.println("=== checking ===");
  3779. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_CHECK_MODE),DEC);
  3780. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER),DEC);
  3781. MYSERIAL.println(eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM),DEC);
  3782. MYSERIAL.println(farm_mode,DEC);
  3783. MYSERIAL.println(eCheckMode,DEC);
  3784. } else if(code_seen("www")) {
  3785. MYSERIAL.println("=== @ FF ===");
  3786. eeprom_update_byte((uint8_t*)EEPROM_CHECK_MODE,0xFF);
  3787. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,0xFF);
  3788. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,0xFFFF);
  3789. */
  3790. } else if (code_seen_P(PSTR("nozzle"))) { // PRUSA nozzle
  3791. uint16_t nDiameter;
  3792. if(code_seen('D'))
  3793. {
  3794. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3795. nozzle_diameter_check(nDiameter);
  3796. }
  3797. else if(code_seen_P(PSTR("set")) && farm_mode)
  3798. {
  3799. strchr_pointer++; // skip 1st char (~ 's')
  3800. strchr_pointer++; // skip 2nd char (~ 'e')
  3801. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3802. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  3803. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  3804. }
  3805. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  3806. //-// !!! SupportMenu
  3807. /*
  3808. // musi byt PRED "PRUSA model"
  3809. } else if (code_seen("smodel")) { //! PRUSA smodel
  3810. size_t nOffset;
  3811. // ! -> "l"
  3812. strchr_pointer+=5*sizeof(*strchr_pointer); // skip 1st - 5th char (~ 'smode')
  3813. nOffset=strspn(strchr_pointer+1," \t\n\r\v\f");
  3814. if(*(strchr_pointer+1+nOffset))
  3815. printer_smodel_check(strchr_pointer);
  3816. else SERIAL_PROTOCOLLN(PRINTER_NAME);
  3817. } else if (code_seen("model")) { //! PRUSA model
  3818. uint16_t nPrinterModel;
  3819. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'mode')
  3820. nPrinterModel=(uint16_t)code_value_long();
  3821. if(nPrinterModel!=0)
  3822. printer_model_check(nPrinterModel);
  3823. else SERIAL_PROTOCOLLN(PRINTER_TYPE);
  3824. } else if (code_seen("version")) { //! PRUSA version
  3825. strchr_pointer+=7*sizeof(*strchr_pointer); // skip 1st - 7th char (~ 'version')
  3826. while(*strchr_pointer==' ') // skip leading spaces
  3827. strchr_pointer++;
  3828. if(*strchr_pointer!=0)
  3829. fw_version_check(strchr_pointer);
  3830. else SERIAL_PROTOCOLLN(FW_VERSION);
  3831. } else if (code_seen("gcode")) { //! PRUSA gcode
  3832. uint16_t nGcodeLevel;
  3833. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'gcod')
  3834. nGcodeLevel=(uint16_t)code_value_long();
  3835. if(nGcodeLevel!=0)
  3836. gcode_level_check(nGcodeLevel);
  3837. else SERIAL_PROTOCOLLN(GCODE_LEVEL);
  3838. */
  3839. }
  3840. //else if (code_seen('Cal')) {
  3841. // lcd_calibration();
  3842. // }
  3843. }
  3844. // This prevents reading files with "^" in their names.
  3845. // Since it is unclear, if there is some usage of this construct,
  3846. // it will be deprecated in 3.9 alpha a possibly completely removed in the future:
  3847. // else if (code_seen('^')) {
  3848. // // nothing, this is a version line
  3849. // }
  3850. else if(code_seen('G'))
  3851. {
  3852. gcode_in_progress = code_value_short();
  3853. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3854. switch (gcode_in_progress)
  3855. {
  3856. /*!
  3857. ---------------------------------------------------------------------------------
  3858. # G Codes
  3859. ### G0, G1 - Coordinated movement X Y Z E <a href="https://reprap.org/wiki/G-code#G0_.26_G1:_Move">G0 & G1: Move</a>
  3860. In Prusa Firmware G0 and G1 are the same.
  3861. #### Usage
  3862. G0 [ X | Y | Z | E | F | S ]
  3863. G1 [ X | Y | Z | E | F | S ]
  3864. #### Parameters
  3865. - `X` - The position to move to on the X axis
  3866. - `Y` - The position to move to on the Y axis
  3867. - `Z` - The position to move to on the Z axis
  3868. - `E` - The amount to extrude between the starting point and ending point
  3869. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3870. */
  3871. case 0: // G0 -> G1
  3872. case 1: // G1
  3873. {
  3874. uint16_t start_segment_idx = restore_interrupted_gcode();
  3875. get_coordinates(); // For X Y Z E F
  3876. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3877. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3878. }
  3879. #ifdef FWRETRACT
  3880. if(cs.autoretract_enabled) {
  3881. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3882. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3883. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3884. st_synchronize();
  3885. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3886. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3887. retract(!retracted[active_extruder]);
  3888. return;
  3889. }
  3890. }
  3891. }
  3892. #endif //FWRETRACT
  3893. prepare_move(start_segment_idx);
  3894. //ClearToSend();
  3895. }
  3896. break;
  3897. /*!
  3898. ### 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>
  3899. These commands don't propperly work with MBL enabled. The compensation only happens at the end of the move, so avoid long arcs.
  3900. #### Usage
  3901. G2 [ X | Y | I | E | F ] (Clockwise Arc)
  3902. G3 [ X | Y | I | E | F ] (Counter-Clockwise Arc)
  3903. #### Parameters
  3904. - `X` - The position to move to on the X axis
  3905. - `Y` - The position to move to on the Y axis
  3906. - 'Z' - The position to move to on the Z axis
  3907. - `I` - The point in X space from the current X position to maintain a constant distance from
  3908. - `J` - The point in Y space from the current Y position to maintain a constant distance from
  3909. - `E` - The amount to extrude between the starting point and ending point
  3910. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3911. */
  3912. case 2:
  3913. case 3:
  3914. {
  3915. uint16_t start_segment_idx = restore_interrupted_gcode();
  3916. #ifdef SF_ARC_FIX
  3917. bool relative_mode_backup = relative_mode;
  3918. relative_mode = true;
  3919. #endif
  3920. get_coordinates(); // For X Y Z E F
  3921. #ifdef SF_ARC_FIX
  3922. relative_mode=relative_mode_backup;
  3923. #endif
  3924. offset[0] = code_seen('I') ? code_value() : 0.f;
  3925. offset[1] = code_seen('J') ? code_value() : 0.f;
  3926. prepare_arc_move((gcode_in_progress == 2), start_segment_idx);
  3927. } break;
  3928. /*!
  3929. ### G4 - Dwell <a href="https://reprap.org/wiki/G-code#G4:_Dwell">G4: Dwell</a>
  3930. Pause the machine for a period of time.
  3931. #### Usage
  3932. G4 [ P | S ]
  3933. #### Parameters
  3934. - `P` - Time to wait, in milliseconds
  3935. - `S` - Time to wait, in seconds
  3936. */
  3937. case 4:
  3938. codenum = 0;
  3939. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3940. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3941. if(codenum != 0)
  3942. {
  3943. if(custom_message_type != CustomMsg::M117)
  3944. {
  3945. LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  3946. }
  3947. }
  3948. st_synchronize();
  3949. codenum += _millis(); // keep track of when we started waiting
  3950. previous_millis_cmd.start();
  3951. while(_millis() < codenum) {
  3952. manage_heater();
  3953. manage_inactivity();
  3954. lcd_update(0);
  3955. }
  3956. break;
  3957. #ifdef FWRETRACT
  3958. /*!
  3959. ### G10 - Retract <a href="https://reprap.org/wiki/G-code#G10:_Retract">G10: Retract</a>
  3960. Retracts filament according to settings of `M207`
  3961. */
  3962. case 10:
  3963. #if EXTRUDERS > 1
  3964. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  3965. retract(true,retracted_swap[active_extruder]);
  3966. #else
  3967. retract(true);
  3968. #endif
  3969. break;
  3970. /*!
  3971. ### G11 - Retract recover <a href="https://reprap.org/wiki/G-code#G11:_Unretract">G11: Unretract</a>
  3972. Unretracts/recovers filament according to settings of `M208`
  3973. */
  3974. case 11:
  3975. #if EXTRUDERS > 1
  3976. retract(false,retracted_swap[active_extruder]);
  3977. #else
  3978. retract(false);
  3979. #endif
  3980. break;
  3981. #endif //FWRETRACT
  3982. /*!
  3983. ### G21 - Sets Units to Millimters <a href="https://reprap.org/wiki/G-code#G21:_Set_Units_to_Millimeters">G21: Set Units to Millimeters</a>
  3984. Units are in millimeters. Prusa doesn't support inches.
  3985. */
  3986. case 21:
  3987. break; //Doing nothing. This is just to prevent serial UNKOWN warnings.
  3988. /*!
  3989. ### 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>
  3990. 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).
  3991. #### Usage
  3992. G28 [ X | Y | Z | W | C ]
  3993. #### Parameters
  3994. - `X` - Flag to go back to the X axis origin
  3995. - `Y` - Flag to go back to the Y axis origin
  3996. - `Z` - Flag to go back to the Z axis origin
  3997. - `W` - Suppress mesh bed leveling if `X`, `Y` or `Z` are not provided
  3998. - `C` - Calibrate X and Y origin (home) - Only on MK3/s
  3999. */
  4000. case 28:
  4001. {
  4002. long home_x_value = 0;
  4003. long home_y_value = 0;
  4004. long home_z_value = 0;
  4005. // Which axes should be homed?
  4006. bool home_x = code_seen(axis_codes[X_AXIS]);
  4007. if (home_x) home_x_value = code_value_long();
  4008. bool home_y = code_seen(axis_codes[Y_AXIS]);
  4009. if (home_y) home_y_value = code_value_long();
  4010. bool home_z = code_seen(axis_codes[Z_AXIS]);
  4011. if (home_z) home_z_value = code_value_long();
  4012. bool without_mbl = code_seen('W');
  4013. // calibrate?
  4014. #ifdef TMC2130
  4015. bool calib = code_seen('C');
  4016. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  4017. #else
  4018. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  4019. #endif //TMC2130
  4020. if ((home_x || home_y || without_mbl || home_z) == false) {
  4021. gcode_G80();
  4022. }
  4023. break;
  4024. }
  4025. #ifdef ENABLE_AUTO_BED_LEVELING
  4026. /*!
  4027. ### G29 - Detailed Z-Probe <a href="https://reprap.org/wiki/G-code#G29:_Detailed_Z-Probe">G29: Detailed Z-Probe</a>
  4028. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4029. See `G81`
  4030. */
  4031. case 29:
  4032. {
  4033. #if Z_MIN_PIN == -1
  4034. #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."
  4035. #endif
  4036. // Prevent user from running a G29 without first homing in X and Y
  4037. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  4038. {
  4039. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  4040. SERIAL_ECHO_START;
  4041. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  4042. break; // abort G29, since we don't know where we are
  4043. }
  4044. st_synchronize();
  4045. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  4046. //vector_3 corrected_position = plan_get_position_mm();
  4047. //corrected_position.debug("position before G29");
  4048. plan_bed_level_matrix.set_to_identity();
  4049. vector_3 uncorrected_position = plan_get_position();
  4050. //uncorrected_position.debug("position durring G29");
  4051. current_position[X_AXIS] = uncorrected_position.x;
  4052. current_position[Y_AXIS] = uncorrected_position.y;
  4053. current_position[Z_AXIS] = uncorrected_position.z;
  4054. plan_set_position_curposXYZE();
  4055. int l_feedmultiply = setup_for_endstop_move();
  4056. feedrate = homing_feedrate[Z_AXIS];
  4057. #ifdef AUTO_BED_LEVELING_GRID
  4058. // probe at the points of a lattice grid
  4059. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4060. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4061. // solve the plane equation ax + by + d = z
  4062. // A is the matrix with rows [x y 1] for all the probed points
  4063. // B is the vector of the Z positions
  4064. // 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
  4065. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4066. // "A" matrix of the linear system of equations
  4067. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  4068. // "B" vector of Z points
  4069. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  4070. int probePointCounter = 0;
  4071. bool zig = true;
  4072. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  4073. {
  4074. int xProbe, xInc;
  4075. if (zig)
  4076. {
  4077. xProbe = LEFT_PROBE_BED_POSITION;
  4078. //xEnd = RIGHT_PROBE_BED_POSITION;
  4079. xInc = xGridSpacing;
  4080. zig = false;
  4081. } else // zag
  4082. {
  4083. xProbe = RIGHT_PROBE_BED_POSITION;
  4084. //xEnd = LEFT_PROBE_BED_POSITION;
  4085. xInc = -xGridSpacing;
  4086. zig = true;
  4087. }
  4088. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  4089. {
  4090. float z_before;
  4091. if (probePointCounter == 0)
  4092. {
  4093. // raise before probing
  4094. z_before = Z_RAISE_BEFORE_PROBING;
  4095. } else
  4096. {
  4097. // raise extruder
  4098. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  4099. }
  4100. float measured_z = probe_pt(xProbe, yProbe, z_before);
  4101. eqnBVector[probePointCounter] = measured_z;
  4102. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  4103. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  4104. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  4105. probePointCounter++;
  4106. xProbe += xInc;
  4107. }
  4108. }
  4109. clean_up_after_endstop_move(l_feedmultiply);
  4110. // solve lsq problem
  4111. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  4112. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4113. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  4114. SERIAL_PROTOCOLPGM(" b: ");
  4115. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  4116. SERIAL_PROTOCOLPGM(" d: ");
  4117. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  4118. set_bed_level_equation_lsq(plane_equation_coefficients);
  4119. free(plane_equation_coefficients);
  4120. #else // AUTO_BED_LEVELING_GRID not defined
  4121. // Probe at 3 arbitrary points
  4122. // probe 1
  4123. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  4124. // probe 2
  4125. 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);
  4126. // probe 3
  4127. 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);
  4128. clean_up_after_endstop_move(l_feedmultiply);
  4129. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  4130. #endif // AUTO_BED_LEVELING_GRID
  4131. st_synchronize();
  4132. // The following code correct the Z height difference from z-probe position and hotend tip position.
  4133. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  4134. // When the bed is uneven, this height must be corrected.
  4135. 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)
  4136. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  4137. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4138. z_tmp = current_position[Z_AXIS];
  4139. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  4140. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  4141. plan_set_position_curposXYZE();
  4142. }
  4143. break;
  4144. #ifndef Z_PROBE_SLED
  4145. /*!
  4146. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4147. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4148. */
  4149. case 30:
  4150. {
  4151. st_synchronize();
  4152. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4153. int l_feedmultiply = setup_for_endstop_move();
  4154. feedrate = homing_feedrate[Z_AXIS];
  4155. run_z_probe();
  4156. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  4157. SERIAL_PROTOCOLPGM(" X: ");
  4158. SERIAL_PROTOCOL(current_position[X_AXIS]);
  4159. SERIAL_PROTOCOLPGM(" Y: ");
  4160. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  4161. SERIAL_PROTOCOLPGM(" Z: ");
  4162. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  4163. SERIAL_PROTOCOLPGM("\n");
  4164. clean_up_after_endstop_move(l_feedmultiply);
  4165. }
  4166. break;
  4167. #else
  4168. /*!
  4169. ### G31 - Dock the sled <a href="https://reprap.org/wiki/G-code#G31:_Dock_Z_Probe_sled">G31: Dock Z Probe sled</a>
  4170. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4171. */
  4172. case 31:
  4173. dock_sled(true);
  4174. break;
  4175. /*!
  4176. ### G32 - Undock the sled <a href="https://reprap.org/wiki/G-code#G32:_Undock_Z_Probe_sled">G32: Undock Z Probe sled</a>
  4177. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4178. */
  4179. case 32:
  4180. dock_sled(false);
  4181. break;
  4182. #endif // Z_PROBE_SLED
  4183. #endif // ENABLE_AUTO_BED_LEVELING
  4184. #ifdef MESH_BED_LEVELING
  4185. /*!
  4186. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4187. Sensor must be over the bed.
  4188. The maximum travel distance before an error is triggered is 10mm.
  4189. */
  4190. case 30:
  4191. {
  4192. st_synchronize();
  4193. homing_flag = true;
  4194. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4195. int l_feedmultiply = setup_for_endstop_move();
  4196. feedrate = homing_feedrate[Z_AXIS];
  4197. find_bed_induction_sensor_point_z(-10.f, 3);
  4198. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  4199. clean_up_after_endstop_move(l_feedmultiply);
  4200. homing_flag = false;
  4201. }
  4202. break;
  4203. /*!
  4204. ### G75 - Print temperature interpolation <a href="https://reprap.org/wiki/G-code#G75:_Print_temperature_interpolation">G75: Print temperature interpolation</a>
  4205. Show/print PINDA temperature interpolating.
  4206. */
  4207. case 75:
  4208. {
  4209. for (uint8_t i = 40; i <= 110; i++)
  4210. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  4211. }
  4212. break;
  4213. /*!
  4214. ### G76 - PINDA probe temperature calibration <a href="https://reprap.org/wiki/G-code#G76:_PINDA_probe_temperature_calibration">G76: PINDA probe temperature calibration</a>
  4215. This G-code is used to calibrate the temperature drift of the PINDA (inductive Sensor).
  4216. The PINDAv2 sensor has a built-in thermistor which has the advantage that the calibration can be done once for all materials.
  4217. The Original i3 Prusa MK2/s uses PINDAv1 and this calibration improves the temperature drift, but not as good as the PINDAv2.
  4218. superPINDA sensor has internal temperature compensation and no thermistor output. There is no point of doing temperature calibration in such case.
  4219. If PINDA_THERMISTOR and SUPERPINDA_SUPPORT is defined during compilation, calibration is skipped with serial message "No PINDA thermistor".
  4220. This can be caused also if PINDA thermistor connection is broken or PINDA temperature is lower than PINDA_MINTEMP.
  4221. #### Example
  4222. ```
  4223. G76
  4224. echo PINDA probe calibration start
  4225. echo start temperature: 35.0°
  4226. echo ...
  4227. echo PINDA temperature -- Z shift (mm): 0.---
  4228. ```
  4229. */
  4230. case 76:
  4231. {
  4232. #ifdef PINDA_THERMISTOR
  4233. if (!has_temperature_compensation())
  4234. {
  4235. SERIAL_ECHOLNPGM("No PINDA thermistor");
  4236. break;
  4237. }
  4238. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  4239. //we need to know accurate position of first calibration point
  4240. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  4241. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first.")); ////MSG_RUN_XYZ c=20 r=4
  4242. break;
  4243. }
  4244. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  4245. {
  4246. // We don't know where we are! HOME!
  4247. // Push the commands to the front of the message queue in the reverse order!
  4248. // There shall be always enough space reserved for these commands.
  4249. repeatcommand_front(); // repeat G76 with all its parameters
  4250. enquecommand_front_P(G28W0);
  4251. break;
  4252. }
  4253. 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
  4254. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  4255. if (result)
  4256. {
  4257. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4258. plan_buffer_line_curposXYZE(3000 / 60);
  4259. current_position[Z_AXIS] = 50;
  4260. current_position[Y_AXIS] = 180;
  4261. plan_buffer_line_curposXYZE(3000 / 60);
  4262. st_synchronize();
  4263. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  4264. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4265. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4266. plan_buffer_line_curposXYZE(3000 / 60);
  4267. st_synchronize();
  4268. gcode_G28(false, false, true);
  4269. }
  4270. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  4271. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  4272. current_position[Z_AXIS] = 100;
  4273. plan_buffer_line_curposXYZE(3000 / 60);
  4274. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  4275. lcd_temp_cal_show_result(false);
  4276. break;
  4277. }
  4278. }
  4279. st_synchronize();
  4280. homing_flag = true; // keep homing on to avoid babystepping while the LCD is enabled
  4281. lcd_update_enable(true);
  4282. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  4283. float zero_z;
  4284. int z_shift = 0; //unit: steps
  4285. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  4286. if (start_temp < 35) start_temp = 35;
  4287. if (start_temp < current_temperature_pinda) start_temp += 5;
  4288. printf_P(_N("start temperature: %.1f\n"), start_temp);
  4289. // setTargetHotend(200, 0);
  4290. setTargetBed(70 + (start_temp - 30));
  4291. custom_message_type = CustomMsg::TempCal;
  4292. custom_message_state = 1;
  4293. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4294. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4295. plan_buffer_line_curposXYZE(3000 / 60);
  4296. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4297. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4298. plan_buffer_line_curposXYZE(3000 / 60);
  4299. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4300. plan_buffer_line_curposXYZE(3000 / 60);
  4301. st_synchronize();
  4302. while (current_temperature_pinda < start_temp)
  4303. {
  4304. delay_keep_alive(1000);
  4305. serialecho_temperatures();
  4306. }
  4307. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4308. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4309. plan_buffer_line_curposXYZE(3000 / 60);
  4310. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4311. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4312. plan_buffer_line_curposXYZE(3000 / 60);
  4313. st_synchronize();
  4314. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4315. if (find_z_result == false) {
  4316. lcd_temp_cal_show_result(find_z_result);
  4317. homing_flag = false;
  4318. break;
  4319. }
  4320. zero_z = current_position[Z_AXIS];
  4321. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4322. int i = -1; for (; i < 5; i++)
  4323. {
  4324. float temp = (40 + i * 5);
  4325. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  4326. if (i >= 0) {
  4327. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4328. }
  4329. if (start_temp <= temp) break;
  4330. }
  4331. for (i++; i < 5; i++)
  4332. {
  4333. float temp = (40 + i * 5);
  4334. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4335. custom_message_state = i + 2;
  4336. setTargetBed(50 + 10 * (temp - 30) / 5);
  4337. // setTargetHotend(255, 0);
  4338. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4339. plan_buffer_line_curposXYZE(3000 / 60);
  4340. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4341. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4342. plan_buffer_line_curposXYZE(3000 / 60);
  4343. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4344. plan_buffer_line_curposXYZE(3000 / 60);
  4345. st_synchronize();
  4346. while (current_temperature_pinda < temp)
  4347. {
  4348. delay_keep_alive(1000);
  4349. serialecho_temperatures();
  4350. }
  4351. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4352. plan_buffer_line_curposXYZE(3000 / 60);
  4353. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4354. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4355. plan_buffer_line_curposXYZE(3000 / 60);
  4356. st_synchronize();
  4357. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4358. if (find_z_result == false) {
  4359. lcd_temp_cal_show_result(find_z_result);
  4360. break;
  4361. }
  4362. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4363. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  4364. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4365. }
  4366. lcd_temp_cal_show_result(true);
  4367. homing_flag = false;
  4368. #else //PINDA_THERMISTOR
  4369. setTargetBed(PINDA_MIN_T);
  4370. float zero_z;
  4371. int z_shift = 0; //unit: steps
  4372. int t_c; // temperature
  4373. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4374. // We don't know where we are! HOME!
  4375. // Push the commands to the front of the message queue in the reverse order!
  4376. // There shall be always enough space reserved for these commands.
  4377. repeatcommand_front(); // repeat G76 with all its parameters
  4378. enquecommand_front_P(G28W0);
  4379. break;
  4380. }
  4381. puts_P(_N("PINDA probe calibration start"));
  4382. custom_message_type = CustomMsg::TempCal;
  4383. custom_message_state = 1;
  4384. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4385. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4386. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4387. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4388. plan_buffer_line_curposXYZE(3000 / 60);
  4389. st_synchronize();
  4390. while (fabs(degBed() - PINDA_MIN_T) > 1) {
  4391. delay_keep_alive(1000);
  4392. serialecho_temperatures();
  4393. }
  4394. //enquecommand_P(PSTR("M190 S50"));
  4395. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4396. delay_keep_alive(1000);
  4397. serialecho_temperatures();
  4398. }
  4399. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4400. current_position[Z_AXIS] = 5;
  4401. plan_buffer_line_curposXYZE(3000 / 60);
  4402. current_position[X_AXIS] = BED_X0;
  4403. current_position[Y_AXIS] = BED_Y0;
  4404. plan_buffer_line_curposXYZE(3000 / 60);
  4405. st_synchronize();
  4406. find_bed_induction_sensor_point_z(-1.f);
  4407. zero_z = current_position[Z_AXIS];
  4408. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4409. for (int i = 0; i<5; i++) {
  4410. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4411. custom_message_state = i + 2;
  4412. t_c = 60 + i * 10;
  4413. setTargetBed(t_c);
  4414. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4415. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4416. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4417. plan_buffer_line_curposXYZE(3000 / 60);
  4418. st_synchronize();
  4419. while (degBed() < t_c) {
  4420. delay_keep_alive(1000);
  4421. serialecho_temperatures();
  4422. }
  4423. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4424. delay_keep_alive(1000);
  4425. serialecho_temperatures();
  4426. }
  4427. current_position[Z_AXIS] = 5;
  4428. plan_buffer_line_curposXYZE(3000 / 60);
  4429. current_position[X_AXIS] = BED_X0;
  4430. current_position[Y_AXIS] = BED_Y0;
  4431. plan_buffer_line_curposXYZE(3000 / 60);
  4432. st_synchronize();
  4433. find_bed_induction_sensor_point_z(-1.f);
  4434. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4435. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  4436. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4437. }
  4438. custom_message_type = CustomMsg::Status;
  4439. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  4440. puts_P(_N("Temperature calibration done."));
  4441. disable_x();
  4442. disable_y();
  4443. disable_z();
  4444. disable_e0();
  4445. disable_e1();
  4446. disable_e2();
  4447. setTargetBed(0); //set bed target temperature back to 0
  4448. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PINDA_CALIBRATION_DONE));
  4449. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  4450. lcd_update_enable(true);
  4451. lcd_update(2);
  4452. #endif //PINDA_THERMISTOR
  4453. }
  4454. break;
  4455. /*!
  4456. ### G80 - Mesh-based Z probe <a href="https://reprap.org/wiki/G-code#G80:_Mesh-based_Z_probe">G80: Mesh-based Z probe</a>
  4457. Default 3x3 grid can be changed on MK2.5/s and MK3/s to 7x7 grid.
  4458. #### Usage
  4459. G80 [ N | R | V | L | R | F | B ]
  4460. #### Parameters
  4461. - `N` - Number of mesh points on x axis. Default is 3. Valid values are 3 and 7.
  4462. - `R` - Probe retries. Default 3 max. 10
  4463. - `V` - Verbosity level 1=low, 10=mid, 20=high. It only can be used if the firmware has been compiled with SUPPORT_VERBOSITY active.
  4464. Using the following parameters enables additional "manual" bed leveling correction. Valid values are -100 microns to 100 microns.
  4465. #### Additional Parameters
  4466. - `L` - Left Bed Level correct value in um.
  4467. - `R` - Right Bed Level correct value in um.
  4468. - `F` - Front Bed Level correct value in um.
  4469. - `B` - Back Bed Level correct value in um.
  4470. */
  4471. /*
  4472. * Probes a grid and produces a mesh to compensate for variable bed height
  4473. * The S0 report the points as below
  4474. * +----> X-axis
  4475. * |
  4476. * |
  4477. * v Y-axis
  4478. */
  4479. case 80: {
  4480. gcode_G80();
  4481. }
  4482. break;
  4483. /*!
  4484. ### G81 - Mesh bed leveling status <a href="https://reprap.org/wiki/G-code#G81:_Mesh_bed_leveling_status">G81: Mesh bed leveling status</a>
  4485. Prints mesh bed leveling status and bed profile if activated.
  4486. */
  4487. case 81:
  4488. if (mbl.active) {
  4489. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4490. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4491. SERIAL_PROTOCOL(',');
  4492. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4493. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4494. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4495. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4496. for (uint8_t y = MESH_NUM_Y_POINTS; y-- > 0;) {
  4497. for (uint8_t x = 0; x < MESH_NUM_X_POINTS; x++) {
  4498. SERIAL_PROTOCOLPGM(" ");
  4499. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4500. }
  4501. SERIAL_PROTOCOLLN();
  4502. }
  4503. }
  4504. else
  4505. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4506. break;
  4507. #if 0
  4508. /*!
  4509. ### 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>
  4510. WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4511. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4512. */
  4513. case 82:
  4514. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4515. int l_feedmultiply = setup_for_endstop_move();
  4516. find_bed_induction_sensor_point_z();
  4517. clean_up_after_endstop_move(l_feedmultiply);
  4518. SERIAL_PROTOCOLPGM("Bed found at: ");
  4519. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4520. SERIAL_PROTOCOLPGM("\n");
  4521. break;
  4522. /*!
  4523. ### 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>
  4524. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4525. */
  4526. case 83:
  4527. {
  4528. int babystepz = code_seen('S') ? code_value() : 0;
  4529. int BabyPosition = code_seen('P') ? code_value() : 0;
  4530. if (babystepz != 0) {
  4531. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4532. // Is the axis indexed starting with zero or one?
  4533. if (BabyPosition > 4) {
  4534. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4535. }else{
  4536. // Save it to the eeprom
  4537. babystepLoadZ = babystepz;
  4538. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z0 + BabyPosition, babystepLoadZ);
  4539. // adjust the Z
  4540. babystepsTodoZadd(babystepLoadZ);
  4541. }
  4542. }
  4543. }
  4544. break;
  4545. /*!
  4546. ### 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>
  4547. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4548. */
  4549. case 84:
  4550. babystepsTodoZsubtract(babystepLoadZ);
  4551. // babystepLoadZ = 0;
  4552. break;
  4553. /*!
  4554. ### G85: Pick best babystep - Not active <a href="https://reprap.org/wiki/G-code#G85:_Pick_best_babystep">G85: Pick best babystep</a>
  4555. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4556. */
  4557. case 85:
  4558. lcd_pick_babystep();
  4559. break;
  4560. #endif
  4561. /*!
  4562. ### 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>
  4563. This G-code will be performed at the start of a calibration script.
  4564. (Prusa3D specific)
  4565. */
  4566. case 86:
  4567. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4568. break;
  4569. /*!
  4570. ### 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>
  4571. This G-code will be performed at the end of a calibration script.
  4572. (Prusa3D specific)
  4573. */
  4574. case 87:
  4575. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4576. break;
  4577. /*!
  4578. ### G88 - Reserved <a href="https://reprap.org/wiki/G-code#G88:_Reserved">G88: Reserved</a>
  4579. Currently has no effect.
  4580. */
  4581. // Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4582. case 88:
  4583. break;
  4584. #endif // ENABLE_MESH_BED_LEVELING
  4585. /*!
  4586. ### G90 - Switch off relative mode <a href="https://reprap.org/wiki/G-code#G90:_Set_to_Absolute_Positioning">G90: Set to Absolute Positioning</a>
  4587. All coordinates from now on are absolute relative to the origin of the machine. E axis is left intact.
  4588. */
  4589. case 90: {
  4590. axis_relative_modes &= ~(X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK);
  4591. }
  4592. break;
  4593. /*!
  4594. ### G91 - Switch on relative mode <a href="https://reprap.org/wiki/G-code#G91:_Set_to_Relative_Positioning">G91: Set to Relative Positioning</a>
  4595. All coordinates from now on are relative to the last position. E axis is left intact.
  4596. */
  4597. case 91: {
  4598. axis_relative_modes |= X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK;
  4599. }
  4600. break;
  4601. /*!
  4602. ### G92 - Set position <a href="https://reprap.org/wiki/G-code#G92:_Set_Position">G92: Set Position</a>
  4603. It is used for setting the current position of each axis. The parameters are always absolute to the origin.
  4604. If a parameter is omitted, that axis will not be affected.
  4605. 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`).
  4606. A G92 without coordinates will reset all axes to zero on some firmware. This is not the case for Prusa-Firmware!
  4607. #### Usage
  4608. G92 [ X | Y | Z | E ]
  4609. #### Parameters
  4610. - `X` - new X axis position
  4611. - `Y` - new Y axis position
  4612. - `Z` - new Z axis position
  4613. - `E` - new extruder position
  4614. */
  4615. case 92: {
  4616. gcode_G92();
  4617. }
  4618. break;
  4619. #ifdef PRUSA_FARM
  4620. /*!
  4621. ### G98 - Activate farm mode <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode</a>
  4622. Enable Prusa-specific Farm functions and g-code.
  4623. See Internal Prusa commands.
  4624. */
  4625. case 98:
  4626. farm_gcode_g98();
  4627. break;
  4628. /*! ### G99 - Deactivate farm mode <a href="https://reprap.org/wiki/G-code#G99:_Deactivate_farm_mode">G99: Deactivate farm mode</a>
  4629. Disables Prusa-specific Farm functions and g-code.
  4630. */
  4631. case 99:
  4632. farm_gcode_g99();
  4633. break;
  4634. #endif //PRUSA_FARM
  4635. default:
  4636. printf_P(MSG_UNKNOWN_CODE, 'G', cmdbuffer + bufindr + CMDHDRSIZE);
  4637. }
  4638. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4639. gcode_in_progress = 0;
  4640. } // end if(code_seen('G'))
  4641. /*!
  4642. ### End of G-Codes
  4643. */
  4644. /*!
  4645. ---------------------------------------------------------------------------------
  4646. # M Commands
  4647. */
  4648. else if(code_seen('M'))
  4649. {
  4650. int index;
  4651. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4652. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4653. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4654. printf_P(PSTR("Invalid M code: %s\n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4655. } else
  4656. {
  4657. mcode_in_progress = code_value_short();
  4658. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4659. switch(mcode_in_progress)
  4660. {
  4661. /*!
  4662. ### 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>
  4663. */
  4664. case 17:
  4665. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE c=20
  4666. enable_x();
  4667. enable_y();
  4668. enable_z();
  4669. enable_e0();
  4670. enable_e1();
  4671. enable_e2();
  4672. break;
  4673. #ifdef SDSUPPORT
  4674. /*!
  4675. ### M20 - SD Card file list <a href="https://reprap.org/wiki/G-code#M20:_List_SD_card">M20: List SD card</a>
  4676. #### Usage
  4677. M20 [ L | T ]
  4678. #### Parameters
  4679. - `T` - Report timestamps as well. The value is one uint32_t encoded as hex. Requires host software parsing (Cap:EXTENDED_M20).
  4680. - `L` - Reports long filenames instead of just short filenames. Requires host software parsing (Cap:EXTENDED_M20).
  4681. */
  4682. case 20:
  4683. KEEPALIVE_STATE(NOT_BUSY); // do not send busy messages during listing. Inhibits the output of manage_heater()
  4684. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4685. card.ls(CardReader::ls_param(code_seen('L'), code_seen('T')));
  4686. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4687. break;
  4688. /*!
  4689. ### M21 - Init SD card <a href="https://reprap.org/wiki/G-code#M21:_Initialize_SD_card">M21: Initialize SD card</a>
  4690. */
  4691. case 21:
  4692. card.initsd();
  4693. break;
  4694. /*!
  4695. ### M22 - Release SD card <a href="https://reprap.org/wiki/G-code#M22:_Release_SD_card">M22: Release SD card</a>
  4696. */
  4697. case 22:
  4698. card.release();
  4699. break;
  4700. /*!
  4701. ### M23 - Select file <a href="https://reprap.org/wiki/G-code#M23:_Select_SD_file">M23: Select SD file</a>
  4702. #### Usage
  4703. M23 [filename]
  4704. */
  4705. case 23:
  4706. starpos = (strchr(strchr_pointer + 4,'*'));
  4707. if(starpos!=NULL)
  4708. *(starpos)='\0';
  4709. card.openFileReadFilteredGcode(strchr_pointer + 4, true);
  4710. break;
  4711. /*!
  4712. ### M24 - Start SD print <a href="https://reprap.org/wiki/G-code#M24:_Start.2Fresume_SD_print">M24: Start/resume SD print</a>
  4713. */
  4714. case 24:
  4715. if (isPrintPaused)
  4716. lcd_resume_print();
  4717. else
  4718. {
  4719. if (!card.get_sdpos())
  4720. {
  4721. // A new print has started from scratch, reset stats
  4722. failstats_reset_print();
  4723. sdpos_atomic = 0;
  4724. #ifndef LA_NOCOMPAT
  4725. la10c_reset();
  4726. #endif
  4727. }
  4728. card.startFileprint();
  4729. starttime=_millis();
  4730. }
  4731. break;
  4732. /*!
  4733. ### M26 - Set SD index <a href="https://reprap.org/wiki/G-code#M26:_Set_SD_position">M26: Set SD position</a>
  4734. Set position in SD card file to index in bytes.
  4735. This command is expected to be called after M23 and before M24.
  4736. Otherwise effect of this command is undefined.
  4737. #### Usage
  4738. M26 [ S ]
  4739. #### Parameters
  4740. - `S` - Index in bytes
  4741. */
  4742. case 26:
  4743. if(card.cardOK && code_seen('S')) {
  4744. long index = code_value_long();
  4745. card.setIndex(index);
  4746. // We don't disable interrupt during update of sdpos_atomic
  4747. // as we expect, that SD card print is not active in this moment
  4748. sdpos_atomic = index;
  4749. }
  4750. break;
  4751. /*!
  4752. ### M27 - Get SD status <a href="https://reprap.org/wiki/G-code#M27:_Report_SD_print_status">M27: Report SD print status</a>
  4753. #### Usage
  4754. M27 [ P ]
  4755. #### Parameters
  4756. - `P` - Show full SFN path instead of LFN only.
  4757. */
  4758. case 27:
  4759. card.getStatus(code_seen('P'));
  4760. break;
  4761. /*!
  4762. ### 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>
  4763. */
  4764. case 28:
  4765. starpos = (strchr(strchr_pointer + 4,'*'));
  4766. if(starpos != NULL){
  4767. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4768. strchr_pointer = strchr(npos,' ') + 1;
  4769. *(starpos) = '\0';
  4770. }
  4771. card.openFileWrite(strchr_pointer+4);
  4772. break;
  4773. /*! ### 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>
  4774. 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.
  4775. */
  4776. case 29:
  4777. //processed in write to file routine above
  4778. //card,saving = false;
  4779. break;
  4780. /*!
  4781. ### 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>
  4782. #### Usage
  4783. M30 [filename]
  4784. */
  4785. case 30:
  4786. if (card.cardOK){
  4787. card.closefile();
  4788. starpos = (strchr(strchr_pointer + 4,'*'));
  4789. if(starpos != NULL){
  4790. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4791. strchr_pointer = strchr(npos,' ') + 1;
  4792. *(starpos) = '\0';
  4793. }
  4794. card.removeFile(strchr_pointer + 4);
  4795. }
  4796. break;
  4797. /*!
  4798. ### 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>
  4799. @todo What are the parameters P and S for in M32?
  4800. */
  4801. case 32:
  4802. {
  4803. if(card.sdprinting) {
  4804. st_synchronize();
  4805. }
  4806. starpos = (strchr(strchr_pointer + 4,'*'));
  4807. const char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4808. if(namestartpos==NULL)
  4809. {
  4810. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4811. }
  4812. else
  4813. namestartpos++; //to skip the '!'
  4814. if(starpos!=NULL)
  4815. *(starpos)='\0';
  4816. bool call_procedure=(code_seen('P'));
  4817. if(strchr_pointer>namestartpos)
  4818. call_procedure=false; //false alert, 'P' found within filename
  4819. if( card.cardOK )
  4820. {
  4821. card.openFileReadFilteredGcode(namestartpos,!call_procedure);
  4822. if(code_seen('S'))
  4823. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4824. card.setIndex(code_value_long());
  4825. card.startFileprint();
  4826. if(!call_procedure)
  4827. {
  4828. if(!card.get_sdpos())
  4829. {
  4830. // A new print has started from scratch, reset stats
  4831. failstats_reset_print();
  4832. sdpos_atomic = 0;
  4833. #ifndef LA_NOCOMPAT
  4834. la10c_reset();
  4835. #endif
  4836. }
  4837. starttime=_millis(); // procedure calls count as normal print time.
  4838. }
  4839. }
  4840. } break;
  4841. /*!
  4842. ### M928 - Start SD logging <a href="https://reprap.org/wiki/G-code#M928:_Start_SD_logging">M928: Start SD logging</a>
  4843. #### Usage
  4844. M928 [filename]
  4845. */
  4846. case 928:
  4847. starpos = (strchr(strchr_pointer + 5,'*'));
  4848. if(starpos != NULL){
  4849. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4850. strchr_pointer = strchr(npos,' ') + 1;
  4851. *(starpos) = '\0';
  4852. }
  4853. card.openLogFile(strchr_pointer+5);
  4854. break;
  4855. #endif //SDSUPPORT
  4856. /*!
  4857. ### 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>
  4858. */
  4859. case 31: //M31 take time since the start of the SD print or an M109 command
  4860. {
  4861. stoptime=_millis();
  4862. char time[30];
  4863. unsigned long t=(stoptime-starttime)/1000;
  4864. int sec,min;
  4865. min=t/60;
  4866. sec=t%60;
  4867. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4868. SERIAL_ECHO_START;
  4869. SERIAL_ECHOLN(time);
  4870. lcd_setstatus(time);
  4871. autotempShutdown();
  4872. }
  4873. break;
  4874. /*!
  4875. ### M42 - Set pin state <a href="https://reprap.org/wiki/G-code#M42:_Switch_I.2FO_pin">M42: Switch I/O pin</a>
  4876. #### Usage
  4877. M42 [ P | S ]
  4878. #### Parameters
  4879. - `P` - Pin number.
  4880. - `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.
  4881. */
  4882. case 42:
  4883. if (code_seen('S'))
  4884. {
  4885. uint8_t pin_status = code_value_uint8();
  4886. int8_t pin_number = LED_PIN;
  4887. if (code_seen('P'))
  4888. pin_number = code_value_uint8();
  4889. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  4890. {
  4891. if ((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number)
  4892. {
  4893. pin_number = -1;
  4894. break;
  4895. }
  4896. }
  4897. #if defined(FAN_PIN) && FAN_PIN > -1
  4898. if (pin_number == FAN_PIN)
  4899. fanSpeed = pin_status;
  4900. #endif
  4901. if (pin_number > -1)
  4902. {
  4903. pinMode(pin_number, OUTPUT);
  4904. digitalWrite(pin_number, pin_status);
  4905. analogWrite(pin_number, pin_status);
  4906. }
  4907. }
  4908. break;
  4909. /*!
  4910. ### 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>
  4911. */
  4912. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  4913. // Reset the baby step value and the baby step applied flag.
  4914. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4915. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  4916. // Reset the skew and offset in both RAM and EEPROM.
  4917. reset_bed_offset_and_skew();
  4918. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4919. // the planner will not perform any adjustments in the XY plane.
  4920. // Wait for the motors to stop and update the current position with the absolute values.
  4921. world2machine_revert_to_uncorrected();
  4922. break;
  4923. /*!
  4924. ### 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>
  4925. #### Usage
  4926. M45 [ V ]
  4927. #### Parameters
  4928. - `V` - Verbosity level 1, 10 and 20 (low, mid, high). Only when SUPPORT_VERBOSITY is defined. Optional.
  4929. - `Z` - If it is provided, only Z calibration will run. Otherwise full calibration is executed.
  4930. */
  4931. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  4932. {
  4933. int8_t verbosity_level = 0;
  4934. bool only_Z = code_seen('Z');
  4935. #ifdef SUPPORT_VERBOSITY
  4936. if (code_seen('V'))
  4937. {
  4938. // Just 'V' without a number counts as V1.
  4939. char c = strchr_pointer[1];
  4940. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4941. }
  4942. #endif //SUPPORT_VERBOSITY
  4943. gcode_M45(only_Z, verbosity_level);
  4944. }
  4945. break;
  4946. /*!
  4947. ### 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>
  4948. */
  4949. case 46:
  4950. {
  4951. // M46: Prusa3D: Show the assigned IP address.
  4952. if (card.ToshibaFlashAir_isEnabled()) {
  4953. uint8_t ip[4];
  4954. if (card.ToshibaFlashAir_GetIP(ip)) {
  4955. // SERIAL_PROTOCOLPGM("Toshiba FlashAir current IP: ");
  4956. SERIAL_PROTOCOL(uint8_t(ip[0]));
  4957. SERIAL_PROTOCOL('.');
  4958. SERIAL_PROTOCOL(uint8_t(ip[1]));
  4959. SERIAL_PROTOCOL('.');
  4960. SERIAL_PROTOCOL(uint8_t(ip[2]));
  4961. SERIAL_PROTOCOL('.');
  4962. SERIAL_PROTOCOLLN(uint8_t(ip[3]));
  4963. } else {
  4964. SERIAL_PROTOCOLPGM("?Toshiba FlashAir GetIP failed\n");
  4965. }
  4966. } else {
  4967. SERIAL_PROTOCOLLNPGM("n/a");
  4968. }
  4969. break;
  4970. }
  4971. /*!
  4972. ### 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>
  4973. */
  4974. case 47:
  4975. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4976. lcd_diag_show_end_stops();
  4977. KEEPALIVE_STATE(IN_HANDLER);
  4978. break;
  4979. #if 0
  4980. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  4981. {
  4982. // Disable the default update procedure of the display. We will do a modal dialog.
  4983. lcd_update_enable(false);
  4984. // Let the planner use the uncorrected coordinates.
  4985. mbl.reset();
  4986. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4987. // the planner will not perform any adjustments in the XY plane.
  4988. // Wait for the motors to stop and update the current position with the absolute values.
  4989. world2machine_revert_to_uncorrected();
  4990. // Move the print head close to the bed.
  4991. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4992. 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);
  4993. st_synchronize();
  4994. // Home in the XY plane.
  4995. set_destination_to_current();
  4996. int l_feedmultiply = setup_for_endstop_move();
  4997. home_xy();
  4998. int8_t verbosity_level = 0;
  4999. if (code_seen('V')) {
  5000. // Just 'V' without a number counts as V1.
  5001. char c = strchr_pointer[1];
  5002. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  5003. }
  5004. bool success = scan_bed_induction_points(verbosity_level);
  5005. clean_up_after_endstop_move(l_feedmultiply);
  5006. // Print head up.
  5007. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5008. 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);
  5009. st_synchronize();
  5010. lcd_update_enable(true);
  5011. break;
  5012. }
  5013. #endif
  5014. #ifdef ENABLE_AUTO_BED_LEVELING
  5015. #ifdef Z_PROBE_REPEATABILITY_TEST
  5016. /*!
  5017. ### 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>
  5018. 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.
  5019. 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.
  5020. @todo Why would you check for both uppercase and lowercase? Seems wasteful.
  5021. #### Usage
  5022. M48 [ n | X | Y | V | L ]
  5023. #### Parameters
  5024. - `n` - Number of samples. Valid values 4-50
  5025. - `X` - X position for samples
  5026. - `Y` - Y position for samples
  5027. - `V` - Verbose level. Valid values 1-4
  5028. - `L` - Legs of movementprior to doing probe. Valid values 1-15
  5029. */
  5030. case 48: // M48 Z-Probe repeatability
  5031. {
  5032. #if Z_MIN_PIN == -1
  5033. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  5034. #endif
  5035. double sum=0.0;
  5036. double mean=0.0;
  5037. double sigma=0.0;
  5038. double sample_set[50];
  5039. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  5040. double X_current, Y_current, Z_current;
  5041. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  5042. if (code_seen('V') || code_seen('v')) {
  5043. verbose_level = code_value();
  5044. if (verbose_level<0 || verbose_level>4 ) {
  5045. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  5046. goto Sigma_Exit;
  5047. }
  5048. }
  5049. if (verbose_level > 0) {
  5050. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  5051. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  5052. }
  5053. if (code_seen('n')) {
  5054. n_samples = code_value();
  5055. if (n_samples<4 || n_samples>50 ) {
  5056. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  5057. goto Sigma_Exit;
  5058. }
  5059. }
  5060. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  5061. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  5062. Z_current = st_get_position_mm(Z_AXIS);
  5063. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5064. ext_position = st_get_position_mm(E_AXIS);
  5065. if (code_seen('X') || code_seen('x') ) {
  5066. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  5067. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  5068. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  5069. goto Sigma_Exit;
  5070. }
  5071. }
  5072. if (code_seen('Y') || code_seen('y') ) {
  5073. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  5074. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  5075. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  5076. goto Sigma_Exit;
  5077. }
  5078. }
  5079. if (code_seen('L') || code_seen('l') ) {
  5080. n_legs = code_value();
  5081. if ( n_legs==1 )
  5082. n_legs = 2;
  5083. if ( n_legs<0 || n_legs>15 ) {
  5084. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  5085. goto Sigma_Exit;
  5086. }
  5087. }
  5088. //
  5089. // Do all the preliminary setup work. First raise the probe.
  5090. //
  5091. st_synchronize();
  5092. plan_bed_level_matrix.set_to_identity();
  5093. plan_buffer_line( X_current, Y_current, Z_start_location,
  5094. ext_position,
  5095. homing_feedrate[Z_AXIS]/60,
  5096. active_extruder);
  5097. st_synchronize();
  5098. //
  5099. // Now get everything to the specified probe point So we can safely do a probe to
  5100. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  5101. // use that as a starting point for each probe.
  5102. //
  5103. if (verbose_level > 2)
  5104. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  5105. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5106. ext_position,
  5107. homing_feedrate[X_AXIS]/60,
  5108. active_extruder);
  5109. st_synchronize();
  5110. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  5111. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  5112. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5113. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  5114. //
  5115. // OK, do the inital probe to get us close to the bed.
  5116. // Then retrace the right amount and use that in subsequent probes
  5117. //
  5118. int l_feedmultiply = setup_for_endstop_move();
  5119. run_z_probe();
  5120. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5121. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5122. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5123. ext_position,
  5124. homing_feedrate[X_AXIS]/60,
  5125. active_extruder);
  5126. st_synchronize();
  5127. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5128. for( n=0; n<n_samples; n++) {
  5129. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  5130. if ( n_legs) {
  5131. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  5132. int rotational_direction, l;
  5133. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  5134. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  5135. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  5136. //SERIAL_ECHOPAIR("starting radius: ",radius);
  5137. //SERIAL_ECHOPAIR(" theta: ",theta);
  5138. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  5139. //SERIAL_PROTOCOLLNPGM("");
  5140. for( l=0; l<n_legs-1; l++) {
  5141. if (rotational_direction==1)
  5142. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5143. else
  5144. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5145. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  5146. if ( radius<0.0 )
  5147. radius = -radius;
  5148. X_current = X_probe_location + cos(theta) * radius;
  5149. Y_current = Y_probe_location + sin(theta) * radius;
  5150. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  5151. X_current = X_MIN_POS;
  5152. if ( X_current>X_MAX_POS)
  5153. X_current = X_MAX_POS;
  5154. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  5155. Y_current = Y_MIN_POS;
  5156. if ( Y_current>Y_MAX_POS)
  5157. Y_current = Y_MAX_POS;
  5158. if (verbose_level>3 ) {
  5159. SERIAL_ECHOPAIR("x: ", X_current);
  5160. SERIAL_ECHOPAIR("y: ", Y_current);
  5161. SERIAL_PROTOCOLLNPGM("");
  5162. }
  5163. do_blocking_move_to( X_current, Y_current, Z_current );
  5164. }
  5165. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5166. }
  5167. int l_feedmultiply = setup_for_endstop_move();
  5168. run_z_probe();
  5169. sample_set[n] = current_position[Z_AXIS];
  5170. //
  5171. // Get the current mean for the data points we have so far
  5172. //
  5173. sum=0.0;
  5174. for( j=0; j<=n; j++) {
  5175. sum = sum + sample_set[j];
  5176. }
  5177. mean = sum / (double (n+1));
  5178. //
  5179. // Now, use that mean to calculate the standard deviation for the
  5180. // data points we have so far
  5181. //
  5182. sum=0.0;
  5183. for( j=0; j<=n; j++) {
  5184. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5185. }
  5186. sigma = sqrt( sum / (double (n+1)) );
  5187. if (verbose_level > 1) {
  5188. SERIAL_PROTOCOL(n+1);
  5189. SERIAL_PROTOCOL(" of ");
  5190. SERIAL_PROTOCOL(n_samples);
  5191. SERIAL_PROTOCOLPGM(" z: ");
  5192. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5193. }
  5194. if (verbose_level > 2) {
  5195. SERIAL_PROTOCOL(" mean: ");
  5196. SERIAL_PROTOCOL_F(mean,6);
  5197. SERIAL_PROTOCOL(" sigma: ");
  5198. SERIAL_PROTOCOL_F(sigma,6);
  5199. }
  5200. if (verbose_level > 0)
  5201. SERIAL_PROTOCOLPGM("\n");
  5202. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5203. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5204. st_synchronize();
  5205. }
  5206. _delay(1000);
  5207. clean_up_after_endstop_move(l_feedmultiply);
  5208. // enable_endstops(true);
  5209. if (verbose_level > 0) {
  5210. SERIAL_PROTOCOLPGM("Mean: ");
  5211. SERIAL_PROTOCOL_F(mean, 6);
  5212. SERIAL_PROTOCOLPGM("\n");
  5213. }
  5214. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5215. SERIAL_PROTOCOL_F(sigma, 6);
  5216. SERIAL_PROTOCOLPGM("\n\n");
  5217. Sigma_Exit:
  5218. break;
  5219. }
  5220. #endif // Z_PROBE_REPEATABILITY_TEST
  5221. #endif // ENABLE_AUTO_BED_LEVELING
  5222. /*!
  5223. ### M73 - Set/get print progress <a href="https://reprap.org/wiki/G-code#M73:_Set.2FGet_build_percentage">M73: Set/Get build percentage</a>
  5224. #### Usage
  5225. M73 [ P | R | Q | S | C | D ]
  5226. #### Parameters
  5227. - `P` - Percent in normal mode
  5228. - `R` - Time remaining in normal mode
  5229. - `Q` - Percent in silent mode
  5230. - `S` - Time in silent mode
  5231. - `C` - Time to change/pause/user interaction in normal mode
  5232. - `D` - Time to change/pause/user interaction in silent mode
  5233. */
  5234. case 73: //M73 show percent done, time remaining and time to change/pause
  5235. {
  5236. if(code_seen('P')) print_percent_done_normal = code_value_uint8();
  5237. if(code_seen('R')) print_time_remaining_normal = code_value();
  5238. if(code_seen('Q')) print_percent_done_silent = code_value_uint8();
  5239. if(code_seen('S')) print_time_remaining_silent = code_value();
  5240. if(code_seen('C')){
  5241. float print_time_to_change_normal_f = code_value_float();
  5242. print_time_to_change_normal = ( print_time_to_change_normal_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_normal_f;
  5243. }
  5244. if(code_seen('D')){
  5245. float print_time_to_change_silent_f = code_value_float();
  5246. print_time_to_change_silent = ( print_time_to_change_silent_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_silent_f;
  5247. }
  5248. {
  5249. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %hhd; print time remaining in mins: %d; Change in mins: %d\n");
  5250. printf_P(_msg_mode_done_remain, _N("NORMAL"), int8_t(print_percent_done_normal), print_time_remaining_normal, print_time_to_change_normal);
  5251. printf_P(_msg_mode_done_remain, _N("SILENT"), int8_t(print_percent_done_silent), print_time_remaining_silent, print_time_to_change_silent);
  5252. }
  5253. break;
  5254. }
  5255. /*!
  5256. ### M104 - Set hotend temperature <a href="https://reprap.org/wiki/G-code#M104:_Set_Extruder_Temperature">M104: Set Extruder Temperature</a>
  5257. #### Usage
  5258. M104 [ S ]
  5259. #### Parameters
  5260. - `S` - Target temperature
  5261. */
  5262. case 104: // M104
  5263. {
  5264. uint8_t extruder;
  5265. if(setTargetedHotend(104,extruder)){
  5266. break;
  5267. }
  5268. if (code_seen('S'))
  5269. {
  5270. setTargetHotendSafe(code_value(), extruder);
  5271. }
  5272. break;
  5273. }
  5274. /*!
  5275. ### M112 - Emergency stop <a href="https://reprap.org/wiki/G-code#M112:_Full_.28Emergency.29_Stop">M112: Full (Emergency) Stop</a>
  5276. It is processed much earlier as to bypass the cmdqueue.
  5277. */
  5278. case 112:
  5279. kill(MSG_M112_KILL, 3);
  5280. break;
  5281. /*!
  5282. ### M140 - Set bed temperature <a href="https://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29">M140: Set Bed Temperature (Fast)</a>
  5283. #### Usage
  5284. M140 [ S ]
  5285. #### Parameters
  5286. - `S` - Target temperature
  5287. */
  5288. case 140:
  5289. if (code_seen('S')) setTargetBed(code_value());
  5290. break;
  5291. /*!
  5292. ### M105 - Report temperatures <a href="https://reprap.org/wiki/G-code#M105:_Get_Extruder_Temperature">M105: Get Extruder Temperature</a>
  5293. Prints temperatures:
  5294. - `T:` - Hotend (actual / target)
  5295. - `B:` - Bed (actual / target)
  5296. - `Tx:` - x Tool (actual / target)
  5297. - `@:` - Hotend power
  5298. - `B@:` - Bed power
  5299. - `P:` - PINDAv2 actual (only MK2.5/s and MK3/s)
  5300. - `A:` - Ambient actual (only MK3/s)
  5301. _Example:_
  5302. 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
  5303. */
  5304. case 105:
  5305. {
  5306. uint8_t extruder;
  5307. if(setTargetedHotend(105, extruder)){
  5308. break;
  5309. }
  5310. SERIAL_PROTOCOLPGM("ok ");
  5311. gcode_M105(extruder);
  5312. cmdqueue_pop_front(); //prevent an ok after the command since this command uses an ok at the beginning.
  5313. cmdbuffer_front_already_processed = true;
  5314. break;
  5315. }
  5316. #if defined(AUTO_REPORT)
  5317. /*!
  5318. ### M155 - Automatically send status <a href="https://reprap.org/wiki/G-code#M155:_Automatically_send_temperatures">M155: Automatically send temperatures</a>
  5319. #### Usage
  5320. M155 [ S ] [ C ]
  5321. #### Parameters
  5322. - `S` - Set autoreporting interval in seconds. 0 to disable. Maximum: 255
  5323. - `C` - Activate auto-report function (bit mask). Default is temperature.
  5324. bit 0 = Auto-report temperatures
  5325. bit 1 = Auto-report fans
  5326. bit 2 = Auto-report position
  5327. bit 3 = free
  5328. bit 4 = free
  5329. bit 5 = free
  5330. bit 6 = free
  5331. bit 7 = free
  5332. */
  5333. case 155:
  5334. {
  5335. if (code_seen('S')){
  5336. autoReportFeatures.SetPeriod( code_value_uint8() );
  5337. }
  5338. if (code_seen('C')){
  5339. autoReportFeatures.SetMask(code_value_uint8());
  5340. } else{
  5341. autoReportFeatures.SetMask(1); //Backwards compability to host systems like Octoprint to send only temp if paramerter `C`isn't used.
  5342. }
  5343. }
  5344. break;
  5345. #endif //AUTO_REPORT
  5346. /*!
  5347. ### 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>
  5348. #### Usage
  5349. M104 [ B | R | S ]
  5350. #### Parameters (not mandatory)
  5351. - `S` - Set extruder temperature
  5352. - `R` - Set extruder temperature
  5353. - `B` - Set max. extruder temperature, while `S` is min. temperature. Not active in default, only if AUTOTEMP is defined in source code.
  5354. Parameters S and R are treated identically.
  5355. Command always waits for both cool down and heat up.
  5356. If no parameters are supplied waits for previously set extruder temperature.
  5357. */
  5358. case 109:
  5359. {
  5360. uint8_t extruder;
  5361. if(setTargetedHotend(109, extruder)){
  5362. break;
  5363. }
  5364. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5365. heating_status = HeatingStatus::EXTRUDER_HEATING;
  5366. prusa_statistics(1);
  5367. #ifdef AUTOTEMP
  5368. autotemp_enabled=false;
  5369. #endif
  5370. if (code_seen('S')) {
  5371. setTargetHotendSafe(code_value(), extruder);
  5372. } else if (code_seen('R')) {
  5373. setTargetHotendSafe(code_value(), extruder);
  5374. }
  5375. #ifdef AUTOTEMP
  5376. if (code_seen('S')) autotemp_min=code_value();
  5377. if (code_seen('B')) autotemp_max=code_value();
  5378. if (code_seen('F'))
  5379. {
  5380. autotemp_factor=code_value();
  5381. autotemp_enabled=true;
  5382. }
  5383. #endif
  5384. codenum = _millis();
  5385. /* See if we are heating up or cooling down */
  5386. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5387. cancel_heatup = false;
  5388. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5389. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5390. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  5391. prusa_statistics(2);
  5392. //starttime=_millis();
  5393. previous_millis_cmd.start();
  5394. }
  5395. break;
  5396. /*!
  5397. ### 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>
  5398. #### Usage
  5399. M190 [ R | S ]
  5400. #### Parameters (not mandatory)
  5401. - `S` - Set extruder temperature and wait for heating
  5402. - `R` - Set extruder temperature and wait for heating or cooling
  5403. If no parameter is supplied, waits for heating or cooling to previously set temperature.
  5404. */
  5405. case 190:
  5406. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5407. {
  5408. bool CooldownNoWait = false;
  5409. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5410. heating_status = HeatingStatus::BED_HEATING;
  5411. prusa_statistics(1);
  5412. if (code_seen('S'))
  5413. {
  5414. setTargetBed(code_value());
  5415. CooldownNoWait = true;
  5416. }
  5417. else if (code_seen('R'))
  5418. {
  5419. setTargetBed(code_value());
  5420. }
  5421. codenum = _millis();
  5422. cancel_heatup = false;
  5423. target_direction = isHeatingBed(); // true if heating, false if cooling
  5424. while ( (!cancel_heatup) && (target_direction ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false))) )
  5425. {
  5426. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5427. {
  5428. if (!farm_mode) {
  5429. float tt = degHotend(active_extruder);
  5430. SERIAL_PROTOCOLPGM("T:");
  5431. SERIAL_PROTOCOL(tt);
  5432. SERIAL_PROTOCOLPGM(" E:");
  5433. SERIAL_PROTOCOL((int)active_extruder);
  5434. SERIAL_PROTOCOLPGM(" B:");
  5435. SERIAL_PROTOCOL_F(degBed(), 1);
  5436. SERIAL_PROTOCOLLN();
  5437. }
  5438. codenum = _millis();
  5439. }
  5440. manage_heater();
  5441. manage_inactivity();
  5442. lcd_update(0);
  5443. }
  5444. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5445. heating_status = HeatingStatus::BED_HEATING_COMPLETE;
  5446. previous_millis_cmd.start();
  5447. }
  5448. #endif
  5449. break;
  5450. #if defined(FAN_PIN) && FAN_PIN > -1
  5451. /*!
  5452. ### M106 - Set fan speed <a href="https://reprap.org/wiki/G-code#M106:_Fan_On">M106: Fan On</a>
  5453. #### Usage
  5454. M106 [ S ]
  5455. #### Parameters
  5456. - `S` - Specifies the duty cycle of the print fan. Allowed values are 0-255. If it's omitted, a value of 255 is used.
  5457. */
  5458. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5459. if (code_seen('S')){
  5460. fanSpeed = code_value_uint8();
  5461. }
  5462. else {
  5463. fanSpeed = 255;
  5464. }
  5465. break;
  5466. /*!
  5467. ### M107 - Fan off <a href="https://reprap.org/wiki/G-code#M107:_Fan_Off">M107: Fan Off</a>
  5468. */
  5469. case 107:
  5470. fanSpeed = 0;
  5471. break;
  5472. #endif //FAN_PIN
  5473. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5474. /*!
  5475. ### M80 - Turn on the Power Supply <a href="https://reprap.org/wiki/G-code#M80:_ATX_Power_On">M80: ATX Power On</a>
  5476. Only works if the firmware is compiled with PS_ON_PIN defined.
  5477. */
  5478. case 80:
  5479. SET_OUTPUT(PS_ON_PIN); //GND
  5480. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5481. // If you have a switch on suicide pin, this is useful
  5482. // if you want to start another print with suicide feature after
  5483. // a print without suicide...
  5484. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5485. SET_OUTPUT(SUICIDE_PIN);
  5486. WRITE(SUICIDE_PIN, HIGH);
  5487. #endif
  5488. powersupply = true;
  5489. LCD_MESSAGERPGM(MSG_WELCOME);
  5490. lcd_update(0);
  5491. break;
  5492. /*!
  5493. ### M81 - Turn off Power Supply <a href="https://reprap.org/wiki/G-code#M81:_ATX_Power_Off">M81: ATX Power Off</a>
  5494. Only works if the firmware is compiled with PS_ON_PIN defined.
  5495. */
  5496. case 81:
  5497. disable_heater();
  5498. st_synchronize();
  5499. disable_e0();
  5500. disable_e1();
  5501. disable_e2();
  5502. finishAndDisableSteppers();
  5503. fanSpeed = 0;
  5504. _delay(1000); // Wait a little before to switch off
  5505. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5506. st_synchronize();
  5507. suicide();
  5508. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5509. SET_OUTPUT(PS_ON_PIN);
  5510. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5511. #endif
  5512. powersupply = false;
  5513. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5514. lcd_update(0);
  5515. break;
  5516. #endif
  5517. /*!
  5518. ### 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>
  5519. Makes the extruder interpret extrusion as absolute positions.
  5520. */
  5521. case 82:
  5522. axis_relative_modes &= ~E_AXIS_MASK;
  5523. break;
  5524. /*!
  5525. ### 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>
  5526. Makes the extruder interpret extrusion values as relative positions.
  5527. */
  5528. case 83:
  5529. axis_relative_modes |= E_AXIS_MASK;
  5530. break;
  5531. /*!
  5532. ### M84 - Disable steppers <a href="https://reprap.org/wiki/G-code#M84:_Stop_idle_hold">M84: Stop idle hold</a>
  5533. This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5534. This command can be used without any additional parameters. In that case all steppers are disabled.
  5535. 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.
  5536. M84 [ S | X | Y | Z | E ]
  5537. - `S` - Seconds
  5538. - `X` - X axis
  5539. - `Y` - Y axis
  5540. - `Z` - Z axis
  5541. - `E` - Extruder
  5542. ### M18 - Disable steppers <a href="https://reprap.org/wiki/G-code#M18:_Disable_all_stepper_motors">M18: Disable all stepper motors</a>
  5543. Equal to M84 (compatibility)
  5544. */
  5545. case 18: //compatibility
  5546. case 84: // M84
  5547. if(code_seen('S')){
  5548. stepper_inactive_time = code_value() * 1000;
  5549. }
  5550. else
  5551. {
  5552. 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])));
  5553. if(all_axis)
  5554. {
  5555. st_synchronize();
  5556. disable_e0();
  5557. disable_e1();
  5558. disable_e2();
  5559. finishAndDisableSteppers();
  5560. }
  5561. else
  5562. {
  5563. st_synchronize();
  5564. if (code_seen('X')) disable_x();
  5565. if (code_seen('Y')) disable_y();
  5566. if (code_seen('Z')) disable_z();
  5567. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5568. if (code_seen('E')) {
  5569. disable_e0();
  5570. disable_e1();
  5571. disable_e2();
  5572. }
  5573. #endif
  5574. }
  5575. }
  5576. break;
  5577. /*!
  5578. ### M85 - Set max inactive time <a href="https://reprap.org/wiki/G-code#M85:_Set_Inactivity_Shutdown_Timer">M85: Set Inactivity Shutdown Timer</a>
  5579. #### Usage
  5580. M85 [ S ]
  5581. #### Parameters
  5582. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5583. */
  5584. case 85: // M85
  5585. if(code_seen('S')) {
  5586. max_inactive_time = code_value() * 1000;
  5587. }
  5588. break;
  5589. #ifdef SAFETYTIMER
  5590. /*!
  5591. ### 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>
  5592. When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5593. #### Usage
  5594. M86 [ S ]
  5595. #### Parameters
  5596. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5597. */
  5598. case 86:
  5599. if (code_seen('S')) {
  5600. safetytimer_inactive_time = code_value() * 1000;
  5601. safetyTimer.start();
  5602. }
  5603. break;
  5604. #endif
  5605. /*!
  5606. ### 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>
  5607. 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)
  5608. #### Usage
  5609. M92 [ X | Y | Z | E ]
  5610. #### Parameters
  5611. - `X` - Steps per unit for the X drive
  5612. - `Y` - Steps per unit for the Y drive
  5613. - `Z` - Steps per unit for the Z drive
  5614. - `E` - Steps per unit for the extruder drive
  5615. */
  5616. case 92:
  5617. for(int8_t i=0; i < NUM_AXIS; i++)
  5618. {
  5619. if(code_seen(axis_codes[i]))
  5620. {
  5621. if(i == E_AXIS) { // E
  5622. float value = code_value();
  5623. if(value < 20.0) {
  5624. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5625. cs.max_jerk[E_AXIS] *= factor;
  5626. max_feedrate[i] *= factor;
  5627. axis_steps_per_sqr_second[i] *= factor;
  5628. }
  5629. cs.axis_steps_per_unit[i] = value;
  5630. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5631. fsensor.init();
  5632. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5633. }
  5634. else {
  5635. cs.axis_steps_per_unit[i] = code_value();
  5636. }
  5637. }
  5638. }
  5639. reset_acceleration_rates();
  5640. break;
  5641. /*!
  5642. ### M110 - Set Line number <a href="https://reprap.org/wiki/G-code#M110:_Set_Current_Line_Number">M110: Set Current Line Number</a>
  5643. Sets the line number in G-code
  5644. #### Usage
  5645. M110 [ N ]
  5646. #### Parameters
  5647. - `N` - Line number
  5648. */
  5649. case 110:
  5650. if (code_seen('N'))
  5651. gcode_LastN = code_value_long();
  5652. break;
  5653. /*!
  5654. ### M113 - Get or set host keep-alive interval <a href="https://reprap.org/wiki/G-code#M113:_Host_Keepalive">M113: Host Keepalive</a>
  5655. 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).
  5656. #### Usage
  5657. M113 [ S ]
  5658. #### Parameters
  5659. - `S` - Seconds. Default is 2 seconds between "busy" messages
  5660. */
  5661. case 113:
  5662. if (code_seen('S')) {
  5663. host_keepalive_interval = code_value_uint8();
  5664. // NOMORE(host_keepalive_interval, 60);
  5665. }
  5666. else {
  5667. SERIAL_ECHO_START;
  5668. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5669. SERIAL_PROTOCOLLN();
  5670. }
  5671. break;
  5672. /*!
  5673. ### M115 - Firmware info <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities">M115: Get Firmware Version and Capabilities</a>
  5674. Print the firmware info and capabilities
  5675. Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5676. `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.
  5677. _Examples:_
  5678. `M115` results:
  5679. `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`
  5680. `M115 V` results:
  5681. `3.8.1`
  5682. `M115 U3.8.2-RC1` results on LCD display for 30s or user interaction:
  5683. `New firmware version available: 3.8.2-RC1 Please upgrade.`
  5684. #### Usage
  5685. M115 [ V | U ]
  5686. #### Parameters
  5687. - V - Report current installed firmware version
  5688. - U - Firmware version provided by G-code to be compared to current one.
  5689. */
  5690. case 115: // M115
  5691. if (code_seen('V')) {
  5692. // Report the Prusa version number.
  5693. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5694. } else if (code_seen('U')) {
  5695. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5696. // pause the print for 30s and ask the user to upgrade the firmware.
  5697. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5698. } else {
  5699. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5700. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5701. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5702. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5703. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5704. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5705. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5706. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5707. SERIAL_ECHOPGM(" UUID:");
  5708. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5709. #ifdef EXTENDED_CAPABILITIES_REPORT
  5710. extended_capabilities_report();
  5711. #endif //EXTENDED_CAPABILITIES_REPORT
  5712. }
  5713. break;
  5714. /*!
  5715. ### M114 - Get current position <a href="https://reprap.org/wiki/G-code#M114:_Get_Current_Position">M114: Get Current Position</a>
  5716. */
  5717. case 114:
  5718. gcode_M114();
  5719. break;
  5720. /*
  5721. M117 moved up to get the high priority
  5722. case 117: // M117 display message
  5723. starpos = (strchr(strchr_pointer + 5,'*'));
  5724. if(starpos!=NULL)
  5725. *(starpos)='\0';
  5726. lcd_setstatus(strchr_pointer + 5);
  5727. break;*/
  5728. #ifdef M120_M121_ENABLED
  5729. /*!
  5730. ### M120 - Enable endstops <a href="https://reprap.org/wiki/G-code#M120:_Enable_endstop_detection">M120: Enable endstop detection</a>
  5731. */
  5732. case 120:
  5733. enable_endstops(true) ;
  5734. break;
  5735. /*!
  5736. ### M121 - Disable endstops <a href="https://reprap.org/wiki/G-code#M121:_Disable_endstop_detection">M121: Disable endstop detection</a>
  5737. */
  5738. case 121:
  5739. enable_endstops(false) ;
  5740. break;
  5741. #endif //M120_M121_ENABLED
  5742. /*!
  5743. ### M119 - Get endstop states <a href="https://reprap.org/wiki/G-code#M119:_Get_Endstop_Status">M119: Get Endstop Status</a>
  5744. 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.
  5745. */
  5746. case 119:
  5747. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5748. SERIAL_PROTOCOLLN();
  5749. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5750. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5751. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5752. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5753. }else{
  5754. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5755. }
  5756. SERIAL_PROTOCOLLN();
  5757. #endif
  5758. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5759. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5760. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5761. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5762. }else{
  5763. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5764. }
  5765. SERIAL_PROTOCOLLN();
  5766. #endif
  5767. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5768. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5769. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5770. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5771. }else{
  5772. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5773. }
  5774. SERIAL_PROTOCOLLN();
  5775. #endif
  5776. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5777. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5778. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5779. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5780. }else{
  5781. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5782. }
  5783. SERIAL_PROTOCOLLN();
  5784. #endif
  5785. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5786. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5787. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5788. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5789. }else{
  5790. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5791. }
  5792. SERIAL_PROTOCOLLN();
  5793. #endif
  5794. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5795. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5796. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5797. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5798. }else{
  5799. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5800. }
  5801. SERIAL_PROTOCOLLN();
  5802. #endif
  5803. break;
  5804. //!@todo update for all axes, use for loop
  5805. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  5806. /*!
  5807. ### M123 - Tachometer value <a href="https://www.reprap.org/wiki/G-code#M123:_Tachometer_value_.28RepRap_.26_Prusa.29">M123: Tachometer value</a>
  5808. This command is used to report fan speeds and fan pwm values.
  5809. #### Usage
  5810. M123
  5811. - E0: - Hotend fan speed in RPM
  5812. - PRN1: - Part cooling fans speed in RPM
  5813. - E0@: - Hotend fan PWM value
  5814. - PRN1@: -Part cooling fan PWM value
  5815. _Example:_
  5816. E0:3240 RPM PRN1:4560 RPM E0@:255 PRN1@:255
  5817. */
  5818. case 123:
  5819. gcode_M123();
  5820. break;
  5821. #endif //FANCHECK and TACH_0 and TACH_1
  5822. #ifdef BLINKM
  5823. /*!
  5824. ### M150 - Set RGB(W) Color <a href="https://reprap.org/wiki/G-code#M150:_Set_LED_color">M150: Set LED color</a>
  5825. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code by defining BLINKM and its dependencies.
  5826. #### Usage
  5827. M150 [ R | U | B ]
  5828. #### Parameters
  5829. - `R` - Red color value
  5830. - `U` - Green color value. It is NOT `G`!
  5831. - `B` - Blue color value
  5832. */
  5833. case 150:
  5834. {
  5835. byte red;
  5836. byte grn;
  5837. byte blu;
  5838. if(code_seen('R')) red = code_value();
  5839. if(code_seen('U')) grn = code_value();
  5840. if(code_seen('B')) blu = code_value();
  5841. SendColors(red,grn,blu);
  5842. }
  5843. break;
  5844. #endif //BLINKM
  5845. /*!
  5846. ### M200 - Set filament diameter <a href="https://reprap.org/wiki/G-code#M200:_Set_filament_diameter">M200: Set filament diameter</a>
  5847. #### Usage
  5848. M200 [ D | T ]
  5849. #### Parameters
  5850. - `D` - Diameter in mm
  5851. - `T` - Number of extruder (MMUs)
  5852. */
  5853. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5854. {
  5855. uint8_t extruder = active_extruder;
  5856. if(code_seen('T')) {
  5857. extruder = code_value_uint8();
  5858. if(extruder >= EXTRUDERS) {
  5859. SERIAL_ECHO_START;
  5860. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  5861. break;
  5862. }
  5863. }
  5864. if(code_seen('D')) {
  5865. float diameter = code_value();
  5866. if (diameter == 0.0) {
  5867. // setting any extruder filament size disables volumetric on the assumption that
  5868. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5869. // for all extruders
  5870. cs.volumetric_enabled = false;
  5871. } else {
  5872. cs.filament_size[extruder] = code_value();
  5873. // make sure all extruders have some sane value for the filament size
  5874. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5875. #if EXTRUDERS > 1
  5876. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5877. #if EXTRUDERS > 2
  5878. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5879. #endif
  5880. #endif
  5881. cs.volumetric_enabled = true;
  5882. }
  5883. } else {
  5884. //reserved for setting filament diameter via UFID or filament measuring device
  5885. break;
  5886. }
  5887. calculate_extruder_multipliers();
  5888. }
  5889. break;
  5890. /*!
  5891. ### M201 - Set Print Max Acceleration <a href="https://reprap.org/wiki/G-code#M201:_Set_max_acceleration">M201: Set max printing acceleration</a>
  5892. For each axis individually.
  5893. ##### Usage
  5894. M201 [ X | Y | Z | E ]
  5895. ##### Parameters
  5896. - `X` - Acceleration for X axis in units/s^2
  5897. - `Y` - Acceleration for Y axis in units/s^2
  5898. - `Z` - Acceleration for Z axis in units/s^2
  5899. - `E` - Acceleration for the active or specified extruder in units/s^2
  5900. */
  5901. case 201:
  5902. for (int8_t i = 0; i < NUM_AXIS; i++)
  5903. {
  5904. if (code_seen(axis_codes[i]))
  5905. {
  5906. unsigned long val = code_value();
  5907. #ifdef TMC2130
  5908. unsigned long val_silent = val;
  5909. if ((i == X_AXIS) || (i == Y_AXIS))
  5910. {
  5911. if (val > NORMAL_MAX_ACCEL_XY)
  5912. val = NORMAL_MAX_ACCEL_XY;
  5913. if (val_silent > SILENT_MAX_ACCEL_XY)
  5914. val_silent = SILENT_MAX_ACCEL_XY;
  5915. }
  5916. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  5917. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  5918. #else //TMC2130
  5919. max_acceleration_units_per_sq_second[i] = val;
  5920. #endif //TMC2130
  5921. }
  5922. }
  5923. // 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)
  5924. reset_acceleration_rates();
  5925. break;
  5926. #if 0 // Not used for Sprinter/grbl gen6
  5927. case 202: // M202
  5928. for(int8_t i=0; i < NUM_AXIS; i++) {
  5929. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  5930. }
  5931. break;
  5932. #endif
  5933. /*!
  5934. ### M203 - Set Max Feedrate <a href="https://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate">M203: Set maximum feedrate</a>
  5935. For each axis individually.
  5936. ##### Usage
  5937. M203 [ X | Y | Z | E ]
  5938. ##### Parameters
  5939. - `X` - Maximum feedrate for X axis
  5940. - `Y` - Maximum feedrate for Y axis
  5941. - `Z` - Maximum feedrate for Z axis
  5942. - `E` - Maximum feedrate for extruder drives
  5943. */
  5944. case 203: // M203 max feedrate mm/sec
  5945. for (uint8_t i = 0; i < NUM_AXIS; i++)
  5946. {
  5947. if (code_seen(axis_codes[i]))
  5948. {
  5949. float val = code_value();
  5950. #ifdef TMC2130
  5951. float val_silent = val;
  5952. if ((i == X_AXIS) || (i == Y_AXIS))
  5953. {
  5954. if (val > NORMAL_MAX_FEEDRATE_XY)
  5955. val = NORMAL_MAX_FEEDRATE_XY;
  5956. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  5957. val_silent = SILENT_MAX_FEEDRATE_XY;
  5958. }
  5959. cs.max_feedrate_normal[i] = val;
  5960. cs.max_feedrate_silent[i] = val_silent;
  5961. #else //TMC2130
  5962. max_feedrate[i] = val;
  5963. #endif //TMC2130
  5964. }
  5965. }
  5966. break;
  5967. /*!
  5968. ### M204 - Acceleration settings <a href="https://reprap.org/wiki/G-code#M204:_Set_default_acceleration">M204: Set default acceleration</a>
  5969. #### Old format:
  5970. ##### Usage
  5971. M204 [ S | T ]
  5972. ##### Parameters
  5973. - `S` - normal moves
  5974. - `T` - filmanent only moves
  5975. #### New format:
  5976. ##### Usage
  5977. M204 [ P | R | T ]
  5978. ##### Parameters
  5979. - `P` - printing moves
  5980. - `R` - filmanent only moves
  5981. - `T` - travel moves (as of now T is ignored)
  5982. */
  5983. case 204:
  5984. {
  5985. if(code_seen('S')) {
  5986. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  5987. // and it is also generated by Slic3r to control acceleration per extrusion type
  5988. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  5989. cs.acceleration = cs.travel_acceleration = code_value();
  5990. // Interpret the T value as retract acceleration in the old Marlin format.
  5991. if(code_seen('T'))
  5992. cs.retract_acceleration = code_value();
  5993. } else {
  5994. // New acceleration format, compatible with the upstream Marlin.
  5995. if(code_seen('P'))
  5996. cs.acceleration = code_value();
  5997. if(code_seen('R'))
  5998. cs.retract_acceleration = code_value();
  5999. if(code_seen('T'))
  6000. cs.travel_acceleration = code_value();
  6001. }
  6002. }
  6003. break;
  6004. /*!
  6005. ### M205 - Set advanced settings <a href="https://reprap.org/wiki/G-code#M205:_Advanced_settings">M205: Advanced settings</a>
  6006. Set some advanced settings related to movement.
  6007. #### Usage
  6008. M205 [ S | T | B | X | Y | Z | E ]
  6009. #### Parameters
  6010. - `S` - Minimum feedrate for print moves (unit/s)
  6011. - `T` - Minimum feedrate for travel moves (units/s)
  6012. - `B` - Minimum segment time (us)
  6013. - `X` - Maximum X jerk (units/s)
  6014. - `Y` - Maximum Y jerk (units/s)
  6015. - `Z` - Maximum Z jerk (units/s)
  6016. - `E` - Maximum E jerk (units/s)
  6017. */
  6018. case 205:
  6019. {
  6020. if(code_seen('S')) cs.minimumfeedrate = code_value();
  6021. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  6022. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  6023. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  6024. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  6025. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  6026. if(code_seen('E'))
  6027. {
  6028. float e = code_value();
  6029. #ifndef LA_NOCOMPAT
  6030. e = la10c_jerk(e);
  6031. #endif
  6032. cs.max_jerk[E_AXIS] = e;
  6033. }
  6034. }
  6035. break;
  6036. /*!
  6037. ### M206 - Set additional homing offsets <a href="https://reprap.org/wiki/G-code#M206:_Offset_axes">M206: Offset axes</a>
  6038. #### Usage
  6039. M206 [ X | Y | Z ]
  6040. #### Parameters
  6041. - `X` - X axis offset
  6042. - `Y` - Y axis offset
  6043. - `Z` - Z axis offset
  6044. */
  6045. case 206:
  6046. for(uint8_t i=0; i < 3; i++)
  6047. {
  6048. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  6049. }
  6050. break;
  6051. #ifdef FWRETRACT
  6052. /*!
  6053. ### M207 - Set firmware retraction <a href="https://reprap.org/wiki/G-code#M207:_Set_retract_length">M207: Set retract length</a>
  6054. #### Usage
  6055. M207 [ S | F | Z ]
  6056. #### Parameters
  6057. - `S` - positive length to retract, in mm
  6058. - `F` - retraction feedrate, in mm/min
  6059. - `Z` - additional zlift/hop
  6060. */
  6061. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  6062. {
  6063. if(code_seen('S'))
  6064. {
  6065. cs.retract_length = code_value() ;
  6066. }
  6067. if(code_seen('F'))
  6068. {
  6069. cs.retract_feedrate = code_value()/60 ;
  6070. }
  6071. if(code_seen('Z'))
  6072. {
  6073. cs.retract_zlift = code_value() ;
  6074. }
  6075. }break;
  6076. /*!
  6077. ### M208 - Set retract recover length <a href="https://reprap.org/wiki/G-code#M208:_Set_unretract_length">M208: Set unretract length</a>
  6078. #### Usage
  6079. M208 [ S | F ]
  6080. #### Parameters
  6081. - `S` - positive length surplus to the M207 Snnn, in mm
  6082. - `F` - feedrate, in mm/sec
  6083. */
  6084. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  6085. {
  6086. if(code_seen('S'))
  6087. {
  6088. cs.retract_recover_length = code_value() ;
  6089. }
  6090. if(code_seen('F'))
  6091. {
  6092. cs.retract_recover_feedrate = code_value()/60 ;
  6093. }
  6094. }break;
  6095. /*!
  6096. ### M209 - Enable/disable automatict retract <a href="https://reprap.org/wiki/G-code#M209:_Enable_automatic_retract">M209: Enable automatic retract</a>
  6097. 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.
  6098. #### Usage
  6099. M209 [ S ]
  6100. #### Parameters
  6101. - `S` - 1=true or 0=false
  6102. */
  6103. 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.
  6104. {
  6105. if(code_seen('S'))
  6106. {
  6107. switch(code_value_uint8())
  6108. {
  6109. case 0:
  6110. {
  6111. cs.autoretract_enabled=false;
  6112. retracted[0]=false;
  6113. #if EXTRUDERS > 1
  6114. retracted[1]=false;
  6115. #endif
  6116. #if EXTRUDERS > 2
  6117. retracted[2]=false;
  6118. #endif
  6119. }break;
  6120. case 1:
  6121. {
  6122. cs.autoretract_enabled=true;
  6123. retracted[0]=false;
  6124. #if EXTRUDERS > 1
  6125. retracted[1]=false;
  6126. #endif
  6127. #if EXTRUDERS > 2
  6128. retracted[2]=false;
  6129. #endif
  6130. }break;
  6131. default:
  6132. SERIAL_ECHO_START;
  6133. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6134. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6135. SERIAL_ECHOLNPGM("\"(1)");
  6136. }
  6137. }
  6138. }break;
  6139. #endif // FWRETRACT
  6140. /*!
  6141. ### M214 - Set Arc configuration values (Use M500 to store in eeprom)
  6142. #### Usage
  6143. M214 [P] [S] [N] [R] [F]
  6144. #### Parameters
  6145. - `P` - A float representing the max and default millimeters per arc segment. Must be greater than 0.
  6146. - `S` - A float representing the minimum allowable millimeters per arc segment. Set to 0 to disable
  6147. - `N` - An int representing the number of arcs to draw before correcting the small angle approximation. Set to 0 to disable.
  6148. - `R` - An int representing the minimum number of segments per arcs of any radius,
  6149. except when the results in segment lengths greater than or less than the minimum
  6150. and maximum segment length. Set to 0 to disable.
  6151. - 'F' - An int representing the number of segments per second, unless this results in segment lengths
  6152. greater than or less than the minimum and maximum segment length. Set to 0 to disable.
  6153. */
  6154. case 214: //!@n M214 - Set Arc Parameters (Use M500 to store in eeprom) P<MM_PER_ARC_SEGMENT> S<MIN_MM_PER_ARC_SEGMENT> R<MIN_ARC_SEGMENTS> F<ARC_SEGMENTS_PER_SEC>
  6155. {
  6156. // Extract all possible parameters if they appear
  6157. float p = code_seen('P') ? code_value_float() : cs.mm_per_arc_segment;
  6158. float s = code_seen('S') ? code_value_float() : cs.min_mm_per_arc_segment;
  6159. unsigned char n = code_seen('N') ? code_value() : cs.n_arc_correction;
  6160. unsigned short r = code_seen('R') ? code_value() : cs.min_arc_segments;
  6161. unsigned short f = code_seen('F') ? code_value() : cs.arc_segments_per_sec;
  6162. // Ensure mm_per_arc_segment is greater than 0, and that min_mm_per_arc_segment is sero or greater than or equal to mm_per_arc_segment
  6163. if (p <=0 || s < 0 || p < s)
  6164. {
  6165. // Should we display some error here?
  6166. break;
  6167. }
  6168. cs.mm_per_arc_segment = p;
  6169. cs.min_mm_per_arc_segment = s;
  6170. cs.n_arc_correction = n;
  6171. cs.min_arc_segments = r;
  6172. cs.arc_segments_per_sec = f;
  6173. }break;
  6174. #if EXTRUDERS > 1
  6175. /*!
  6176. ### M218 - Set hotend offset <a href="https://reprap.org/wiki/G-code#M218:_Set_Hotend_Offset">M218: Set Hotend Offset</a>
  6177. 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.
  6178. #### Usage
  6179. M218 [ X | Y ]
  6180. #### Parameters
  6181. - `X` - X offset
  6182. - `Y` - Y offset
  6183. */
  6184. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  6185. {
  6186. uint8_t extruder;
  6187. if(setTargetedHotend(218, extruder)){
  6188. break;
  6189. }
  6190. if(code_seen('X'))
  6191. {
  6192. extruder_offset[X_AXIS][extruder] = code_value();
  6193. }
  6194. if(code_seen('Y'))
  6195. {
  6196. extruder_offset[Y_AXIS][extruder] = code_value();
  6197. }
  6198. SERIAL_ECHO_START;
  6199. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  6200. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  6201. {
  6202. SERIAL_ECHO(" ");
  6203. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  6204. SERIAL_ECHO(",");
  6205. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  6206. }
  6207. SERIAL_ECHOLN("");
  6208. }break;
  6209. #endif
  6210. /*!
  6211. ### 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>
  6212. #### Usage
  6213. M220 [ B | S | R ]
  6214. #### Parameters
  6215. - `B` - Backup current speed factor
  6216. - `S` - Speed factor override percentage (0..100 or higher)
  6217. - `R` - Restore previous speed factor
  6218. */
  6219. case 220: // M220 S<factor in percent>- set speed factor override percentage
  6220. {
  6221. bool codesWereSeen = false;
  6222. if (code_seen('B')) //backup current speed factor
  6223. {
  6224. saved_feedmultiply_mm = feedmultiply;
  6225. codesWereSeen = true;
  6226. }
  6227. if (code_seen('S'))
  6228. {
  6229. feedmultiply = code_value_short();
  6230. codesWereSeen = true;
  6231. }
  6232. if (code_seen('R')) //restore previous feedmultiply
  6233. {
  6234. feedmultiply = saved_feedmultiply_mm;
  6235. codesWereSeen = true;
  6236. }
  6237. if (!codesWereSeen)
  6238. {
  6239. printf_P(PSTR("%i%%\n"), feedmultiply);
  6240. }
  6241. }
  6242. break;
  6243. /*!
  6244. ### 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>
  6245. #### Usage
  6246. M221 [ S | T ]
  6247. #### Parameters
  6248. - `S` - Extrude factor override percentage (0..100 or higher), default 100%
  6249. - `T` - Extruder drive number (Prusa Firmware only), default 0 if not set.
  6250. */
  6251. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  6252. {
  6253. if (code_seen('S'))
  6254. {
  6255. int tmp_code = code_value_short();
  6256. if (code_seen('T'))
  6257. {
  6258. uint8_t extruder;
  6259. if (setTargetedHotend(221, extruder))
  6260. break;
  6261. extruder_multiply[extruder] = tmp_code;
  6262. }
  6263. else
  6264. {
  6265. extrudemultiply = tmp_code ;
  6266. }
  6267. }
  6268. else
  6269. {
  6270. printf_P(PSTR("%i%%\n"), extrudemultiply);
  6271. }
  6272. calculate_extruder_multipliers();
  6273. }
  6274. break;
  6275. /*!
  6276. ### M226 - Wait for Pin state <a href="https://reprap.org/wiki/G-code#M226:_Wait_for_pin_state">M226: Wait for pin state</a>
  6277. Wait until the specified pin reaches the state required
  6278. #### Usage
  6279. M226 [ P | S ]
  6280. #### Parameters
  6281. - `P` - pin number
  6282. - `S` - pin state
  6283. */
  6284. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  6285. {
  6286. if(code_seen('P')){
  6287. int pin_number = code_value_short(); // pin number
  6288. int pin_state = -1; // required pin state - default is inverted
  6289. if(code_seen('S')) pin_state = code_value_short(); // required pin state
  6290. if(pin_state >= -1 && pin_state <= 1){
  6291. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  6292. {
  6293. if (((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number))
  6294. {
  6295. pin_number = -1;
  6296. break;
  6297. }
  6298. }
  6299. if (pin_number > -1)
  6300. {
  6301. int target = LOW;
  6302. st_synchronize();
  6303. pinMode(pin_number, INPUT);
  6304. switch(pin_state){
  6305. case 1:
  6306. target = HIGH;
  6307. break;
  6308. case 0:
  6309. target = LOW;
  6310. break;
  6311. case -1:
  6312. target = !digitalRead(pin_number);
  6313. break;
  6314. }
  6315. while(digitalRead(pin_number) != target){
  6316. manage_heater();
  6317. manage_inactivity();
  6318. lcd_update(0);
  6319. }
  6320. }
  6321. }
  6322. }
  6323. }
  6324. break;
  6325. #if NUM_SERVOS > 0
  6326. /*!
  6327. ### M280 - Set/Get servo position <a href="https://reprap.org/wiki/G-code#M280:_Set_servo_position">M280: Set servo position</a>
  6328. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6329. #### Usage
  6330. M280 [ P | S ]
  6331. #### Parameters
  6332. - `P` - Servo index (id)
  6333. - `S` - Target position
  6334. */
  6335. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6336. {
  6337. int servo_index = -1;
  6338. int servo_position = 0;
  6339. if (code_seen('P'))
  6340. servo_index = code_value();
  6341. if (code_seen('S')) {
  6342. servo_position = code_value();
  6343. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  6344. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6345. servos[servo_index].attach(0);
  6346. #endif
  6347. servos[servo_index].write(servo_position);
  6348. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6349. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  6350. servos[servo_index].detach();
  6351. #endif
  6352. }
  6353. else {
  6354. SERIAL_ECHO_START;
  6355. SERIAL_ECHO("Servo ");
  6356. SERIAL_ECHO(servo_index);
  6357. SERIAL_ECHOLN(" out of range");
  6358. }
  6359. }
  6360. else if (servo_index >= 0) {
  6361. SERIAL_PROTOCOL(MSG_OK);
  6362. SERIAL_PROTOCOL(" Servo ");
  6363. SERIAL_PROTOCOL(servo_index);
  6364. SERIAL_PROTOCOL(": ");
  6365. SERIAL_PROTOCOLLN(servos[servo_index].read());
  6366. }
  6367. }
  6368. break;
  6369. #endif // NUM_SERVOS > 0
  6370. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  6371. /*!
  6372. ### M300 - Play tone <a href="https://reprap.org/wiki/G-code#M300:_Play_beep_sound">M300: Play beep sound</a>
  6373. In Prusa Firmware the defaults are `100Hz` and `1000ms`, so that `M300` without parameters will beep for a second.
  6374. #### Usage
  6375. M300 [ S | P ]
  6376. #### Parameters
  6377. - `S` - frequency in Hz. Not all firmware versions support this parameter
  6378. - `P` - duration in milliseconds
  6379. */
  6380. case 300: // M300
  6381. {
  6382. uint16_t beepS = code_seen('S') ? code_value() : 0;
  6383. uint16_t beepP = code_seen('P') ? code_value() : 1000;
  6384. #if BEEPER > 0
  6385. if (beepP > 0)
  6386. Sound_MakeCustom(beepP,beepS,false);
  6387. #endif
  6388. }
  6389. break;
  6390. #endif // M300
  6391. #ifdef PIDTEMP
  6392. /*!
  6393. ### M301 - Set hotend PID <a href="https://reprap.org/wiki/G-code#M301:_Set_PID_parameters">M301: Set PID parameters</a>
  6394. Sets Proportional (P), Integral (I) and Derivative (D) values for hot end.
  6395. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6396. #### Usage
  6397. M301 [ P | I | D ]
  6398. #### Parameters
  6399. - `P` - proportional (Kp)
  6400. - `I` - integral (Ki)
  6401. - `D` - derivative (Kd)
  6402. */
  6403. case 301:
  6404. {
  6405. if(code_seen('P')) cs.Kp = code_value();
  6406. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  6407. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6408. updatePID();
  6409. SERIAL_PROTOCOLRPGM(MSG_OK);
  6410. SERIAL_PROTOCOLPGM(" p:");
  6411. SERIAL_PROTOCOL(cs.Kp);
  6412. SERIAL_PROTOCOLPGM(" i:");
  6413. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6414. SERIAL_PROTOCOLPGM(" d:");
  6415. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6416. SERIAL_PROTOCOLLN();
  6417. }
  6418. break;
  6419. #endif //PIDTEMP
  6420. #ifdef PIDTEMPBED
  6421. /*!
  6422. ### M304 - Set bed PID <a href="https://reprap.org/wiki/G-code#M304:_Set_PID_parameters_-_Bed">M304: Set PID parameters - Bed</a>
  6423. Sets Proportional (P), Integral (I) and Derivative (D) values for bed.
  6424. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6425. #### Usage
  6426. M304 [ P | I | D ]
  6427. #### Parameters
  6428. - `P` - proportional (Kp)
  6429. - `I` - integral (Ki)
  6430. - `D` - derivative (Kd)
  6431. */
  6432. case 304:
  6433. {
  6434. if(code_seen('P')) cs.bedKp = code_value();
  6435. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6436. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6437. updatePID();
  6438. SERIAL_PROTOCOLRPGM(MSG_OK);
  6439. SERIAL_PROTOCOLPGM(" p:");
  6440. SERIAL_PROTOCOL(cs.bedKp);
  6441. SERIAL_PROTOCOLPGM(" i:");
  6442. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6443. SERIAL_PROTOCOLPGM(" d:");
  6444. SERIAL_PROTOCOLLN(unscalePID_d(cs.bedKd));
  6445. }
  6446. break;
  6447. #endif //PIDTEMP
  6448. /*!
  6449. ### M240 - Trigger camera <a href="https://reprap.org/wiki/G-code#M240:_Trigger_camera">M240: Trigger camera</a>
  6450. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6451. You need to (re)define and assign `CHDK` or `PHOTOGRAPH_PIN` the correct pin number to be able to use the feature.
  6452. */
  6453. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6454. {
  6455. #ifdef CHDK
  6456. SET_OUTPUT(CHDK);
  6457. WRITE(CHDK, HIGH);
  6458. chdkHigh = _millis();
  6459. chdkActive = true;
  6460. #else
  6461. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6462. const uint8_t NUM_PULSES=16;
  6463. const float PULSE_LENGTH=0.01524;
  6464. for(int i=0; i < NUM_PULSES; i++) {
  6465. WRITE(PHOTOGRAPH_PIN, HIGH);
  6466. _delay_ms(PULSE_LENGTH);
  6467. WRITE(PHOTOGRAPH_PIN, LOW);
  6468. _delay_ms(PULSE_LENGTH);
  6469. }
  6470. _delay(7.33);
  6471. for(int i=0; i < NUM_PULSES; i++) {
  6472. WRITE(PHOTOGRAPH_PIN, HIGH);
  6473. _delay_ms(PULSE_LENGTH);
  6474. WRITE(PHOTOGRAPH_PIN, LOW);
  6475. _delay_ms(PULSE_LENGTH);
  6476. }
  6477. #endif
  6478. #endif //chdk end if
  6479. }
  6480. break;
  6481. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6482. /*!
  6483. ### 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>
  6484. 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.
  6485. #### Usage
  6486. M302 [ S ]
  6487. #### Parameters
  6488. - `S` - Cold extrude minimum temperature
  6489. */
  6490. case 302:
  6491. {
  6492. int temp = 0;
  6493. if (code_seen('S')) temp=code_value_short();
  6494. set_extrude_min_temp(temp);
  6495. }
  6496. break;
  6497. #endif
  6498. /*!
  6499. ### M303 - PID autotune <a href="https://reprap.org/wiki/G-code#M303:_Run_PID_tuning">M303: Run PID tuning</a>
  6500. 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.
  6501. #### Usage
  6502. M303 [ E | S | C ]
  6503. #### Parameters
  6504. - `E` - Extruder, default `E0`. Use `E-1` to calibrate the bed PID
  6505. - `S` - Target temperature, default `210°C` for hotend, 70 for bed
  6506. - `C` - Cycles, default `5`
  6507. */
  6508. case 303:
  6509. {
  6510. float temp = 150.0;
  6511. int e = 0;
  6512. int c = 5;
  6513. if (code_seen('E')) e = code_value_short();
  6514. if (e < 0)
  6515. temp = 70;
  6516. if (code_seen('S')) temp = code_value();
  6517. if (code_seen('C')) c = code_value_short();
  6518. PID_autotune(temp, e, c);
  6519. }
  6520. break;
  6521. #ifdef TEMP_MODEL
  6522. /*!
  6523. ### M310 - Temperature model settings <a href="https://reprap.org/wiki/G-code#M310:_Temperature_model_settings">M310: Temperature model settings</a>
  6524. #### Usage
  6525. M310 ; report values
  6526. M310 [ A ] [ F ] ; autotune
  6527. M310 [ S ] ; set 0=disable 1=enable
  6528. M310 [ I ] [ R ] ; set resistance at index
  6529. M310 [ P | C ] ; set power, capacitance
  6530. M310 [ B | E | W ] ; set beeper, warning and error threshold
  6531. M310 [ T ] ; set ambient temperature correction
  6532. #### Parameters
  6533. - `I` - resistance index position (0-15)
  6534. - `R` - resistance value at index (K/W; requires `I`)
  6535. - `P` - power (W)
  6536. - `C` - capacitance (J/K)
  6537. - `S` - set 0=disable 1=enable
  6538. - `B` - beep and warn when reaching warning threshold 0=disable 1=enable (default: 1)
  6539. - `E` - error threshold (K/s; default in variant)
  6540. - `W` - warning threshold (K/s; default in variant)
  6541. - `T` - ambient temperature correction (K; default in variant)
  6542. - `A` - autotune C+R values
  6543. - `F` - force model self-test state (0=off 1=on) during autotune using current values
  6544. */
  6545. case 310:
  6546. {
  6547. // parse all parameters
  6548. float P = NAN, C = NAN, R = NAN, E = NAN, W = NAN, T = NAN;
  6549. int8_t I = -1, S = -1, B = -1, A = -1, F = -1;
  6550. if(code_seen('C')) C = code_value();
  6551. if(code_seen('P')) P = code_value();
  6552. if(code_seen('I')) I = code_value_short();
  6553. if(code_seen('R')) R = code_value();
  6554. if(code_seen('S')) S = code_value_short();
  6555. if(code_seen('B')) B = code_value_short();
  6556. if(code_seen('E')) E = code_value();
  6557. if(code_seen('W')) W = code_value();
  6558. if(code_seen('T')) T = code_value();
  6559. if(code_seen('A')) A = code_value_short();
  6560. if(code_seen('F')) F = code_value_short();
  6561. // report values if nothing has been requested
  6562. if(isnan(C) && isnan(P) && isnan(R) && isnan(E) && isnan(W) && isnan(T) && I < 0 && S < 0 && B < 0 && A < 0) {
  6563. temp_model_report_settings();
  6564. break;
  6565. }
  6566. // update all parameters
  6567. if(B >= 0) temp_model_set_warn_beep(B);
  6568. if(!isnan(C) || !isnan(P) || !isnan(T) || !isnan(W) || !isnan(E)) temp_model_set_params(C, P, T, W, E);
  6569. if(I >= 0 && !isnan(R)) temp_model_set_resistance(I, R);
  6570. // enable the model last, if requested
  6571. if(S >= 0) temp_model_set_enabled(S);
  6572. // run autotune
  6573. if(A >= 0) temp_model_autotune(A, F > 0);
  6574. }
  6575. break;
  6576. #endif
  6577. /*!
  6578. ### 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>
  6579. Finishes all current moves and and thus clears the buffer.
  6580. Equivalent to `G4` with no parameters.
  6581. */
  6582. case 400:
  6583. {
  6584. st_synchronize();
  6585. }
  6586. break;
  6587. /*!
  6588. ### 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>
  6589. Currently three different materials are needed (default, flex and PVA).
  6590. And storing this information for different load/unload profiles etc. in the future firmware does not have to wait for "ok" from MMU.
  6591. #### Usage
  6592. M403 [ E | F ]
  6593. #### Parameters
  6594. - `E` - Extruder number. 0-indexed.
  6595. - `F` - Filament type
  6596. */
  6597. case 403:
  6598. {
  6599. // currently three different materials are needed (default, flex and PVA)
  6600. // add storing this information for different load/unload profiles etc. in the future
  6601. if (MMU2::mmu2.Enabled())
  6602. {
  6603. uint8_t extruder = 255;
  6604. uint8_t filament = FILAMENT_UNDEFINED;
  6605. if(code_seen('E')) extruder = code_value_uint8();
  6606. if(code_seen('F')) filament = code_value_uint8();
  6607. MMU2::mmu2.set_filament_type(extruder, filament);
  6608. }
  6609. }
  6610. break;
  6611. /*!
  6612. ### 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>
  6613. Save current parameters to EEPROM.
  6614. */
  6615. case 500:
  6616. {
  6617. Config_StoreSettings();
  6618. }
  6619. break;
  6620. /*!
  6621. ### M501 - Read settings from EEPROM <a href="https://reprap.org/wiki/G-code#M501:_Read_parameters_from_EEPROM">M501: Read parameters from EEPROM</a>
  6622. Set the active parameters to those stored in the EEPROM. This is useful to revert parameters after experimenting with them.
  6623. */
  6624. case 501:
  6625. {
  6626. Config_RetrieveSettings();
  6627. }
  6628. break;
  6629. /*!
  6630. ### M502 - Revert all settings to factory default <a href="https://reprap.org/wiki/G-code#M502:_Restore_Default_Settings">M502: Restore Default Settings</a>
  6631. 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.
  6632. */
  6633. case 502:
  6634. {
  6635. Config_ResetDefault();
  6636. }
  6637. break;
  6638. /*!
  6639. ### M503 - Repport all settings currently in memory <a href="https://reprap.org/wiki/G-code#M503:_Report_Current_Settings">M503: Report Current Settings</a>
  6640. 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.
  6641. */
  6642. case 503:
  6643. {
  6644. Config_PrintSettings();
  6645. }
  6646. break;
  6647. /*!
  6648. ### M509 - Force language selection <a href="https://reprap.org/wiki/G-code#M509:_Force_language_selection">M509: Force language selection</a>
  6649. Resets the language to English.
  6650. Only on Original Prusa i3 MK2.5/s and MK3/s with multiple languages.
  6651. */
  6652. case 509:
  6653. {
  6654. lang_reset();
  6655. SERIAL_ECHO_START;
  6656. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6657. }
  6658. break;
  6659. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6660. /*!
  6661. ### 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>
  6662. 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`.
  6663. #### Usage
  6664. M540 [ S ]
  6665. #### Parameters
  6666. - `S` - disabled=0, enabled=1
  6667. */
  6668. case 540:
  6669. {
  6670. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6671. }
  6672. break;
  6673. #endif
  6674. #ifdef ENABLE_AUTO_BED_LEVELING
  6675. /*!
  6676. ### M851 - Set Z-Probe Offset <a href="https://reprap.org/wiki/G-code#M851:_Set_Z-Probe_Offset">M851: Set Z-Probe Offset"</a>
  6677. 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.
  6678. 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.)
  6679. #### Usage
  6680. M851 [ Z ]
  6681. #### Parameters
  6682. - `Z` - Z offset probe to nozzle.
  6683. */
  6684. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6685. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6686. {
  6687. float value;
  6688. if (code_seen('Z'))
  6689. {
  6690. value = code_value();
  6691. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6692. {
  6693. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6694. SERIAL_ECHO_START;
  6695. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6696. SERIAL_PROTOCOLLN();
  6697. }
  6698. else
  6699. {
  6700. SERIAL_ECHO_START;
  6701. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6702. SERIAL_ECHORPGM(MSG_Z_MIN);
  6703. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6704. SERIAL_ECHORPGM(MSG_Z_MAX);
  6705. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6706. SERIAL_PROTOCOLLN();
  6707. }
  6708. }
  6709. else
  6710. {
  6711. SERIAL_ECHO_START;
  6712. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6713. SERIAL_ECHO(-cs.zprobe_zoffset);
  6714. SERIAL_PROTOCOLLN();
  6715. }
  6716. break;
  6717. }
  6718. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6719. #endif // ENABLE_AUTO_BED_LEVELING
  6720. /*!
  6721. ### M552 - Set IP address <a href="https://reprap.org/wiki/G-code#M552:_Set_IP_address.2C_enable.2Fdisable_network_interface">M552: Set IP address, enable/disable network interface"</a>
  6722. Sets the printer IP address that is shown in the support menu. Designed to be used with the help of host software.
  6723. If P is not specified nothing happens.
  6724. If the structure of the IP address is invalid, 0.0.0.0 is assumed and nothing is shown on the screen in the Support menu.
  6725. #### Usage
  6726. M552 [ P<IP_address> ]
  6727. #### Parameters
  6728. - `P` - The IP address in xxx.xxx.xxx.xxx format. Eg: P192.168.1.14
  6729. */
  6730. case 552:
  6731. {
  6732. if (code_seen('P'))
  6733. {
  6734. uint8_t valCnt = 0;
  6735. IP_address = 0;
  6736. do
  6737. {
  6738. *strchr_pointer = '*';
  6739. ((uint8_t*)&IP_address)[valCnt] = code_value_short();
  6740. valCnt++;
  6741. } while ((valCnt < 4) && code_seen('.'));
  6742. if (valCnt != 4)
  6743. IP_address = 0;
  6744. }
  6745. } break;
  6746. #ifdef FILAMENTCHANGEENABLE
  6747. /*!
  6748. ### M600 - Initiate Filament change procedure <a href="https://reprap.org/wiki/G-code#M600:_Filament_change_pause">M600: Filament change pause</a>
  6749. Initiates Filament change, it is also used during Filament Runout Sensor process.
  6750. If the `M600` is triggered under 25mm it will do a Z-lift of 25mm to prevent a filament blob.
  6751. #### Usage
  6752. M600 [ X | Y | Z | E | L | AUTO ]
  6753. - `X` - X position, default 211
  6754. - `Y` - Y position, default 0
  6755. - `Z` - relative lift Z, default 2.
  6756. - `E` - initial retract, default -2
  6757. - `L` - later retract distance for removal, default -80
  6758. - `AUTO` - Automatically (only with MMU)
  6759. */
  6760. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6761. {
  6762. st_synchronize();
  6763. float x_position = current_position[X_AXIS];
  6764. float y_position = current_position[Y_AXIS];
  6765. float z_shift = 0; // is it necessary to be a float?
  6766. float e_shift_init = 0;
  6767. float e_shift_late = 0;
  6768. bool automatic = false;
  6769. //Retract extruder
  6770. if(code_seen('E'))
  6771. {
  6772. e_shift_init = code_value();
  6773. }
  6774. else
  6775. {
  6776. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6777. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6778. #endif
  6779. }
  6780. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6781. if (code_seen('L'))
  6782. {
  6783. e_shift_late = code_value();
  6784. }
  6785. else
  6786. {
  6787. #ifdef FILAMENTCHANGE_FINALRETRACT
  6788. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6789. #endif
  6790. }
  6791. //Lift Z
  6792. if(code_seen('Z'))
  6793. {
  6794. z_shift = code_value();
  6795. }
  6796. else
  6797. {
  6798. z_shift = gcode_M600_filament_change_z_shift<uint8_t>();
  6799. }
  6800. //Move XY to side
  6801. if(code_seen('X'))
  6802. {
  6803. x_position = code_value();
  6804. }
  6805. else
  6806. {
  6807. #ifdef FILAMENTCHANGE_XPOS
  6808. x_position = FILAMENTCHANGE_XPOS;
  6809. #endif
  6810. }
  6811. if(code_seen('Y'))
  6812. {
  6813. y_position = code_value();
  6814. }
  6815. else
  6816. {
  6817. #ifdef FILAMENTCHANGE_YPOS
  6818. y_position = FILAMENTCHANGE_YPOS ;
  6819. #endif
  6820. }
  6821. if (MMU2::mmu2.Enabled() && code_seen_P(PSTR("AUTO")))
  6822. automatic = true;
  6823. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6824. }
  6825. break;
  6826. #endif //FILAMENTCHANGEENABLE
  6827. /*!
  6828. ### M601 - Pause print <a href="https://reprap.org/wiki/G-code#M601:_Pause_print">M601: Pause print</a>
  6829. */
  6830. /*!
  6831. ### M125 - Pause print (TODO: not implemented)
  6832. */
  6833. /*!
  6834. ### M25 - Pause SD print <a href="https://reprap.org/wiki/G-code#M25:_Pause_SD_print">M25: Pause SD print</a>
  6835. */
  6836. case 25:
  6837. case 601:
  6838. {
  6839. if (!isPrintPaused) {
  6840. st_synchronize();
  6841. ClearToSend(); //send OK even before the command finishes executing because we want to make sure it is not skipped because of cmdqueue_pop_front();
  6842. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  6843. lcd_pause_print();
  6844. }
  6845. }
  6846. break;
  6847. /*!
  6848. ### M602 - Resume print <a href="https://reprap.org/wiki/G-code#M602:_Resume_print">M602: Resume print</a>
  6849. */
  6850. case 602:
  6851. {
  6852. if (isPrintPaused) lcd_resume_print();
  6853. }
  6854. break;
  6855. /*!
  6856. ### M603 - Stop print <a href="https://reprap.org/wiki/G-code#M603:_Stop_print">M603: Stop print</a>
  6857. */
  6858. case 603: {
  6859. lcd_print_stop();
  6860. }
  6861. break;
  6862. #ifdef PINDA_THERMISTOR
  6863. /*!
  6864. ### 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>
  6865. Wait for PINDA thermistor to reach target temperature
  6866. #### Usage
  6867. M860 [ S ]
  6868. #### Parameters
  6869. - `S` - Target temperature
  6870. */
  6871. case 860:
  6872. {
  6873. int set_target_pinda = 0;
  6874. if (code_seen('S')) {
  6875. set_target_pinda = code_value_short();
  6876. }
  6877. else {
  6878. break;
  6879. }
  6880. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  6881. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  6882. SERIAL_PROTOCOLLN(set_target_pinda);
  6883. codenum = _millis();
  6884. cancel_heatup = false;
  6885. bool is_pinda_cooling = false;
  6886. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  6887. is_pinda_cooling = true;
  6888. }
  6889. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  6890. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  6891. {
  6892. SERIAL_PROTOCOLPGM("P:");
  6893. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  6894. SERIAL_PROTOCOL('/');
  6895. SERIAL_PROTOCOLLN(set_target_pinda);
  6896. codenum = _millis();
  6897. }
  6898. manage_heater();
  6899. manage_inactivity();
  6900. lcd_update(0);
  6901. }
  6902. LCD_MESSAGERPGM(MSG_OK);
  6903. break;
  6904. }
  6905. /*!
  6906. ### 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>
  6907. Set compensation ustep value `S` for compensation table index `I`.
  6908. #### Usage
  6909. M861 [ ? | ! | Z | S | I ]
  6910. #### Parameters
  6911. - `?` - Print current EEPROM offset values
  6912. - `!` - Set factory default values
  6913. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6914. - `S` - Microsteps
  6915. - `I` - Table index
  6916. */
  6917. case 861: {
  6918. const char * const _header = PSTR("index, temp, ustep, um");
  6919. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  6920. int16_t usteps = 0;
  6921. SERIAL_PROTOCOLPGM("PINDA cal status: ");
  6922. SERIAL_PROTOCOLLN(calibration_status_pinda());
  6923. SERIAL_PROTOCOLLNRPGM(_header);
  6924. for (uint8_t i = 0; i < 6; i++)
  6925. {
  6926. if(i > 0) {
  6927. usteps = eeprom_read_word((uint16_t*) EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6928. }
  6929. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6930. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6931. SERIAL_PROTOCOLPGM(", ");
  6932. SERIAL_PROTOCOL(35 + (i * 5));
  6933. SERIAL_PROTOCOLPGM(", ");
  6934. SERIAL_PROTOCOL(usteps);
  6935. SERIAL_PROTOCOLPGM(", ");
  6936. SERIAL_PROTOCOLLN(mm * 1000);
  6937. }
  6938. }
  6939. else if (code_seen('!')) { // ! - Set factory default values
  6940. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6941. int16_t z_shift = 8; //40C - 20um - 8usteps
  6942. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT, z_shift);
  6943. z_shift = 24; //45C - 60um - 24usteps
  6944. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 1, z_shift);
  6945. z_shift = 48; //50C - 120um - 48usteps
  6946. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 2, z_shift);
  6947. z_shift = 80; //55C - 200um - 80usteps
  6948. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 3, z_shift);
  6949. z_shift = 120; //60C - 300um - 120usteps
  6950. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 4, z_shift);
  6951. SERIAL_PROTOCOLLNPGM("factory restored");
  6952. }
  6953. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6954. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6955. int16_t z_shift = 0;
  6956. for (uint8_t i = 0; i < 5; i++) {
  6957. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  6958. }
  6959. SERIAL_PROTOCOLLNPGM("zerorized");
  6960. }
  6961. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  6962. int16_t usteps = code_value_short();
  6963. if (code_seen('I')) {
  6964. uint8_t index = code_value_uint8();
  6965. if (index < 5) {
  6966. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + index, usteps);
  6967. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  6968. SERIAL_PROTOCOLLNRPGM(_header);
  6969. for (uint8_t i = 0; i < 6; i++)
  6970. {
  6971. usteps = 0;
  6972. if (i > 0) {
  6973. usteps = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6974. }
  6975. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6976. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6977. SERIAL_PROTOCOLPGM(", ");
  6978. SERIAL_PROTOCOL(35 + (i * 5));
  6979. SERIAL_PROTOCOLPGM(", ");
  6980. SERIAL_PROTOCOL(usteps);
  6981. SERIAL_PROTOCOLPGM(", ");
  6982. SERIAL_PROTOCOLLN(mm * 1000);
  6983. }
  6984. }
  6985. }
  6986. }
  6987. else {
  6988. SERIAL_PROTOCOLLNPGM("no valid command");
  6989. }
  6990. } break;
  6991. #endif //PINDA_THERMISTOR
  6992. /*!
  6993. ### M862 - Print checking <a href="https://reprap.org/wiki/G-code#M862:_Print_checking">M862: Print checking</a>
  6994. Checks the parameters of the printer and gcode and performs compatibility check
  6995. - M862.1 { P<nozzle_diameter> | Q } 0.25/0.40/0.60
  6996. - M862.2 { P<model_code> | Q }
  6997. - M862.3 { P"<model_name>" | Q }
  6998. - M862.4 { P<fw_version> | Q }
  6999. - M862.5 { P<gcode_level> | Q }
  7000. When run with P<> argument, the check is performed against the input value.
  7001. When run with Q argument, the current value is shown.
  7002. M862.3 accepts text identifiers of printer types too.
  7003. The syntax of M862.3 is (note the quotes around the type):
  7004. M862.3 P "MK3S"
  7005. Accepted printer type identifiers and their numeric counterparts:
  7006. - MK1 (100)
  7007. - MK2 (200)
  7008. - MK2MM (201)
  7009. - MK2S (202)
  7010. - MK2SMM (203)
  7011. - MK2.5 (250)
  7012. - MK2.5MMU2 (20250)
  7013. - MK2.5S (252)
  7014. - MK2.5SMMU2S (20252)
  7015. - MK3 (300)
  7016. - MK3MMU2 (20300)
  7017. - MK3S (302)
  7018. - MK3SMMU2S (20302)
  7019. */
  7020. case 862: // M862: print checking
  7021. float nDummy;
  7022. uint8_t nCommand;
  7023. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  7024. switch((ClPrintChecking)nCommand)
  7025. {
  7026. case ClPrintChecking::_Nozzle: // ~ .1
  7027. uint16_t nDiameter;
  7028. if(code_seen('P'))
  7029. {
  7030. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  7031. nozzle_diameter_check(nDiameter);
  7032. }
  7033. else if(code_seen('Q'))
  7034. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  7035. break;
  7036. case ClPrintChecking::_Model: // ~ .2
  7037. if(code_seen('P'))
  7038. {
  7039. uint16_t nPrinterModel;
  7040. nPrinterModel=(uint16_t)code_value_long();
  7041. printer_model_check(nPrinterModel);
  7042. }
  7043. else if(code_seen('Q'))
  7044. SERIAL_PROTOCOLLN(nPrinterType);
  7045. break;
  7046. case ClPrintChecking::_Smodel: // ~ .3
  7047. if(code_seen('P'))
  7048. printer_smodel_check(strchr_pointer);
  7049. else if(code_seen('Q'))
  7050. SERIAL_PROTOCOLLNRPGM(sPrinterName);
  7051. break;
  7052. case ClPrintChecking::_Version: // ~ .4
  7053. if(code_seen('P'))
  7054. fw_version_check(++strchr_pointer);
  7055. else if(code_seen('Q'))
  7056. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  7057. break;
  7058. case ClPrintChecking::_Gcode: // ~ .5
  7059. if(code_seen('P'))
  7060. {
  7061. uint16_t nGcodeLevel;
  7062. nGcodeLevel=(uint16_t)code_value_long();
  7063. gcode_level_check(nGcodeLevel);
  7064. }
  7065. else if(code_seen('Q'))
  7066. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  7067. break;
  7068. }
  7069. break;
  7070. #ifdef LIN_ADVANCE
  7071. /*!
  7072. ### 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>
  7073. 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.
  7074. #### Usage
  7075. M900 [ K | R | W | H | D]
  7076. #### Parameters
  7077. - `K` - Advance K factor
  7078. - `R` - Set ratio directly (overrides WH/D)
  7079. - `W` - Width
  7080. - `H` - Height
  7081. - `D` - Diameter Set ratio from WH/D
  7082. */
  7083. case 900:
  7084. gcode_M900();
  7085. break;
  7086. #endif
  7087. /*!
  7088. ### 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>
  7089. Set digital trimpot motor current using axis codes (X, Y, Z, E, B, S).
  7090. M907 has no effect when the experimental Extruder motor current scaling mode is active (that applies to farm printing as well)
  7091. #### Usage
  7092. M907 [ X | Y | Z | E | B | S ]
  7093. #### Parameters
  7094. - `X` - X motor driver
  7095. - `Y` - Y motor driver
  7096. - `Z` - Z motor driver
  7097. - `E` - Extruder motor driver
  7098. - `B` - Second Extruder motor driver
  7099. - `S` - All motors
  7100. */
  7101. case 907:
  7102. {
  7103. #ifdef TMC2130
  7104. // See tmc2130_cur2val() for translation to 0 .. 63 range
  7105. for (uint_least8_t i = 0; i < NUM_AXIS; i++){
  7106. if(code_seen(axis_codes[i])){
  7107. if( i == E_AXIS && FarmOrUserECool() ){
  7108. SERIAL_ECHORPGM(eMotorCurrentScalingEnabled);
  7109. SERIAL_ECHOLNPGM(", M907 E ignored");
  7110. continue;
  7111. }
  7112. long cur_mA = code_value_long();
  7113. uint8_t val = tmc2130_cur2val(cur_mA);
  7114. tmc2130_set_current_h(i, val);
  7115. tmc2130_set_current_r(i, val);
  7116. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  7117. }
  7118. }
  7119. #else //TMC2130
  7120. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7121. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  7122. if(code_seen('B')) st_current_set(4,code_value());
  7123. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  7124. #endif
  7125. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  7126. if(code_seen('X')) st_current_set(0, code_value());
  7127. #endif
  7128. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  7129. if(code_seen('Z')) st_current_set(1, code_value());
  7130. #endif
  7131. #ifdef MOTOR_CURRENT_PWM_E_PIN
  7132. if(code_seen('E')) st_current_set(2, code_value());
  7133. #endif
  7134. #endif //TMC2130
  7135. }
  7136. break;
  7137. /*!
  7138. ### M908 - Control digital trimpot directly <a href="https://reprap.org/wiki/G-code#M908:_Control_digital_trimpot_directly">M908: Control digital trimpot directly</a>
  7139. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. Not usable on Prusa printers.
  7140. #### Usage
  7141. M908 [ P | S ]
  7142. #### Parameters
  7143. - `P` - channel
  7144. - `S` - current
  7145. */
  7146. case 908:
  7147. {
  7148. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7149. uint8_t channel,current;
  7150. if(code_seen('P')) channel=code_value();
  7151. if(code_seen('S')) current=code_value();
  7152. digitalPotWrite(channel, current);
  7153. #endif
  7154. }
  7155. break;
  7156. #ifdef TMC2130_SERVICE_CODES_M910_M918
  7157. /*!
  7158. ### M910 - TMC2130 init <a href="https://reprap.org/wiki/G-code#M910:_TMC2130_init">M910: TMC2130 init</a>
  7159. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7160. */
  7161. case 910:
  7162. {
  7163. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7164. }
  7165. break;
  7166. /*!
  7167. ### M911 - Set TMC2130 holding currents <a href="https://reprap.org/wiki/G-code#M911:_Set_TMC2130_holding_currents">M911: Set TMC2130 holding currents</a>
  7168. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7169. #### Usage
  7170. M911 [ X | Y | Z | E ]
  7171. #### Parameters
  7172. - `X` - X stepper driver holding current value
  7173. - `Y` - Y stepper driver holding current value
  7174. - `Z` - Z stepper driver holding current value
  7175. - `E` - Extruder stepper driver holding current value
  7176. */
  7177. case 911:
  7178. {
  7179. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  7180. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  7181. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  7182. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  7183. }
  7184. break;
  7185. /*!
  7186. ### M912 - Set TMC2130 running currents <a href="https://reprap.org/wiki/G-code#M912:_Set_TMC2130_running_currents">M912: Set TMC2130 running currents</a>
  7187. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7188. #### Usage
  7189. M912 [ X | Y | Z | E ]
  7190. #### Parameters
  7191. - `X` - X stepper driver running current value
  7192. - `Y` - Y stepper driver running current value
  7193. - `Z` - Z stepper driver running current value
  7194. - `E` - Extruder stepper driver running current value
  7195. */
  7196. case 912:
  7197. {
  7198. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  7199. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  7200. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  7201. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  7202. }
  7203. break;
  7204. /*!
  7205. ### M913 - Print TMC2130 currents <a href="https://reprap.org/wiki/G-code#M913:_Print_TMC2130_currents">M913: Print TMC2130 currents</a>
  7206. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7207. Shows TMC2130 currents.
  7208. */
  7209. case 913:
  7210. {
  7211. tmc2130_print_currents();
  7212. }
  7213. break;
  7214. /*!
  7215. ### M914 - Set TMC2130 normal mode <a href="https://reprap.org/wiki/G-code#M914:_Set_TMC2130_normal_mode">M914: Set TMC2130 normal mode</a>
  7216. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7217. */
  7218. case 914:
  7219. {
  7220. tmc2130_mode = TMC2130_MODE_NORMAL;
  7221. update_mode_profile();
  7222. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7223. }
  7224. break;
  7225. /*!
  7226. ### M915 - Set TMC2130 silent mode <a href="https://reprap.org/wiki/G-code#M915:_Set_TMC2130_silent_mode">M915: Set TMC2130 silent mode</a>
  7227. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7228. */
  7229. case 915:
  7230. {
  7231. tmc2130_mode = TMC2130_MODE_SILENT;
  7232. update_mode_profile();
  7233. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7234. }
  7235. break;
  7236. /*!
  7237. ### 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>
  7238. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7239. #### Usage
  7240. M916 [ X | Y | Z | E ]
  7241. #### Parameters
  7242. - `X` - X stepper driver stallguard sensitivity threshold value
  7243. - `Y` - Y stepper driver stallguard sensitivity threshold value
  7244. - `Z` - Z stepper driver stallguard sensitivity threshold value
  7245. - `E` - Extruder stepper driver stallguard sensitivity threshold value
  7246. */
  7247. case 916:
  7248. {
  7249. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  7250. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  7251. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  7252. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  7253. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  7254. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  7255. }
  7256. break;
  7257. /*!
  7258. ### 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>
  7259. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7260. #### Usage
  7261. M917 [ X | Y | Z | E ]
  7262. #### Parameters
  7263. - `X` - X stepper driver PWM amplitude offset value
  7264. - `Y` - Y stepper driver PWM amplitude offset value
  7265. - `Z` - Z stepper driver PWM amplitude offset value
  7266. - `E` - Extruder stepper driver PWM amplitude offset value
  7267. */
  7268. case 917:
  7269. {
  7270. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  7271. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  7272. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  7273. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  7274. }
  7275. break;
  7276. /*!
  7277. ### 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>
  7278. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7279. #### Usage
  7280. M918 [ X | Y | Z | E ]
  7281. #### Parameters
  7282. - `X` - X stepper driver PWM amplitude gradient value
  7283. - `Y` - Y stepper driver PWM amplitude gradient value
  7284. - `Z` - Z stepper driver PWM amplitude gradient value
  7285. - `E` - Extruder stepper driver PWM amplitude gradient value
  7286. */
  7287. case 918:
  7288. {
  7289. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  7290. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  7291. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  7292. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  7293. }
  7294. break;
  7295. #endif //TMC2130_SERVICE_CODES_M910_M918
  7296. /*!
  7297. ### M350 - Set microstepping mode <a href="https://reprap.org/wiki/G-code#M350:_Set_microstepping_mode">M350: Set microstepping mode</a>
  7298. 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!
  7299. Printers without TMC2130 drivers also have `B` and `S` options. In this case, the steps-per-unit value in not changed!
  7300. #### Usage
  7301. M350 [ X | Y | Z | E | B | S ]
  7302. #### Parameters
  7303. - `X` - X new resolution
  7304. - `Y` - Y new resolution
  7305. - `Z` - Z new resolution
  7306. - `E` - E new resolution
  7307. Only valid for MK2.5(S) or printers without TMC2130 drivers
  7308. - `B` - Second extruder new resolution
  7309. - `S` - All axes new resolution
  7310. */
  7311. case 350:
  7312. {
  7313. #ifdef TMC2130
  7314. for (uint_least8_t i=0; i<NUM_AXIS; i++)
  7315. {
  7316. if(code_seen(axis_codes[i]))
  7317. {
  7318. uint16_t res_new = code_value();
  7319. #ifdef ALLOW_ALL_MRES
  7320. bool res_valid = res_new > 0 && res_new <= 256 && !(res_new & (res_new - 1)); // must be a power of two
  7321. #else
  7322. bool res_valid = (res_new == 8) || (res_new == 16) || (res_new == 32); // resolutions valid for all axis
  7323. res_valid |= (i != E_AXIS) && ((res_new == 1) || (res_new == 2) || (res_new == 4)); // resolutions valid for X Y Z only
  7324. res_valid |= (i == E_AXIS) && ((res_new == 64) || (res_new == 128)); // resolutions valid for E only
  7325. #endif
  7326. if (res_valid)
  7327. {
  7328. st_synchronize();
  7329. uint16_t res = tmc2130_get_res(i);
  7330. tmc2130_set_res(i, res_new);
  7331. cs.axis_ustep_resolution[i] = res_new;
  7332. if (res_new > res)
  7333. {
  7334. uint16_t fac = (res_new / res);
  7335. cs.axis_steps_per_unit[i] *= fac;
  7336. position[i] *= fac;
  7337. }
  7338. else
  7339. {
  7340. uint16_t fac = (res / res_new);
  7341. cs.axis_steps_per_unit[i] /= fac;
  7342. position[i] /= fac;
  7343. }
  7344. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7345. if (i == E_AXIS)
  7346. fsensor.init();
  7347. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7348. }
  7349. }
  7350. }
  7351. reset_acceleration_rates();
  7352. #else //TMC2130
  7353. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7354. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  7355. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  7356. if(code_seen('B')) microstep_mode(4,code_value());
  7357. microstep_readings();
  7358. #endif
  7359. #endif //TMC2130
  7360. }
  7361. break;
  7362. /*!
  7363. ### 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>
  7364. Toggle MS1 MS2 pins directly.
  7365. #### Usage
  7366. M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  7367. #### Parameters
  7368. - `X` - Update X axis
  7369. - `Y` - Update Y axis
  7370. - `Z` - Update Z axis
  7371. - `E` - Update E axis
  7372. - `S` - which MSx pin to toggle
  7373. - `B` - new pin value
  7374. */
  7375. case 351:
  7376. {
  7377. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7378. if(code_seen('S')) switch((int)code_value())
  7379. {
  7380. case 1:
  7381. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  7382. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  7383. break;
  7384. case 2:
  7385. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  7386. if(code_seen('B')) microstep_ms(4,-1,code_value());
  7387. break;
  7388. }
  7389. microstep_readings();
  7390. #endif
  7391. }
  7392. break;
  7393. /*!
  7394. ### M701 - Load filament <a href="https://reprap.org/wiki/G-code#M701:_Load_filament">M701: Load filament</a>
  7395. #### Usage
  7396. M701 [ E | T ]
  7397. #### Parameters
  7398. - `E` - ID of filament to load, ranges from 0 to 4
  7399. - `T` - Alias of `E`. Used for compatibility with Marlin
  7400. */
  7401. case 701:
  7402. {
  7403. uint8_t mmuSlotIndex = 0xffU;
  7404. if (MMU2::mmu2.Enabled() && code_seen('E'))
  7405. mmuSlotIndex = code_value_uint8();
  7406. gcode_M701(mmuSlotIndex);
  7407. }
  7408. break;
  7409. /*!
  7410. ### M702 - Unload filament <a href="https://reprap.org/wiki/G-code#M702:_Unload_filament">G32: Undock Z Probe sled</a>
  7411. #### Usage
  7412. M702 [ C ]
  7413. #### Parameters
  7414. - `C` - Unload just current filament
  7415. - without any parameters unload all filaments
  7416. */
  7417. case 702:
  7418. {
  7419. if (code_seen('C')) {
  7420. if(MMU2::mmu2.Enabled()) MMU2::mmu2.unload(); //! if "C" unload current filament; if mmu is not present no action is performed
  7421. }
  7422. else {
  7423. if(MMU2::mmu2.Enabled()) MMU2::mmu2.unload(); //! unload current filament
  7424. else unload_filament();
  7425. }
  7426. }
  7427. break;
  7428. /*!
  7429. #### End of M-Commands
  7430. */
  7431. default:
  7432. printf_P(MSG_UNKNOWN_CODE, 'M', cmdbuffer + bufindr + CMDHDRSIZE);
  7433. }
  7434. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  7435. mcode_in_progress = 0;
  7436. }
  7437. }
  7438. // end if(code_seen('M')) (end of M codes)
  7439. /*!
  7440. -----------------------------------------------------------------------------------------
  7441. # T Codes
  7442. T<extruder nr.> - select extruder in case of multi extruder printer. select filament in case of MMU_V2.
  7443. #### For MMU_V2:
  7444. T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  7445. @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  7446. @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.
  7447. @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  7448. */
  7449. else if(code_seen('T')){
  7450. TCodes(strchr_pointer, code_value());
  7451. } // end if(code_seen('T')) (end of T codes)
  7452. /*!
  7453. #### End of T-Codes
  7454. */
  7455. /**
  7456. *---------------------------------------------------------------------------------
  7457. *# D codes
  7458. */
  7459. else if (code_seen('D')) // D codes (debug)
  7460. {
  7461. switch(code_value_short())
  7462. {
  7463. /*!
  7464. ### D-1 - Endless Loop <a href="https://reprap.org/wiki/G-code#D-1:_Endless_Loop">D-1: Endless Loop</a>
  7465. */
  7466. case -1:
  7467. dcode__1(); break;
  7468. #ifdef DEBUG_DCODES
  7469. /*!
  7470. ### D0 - Reset <a href="https://reprap.org/wiki/G-code#D0:_Reset">D0: Reset</a>
  7471. #### Usage
  7472. D0 [ B ]
  7473. #### Parameters
  7474. - `B` - Bootloader
  7475. */
  7476. case 0:
  7477. dcode_0(); break;
  7478. /*!
  7479. *
  7480. ### D1 - Clear EEPROM and RESET <a href="https://reprap.org/wiki/G-code#D1:_Clear_EEPROM_and_RESET">D1: Clear EEPROM and RESET</a>
  7481. D1
  7482. *
  7483. */
  7484. case 1:
  7485. dcode_1(); break;
  7486. #endif
  7487. #if defined DEBUG_DCODE2 || defined DEBUG_DCODES
  7488. /*!
  7489. ### D2 - Read/Write RAM <a href="https://reprap.org/wiki/G-code#D2:_Read.2FWrite_RAM">D3: Read/Write RAM</a>
  7490. This command can be used without any additional parameters. It will read the entire RAM.
  7491. #### Usage
  7492. D2 [ A | C | X ]
  7493. #### Parameters
  7494. - `A` - Address (x0000-x1fff)
  7495. - `C` - Count (1-8192)
  7496. - `X` - Data
  7497. #### Notes
  7498. - The hex address needs to be lowercase without the 0 before the x
  7499. - Count is decimal
  7500. - The hex data needs to be lowercase
  7501. */
  7502. case 2:
  7503. dcode_2(); break;
  7504. #endif //DEBUG_DCODES
  7505. #if defined DEBUG_DCODE3 || defined DEBUG_DCODES
  7506. /*!
  7507. ### D3 - Read/Write EEPROM <a href="https://reprap.org/wiki/G-code#D3:_Read.2FWrite_EEPROM">D3: Read/Write EEPROM</a>
  7508. This command can be used without any additional parameters. It will read the entire eeprom.
  7509. #### Usage
  7510. D3 [ A | C | X ]
  7511. #### Parameters
  7512. - `A` - Address (x0000-x0fff)
  7513. - `C` - Count (1-4096)
  7514. - `X` - Data (hex)
  7515. #### Notes
  7516. - The hex address needs to be lowercase without the 0 before the x
  7517. - Count is decimal
  7518. - The hex data needs to be lowercase
  7519. */
  7520. case 3:
  7521. dcode_3(); break;
  7522. #endif //DEBUG_DCODE3
  7523. #ifdef DEBUG_DCODES
  7524. /*!
  7525. ### D4 - Read/Write PIN <a href="https://reprap.org/wiki/G-code#D4:_Read.2FWrite_PIN">D4: Read/Write PIN</a>
  7526. To read the digital value of a pin you need only to define the pin number.
  7527. #### Usage
  7528. D4 [ P | F | V ]
  7529. #### Parameters
  7530. - `P` - Pin (0-255)
  7531. - `F` - Function in/out (0/1)
  7532. - `V` - Value (0/1)
  7533. */
  7534. case 4:
  7535. dcode_4(); break;
  7536. #endif //DEBUG_DCODES
  7537. #if defined DEBUG_DCODE5 || defined DEBUG_DCODES
  7538. /*!
  7539. ### D5 - Read/Write FLASH <a href="https://reprap.org/wiki/G-code#D5:_Read.2FWrite_FLASH">D5: Read/Write Flash</a>
  7540. This command can be used without any additional parameters. It will read the 1kb FLASH.
  7541. #### Usage
  7542. D5 [ A | C | X | E ]
  7543. #### Parameters
  7544. - `A` - Address (x00000-x3ffff)
  7545. - `C` - Count (1-8192)
  7546. - `X` - Data (hex)
  7547. - `E` - Erase
  7548. #### Notes
  7549. - The hex address needs to be lowercase without the 0 before the x
  7550. - Count is decimal
  7551. - The hex data needs to be lowercase
  7552. */
  7553. case 5:
  7554. dcode_5(); break;
  7555. #endif //DEBUG_DCODE5
  7556. #if defined DEBUG_DCODE6 || defined DEBUG_DCODES
  7557. /*!
  7558. ### D6 - Read/Write external FLASH <a href="https://reprap.org/wiki/G-code#D6:_Read.2FWrite_external_FLASH">D6: Read/Write external Flash</a>
  7559. Reserved
  7560. */
  7561. case 6:
  7562. dcode_6(); break;
  7563. #endif
  7564. #ifdef DEBUG_DCODES
  7565. /*!
  7566. ### D7 - Read/Write Bootloader <a href="https://reprap.org/wiki/G-code#D7:_Read.2FWrite_Bootloader">D7: Read/Write Bootloader</a>
  7567. Reserved
  7568. */
  7569. case 7:
  7570. dcode_7(); break;
  7571. /*!
  7572. ### D8 - Read/Write PINDA <a href="https://reprap.org/wiki/G-code#D8:_Read.2FWrite_PINDA">D8: Read/Write PINDA</a>
  7573. #### Usage
  7574. D8 [ ? | ! | P | Z ]
  7575. #### Parameters
  7576. - `?` - Read PINDA temperature shift values
  7577. - `!` - Reset PINDA temperature shift values to default
  7578. - `P` - Pinda temperature [C]
  7579. - `Z` - Z Offset [mm]
  7580. */
  7581. case 8:
  7582. dcode_8(); break;
  7583. /*!
  7584. ### D9 - Read ADC <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9: Read ADC</a>
  7585. #### Usage
  7586. D9 [ I | V ]
  7587. #### Parameters
  7588. - `I` - ADC channel index
  7589. - `0` - Heater 0 temperature
  7590. - `1` - Heater 1 temperature
  7591. - `2` - Bed temperature
  7592. - `3` - PINDA temperature
  7593. - `4` - PWR voltage
  7594. - `5` - Ambient temperature
  7595. - `6` - BED voltage
  7596. - `V` Value to be written as simulated
  7597. */
  7598. case 9:
  7599. dcode_9(); break;
  7600. /*!
  7601. ### 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>
  7602. */
  7603. case 10:
  7604. dcode_10(); break;
  7605. /*!
  7606. ### D12 - Time <a href="https://reprap.org/wiki/G-code#D12:_Time">D12: Time</a>
  7607. Writes the current time in the log file.
  7608. */
  7609. #endif //DEBUG_DCODES
  7610. #ifdef XFLASH_DUMP
  7611. /*!
  7612. ### D20 - Generate an offline crash dump <a href="https://reprap.org/wiki/G-code#D20:_Generate_an_offline_crash_dump">D20: Generate an offline crash dump</a>
  7613. Generate a crash dump for later retrival.
  7614. #### Usage
  7615. D20 [E]
  7616. ### Parameters
  7617. - `E` - Perform an emergency crash dump (resets the printer).
  7618. ### Notes
  7619. - A crash dump can be later recovered with D21, or cleared with D22.
  7620. - An emergency crash dump includes register data, but will cause the printer to reset after the dump
  7621. is completed.
  7622. */
  7623. case 20: {
  7624. dcode_20();
  7625. break;
  7626. };
  7627. /*!
  7628. ### D21 - Print crash dump to serial <a href="https://reprap.org/wiki/G-code#D21:_Print_crash_dump_to_serial">D21: Print crash dump to serial</a>
  7629. Output the complete crash dump (if present) to the serial.
  7630. #### Usage
  7631. D21
  7632. ### Notes
  7633. - The starting address can vary between builds, but it's always at the beginning of the data section.
  7634. */
  7635. case 21: {
  7636. dcode_21();
  7637. break;
  7638. };
  7639. /*!
  7640. ### D22 - Clear crash dump state <a href="https://reprap.org/wiki/G-code#D22:_Clear_crash_dump_state">D22: Clear crash dump state</a>
  7641. Clear an existing internal crash dump.
  7642. #### Usage
  7643. D22
  7644. */
  7645. case 22: {
  7646. dcode_22();
  7647. break;
  7648. };
  7649. #endif //XFLASH_DUMP
  7650. #ifdef EMERGENCY_SERIAL_DUMP
  7651. /*!
  7652. ### D23 - Request emergency dump on serial <a href="https://reprap.org/wiki/G-code#D23:_Request_emergency_dump_on_serial">D23: Request emergency dump on serial</a>
  7653. On boards without offline dump support, request online dumps to the serial port on firmware faults.
  7654. When online dumps are enabled, the FW will dump memory on the serial before resetting.
  7655. #### Usage
  7656. D23 [E] [R]
  7657. #### Parameters
  7658. - `E` - Perform an emergency crash dump (resets the printer).
  7659. - `R` - Disable online dumps.
  7660. */
  7661. case 23: {
  7662. dcode_23();
  7663. break;
  7664. };
  7665. #endif
  7666. #ifdef TEMP_MODEL_DEBUG
  7667. /*!
  7668. ## D70 - Enable low-level temperature model logging for offline simulation
  7669. #### Usage
  7670. D70 [ S ]
  7671. #### Parameters
  7672. - `S` - Enable 0-1 (default 0)
  7673. */
  7674. case 70: {
  7675. if(code_seen('S'))
  7676. temp_model_log_enable(code_value_short());
  7677. break;
  7678. }
  7679. #endif
  7680. #ifdef HEATBED_ANALYSIS
  7681. /*!
  7682. ### D80 - Bed check <a href="https://reprap.org/wiki/G-code#D80:_Bed_check">D80: Bed check</a>
  7683. This command will log data to SD card file "mesh.txt".
  7684. #### Usage
  7685. D80 [ E | F | G | H | I | J ]
  7686. #### Parameters
  7687. - `E` - Dimension X (default 40)
  7688. - `F` - Dimention Y (default 40)
  7689. - `G` - Points X (default 40)
  7690. - `H` - Points Y (default 40)
  7691. - `I` - Offset X (default 74)
  7692. - `J` - Offset Y (default 34)
  7693. */
  7694. case 80:
  7695. dcode_80(); break;
  7696. /*!
  7697. ### D81 - Bed analysis <a href="https://reprap.org/wiki/G-code#D81:_Bed_analysis">D80: Bed analysis</a>
  7698. This command will log data to SD card file "wldsd.txt".
  7699. #### Usage
  7700. D81 [ E | F | G | H | I | J ]
  7701. #### Parameters
  7702. - `E` - Dimension X (default 40)
  7703. - `F` - Dimention Y (default 40)
  7704. - `G` - Points X (default 40)
  7705. - `H` - Points Y (default 40)
  7706. - `I` - Offset X (default 74)
  7707. - `J` - Offset Y (default 34)
  7708. */
  7709. case 81:
  7710. dcode_81(); break;
  7711. #endif //HEATBED_ANALYSIS
  7712. #ifdef DEBUG_DCODES
  7713. /*!
  7714. ### 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>
  7715. */
  7716. case 106:
  7717. dcode_106(); break;
  7718. #ifdef TMC2130
  7719. /*!
  7720. ### D2130 - Trinamic stepper controller <a href="https://reprap.org/wiki/G-code#D2130:_Trinamic_stepper_controller">D2130: Trinamic stepper controller</a>
  7721. @todo Please review by owner of the code. RepRap Wiki Gcode needs to be updated after review of owner as well.
  7722. #### Usage
  7723. D2130 [ Axis | Command | Subcommand | Value ]
  7724. #### Parameters
  7725. - Axis
  7726. - `X` - X stepper driver
  7727. - `Y` - Y stepper driver
  7728. - `Z` - Z stepper driver
  7729. - `E` - Extruder stepper driver
  7730. - Commands
  7731. - `0` - Current off
  7732. - `1` - Current on
  7733. - `+` - Single step
  7734. - `-` - Single step oposite direction
  7735. - `NNN` - Value sereval steps
  7736. - `?` - Read register
  7737. - Subcommands for read register
  7738. - `mres` - Micro step resolution. More information in datasheet '5.5.2 CHOPCONF – Chopper Configuration'
  7739. - `step` - Step
  7740. - `mscnt` - Microstep counter. More information in datasheet '5.5 Motor Driver Registers'
  7741. - `mscuract` - Actual microstep current for motor. More information in datasheet '5.5 Motor Driver Registers'
  7742. - `wave` - Microstep linearity compensation curve
  7743. - `!` - Set register
  7744. - Subcommands for set register
  7745. - `mres` - Micro step resolution
  7746. - `step` - Step
  7747. - `wave` - Microstep linearity compensation curve
  7748. - Values for set register
  7749. - `0, 180 --> 250` - Off
  7750. - `0.9 --> 1.25` - Valid values (recommended is 1.1)
  7751. - `@` - Home calibrate axis
  7752. Examples:
  7753. D2130E?wave
  7754. Print extruder microstep linearity compensation curve
  7755. D2130E!wave0
  7756. Disable extruder linearity compensation curve, (sine curve is used)
  7757. D2130E!wave220
  7758. (sin(x))^1.1 extruder microstep compensation curve used
  7759. Notes:
  7760. For more information see https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC2130_datasheet.pdf
  7761. *
  7762. */
  7763. case 2130:
  7764. dcode_2130(); break;
  7765. #endif //TMC2130
  7766. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7767. /*!
  7768. ### D9125 - PAT9125 filament sensor <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9125: PAT9125 filament sensor</a>
  7769. #### Usage
  7770. D9125 [ ? | ! | R | X | Y | L ]
  7771. #### Parameters
  7772. - `?` - Print values
  7773. - `!` - Print values
  7774. - `R` - Resolution. Not active in code
  7775. - `X` - X values
  7776. - `Y` - Y values
  7777. - `L` - Activate filament sensor log
  7778. */
  7779. case 9125:
  7780. dcode_9125(); break;
  7781. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7782. #endif //DEBUG_DCODES
  7783. default:
  7784. printf_P(MSG_UNKNOWN_CODE, 'D', cmdbuffer + bufindr + CMDHDRSIZE);
  7785. }
  7786. }
  7787. else
  7788. {
  7789. SERIAL_ECHO_START;
  7790. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  7791. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  7792. SERIAL_ECHOLNPGM("\"(2)");
  7793. }
  7794. KEEPALIVE_STATE(NOT_BUSY);
  7795. ClearToSend();
  7796. }
  7797. /*!
  7798. #### End of D-Codes
  7799. */
  7800. /** @defgroup GCodes G-Code List
  7801. */
  7802. // ---------------------------------------------------
  7803. void FlushSerialRequestResend()
  7804. {
  7805. //char cmdbuffer[bufindr][100]="Resend:";
  7806. MYSERIAL.flush();
  7807. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  7808. }
  7809. // Confirm the execution of a command, if sent from a serial line.
  7810. // Execution of a command from a SD card will not be confirmed.
  7811. void ClearToSend()
  7812. {
  7813. previous_millis_cmd.start();
  7814. if (buflen && ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  7815. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7816. }
  7817. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7818. void update_currents() {
  7819. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  7820. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  7821. float tmp_motor[3];
  7822. //SERIAL_ECHOLNPGM("Currents updated: ");
  7823. if (destination[Z_AXIS] < Z_SILENT) {
  7824. //SERIAL_ECHOLNPGM("LOW");
  7825. for (uint8_t i = 0; i < 3; i++) {
  7826. st_current_set(i, current_low[i]);
  7827. /*MYSERIAL.print(int(i));
  7828. SERIAL_ECHOPGM(": ");
  7829. MYSERIAL.println(current_low[i]);*/
  7830. }
  7831. }
  7832. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  7833. //SERIAL_ECHOLNPGM("HIGH");
  7834. for (uint8_t i = 0; i < 3; i++) {
  7835. st_current_set(i, current_high[i]);
  7836. /*MYSERIAL.print(int(i));
  7837. SERIAL_ECHOPGM(": ");
  7838. MYSERIAL.println(current_high[i]);*/
  7839. }
  7840. }
  7841. else {
  7842. for (uint8_t i = 0; i < 3; i++) {
  7843. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  7844. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  7845. st_current_set(i, tmp_motor[i]);
  7846. /*MYSERIAL.print(int(i));
  7847. SERIAL_ECHOPGM(": ");
  7848. MYSERIAL.println(tmp_motor[i]);*/
  7849. }
  7850. }
  7851. }
  7852. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7853. void get_coordinates() {
  7854. bool seen[4]={false,false,false,false};
  7855. for(int8_t i=0; i < NUM_AXIS; i++) {
  7856. if(code_seen(axis_codes[i]))
  7857. {
  7858. bool relative = axis_relative_modes & (1 << i);
  7859. destination[i] = code_value();
  7860. if (i == E_AXIS) {
  7861. float emult = extruder_multiplier[active_extruder];
  7862. if (emult != 1.) {
  7863. if (! relative) {
  7864. destination[i] -= current_position[i];
  7865. relative = true;
  7866. }
  7867. destination[i] *= emult;
  7868. }
  7869. }
  7870. if (relative)
  7871. destination[i] += current_position[i];
  7872. seen[i]=true;
  7873. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7874. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  7875. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7876. }
  7877. else destination[i] = current_position[i]; //Are these else lines really needed?
  7878. }
  7879. if(code_seen('F')) {
  7880. next_feedrate = code_value();
  7881. if(next_feedrate > 0.0) feedrate = next_feedrate;
  7882. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  7883. {
  7884. // float e_max_speed =
  7885. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  7886. }
  7887. }
  7888. }
  7889. void clamp_to_software_endstops(float target[3])
  7890. {
  7891. #ifdef DEBUG_DISABLE_SWLIMITS
  7892. return;
  7893. #endif //DEBUG_DISABLE_SWLIMITS
  7894. world2machine_clamp(target[0], target[1]);
  7895. // Clamp the Z coordinate.
  7896. if (min_software_endstops) {
  7897. float negative_z_offset = 0;
  7898. #ifdef ENABLE_AUTO_BED_LEVELING
  7899. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  7900. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  7901. #endif
  7902. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  7903. }
  7904. if (max_software_endstops) {
  7905. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  7906. }
  7907. }
  7908. uint16_t restore_interrupted_gcode() {
  7909. // When recovering from a previous print move, restore the originally
  7910. // calculated start position on the first USB/SD command. This accounts
  7911. // properly for relative moves
  7912. if (
  7913. (saved_start_position[0] != SAVED_START_POSITION_UNSET) && (
  7914. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) ||
  7915. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)
  7916. )
  7917. ) {
  7918. memcpy(current_position, saved_start_position, sizeof(current_position));
  7919. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  7920. return saved_segment_idx;
  7921. }
  7922. else
  7923. return 1; //begin with the first segment
  7924. }
  7925. #ifdef MESH_BED_LEVELING
  7926. 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, uint16_t start_segment_idx = 0) {
  7927. float dx = x - current_position[X_AXIS];
  7928. float dy = y - current_position[Y_AXIS];
  7929. uint16_t n_segments = 0;
  7930. if (mbl.active) {
  7931. float len = fabs(dx) + fabs(dy);
  7932. if (len > 0)
  7933. // Split to 3cm segments or shorter.
  7934. n_segments = uint16_t(ceil(len / 30.f));
  7935. }
  7936. if (n_segments > 1 && start_segment_idx) {
  7937. float dz = z - current_position[Z_AXIS];
  7938. float de = e - current_position[E_AXIS];
  7939. for (uint16_t i = start_segment_idx; i < n_segments; ++ i) {
  7940. float t = float(i) / float(n_segments);
  7941. plan_buffer_line(current_position[X_AXIS] + t * dx,
  7942. current_position[Y_AXIS] + t * dy,
  7943. current_position[Z_AXIS] + t * dz,
  7944. current_position[E_AXIS] + t * de,
  7945. feed_rate, extruder, current_position, i);
  7946. if (planner_aborted)
  7947. return;
  7948. }
  7949. }
  7950. // The rest of the path.
  7951. plan_buffer_line(x, y, z, e, feed_rate, extruder, current_position);
  7952. }
  7953. #endif // MESH_BED_LEVELING
  7954. void prepare_move(uint16_t start_segment_idx)
  7955. {
  7956. clamp_to_software_endstops(destination);
  7957. previous_millis_cmd.start();
  7958. // Do not use feedmultiply for E or Z only moves
  7959. if((current_position[X_AXIS] == destination[X_AXIS]) && (current_position[Y_AXIS] == destination[Y_AXIS])) {
  7960. plan_buffer_line_destinationXYZE(feedrate/60);
  7961. }
  7962. else {
  7963. #ifdef MESH_BED_LEVELING
  7964. 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, start_segment_idx);
  7965. #else
  7966. plan_buffer_line_destinationXYZE(feedrate*feedmultiply*(1./(60.f*100.f)));
  7967. #endif
  7968. }
  7969. set_current_to_destination();
  7970. }
  7971. void prepare_arc_move(bool isclockwise, uint16_t start_segment_idx) {
  7972. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  7973. // Trace the arc
  7974. mc_arc(current_position, destination, offset, feedrate * feedmultiply / 60 / 100.0, r, isclockwise, active_extruder, start_segment_idx);
  7975. // As far as the parser is concerned, the position is now == target. In reality the
  7976. // motion control system might still be processing the action and the real tool position
  7977. // in any intermediate location.
  7978. set_current_to_destination();
  7979. previous_millis_cmd.start();
  7980. }
  7981. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  7982. #if defined(FAN_PIN)
  7983. #if CONTROLLERFAN_PIN == FAN_PIN
  7984. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  7985. #endif
  7986. #endif
  7987. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  7988. unsigned long lastMotorCheck = 0;
  7989. void controllerFan()
  7990. {
  7991. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  7992. {
  7993. lastMotorCheck = _millis();
  7994. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  7995. #if EXTRUDERS > 2
  7996. || !READ(E2_ENABLE_PIN)
  7997. #endif
  7998. #if EXTRUDER > 1
  7999. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  8000. || !READ(X2_ENABLE_PIN)
  8001. #endif
  8002. || !READ(E1_ENABLE_PIN)
  8003. #endif
  8004. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  8005. {
  8006. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  8007. }
  8008. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  8009. {
  8010. digitalWrite(CONTROLLERFAN_PIN, 0);
  8011. analogWrite(CONTROLLERFAN_PIN, 0);
  8012. }
  8013. else
  8014. {
  8015. // allows digital or PWM fan output to be used (see M42 handling)
  8016. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8017. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8018. }
  8019. }
  8020. }
  8021. #endif
  8022. #ifdef SAFETYTIMER
  8023. /**
  8024. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  8025. *
  8026. * Full screen blocking notification message is shown after heater turning off.
  8027. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  8028. * damage print.
  8029. *
  8030. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  8031. */
  8032. static void handleSafetyTimer()
  8033. {
  8034. #if (EXTRUDERS > 1)
  8035. #error Implemented only for one extruder.
  8036. #endif //(EXTRUDERS > 1)
  8037. if (printer_active() || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  8038. {
  8039. safetyTimer.stop();
  8040. }
  8041. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  8042. {
  8043. safetyTimer.start();
  8044. }
  8045. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  8046. {
  8047. setTargetBed(0);
  8048. setAllTargetHotends(0);
  8049. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED c=20 r=4
  8050. }
  8051. }
  8052. #endif //SAFETYTIMER
  8053. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  8054. {
  8055. #ifdef FILAMENT_SENSOR
  8056. if (fsensor.update()) {
  8057. lcd_draw_update = 1; //cause lcd update so that fsensor event polling can be done from the lcd draw routine.
  8058. }
  8059. #endif
  8060. #ifdef SAFETYTIMER
  8061. handleSafetyTimer();
  8062. #endif //SAFETYTIMER
  8063. #if defined(KILL_PIN) && KILL_PIN > -1
  8064. static int killCount = 0; // make the inactivity button a bit less responsive
  8065. const int KILL_DELAY = 10000;
  8066. #endif
  8067. if(buflen < (BUFSIZE-1)){
  8068. get_command();
  8069. }
  8070. if(previous_millis_cmd.expired(max_inactive_time))
  8071. if(max_inactive_time)
  8072. kill(_n("Inactivity Shutdown"), 4);
  8073. if(stepper_inactive_time) {
  8074. if(previous_millis_cmd.expired(stepper_inactive_time))
  8075. {
  8076. if(blocks_queued() == false && ignore_stepper_queue == false) {
  8077. disable_x();
  8078. disable_y();
  8079. disable_z();
  8080. disable_e0();
  8081. disable_e1();
  8082. disable_e2();
  8083. }
  8084. }
  8085. }
  8086. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  8087. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  8088. {
  8089. chdkActive = false;
  8090. WRITE(CHDK, LOW);
  8091. }
  8092. #endif
  8093. #if defined(KILL_PIN) && KILL_PIN > -1
  8094. // Check if the kill button was pressed and wait just in case it was an accidental
  8095. // key kill key press
  8096. // -------------------------------------------------------------------------------
  8097. if( 0 == READ(KILL_PIN) )
  8098. {
  8099. killCount++;
  8100. }
  8101. else if (killCount > 0)
  8102. {
  8103. killCount--;
  8104. }
  8105. // Exceeded threshold and we can confirm that it was not accidental
  8106. // KILL the machine
  8107. // ----------------------------------------------------------------
  8108. if ( killCount >= KILL_DELAY)
  8109. {
  8110. kill(NULL, 5);
  8111. }
  8112. #endif
  8113. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8114. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  8115. #endif
  8116. #ifdef EXTRUDER_RUNOUT_PREVENT
  8117. if(previous_millis_cmd.expired(EXTRUDER_RUNOUT_SECONDS*1000))
  8118. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  8119. {
  8120. bool oldstatus=READ(E0_ENABLE_PIN);
  8121. enable_e0();
  8122. float oldepos=current_position[E_AXIS];
  8123. float oldedes=destination[E_AXIS];
  8124. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  8125. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  8126. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  8127. current_position[E_AXIS]=oldepos;
  8128. destination[E_AXIS]=oldedes;
  8129. plan_set_e_position(oldepos);
  8130. previous_millis_cmd.start();
  8131. st_synchronize();
  8132. WRITE(E0_ENABLE_PIN,oldstatus);
  8133. }
  8134. #endif
  8135. check_axes_activity();
  8136. MMU2::mmu2.mmu_loop();
  8137. // handle longpress
  8138. if(lcd_longpress_trigger)
  8139. {
  8140. // long press is not possible in modal mode, wait until ready
  8141. if (lcd_longpress_func && lcd_update_enabled)
  8142. {
  8143. lcd_longpress_func();
  8144. lcd_longpress_trigger = 0;
  8145. }
  8146. }
  8147. #if defined(AUTO_REPORT)
  8148. host_autoreport();
  8149. #endif //AUTO_REPORT
  8150. host_keepalive();
  8151. }
  8152. void kill(const char *full_screen_message, unsigned char id)
  8153. {
  8154. printf_P(_N("KILL: %d\n"), id);
  8155. //return;
  8156. cli(); // Stop interrupts
  8157. disable_heater();
  8158. disable_x();
  8159. // SERIAL_ECHOLNPGM("kill - disable Y");
  8160. disable_y();
  8161. poweroff_z();
  8162. disable_e0();
  8163. disable_e1();
  8164. disable_e2();
  8165. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  8166. pinMode(PS_ON_PIN,INPUT);
  8167. #endif
  8168. SERIAL_ERROR_START;
  8169. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  8170. if (full_screen_message != NULL) {
  8171. SERIAL_ERRORLNRPGM(full_screen_message);
  8172. lcd_display_message_fullscreen_P(full_screen_message);
  8173. } else {
  8174. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  8175. }
  8176. // FMC small patch to update the LCD before ending
  8177. sei(); // enable interrupts
  8178. for ( int i=5; i--; lcd_update(0))
  8179. {
  8180. _delay(200);
  8181. }
  8182. cli(); // disable interrupts
  8183. suicide();
  8184. while(1)
  8185. {
  8186. #ifdef WATCHDOG
  8187. wdt_reset();
  8188. #endif //WATCHDOG
  8189. /* Intentionally left empty */
  8190. } // Wait for reset
  8191. }
  8192. void UnconditionalStop()
  8193. {
  8194. CRITICAL_SECTION_START;
  8195. // Disable all heaters and unroll the temperature wait loop stack
  8196. disable_heater();
  8197. cancel_heatup = true;
  8198. heating_status = HeatingStatus::NO_HEATING;
  8199. // Clear any saved printing state
  8200. cancel_saved_printing();
  8201. // Abort the planner
  8202. planner_abort_hard();
  8203. // Reset the queue
  8204. cmdqueue_reset();
  8205. cmdqueue_serial_disabled = false;
  8206. // Reset the sd status
  8207. card.sdprinting = false;
  8208. card.closefile();
  8209. st_reset_timer();
  8210. CRITICAL_SECTION_END;
  8211. }
  8212. // Emergency stop used by overtemp functions which allows recovery
  8213. // WARNING: This function is called *continuously* during a thermal failure.
  8214. //
  8215. // This either pauses (for thermal model errors) or stops *without recovery* depending on
  8216. // "allow_pause". If pause is allowed, this forces a printer-initiated instantanenous pause (just
  8217. // like an LCD pause) that bypasses the host pausing functionality. In this state the printer is
  8218. // kept in busy state and *must* be recovered from the LCD.
  8219. void ThermalStop(bool allow_pause)
  8220. {
  8221. if(Stopped == false) {
  8222. Stopped = true;
  8223. if(allow_pause && (IS_SD_PRINTING || usb_timer.running())) {
  8224. if (!isPrintPaused) {
  8225. lcd_setalertstatuspgm(_T(MSG_PAUSED_THERMAL_ERROR), LCD_STATUS_CRITICAL);
  8226. // we cannot make a distinction for the host here, the pause must be instantaneous
  8227. // so we call the lcd_pause_print to save the print state internally. Thermal errors
  8228. // disable heaters and save the original temperatures to saved_*, which will get
  8229. // overwritten by stop_and_save_print_to_ram. For this corner-case, re-instate the
  8230. // original values after the pause handler is called.
  8231. float bed_temp = saved_bed_temperature;
  8232. float ext_temp = saved_extruder_temperature;
  8233. int fan_speed = saved_fan_speed;
  8234. lcd_pause_print();
  8235. saved_bed_temperature = bed_temp;
  8236. saved_extruder_temperature = ext_temp;
  8237. saved_fan_speed = fan_speed;
  8238. }
  8239. } else {
  8240. // We got a hard thermal error and/or there is no print going on. Just stop.
  8241. lcd_print_stop();
  8242. // Also prevent further menu entry
  8243. menu_set_block(MENU_BLOCK_THERMAL_ERROR);
  8244. }
  8245. // Report the status on the serial, switch to a busy state
  8246. SERIAL_ERROR_START;
  8247. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  8248. // Eventually report the stopped status on the lcd (though this is usually overridden by a
  8249. // higher-priority alert status message)
  8250. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  8251. // Make a warning sound! We cannot use Sound_MakeCustom as this would stop further moves.
  8252. // Turn on the speaker here (if not already), and turn it off when back in the main loop.
  8253. WRITE(BEEPER, HIGH);
  8254. }
  8255. // Return to the status screen to stop any pending menu action which could have been
  8256. // started by the user while stuck in the Stopped state. This also ensures the NEW
  8257. // error is immediately shown.
  8258. if (menu_menu != lcd_status_screen)
  8259. lcd_return_to_status();
  8260. }
  8261. bool IsStopped() { return Stopped; };
  8262. void finishAndDisableSteppers()
  8263. {
  8264. st_synchronize();
  8265. disable_x();
  8266. disable_y();
  8267. disable_z();
  8268. disable_e0();
  8269. disable_e1();
  8270. disable_e2();
  8271. #ifndef LA_NOCOMPAT
  8272. // Steppers are disabled both when a print is stopped and also via M84 (which is additionally
  8273. // checked-for to indicate a complete file), so abuse this function to reset the LA detection
  8274. // state for the next print.
  8275. la10c_reset();
  8276. #endif
  8277. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  8278. print_time_remaining_init();
  8279. }
  8280. #ifdef FAST_PWM_FAN
  8281. void setPwmFrequency(uint8_t pin, int val)
  8282. {
  8283. val &= 0x07;
  8284. switch(digitalPinToTimer(pin))
  8285. {
  8286. #if defined(TCCR0A)
  8287. case TIMER0A:
  8288. case TIMER0B:
  8289. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8290. // TCCR0B |= val;
  8291. break;
  8292. #endif
  8293. #if defined(TCCR1A)
  8294. case TIMER1A:
  8295. case TIMER1B:
  8296. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8297. // TCCR1B |= val;
  8298. break;
  8299. #endif
  8300. #if defined(TCCR2)
  8301. case TIMER2:
  8302. case TIMER2:
  8303. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8304. TCCR2 |= val;
  8305. break;
  8306. #endif
  8307. #if defined(TCCR2A)
  8308. case TIMER2A:
  8309. case TIMER2B:
  8310. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8311. TCCR2B |= val;
  8312. break;
  8313. #endif
  8314. #if defined(TCCR3A)
  8315. case TIMER3A:
  8316. case TIMER3B:
  8317. case TIMER3C:
  8318. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8319. TCCR3B |= val;
  8320. break;
  8321. #endif
  8322. #if defined(TCCR4A)
  8323. case TIMER4A:
  8324. case TIMER4B:
  8325. case TIMER4C:
  8326. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8327. TCCR4B |= val;
  8328. break;
  8329. #endif
  8330. #if defined(TCCR5A)
  8331. case TIMER5A:
  8332. case TIMER5B:
  8333. case TIMER5C:
  8334. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8335. TCCR5B |= val;
  8336. break;
  8337. #endif
  8338. }
  8339. }
  8340. #endif //FAST_PWM_FAN
  8341. //! @brief Get and validate extruder number
  8342. //!
  8343. //! If it is not specified, active_extruder is returned in parameter extruder.
  8344. //! @param [in] code M code number
  8345. //! @param [out] extruder
  8346. //! @return error
  8347. //! @retval true Invalid extruder specified in T code
  8348. //! @retval false Valid extruder specified in T code, or not specifiead
  8349. bool setTargetedHotend(int code, uint8_t &extruder)
  8350. {
  8351. extruder = active_extruder;
  8352. if(code_seen('T')) {
  8353. extruder = code_value_uint8();
  8354. if(extruder >= EXTRUDERS) {
  8355. SERIAL_ECHO_START;
  8356. switch(code){
  8357. case 104:
  8358. SERIAL_ECHORPGM(_n("M104 Invalid extruder "));////MSG_M104_INVALID_EXTRUDER
  8359. break;
  8360. case 105:
  8361. SERIAL_ECHORPGM(_n("M105 Invalid extruder "));////MSG_M105_INVALID_EXTRUDER
  8362. break;
  8363. case 109:
  8364. SERIAL_ECHORPGM(_n("M109 Invalid extruder "));////MSG_M109_INVALID_EXTRUDER
  8365. break;
  8366. case 218:
  8367. SERIAL_ECHORPGM(_n("M218 Invalid extruder "));////MSG_M218_INVALID_EXTRUDER
  8368. break;
  8369. case 221:
  8370. SERIAL_ECHORPGM(_n("M221 Invalid extruder "));////MSG_M221_INVALID_EXTRUDER
  8371. break;
  8372. }
  8373. SERIAL_PROTOCOLLN((int)extruder);
  8374. return true;
  8375. }
  8376. }
  8377. return false;
  8378. }
  8379. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  8380. {
  8381. 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)
  8382. {
  8383. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  8384. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  8385. }
  8386. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  8387. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  8388. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  8389. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  8390. total_filament_used = 0;
  8391. }
  8392. float calculate_extruder_multiplier(float diameter) {
  8393. float out = 1.f;
  8394. if (cs.volumetric_enabled && diameter > 0.f) {
  8395. float area = M_PI * diameter * diameter * 0.25;
  8396. out = 1.f / area;
  8397. }
  8398. if (extrudemultiply != 100)
  8399. out *= float(extrudemultiply) * 0.01f;
  8400. return out;
  8401. }
  8402. void calculate_extruder_multipliers() {
  8403. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  8404. #if EXTRUDERS > 1
  8405. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  8406. #if EXTRUDERS > 2
  8407. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  8408. #endif
  8409. #endif
  8410. }
  8411. void delay_keep_alive(unsigned int ms)
  8412. {
  8413. for (;;) {
  8414. manage_heater();
  8415. // Manage inactivity, but don't disable steppers on timeout.
  8416. manage_inactivity(true);
  8417. lcd_update(0);
  8418. if (ms == 0)
  8419. break;
  8420. else if (ms >= 50) {
  8421. _delay(50);
  8422. ms -= 50;
  8423. } else {
  8424. _delay(ms);
  8425. ms = 0;
  8426. }
  8427. }
  8428. }
  8429. static void wait_for_heater(long codenum, uint8_t extruder) {
  8430. if (!degTargetHotend(extruder))
  8431. return;
  8432. #ifdef TEMP_RESIDENCY_TIME
  8433. long residencyStart;
  8434. residencyStart = -1;
  8435. /* continue to loop until we have reached the target temp
  8436. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  8437. cancel_heatup = false;
  8438. while ((!cancel_heatup) && ((residencyStart == -1) ||
  8439. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  8440. #else
  8441. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  8442. #endif //TEMP_RESIDENCY_TIME
  8443. if ((_millis() - codenum) > 1000UL)
  8444. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  8445. if (!farm_mode) {
  8446. SERIAL_PROTOCOLPGM("T:");
  8447. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  8448. SERIAL_PROTOCOLPGM(" E:");
  8449. SERIAL_PROTOCOL((int)extruder);
  8450. #ifdef TEMP_RESIDENCY_TIME
  8451. SERIAL_PROTOCOLPGM(" W:");
  8452. if (residencyStart > -1)
  8453. {
  8454. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  8455. SERIAL_PROTOCOLLN(codenum);
  8456. }
  8457. else
  8458. {
  8459. SERIAL_PROTOCOLLN('?');
  8460. }
  8461. }
  8462. #else
  8463. SERIAL_PROTOCOLLN();
  8464. #endif
  8465. codenum = _millis();
  8466. }
  8467. manage_heater();
  8468. manage_inactivity(true); //do not disable steppers
  8469. lcd_update(0);
  8470. #ifdef TEMP_RESIDENCY_TIME
  8471. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  8472. or when current temp falls outside the hysteresis after target temp was reached */
  8473. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  8474. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  8475. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  8476. {
  8477. residencyStart = _millis();
  8478. }
  8479. #endif //TEMP_RESIDENCY_TIME
  8480. }
  8481. }
  8482. void check_babystep()
  8483. {
  8484. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8485. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  8486. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  8487. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  8488. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  8489. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8490. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  8491. babystep_z);
  8492. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  8493. lcd_update_enable(true);
  8494. }
  8495. }
  8496. #ifdef HEATBED_ANALYSIS
  8497. void d_setup()
  8498. {
  8499. pinMode(D_DATACLOCK, INPUT_PULLUP);
  8500. pinMode(D_DATA, INPUT_PULLUP);
  8501. pinMode(D_REQUIRE, OUTPUT);
  8502. digitalWrite(D_REQUIRE, HIGH);
  8503. }
  8504. float d_ReadData()
  8505. {
  8506. int digit[13];
  8507. String mergeOutput;
  8508. float output;
  8509. digitalWrite(D_REQUIRE, HIGH);
  8510. for (int i = 0; i<13; i++)
  8511. {
  8512. for (int j = 0; j < 4; j++)
  8513. {
  8514. while (digitalRead(D_DATACLOCK) == LOW) {}
  8515. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8516. bitWrite(digit[i], j, digitalRead(D_DATA));
  8517. }
  8518. }
  8519. digitalWrite(D_REQUIRE, LOW);
  8520. mergeOutput = "";
  8521. output = 0;
  8522. for (int r = 5; r <= 10; r++) //Merge digits
  8523. {
  8524. mergeOutput += digit[r];
  8525. }
  8526. output = mergeOutput.toFloat();
  8527. if (digit[4] == 8) //Handle sign
  8528. {
  8529. output *= -1;
  8530. }
  8531. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8532. {
  8533. output /= 10;
  8534. }
  8535. return output;
  8536. }
  8537. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8538. int t1 = 0;
  8539. int t_delay = 0;
  8540. int digit[13];
  8541. int m;
  8542. char str[3];
  8543. //String mergeOutput;
  8544. char mergeOutput[15];
  8545. float output;
  8546. int mesh_point = 0; //index number of calibration point
  8547. 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
  8548. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8549. float mesh_home_z_search = 4;
  8550. float measure_z_height = 0.2f;
  8551. float row[x_points_num];
  8552. int ix = 0;
  8553. int iy = 0;
  8554. const char* filename_wldsd = "mesh.txt";
  8555. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  8556. char numb_wldsd[8]; // (" -A.BCD" + null)
  8557. #ifdef MICROMETER_LOGGING
  8558. d_setup();
  8559. #endif //MICROMETER_LOGGING
  8560. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8561. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8562. unsigned int custom_message_type_old = custom_message_type;
  8563. unsigned int custom_message_state_old = custom_message_state;
  8564. custom_message_type = CustomMsg::MeshBedLeveling;
  8565. custom_message_state = (x_points_num * y_points_num) + 10;
  8566. lcd_update(1);
  8567. //mbl.reset();
  8568. babystep_undo();
  8569. card.openFile(filename_wldsd, false);
  8570. /*destination[Z_AXIS] = mesh_home_z_search;
  8571. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8572. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8573. for(int8_t i=0; i < NUM_AXIS; i++) {
  8574. current_position[i] = destination[i];
  8575. }
  8576. st_synchronize();
  8577. */
  8578. destination[Z_AXIS] = measure_z_height;
  8579. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8580. for(int8_t i=0; i < NUM_AXIS; i++) {
  8581. current_position[i] = destination[i];
  8582. }
  8583. st_synchronize();
  8584. /*int l_feedmultiply = */setup_for_endstop_move(false);
  8585. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8586. SERIAL_PROTOCOL(x_points_num);
  8587. SERIAL_PROTOCOLPGM(",");
  8588. SERIAL_PROTOCOL(y_points_num);
  8589. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8590. SERIAL_PROTOCOL(mesh_home_z_search);
  8591. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8592. SERIAL_PROTOCOL(x_dimension);
  8593. SERIAL_PROTOCOLPGM(",");
  8594. SERIAL_PROTOCOL(y_dimension);
  8595. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8596. while (mesh_point != x_points_num * y_points_num) {
  8597. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8598. iy = mesh_point / x_points_num;
  8599. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8600. float z0 = 0.f;
  8601. /*destination[Z_AXIS] = mesh_home_z_search;
  8602. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8603. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8604. for(int8_t i=0; i < NUM_AXIS; i++) {
  8605. current_position[i] = destination[i];
  8606. }
  8607. st_synchronize();*/
  8608. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8609. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8610. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  8611. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  8612. mesh_plan_buffer_line_destinationXYZE(XY_AXIS_FEEDRATE/6);
  8613. set_current_to_destination();
  8614. st_synchronize();
  8615. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  8616. delay_keep_alive(1000);
  8617. #ifdef MICROMETER_LOGGING
  8618. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8619. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8620. //strcat(data_wldsd, numb_wldsd);
  8621. //MYSERIAL.println(data_wldsd);
  8622. //delay(1000);
  8623. //delay(3000);
  8624. //t1 = millis();
  8625. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8626. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8627. memset(digit, 0, sizeof(digit));
  8628. //cli();
  8629. digitalWrite(D_REQUIRE, LOW);
  8630. for (int i = 0; i<13; i++)
  8631. {
  8632. //t1 = millis();
  8633. for (int j = 0; j < 4; j++)
  8634. {
  8635. while (digitalRead(D_DATACLOCK) == LOW) {}
  8636. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8637. //printf_P(PSTR("Done %d\n"), j);
  8638. bitWrite(digit[i], j, digitalRead(D_DATA));
  8639. }
  8640. //t_delay = (millis() - t1);
  8641. //SERIAL_PROTOCOLPGM(" ");
  8642. //SERIAL_PROTOCOL_F(t_delay, 5);
  8643. //SERIAL_PROTOCOLPGM(" ");
  8644. }
  8645. //sei();
  8646. digitalWrite(D_REQUIRE, HIGH);
  8647. mergeOutput[0] = '\0';
  8648. output = 0;
  8649. for (int r = 5; r <= 10; r++) //Merge digits
  8650. {
  8651. sprintf(str, "%d", digit[r]);
  8652. strcat(mergeOutput, str);
  8653. }
  8654. output = atof(mergeOutput);
  8655. if (digit[4] == 8) //Handle sign
  8656. {
  8657. output *= -1;
  8658. }
  8659. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8660. {
  8661. output *= 0.1;
  8662. }
  8663. //output = d_ReadData();
  8664. //row[ix] = current_position[Z_AXIS];
  8665. //row[ix] = d_ReadData();
  8666. row[ix] = output;
  8667. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8668. memset(data_wldsd, 0, sizeof(data_wldsd));
  8669. for (int i = 0; i < x_points_num; i++) {
  8670. SERIAL_PROTOCOLPGM(" ");
  8671. SERIAL_PROTOCOL_F(row[i], 5);
  8672. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8673. dtostrf(row[i], 7, 3, numb_wldsd);
  8674. strcat(data_wldsd, numb_wldsd);
  8675. }
  8676. card.write_command(data_wldsd);
  8677. SERIAL_PROTOCOLPGM("\n");
  8678. }
  8679. custom_message_state--;
  8680. mesh_point++;
  8681. lcd_update(1);
  8682. }
  8683. #endif //MICROMETER_LOGGING
  8684. card.closefile();
  8685. //clean_up_after_endstop_move(l_feedmultiply);
  8686. }
  8687. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8688. int t1 = 0;
  8689. int t_delay = 0;
  8690. int digit[13];
  8691. int m;
  8692. char str[3];
  8693. //String mergeOutput;
  8694. char mergeOutput[15];
  8695. float output;
  8696. int mesh_point = 0; //index number of calibration point
  8697. 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
  8698. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8699. float mesh_home_z_search = 4;
  8700. float row[x_points_num];
  8701. int ix = 0;
  8702. int iy = 0;
  8703. const char* filename_wldsd = "wldsd.txt";
  8704. char data_wldsd[70];
  8705. char numb_wldsd[10];
  8706. d_setup();
  8707. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  8708. // We don't know where we are! HOME!
  8709. // Push the commands to the front of the message queue in the reverse order!
  8710. // There shall be always enough space reserved for these commands.
  8711. repeatcommand_front(); // repeat G80 with all its parameters
  8712. enquecommand_front_P(G28W0);
  8713. enquecommand_front_P((PSTR("G1 Z5")));
  8714. return;
  8715. }
  8716. unsigned int custom_message_type_old = custom_message_type;
  8717. unsigned int custom_message_state_old = custom_message_state;
  8718. custom_message_type = CustomMsg::MeshBedLeveling;
  8719. custom_message_state = (x_points_num * y_points_num) + 10;
  8720. lcd_update(1);
  8721. mbl.reset();
  8722. babystep_undo();
  8723. card.openFile(filename_wldsd, false);
  8724. current_position[Z_AXIS] = mesh_home_z_search;
  8725. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  8726. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8727. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8728. int l_feedmultiply = setup_for_endstop_move(false);
  8729. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8730. SERIAL_PROTOCOL(x_points_num);
  8731. SERIAL_PROTOCOLPGM(",");
  8732. SERIAL_PROTOCOL(y_points_num);
  8733. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8734. SERIAL_PROTOCOL(mesh_home_z_search);
  8735. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8736. SERIAL_PROTOCOL(x_dimension);
  8737. SERIAL_PROTOCOLPGM(",");
  8738. SERIAL_PROTOCOL(y_dimension);
  8739. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8740. while (mesh_point != x_points_num * y_points_num) {
  8741. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8742. iy = mesh_point / x_points_num;
  8743. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8744. float z0 = 0.f;
  8745. current_position[Z_AXIS] = mesh_home_z_search;
  8746. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8747. st_synchronize();
  8748. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8749. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8750. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  8751. st_synchronize();
  8752. 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
  8753. break;
  8754. card.closefile();
  8755. }
  8756. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8757. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8758. //strcat(data_wldsd, numb_wldsd);
  8759. //MYSERIAL.println(data_wldsd);
  8760. //_delay(1000);
  8761. //_delay(3000);
  8762. //t1 = _millis();
  8763. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8764. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8765. memset(digit, 0, sizeof(digit));
  8766. //cli();
  8767. digitalWrite(D_REQUIRE, LOW);
  8768. for (int i = 0; i<13; i++)
  8769. {
  8770. //t1 = _millis();
  8771. for (int j = 0; j < 4; j++)
  8772. {
  8773. while (digitalRead(D_DATACLOCK) == LOW) {}
  8774. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8775. bitWrite(digit[i], j, digitalRead(D_DATA));
  8776. }
  8777. //t_delay = (_millis() - t1);
  8778. //SERIAL_PROTOCOLPGM(" ");
  8779. //SERIAL_PROTOCOL_F(t_delay, 5);
  8780. //SERIAL_PROTOCOLPGM(" ");
  8781. }
  8782. //sei();
  8783. digitalWrite(D_REQUIRE, HIGH);
  8784. mergeOutput[0] = '\0';
  8785. output = 0;
  8786. for (int r = 5; r <= 10; r++) //Merge digits
  8787. {
  8788. sprintf(str, "%d", digit[r]);
  8789. strcat(mergeOutput, str);
  8790. }
  8791. output = atof(mergeOutput);
  8792. if (digit[4] == 8) //Handle sign
  8793. {
  8794. output *= -1;
  8795. }
  8796. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8797. {
  8798. output *= 0.1;
  8799. }
  8800. //output = d_ReadData();
  8801. //row[ix] = current_position[Z_AXIS];
  8802. memset(data_wldsd, 0, sizeof(data_wldsd));
  8803. for (int i = 0; i <3; i++) {
  8804. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8805. dtostrf(current_position[i], 8, 5, numb_wldsd);
  8806. strcat(data_wldsd, numb_wldsd);
  8807. strcat(data_wldsd, ";");
  8808. }
  8809. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8810. dtostrf(output, 8, 5, numb_wldsd);
  8811. strcat(data_wldsd, numb_wldsd);
  8812. //strcat(data_wldsd, ";");
  8813. card.write_command(data_wldsd);
  8814. //row[ix] = d_ReadData();
  8815. row[ix] = output; // current_position[Z_AXIS];
  8816. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8817. for (int i = 0; i < x_points_num; i++) {
  8818. SERIAL_PROTOCOLPGM(" ");
  8819. SERIAL_PROTOCOL_F(row[i], 5);
  8820. }
  8821. SERIAL_PROTOCOLPGM("\n");
  8822. }
  8823. custom_message_state--;
  8824. mesh_point++;
  8825. lcd_update(1);
  8826. }
  8827. card.closefile();
  8828. clean_up_after_endstop_move(l_feedmultiply);
  8829. }
  8830. #endif //HEATBED_ANALYSIS
  8831. #ifndef PINDA_THERMISTOR
  8832. static void temp_compensation_start() {
  8833. custom_message_type = CustomMsg::TempCompPreheat;
  8834. custom_message_state = PINDA_HEAT_T + 1;
  8835. lcd_update(2);
  8836. if ((int)degHotend(active_extruder) > extrude_min_temp) {
  8837. current_position[E_AXIS] -= default_retraction;
  8838. }
  8839. plan_buffer_line_curposXYZE(400, active_extruder);
  8840. current_position[X_AXIS] = PINDA_PREHEAT_X;
  8841. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  8842. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  8843. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  8844. st_synchronize();
  8845. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  8846. for (int i = 0; i < PINDA_HEAT_T; i++) {
  8847. delay_keep_alive(1000);
  8848. custom_message_state = PINDA_HEAT_T - i;
  8849. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  8850. else lcd_update(1);
  8851. }
  8852. custom_message_type = CustomMsg::Status;
  8853. custom_message_state = 0;
  8854. }
  8855. static void temp_compensation_apply() {
  8856. int i_add;
  8857. int z_shift = 0;
  8858. float z_shift_mm;
  8859. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  8860. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  8861. i_add = (target_temperature_bed - 60) / 10;
  8862. z_shift = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i_add);
  8863. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  8864. }else {
  8865. //interpolation
  8866. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  8867. }
  8868. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  8869. 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);
  8870. st_synchronize();
  8871. plan_set_z_position(current_position[Z_AXIS]);
  8872. }
  8873. else {
  8874. //we have no temp compensation data
  8875. }
  8876. }
  8877. #endif //ndef PINDA_THERMISTOR
  8878. float temp_comp_interpolation(float inp_temperature) {
  8879. //cubic spline interpolation
  8880. int n, i, j;
  8881. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  8882. int shift[10];
  8883. int temp_C[10];
  8884. n = 6; //number of measured points
  8885. shift[0] = 0;
  8886. for (i = 0; i < n; i++) {
  8887. if (i > 0) {
  8888. //read shift in steps from EEPROM
  8889. shift[i] = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  8890. }
  8891. temp_C[i] = 50 + i * 10; //temperature in C
  8892. #ifdef PINDA_THERMISTOR
  8893. constexpr int start_compensating_temp = 35;
  8894. temp_C[i] = start_compensating_temp + i * 5; //temperature in degrees C
  8895. #ifdef SUPERPINDA_SUPPORT
  8896. static_assert(start_compensating_temp >= PINDA_MINTEMP, "Temperature compensation start point is lower than PINDA_MINTEMP.");
  8897. #endif //SUPERPINDA_SUPPORT
  8898. #else
  8899. temp_C[i] = 50 + i * 10; //temperature in C
  8900. #endif
  8901. x[i] = (float)temp_C[i];
  8902. f[i] = (float)shift[i];
  8903. }
  8904. if (inp_temperature < x[0]) return 0;
  8905. for (i = n - 1; i>0; i--) {
  8906. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  8907. h[i - 1] = x[i] - x[i - 1];
  8908. }
  8909. //*********** formation of h, s , f matrix **************
  8910. for (i = 1; i<n - 1; i++) {
  8911. m[i][i] = 2 * (h[i - 1] + h[i]);
  8912. if (i != 1) {
  8913. m[i][i - 1] = h[i - 1];
  8914. m[i - 1][i] = h[i - 1];
  8915. }
  8916. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  8917. }
  8918. //*********** forward elimination **************
  8919. for (i = 1; i<n - 2; i++) {
  8920. temp = (m[i + 1][i] / m[i][i]);
  8921. for (j = 1; j <= n - 1; j++)
  8922. m[i + 1][j] -= temp*m[i][j];
  8923. }
  8924. //*********** backward substitution *********
  8925. for (i = n - 2; i>0; i--) {
  8926. sum = 0;
  8927. for (j = i; j <= n - 2; j++)
  8928. sum += m[i][j] * s[j];
  8929. s[i] = (m[i][n - 1] - sum) / m[i][i];
  8930. }
  8931. for (i = 0; i<n - 1; i++)
  8932. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  8933. a = (s[i + 1] - s[i]) / (6 * h[i]);
  8934. b = s[i] / 2;
  8935. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  8936. d = f[i];
  8937. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  8938. }
  8939. return sum;
  8940. }
  8941. #ifdef PINDA_THERMISTOR
  8942. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  8943. {
  8944. if (!eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE)) return 0;
  8945. if (!calibration_status_pinda()) return 0;
  8946. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  8947. }
  8948. #endif //PINDA_THERMISTOR
  8949. void long_pause() //long pause print
  8950. {
  8951. st_synchronize();
  8952. start_pause_print = _millis();
  8953. // Stop heaters
  8954. heating_status = HeatingStatus::NO_HEATING;
  8955. setAllTargetHotends(0);
  8956. // Lift z
  8957. raise_z_above(current_position[Z_AXIS] + Z_PAUSE_LIFT, true);
  8958. // Move XY to side
  8959. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) {
  8960. current_position[X_AXIS] = X_PAUSE_POS;
  8961. current_position[Y_AXIS] = Y_PAUSE_POS;
  8962. plan_buffer_line_curposXYZE(50);
  8963. }
  8964. // did we come here from a thermal error?
  8965. if(get_temp_error()) {
  8966. // time to stop the error beep
  8967. WRITE(BEEPER, LOW);
  8968. } else {
  8969. // Turn off the print fan
  8970. fanSpeed = 0;
  8971. }
  8972. }
  8973. void serialecho_temperatures() {
  8974. float tt = degHotend(active_extruder);
  8975. SERIAL_PROTOCOLPGM("T:");
  8976. SERIAL_PROTOCOL(tt);
  8977. SERIAL_PROTOCOLPGM(" E:");
  8978. SERIAL_PROTOCOL((int)active_extruder);
  8979. SERIAL_PROTOCOLPGM(" B:");
  8980. SERIAL_PROTOCOL_F(degBed(), 1);
  8981. SERIAL_PROTOCOLLN();
  8982. }
  8983. #ifdef UVLO_SUPPORT
  8984. void uvlo_drain_reset()
  8985. {
  8986. // burn all that residual power
  8987. wdt_enable(WDTO_1S);
  8988. WRITE(BEEPER,HIGH);
  8989. lcd_clear();
  8990. lcd_puts_at_P(0, 1, MSG_POWERPANIC_DETECTED);
  8991. while(1);
  8992. }
  8993. void uvlo_()
  8994. {
  8995. unsigned long time_start = _millis();
  8996. bool sd_print = card.sdprinting;
  8997. // Conserve power as soon as possible.
  8998. #ifdef LCD_BL_PIN
  8999. backlightMode = BACKLIGHT_MODE_DIM;
  9000. backlightLevel_LOW = 0;
  9001. backlight_update();
  9002. #endif //LCD_BL_PIN
  9003. disable_x();
  9004. disable_y();
  9005. #ifdef TMC2130
  9006. tmc2130_set_current_h(Z_AXIS, 20);
  9007. tmc2130_set_current_r(Z_AXIS, 20);
  9008. tmc2130_set_current_h(E_AXIS, 20);
  9009. tmc2130_set_current_r(E_AXIS, 20);
  9010. #endif //TMC2130
  9011. // Stop all heaters
  9012. uint8_t saved_target_temperature_bed = target_temperature_bed;
  9013. uint16_t saved_target_temperature_ext = target_temperature[active_extruder];
  9014. setAllTargetHotends(0);
  9015. setTargetBed(0);
  9016. // Calculate the file position, from which to resume this print.
  9017. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  9018. {
  9019. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9020. sd_position -= sdlen_planner;
  9021. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9022. sd_position -= sdlen_cmdqueue;
  9023. if (sd_position < 0) sd_position = 0;
  9024. }
  9025. // save the global state at planning time
  9026. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9027. uint16_t feedrate_bckp;
  9028. if (current_block && !pos_invalid)
  9029. {
  9030. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9031. feedrate_bckp = current_block->gcode_feedrate;
  9032. saved_segment_idx = current_block->segment_idx;
  9033. }
  9034. else
  9035. {
  9036. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9037. feedrate_bckp = feedrate;
  9038. saved_segment_idx = 0;
  9039. }
  9040. // From this point on and up to the print recovery, Z should not move during X/Y travels and
  9041. // should be controlled precisely. Reset the MBL status before planner_abort_hard in order to
  9042. // get the physical Z for further manipulation.
  9043. bool mbl_was_active = mbl.active;
  9044. mbl.active = false;
  9045. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  9046. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  9047. // are in action.
  9048. planner_abort_hard();
  9049. // Store the print logical Z position, which we need to recover (a slight error here would be
  9050. // recovered on the next Gcode instruction, while a physical location error would not)
  9051. float logical_z = current_position[Z_AXIS];
  9052. if(mbl_was_active) logical_z -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  9053. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z, logical_z);
  9054. // Store the print E position before we lose track
  9055. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), current_position[E_AXIS]);
  9056. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, (axis_relative_modes & E_AXIS_MASK)?0:1);
  9057. // Clean the input command queue, inhibit serial processing using saved_printing
  9058. cmdqueue_reset();
  9059. card.sdprinting = false;
  9060. saved_printing = true;
  9061. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9062. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9063. planner_aborted = false;
  9064. sei();
  9065. // Retract
  9066. current_position[E_AXIS] -= default_retraction;
  9067. plan_buffer_line_curposXYZE(95);
  9068. st_synchronize();
  9069. disable_e0();
  9070. // Read out the current Z motor microstep counter to move the axis up towards
  9071. // a full step before powering off. NOTE: we need to ensure to schedule more
  9072. // than "dropsegments" steps in order to move (this is always the case here
  9073. // due to UVLO_Z_AXIS_SHIFT being used)
  9074. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9075. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9076. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9077. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9078. + UVLO_Z_AXIS_SHIFT;
  9079. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9080. st_synchronize();
  9081. poweroff_z();
  9082. // Write the file position.
  9083. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  9084. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9085. for (uint8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9086. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9087. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9088. // Scale the z value to 1u resolution.
  9089. int16_t v = mbl_was_active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  9090. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  9091. }
  9092. // Write the _final_ Z position and motor microstep counter (unused).
  9093. eeprom_update_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z, current_position[Z_AXIS]);
  9094. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9095. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9096. // Store the current position.
  9097. if (pos_invalid)
  9098. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), X_COORD_INVALID);
  9099. else
  9100. {
  9101. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  9102. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  9103. }
  9104. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  9105. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDRATE, feedrate_bckp);
  9106. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY, feedmultiply);
  9107. eeprom_update_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND, saved_target_temperature_ext);
  9108. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, saved_target_temperature_bed);
  9109. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  9110. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  9111. #if EXTRUDERS > 1
  9112. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  9113. #if EXTRUDERS > 2
  9114. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  9115. #endif
  9116. #endif
  9117. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  9118. eeprom_update_float((float*)(EEPROM_UVLO_ACCELL), cs.acceleration);
  9119. eeprom_update_float((float*)(EEPROM_UVLO_RETRACT_ACCELL), cs.retract_acceleration);
  9120. eeprom_update_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL), cs.travel_acceleration);
  9121. // Store the saved target
  9122. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4), saved_start_position[X_AXIS]);
  9123. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4), saved_start_position[Y_AXIS]);
  9124. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4), saved_start_position[Z_AXIS]);
  9125. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4), saved_start_position[E_AXIS]);
  9126. eeprom_update_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX, saved_segment_idx);
  9127. #ifdef LIN_ADVANCE
  9128. eeprom_update_float((float*)(EEPROM_UVLO_LA_K), extruder_advance_K);
  9129. #endif
  9130. // Finaly store the "power outage" flag.
  9131. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  9132. // Increment power failure counter
  9133. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9134. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9135. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  9136. WRITE(BEEPER,HIGH);
  9137. // All is set: with all the juice left, try to move extruder away to detach the nozzle completely from the print
  9138. poweron_z();
  9139. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  9140. plan_buffer_line_curposXYZE(500);
  9141. st_synchronize();
  9142. wdt_enable(WDTO_1S);
  9143. while(1);
  9144. }
  9145. void uvlo_tiny()
  9146. {
  9147. unsigned long time_start = _millis();
  9148. // Conserve power as soon as possible.
  9149. disable_x();
  9150. disable_y();
  9151. disable_e0();
  9152. #ifdef TMC2130
  9153. tmc2130_set_current_h(Z_AXIS, 20);
  9154. tmc2130_set_current_r(Z_AXIS, 20);
  9155. #endif //TMC2130
  9156. // Stop all heaters
  9157. setAllTargetHotends(0);
  9158. setTargetBed(0);
  9159. // When power is interrupted on the _first_ recovery an attempt can be made to raise the
  9160. // extruder, causing the Z position to change. Similarly, when recovering, the Z position is
  9161. // lowered. In such cases we cannot just save Z, we need to re-align the steppers to a fullstep.
  9162. // Disable MBL (if not already) to work with physical coordinates.
  9163. mbl.active = false;
  9164. planner_abort_hard();
  9165. // Allow for small roundoffs to be ignored
  9166. if(fabs(current_position[Z_AXIS] - eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z))) >= 1.f/cs.axis_steps_per_unit[Z_AXIS])
  9167. {
  9168. // Clean the input command queue, inhibit serial processing using saved_printing
  9169. cmdqueue_reset();
  9170. card.sdprinting = false;
  9171. saved_printing = true;
  9172. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9173. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9174. planner_aborted = false;
  9175. sei();
  9176. // The axis was moved: adjust Z as done on a regular UVLO.
  9177. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9178. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9179. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9180. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9181. + UVLO_TINY_Z_AXIS_SHIFT;
  9182. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9183. st_synchronize();
  9184. poweroff_z();
  9185. // Update Z position
  9186. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  9187. // Update the _final_ Z motor microstep counter (unused).
  9188. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9189. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9190. }
  9191. // Update the the "power outage" flag.
  9192. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  9193. // Increment power failure counter
  9194. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9195. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9196. printf_P(_N("UVLO_TINY - end %d\n"), _millis() - time_start);
  9197. uvlo_drain_reset();
  9198. }
  9199. #endif //UVLO_SUPPORT
  9200. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  9201. void setup_fan_interrupt() {
  9202. //INT7
  9203. DDRE &= ~(1 << 7); //input pin
  9204. PORTE &= ~(1 << 7); //no internal pull-up
  9205. //start with sensing rising edge
  9206. EICRB &= ~(1 << 6);
  9207. EICRB |= (1 << 7);
  9208. //enable INT7 interrupt
  9209. EIMSK |= (1 << 7);
  9210. }
  9211. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  9212. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  9213. ISR(INT7_vect) {
  9214. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  9215. #ifdef FAN_SOFT_PWM
  9216. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  9217. #else //FAN_SOFT_PWM
  9218. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  9219. #endif //FAN_SOFT_PWM
  9220. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  9221. t_fan_rising_edge = millis_nc();
  9222. }
  9223. else { //interrupt was triggered by falling edge
  9224. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  9225. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  9226. }
  9227. }
  9228. EICRB ^= (1 << 6); //change edge
  9229. }
  9230. #endif
  9231. #ifdef UVLO_SUPPORT
  9232. void setup_uvlo_interrupt() {
  9233. DDRE &= ~(1 << 4); //input pin
  9234. PORTE &= ~(1 << 4); //no internal pull-up
  9235. // sensing falling edge
  9236. EICRB |= (1 << 0);
  9237. EICRB &= ~(1 << 1);
  9238. // enable INT4 interrupt
  9239. EIMSK |= (1 << 4);
  9240. // check if power was lost before we armed the interrupt
  9241. if(!(PINE & (1 << 4)) && eeprom_read_byte((uint8_t*)EEPROM_UVLO))
  9242. {
  9243. SERIAL_ECHOLNPGM("INT4");
  9244. uvlo_drain_reset();
  9245. }
  9246. }
  9247. ISR(INT4_vect) {
  9248. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  9249. SERIAL_ECHOLNPGM("INT4");
  9250. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  9251. if(printer_active() && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  9252. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  9253. }
  9254. void recover_print(uint8_t automatic) {
  9255. char cmd[30];
  9256. lcd_update_enable(true);
  9257. lcd_update(2);
  9258. lcd_setstatuspgm(_i("Recovering print"));////MSG_RECOVERING_PRINT c=20
  9259. // Recover position, temperatures and extrude_multipliers
  9260. bool mbl_was_active = recover_machine_state_after_power_panic();
  9261. // Lift the print head 25mm, first to avoid collisions with oozed material with the print,
  9262. // and second also so one may remove the excess priming material.
  9263. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 1)
  9264. {
  9265. sprintf_P(cmd, PSTR("G1 Z%.3f F800"), current_position[Z_AXIS] + 25);
  9266. enquecommand(cmd);
  9267. }
  9268. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine
  9269. // transformation status. G28 will not touch Z when MBL is off.
  9270. enquecommand_P(PSTR("G28 X Y"));
  9271. // Set the target bed and nozzle temperatures and wait.
  9272. sprintf_P(cmd, PSTR("M104 S%d"), target_temperature[active_extruder]);
  9273. enquecommand(cmd);
  9274. sprintf_P(cmd, PSTR("M140 S%d"), target_temperature_bed);
  9275. enquecommand(cmd);
  9276. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  9277. enquecommand(cmd);
  9278. enquecommand_P(PSTR("M83")); //E axis relative mode
  9279. // If not automatically recoreverd (long power loss)
  9280. if(automatic == 0){
  9281. //Extrude some filament to stabilize the pressure
  9282. enquecommand_P(PSTR("G1 E5 F120"));
  9283. // Retract to be consistent with a short pause
  9284. sprintf_P(cmd, PSTR("G1 E%-0.3f F2700"), default_retraction);
  9285. enquecommand(cmd);
  9286. }
  9287. 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]);
  9288. // Restart the print.
  9289. restore_print_from_eeprom(mbl_was_active);
  9290. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  9291. }
  9292. bool recover_machine_state_after_power_panic()
  9293. {
  9294. // 1) Preset some dummy values for the XY axes
  9295. current_position[X_AXIS] = 0;
  9296. current_position[Y_AXIS] = 0;
  9297. // 2) Restore the mesh bed leveling offsets, but not the MBL status.
  9298. // This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9299. bool mbl_was_active = false;
  9300. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9301. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9302. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9303. // Scale the z value to 10u resolution.
  9304. int16_t v;
  9305. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  9306. if (v != 0)
  9307. mbl_was_active = true;
  9308. mbl.z_values[iy][ix] = float(v) * 0.001f;
  9309. }
  9310. // Recover the physical coordinate of the Z axis at the time of the power panic.
  9311. // The current position after power panic is moved to the next closest 0th full step.
  9312. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z));
  9313. // Recover last E axis position
  9314. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9315. // 3) Initialize the logical to physical coordinate system transformation.
  9316. world2machine_initialize();
  9317. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9318. // print_mesh_bed_leveling_table();
  9319. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  9320. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  9321. babystep_load();
  9322. // 5) Set the physical positions from the logical positions using the world2machine transformation
  9323. // This is only done to inizialize Z/E axes with physical locations, since X/Y are unknown.
  9324. clamp_to_software_endstops(current_position);
  9325. set_destination_to_current();
  9326. plan_set_position_curposXYZE();
  9327. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9328. print_world_coordinates();
  9329. // 6) Power up the Z motors, mark their positions as known.
  9330. axis_known_position[Z_AXIS] = true;
  9331. enable_z();
  9332. // 7) Recover the target temperatures.
  9333. target_temperature[active_extruder] = eeprom_read_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND);
  9334. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  9335. // 8) Recover extruder multipilers
  9336. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  9337. #if EXTRUDERS > 1
  9338. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  9339. #if EXTRUDERS > 2
  9340. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  9341. #endif
  9342. #endif
  9343. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  9344. // 9) Recover the saved target
  9345. saved_start_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4));
  9346. saved_start_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4));
  9347. saved_start_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4));
  9348. saved_start_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4));
  9349. saved_segment_idx = eeprom_read_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX);
  9350. #ifdef LIN_ADVANCE
  9351. extruder_advance_K = eeprom_read_float((float*)EEPROM_UVLO_LA_K);
  9352. #endif
  9353. return mbl_was_active;
  9354. }
  9355. void restore_print_from_eeprom(bool mbl_was_active) {
  9356. int feedrate_rec;
  9357. int feedmultiply_rec;
  9358. uint8_t fan_speed_rec;
  9359. char cmd[48];
  9360. char filename[FILENAME_LENGTH];
  9361. uint8_t depth = 0;
  9362. char dir_name[9];
  9363. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  9364. feedrate_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDRATE);
  9365. feedmultiply_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY);
  9366. SERIAL_ECHOPGM("Feedrate:");
  9367. MYSERIAL.print(feedrate_rec);
  9368. SERIAL_ECHOPGM(", feedmultiply:");
  9369. MYSERIAL.println(feedmultiply_rec);
  9370. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  9371. MYSERIAL.println(int(depth));
  9372. for (uint8_t i = 0; i < depth; i++) {
  9373. for (uint8_t j = 0; j < 8; j++) {
  9374. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  9375. }
  9376. dir_name[8] = '\0';
  9377. MYSERIAL.println(dir_name);
  9378. // strcpy(card.dir_names[i], dir_name);
  9379. card.chdir(dir_name, false);
  9380. }
  9381. for (uint8_t i = 0; i < 8; i++) {
  9382. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  9383. }
  9384. filename[8] = '\0';
  9385. MYSERIAL.print(filename);
  9386. strcat_P(filename, PSTR(".gco"));
  9387. sprintf_P(cmd, PSTR("M23 %s"), filename);
  9388. enquecommand(cmd);
  9389. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  9390. SERIAL_ECHOPGM("Position read from eeprom:");
  9391. MYSERIAL.println(position);
  9392. // Move to the XY print position in logical coordinates, where the print has been killed, but
  9393. // without shifting Z along the way. This requires performing the move without mbl.
  9394. float pos_x = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  9395. float pos_y = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  9396. if (pos_x != X_COORD_INVALID)
  9397. {
  9398. sprintf_P(cmd, PSTR("G1 X%f Y%f F3000"), pos_x, pos_y);
  9399. enquecommand(cmd);
  9400. }
  9401. // Enable MBL and switch to logical positioning
  9402. if (mbl_was_active)
  9403. enquecommand_P(PSTR("PRUSA MBL V1"));
  9404. // Move the Z axis down to the print, in logical coordinates.
  9405. sprintf_P(cmd, PSTR("G1 Z%f"), eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)));
  9406. enquecommand(cmd);
  9407. // Restore acceleration settings
  9408. float acceleration = eeprom_read_float((float*)(EEPROM_UVLO_ACCELL));
  9409. float retract_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_RETRACT_ACCELL));
  9410. float travel_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL));
  9411. sprintf_P(cmd, PSTR("M204 P%f R%f T%f"), acceleration, retract_acceleration, travel_acceleration);
  9412. enquecommand(cmd);
  9413. // Unretract.
  9414. sprintf_P(cmd, PSTR("G1 E%0.3f F2700"), default_retraction);
  9415. enquecommand(cmd);
  9416. // Recover final E axis position and mode
  9417. float pos_e = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9418. sprintf_P(cmd, PSTR("G92 E%6.3f"), pos_e);
  9419. enquecommand(cmd);
  9420. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  9421. enquecommand_P(PSTR("M82")); //E axis abslute mode
  9422. // Set the feedrates saved at the power panic.
  9423. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  9424. enquecommand(cmd);
  9425. sprintf_P(cmd, PSTR("M220 S%d"), feedmultiply_rec);
  9426. enquecommand(cmd);
  9427. // Set the fan speed saved at the power panic.
  9428. strcpy_P(cmd, PSTR("M106 S"));
  9429. strcat(cmd, itostr3(int(fan_speed_rec)));
  9430. enquecommand(cmd);
  9431. // Set a position in the file.
  9432. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  9433. enquecommand(cmd);
  9434. enquecommand_P(PSTR("G4 S0"));
  9435. enquecommand_P(PSTR("PRUSA uvlo"));
  9436. }
  9437. #endif //UVLO_SUPPORT
  9438. //! @brief Immediately stop print moves
  9439. //!
  9440. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  9441. //! If printing from sd card, position in file is saved.
  9442. //! If printing from USB, line number is saved.
  9443. //!
  9444. //! @param z_move
  9445. //! @param e_move
  9446. void stop_and_save_print_to_ram(float z_move, float e_move)
  9447. {
  9448. if (saved_printing) return;
  9449. #if 0
  9450. unsigned char nplanner_blocks;
  9451. #endif
  9452. unsigned char nlines;
  9453. uint16_t sdlen_planner;
  9454. uint16_t sdlen_cmdqueue;
  9455. cli();
  9456. if (card.sdprinting) {
  9457. #if 0
  9458. nplanner_blocks = number_of_blocks();
  9459. #endif
  9460. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  9461. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9462. saved_sdpos -= sdlen_planner;
  9463. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9464. saved_sdpos -= sdlen_cmdqueue;
  9465. saved_printing_type = PRINTING_TYPE_SD;
  9466. }
  9467. else if (usb_timer.running()) { //reuse saved_sdpos for storing line number
  9468. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  9469. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  9470. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  9471. saved_sdpos -= nlines;
  9472. saved_sdpos -= buflen; //number of blocks in cmd buffer
  9473. saved_printing_type = PRINTING_TYPE_USB;
  9474. }
  9475. else {
  9476. saved_printing_type = PRINTING_TYPE_NONE;
  9477. //not sd printing nor usb printing
  9478. }
  9479. #if 0
  9480. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  9481. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  9482. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  9483. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  9484. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  9485. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  9486. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  9487. {
  9488. card.setIndex(saved_sdpos);
  9489. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  9490. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  9491. MYSERIAL.print(char(card.get()));
  9492. SERIAL_ECHOLNPGM("Content of command buffer: ");
  9493. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  9494. MYSERIAL.print(char(card.get()));
  9495. SERIAL_ECHOLNPGM("End of command buffer");
  9496. }
  9497. {
  9498. // Print the content of the planner buffer, line by line:
  9499. card.setIndex(saved_sdpos);
  9500. int8_t iline = 0;
  9501. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  9502. SERIAL_ECHOPGM("Planner line (from file): ");
  9503. MYSERIAL.print(int(iline), DEC);
  9504. SERIAL_ECHOPGM(", length: ");
  9505. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  9506. SERIAL_ECHOPGM(", steps: (");
  9507. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  9508. SERIAL_ECHOPGM(",");
  9509. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  9510. SERIAL_ECHOPGM(",");
  9511. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  9512. SERIAL_ECHOPGM(",");
  9513. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  9514. SERIAL_ECHOPGM("), events: ");
  9515. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  9516. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  9517. MYSERIAL.print(char(card.get()));
  9518. }
  9519. }
  9520. {
  9521. // Print the content of the command buffer, line by line:
  9522. int8_t iline = 0;
  9523. union {
  9524. struct {
  9525. char lo;
  9526. char hi;
  9527. } lohi;
  9528. uint16_t value;
  9529. } sdlen_single;
  9530. int _bufindr = bufindr;
  9531. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  9532. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  9533. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  9534. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  9535. }
  9536. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  9537. MYSERIAL.print(int(iline), DEC);
  9538. SERIAL_ECHOPGM(", type: ");
  9539. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  9540. SERIAL_ECHOPGM(", len: ");
  9541. MYSERIAL.println(sdlen_single.value, DEC);
  9542. // Print the content of the buffer line.
  9543. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  9544. SERIAL_ECHOPGM("Buffer line (from file): ");
  9545. MYSERIAL.println(int(iline), DEC);
  9546. for (; sdlen_single.value > 0; -- sdlen_single.value)
  9547. MYSERIAL.print(char(card.get()));
  9548. if (-- _buflen == 0)
  9549. break;
  9550. // First skip the current command ID and iterate up to the end of the string.
  9551. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  9552. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  9553. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9554. // If the end of the buffer was empty,
  9555. if (_bufindr == sizeof(cmdbuffer)) {
  9556. // skip to the start and find the nonzero command.
  9557. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9558. }
  9559. }
  9560. }
  9561. #endif
  9562. // save the global state at planning time
  9563. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9564. if (current_block && !pos_invalid)
  9565. {
  9566. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9567. saved_feedrate2 = current_block->gcode_feedrate;
  9568. saved_segment_idx = current_block->segment_idx;
  9569. // printf_P(PSTR("stop_and_save_print_to_ram: %f, %f, %f, %f, %u\n"), saved_start_position[0], saved_start_position[1], saved_start_position[2], saved_start_position[3], saved_segment_idx);
  9570. }
  9571. else
  9572. {
  9573. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9574. saved_feedrate2 = feedrate;
  9575. saved_segment_idx = 0;
  9576. }
  9577. planner_abort_hard(); //abort printing
  9578. memcpy(saved_pos, current_position, sizeof(saved_pos));
  9579. if (pos_invalid) saved_pos[X_AXIS] = X_COORD_INVALID;
  9580. saved_feedmultiply2 = feedmultiply; //save feedmultiply
  9581. saved_active_extruder = active_extruder; //save active_extruder
  9582. saved_extruder_temperature = degTargetHotend(active_extruder);
  9583. saved_bed_temperature = degTargetBed();
  9584. saved_extruder_relative_mode = axis_relative_modes & E_AXIS_MASK;
  9585. saved_fan_speed = fanSpeed;
  9586. cmdqueue_reset(); //empty cmdqueue
  9587. card.sdprinting = false;
  9588. // card.closefile();
  9589. saved_printing = true;
  9590. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  9591. st_reset_timer();
  9592. sei();
  9593. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  9594. // Rather than calling plan_buffer_line directly, push the move into the command queue so that
  9595. // the caller can continue processing. This is used during powerpanic to save the state as we
  9596. // move away from the print.
  9597. char buf[48];
  9598. if(e_move)
  9599. {
  9600. // First unretract (relative extrusion)
  9601. if(!saved_extruder_relative_mode){
  9602. enquecommand(PSTR("M83"), true);
  9603. }
  9604. //retract 45mm/s
  9605. // A single sprintf may not be faster, but is definitely 20B shorter
  9606. // than a sequence of commands building the string piece by piece
  9607. // A snprintf would have been a safer call, but since it is not used
  9608. // in the whole program, its implementation would bring more bytes to the total size
  9609. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  9610. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  9611. enquecommand(buf, false);
  9612. }
  9613. if(z_move)
  9614. {
  9615. // Then lift Z axis
  9616. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  9617. enquecommand(buf, false);
  9618. }
  9619. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  9620. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  9621. repeatcommand_front();
  9622. }
  9623. }
  9624. //! @brief Restore print from ram
  9625. //!
  9626. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  9627. //! print fan speed, waits for extruder temperature restore, then restores
  9628. //! position and continues print moves.
  9629. //!
  9630. //! Internally lcd_update() is called by wait_for_heater().
  9631. //!
  9632. //! @param e_move
  9633. void restore_print_from_ram_and_continue(float e_move)
  9634. {
  9635. if (!saved_printing) return;
  9636. #ifdef FANCHECK
  9637. // Do not allow resume printing if fans are still not ok
  9638. if ((fan_check_error != EFCE_OK) && (fan_check_error != EFCE_FIXED)) return;
  9639. if (fan_check_error == EFCE_FIXED) fan_check_error = EFCE_OK; //reenable serial stream processing if printing from usb
  9640. #endif
  9641. // restore bed temperature (bed can be disabled during a thermal warning)
  9642. if (degBed() != saved_bed_temperature)
  9643. setTargetBed(saved_bed_temperature);
  9644. // restore active_extruder
  9645. active_extruder = saved_active_extruder;
  9646. fanSpeed = saved_fan_speed;
  9647. if (degTargetHotend(saved_active_extruder) != saved_extruder_temperature)
  9648. {
  9649. setTargetHotendSafe(saved_extruder_temperature, saved_active_extruder);
  9650. heating_status = HeatingStatus::EXTRUDER_HEATING;
  9651. wait_for_heater(_millis(), saved_active_extruder);
  9652. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  9653. }
  9654. axis_relative_modes ^= (-saved_extruder_relative_mode ^ axis_relative_modes) & E_AXIS_MASK;
  9655. float e = saved_pos[E_AXIS] - e_move;
  9656. plan_set_e_position(e);
  9657. #ifdef FANCHECK
  9658. fans_check_enabled = false;
  9659. #endif
  9660. // do not restore XY for commands that do not require that
  9661. if (saved_pos[X_AXIS] == X_COORD_INVALID)
  9662. {
  9663. saved_pos[X_AXIS] = current_position[X_AXIS];
  9664. saved_pos[Y_AXIS] = current_position[Y_AXIS];
  9665. }
  9666. //first move print head in XY to the saved position:
  9667. 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);
  9668. //then move Z
  9669. 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);
  9670. //and finaly unretract (35mm/s)
  9671. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  9672. st_synchronize();
  9673. #ifdef FANCHECK
  9674. fans_check_enabled = true;
  9675. #endif
  9676. // restore original feedrate/feedmultiply _after_ restoring the extruder position
  9677. feedrate = saved_feedrate2;
  9678. feedmultiply = saved_feedmultiply2;
  9679. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9680. set_destination_to_current();
  9681. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  9682. card.setIndex(saved_sdpos);
  9683. sdpos_atomic = saved_sdpos;
  9684. card.sdprinting = true;
  9685. }
  9686. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  9687. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  9688. serial_count = 0;
  9689. FlushSerialRequestResend();
  9690. }
  9691. else {
  9692. //not sd printing nor usb printing
  9693. }
  9694. lcd_setstatuspgm(MSG_WELCOME);
  9695. saved_printing_type = PRINTING_TYPE_NONE;
  9696. saved_printing = false;
  9697. planner_aborted = true; // unroll the stack
  9698. }
  9699. // Cancel the state related to a currently saved print
  9700. void cancel_saved_printing()
  9701. {
  9702. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  9703. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9704. saved_printing_type = PRINTING_TYPE_NONE;
  9705. saved_printing = false;
  9706. }
  9707. void print_world_coordinates()
  9708. {
  9709. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  9710. }
  9711. void print_physical_coordinates()
  9712. {
  9713. 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));
  9714. }
  9715. void print_mesh_bed_leveling_table()
  9716. {
  9717. SERIAL_ECHOPGM("mesh bed leveling: ");
  9718. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  9719. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  9720. MYSERIAL.print(mbl.z_values[y][x], 3);
  9721. SERIAL_ECHO(' ');
  9722. }
  9723. SERIAL_ECHOLN();
  9724. }
  9725. uint8_t calc_percent_done()
  9726. {
  9727. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  9728. uint8_t percent_done = 0;
  9729. #ifdef TMC2130
  9730. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100)
  9731. {
  9732. percent_done = print_percent_done_normal;
  9733. }
  9734. else if (print_percent_done_silent <= 100)
  9735. {
  9736. percent_done = print_percent_done_silent;
  9737. }
  9738. #else
  9739. if (print_percent_done_normal <= 100)
  9740. {
  9741. percent_done = print_percent_done_normal;
  9742. }
  9743. #endif //TMC2130
  9744. else
  9745. {
  9746. percent_done = card.percentDone();
  9747. }
  9748. return percent_done;
  9749. }
  9750. static void print_time_remaining_init()
  9751. {
  9752. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  9753. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  9754. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  9755. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  9756. print_time_to_change_normal = PRINT_TIME_REMAINING_INIT;
  9757. print_time_to_change_silent = PRINT_TIME_REMAINING_INIT;
  9758. }
  9759. void load_filament_final_feed()
  9760. {
  9761. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  9762. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FINAL);
  9763. }
  9764. //! @brief Wait for user to check the state
  9765. //! @par nozzle_temp nozzle temperature to load filament
  9766. void M600_check_state(float nozzle_temp)
  9767. {
  9768. lcd_change_fil_state = 0;
  9769. while (lcd_change_fil_state != 1)
  9770. {
  9771. lcd_change_fil_state = 0;
  9772. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9773. lcd_alright();
  9774. KEEPALIVE_STATE(IN_HANDLER);
  9775. switch(lcd_change_fil_state)
  9776. {
  9777. // Filament failed to load so load it again
  9778. case 2:
  9779. if (MMU2::mmu2.Enabled()){
  9780. //@@TODO mmu_M600_load_filament(false, nozzle_temp); //nonautomatic load; change to "wrong filament loaded" option?
  9781. } else {
  9782. M600_load_filament_movements();
  9783. }
  9784. break;
  9785. // Filament loaded properly but color is not clear
  9786. case 3:
  9787. st_synchronize();
  9788. load_filament_final_feed();
  9789. lcd_loading_color();
  9790. st_synchronize();
  9791. break;
  9792. // Everything good
  9793. default:
  9794. lcd_change_success();
  9795. break;
  9796. }
  9797. }
  9798. }
  9799. //! @brief Wait for user action
  9800. //!
  9801. //! Beep, manage nozzle heater and wait for user to start unload filament
  9802. //! If times out, active extruder temperature is set to 0.
  9803. //!
  9804. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  9805. void M600_wait_for_user(float HotendTempBckp) {
  9806. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9807. int counterBeep = 0;
  9808. unsigned long waiting_start_time = _millis();
  9809. uint8_t wait_for_user_state = 0;
  9810. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9811. bool bFirst=true;
  9812. while (!(wait_for_user_state == 0 && lcd_clicked())){
  9813. manage_heater();
  9814. manage_inactivity(true);
  9815. #if BEEPER > 0
  9816. if (counterBeep == 500) {
  9817. counterBeep = 0;
  9818. }
  9819. SET_OUTPUT(BEEPER);
  9820. if (counterBeep == 0) {
  9821. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  9822. {
  9823. bFirst=false;
  9824. WRITE(BEEPER, HIGH);
  9825. }
  9826. }
  9827. if (counterBeep == 20) {
  9828. WRITE(BEEPER, LOW);
  9829. }
  9830. counterBeep++;
  9831. #endif //BEEPER > 0
  9832. switch (wait_for_user_state) {
  9833. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  9834. delay_keep_alive(4);
  9835. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  9836. lcd_display_message_fullscreen_P(_i("Press the knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  9837. wait_for_user_state = 1;
  9838. setAllTargetHotends(0);
  9839. st_synchronize();
  9840. disable_e0();
  9841. disable_e1();
  9842. disable_e2();
  9843. }
  9844. break;
  9845. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  9846. delay_keep_alive(4);
  9847. if (lcd_clicked()) {
  9848. setTargetHotend(HotendTempBckp, active_extruder);
  9849. lcd_wait_for_heater();
  9850. wait_for_user_state = 2;
  9851. }
  9852. break;
  9853. case 2: //waiting for nozzle to reach target temperature
  9854. if (fabs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  9855. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9856. waiting_start_time = _millis();
  9857. wait_for_user_state = 0;
  9858. }
  9859. else {
  9860. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  9861. lcd_set_cursor(1, 4);
  9862. lcd_printf_P(PSTR("%3d"), (int16_t)degHotend(active_extruder));
  9863. }
  9864. break;
  9865. }
  9866. }
  9867. WRITE(BEEPER, LOW);
  9868. }
  9869. void M600_load_filament_movements()
  9870. {
  9871. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED;
  9872. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST);
  9873. load_filament_final_feed();
  9874. lcd_loading_filament();
  9875. st_synchronize();
  9876. }
  9877. void M600_load_filament() {
  9878. //load filament for single material and MMU
  9879. lcd_wait_interact();
  9880. //load_filament_time = _millis();
  9881. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9882. while(!lcd_clicked())
  9883. {
  9884. manage_heater();
  9885. manage_inactivity(true);
  9886. #ifdef FILAMENT_SENSOR
  9887. if (fsensor.getFilamentLoadEvent()) {
  9888. Sound_MakeCustom(50,1000,false);
  9889. break;
  9890. }
  9891. #endif //FILAMENT_SENSOR
  9892. }
  9893. KEEPALIVE_STATE(IN_HANDLER);
  9894. M600_load_filament_movements();
  9895. Sound_MakeCustom(50,1000,false);
  9896. lcd_update_enable(false);
  9897. }
  9898. //! @brief Wait for click
  9899. //!
  9900. //! Set
  9901. void marlin_wait_for_click()
  9902. {
  9903. int8_t busy_state_backup = busy_state;
  9904. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9905. lcd_consume_click();
  9906. while(!lcd_clicked())
  9907. {
  9908. manage_heater();
  9909. manage_inactivity(true);
  9910. lcd_update(0);
  9911. }
  9912. KEEPALIVE_STATE(busy_state_backup);
  9913. }
  9914. #define FIL_LOAD_LENGTH 60
  9915. #ifdef PSU_Delta
  9916. bool bEnableForce_z;
  9917. void init_force_z()
  9918. {
  9919. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  9920. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  9921. disable_force_z();
  9922. }
  9923. void check_force_z()
  9924. {
  9925. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  9926. init_force_z(); // causes enforced switching into disable-state
  9927. }
  9928. void disable_force_z()
  9929. {
  9930. if(!bEnableForce_z) return; // motor already disabled (may be ;-p )
  9931. bEnableForce_z=false;
  9932. // switching to silent mode
  9933. #ifdef TMC2130
  9934. tmc2130_mode=TMC2130_MODE_SILENT;
  9935. update_mode_profile();
  9936. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  9937. #endif // TMC2130
  9938. }
  9939. void enable_force_z()
  9940. {
  9941. if(bEnableForce_z)
  9942. return; // motor already enabled (may be ;-p )
  9943. bEnableForce_z=true;
  9944. // mode recovering
  9945. #ifdef TMC2130
  9946. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  9947. update_mode_profile();
  9948. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  9949. #endif // TMC2130
  9950. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  9951. }
  9952. #endif // PSU_Delta