Marlin_main.cpp 353 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735
  1. /* -*- c++ -*- */
  2. /**
  3. * @file
  4. */
  5. /**
  6. * @mainpage Reprap 3D printer firmware based on Sprinter and grbl.
  7. *
  8. * @section intro_sec Introduction
  9. *
  10. * This firmware is a mashup between Sprinter and grbl.
  11. * https://github.com/kliment/Sprinter
  12. * https://github.com/simen/grbl/tree
  13. *
  14. * It has preliminary support for Matthew Roberts advance algorithm
  15. * http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
  16. *
  17. * Prusa Research s.r.o. https://www.prusa3d.cz
  18. *
  19. * @section copyright_sec Copyright
  20. *
  21. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  22. *
  23. * This program is free software: you can redistribute it and/or modify
  24. * it under the terms of the GNU General Public License as published by
  25. * the Free Software Foundation, either version 3 of the License, or
  26. * (at your option) any later version.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU General Public License
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  35. *
  36. * @section notes_sec Notes
  37. *
  38. * * Do not create static objects in global functions.
  39. * Otherwise constructor guard against concurrent calls is generated costing
  40. * about 8B RAM and 14B flash.
  41. *
  42. *
  43. */
  44. //-//
  45. #include "Configuration.h"
  46. #include "Marlin.h"
  47. #ifdef ENABLE_AUTO_BED_LEVELING
  48. #include "vector_3.h"
  49. #ifdef AUTO_BED_LEVELING_GRID
  50. #include "qr_solve.h"
  51. #endif
  52. #endif // ENABLE_AUTO_BED_LEVELING
  53. #ifdef MESH_BED_LEVELING
  54. #include "mesh_bed_leveling.h"
  55. #include "mesh_bed_calibration.h"
  56. #endif
  57. #include "printers.h"
  58. #include "menu.h"
  59. #include "ultralcd.h"
  60. #include "backlight.h"
  61. #include "planner.h"
  62. #include "stepper.h"
  63. #include "temperature.h"
  64. #include "motion_control.h"
  65. #include "cardreader.h"
  66. #include "ConfigurationStore.h"
  67. #include "language.h"
  68. #include "pins_arduino.h"
  69. #include "math.h"
  70. #include "util.h"
  71. #include "Timer.h"
  72. #include <avr/wdt.h>
  73. #include <avr/pgmspace.h>
  74. #include "Dcodes.h"
  75. #include "AutoDeplete.h"
  76. #ifndef LA_NOCOMPAT
  77. #include "la10compat.h"
  78. #endif
  79. #ifdef SWSPI
  80. #include "swspi.h"
  81. #endif //SWSPI
  82. #include "spi.h"
  83. #ifdef SWI2C
  84. #include "swi2c.h"
  85. #endif //SWI2C
  86. #ifdef FILAMENT_SENSOR
  87. #include "fsensor.h"
  88. #endif //FILAMENT_SENSOR
  89. #ifdef TMC2130
  90. #include "tmc2130.h"
  91. #endif //TMC2130
  92. #ifdef W25X20CL
  93. #include "w25x20cl.h"
  94. #include "optiboot_w25x20cl.h"
  95. #endif //W25X20CL
  96. #ifdef BLINKM
  97. #include "BlinkM.h"
  98. #include "Wire.h"
  99. #endif
  100. #ifdef ULTRALCD
  101. #include "ultralcd.h"
  102. #endif
  103. #if NUM_SERVOS > 0
  104. #include "Servo.h"
  105. #endif
  106. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  107. #include <SPI.h>
  108. #endif
  109. #include "mmu.h"
  110. #define VERSION_STRING "1.0.2"
  111. #include "ultralcd.h"
  112. #include "sound.h"
  113. #include "cmdqueue.h"
  114. #include "io_atmega2560.h"
  115. // Macros for bit masks
  116. #define BIT(b) (1<<(b))
  117. #define TEST(n,b) (((n)&BIT(b))!=0)
  118. #define SET_BIT(n,b,value) (n) ^= ((-value)^(n)) & (BIT(b))
  119. //Macro for print fan speed
  120. #define FAN_PULSE_WIDTH_LIMIT ((fanSpeed > 100) ? 3 : 4) //time in ms
  121. //filament types
  122. #define FILAMENT_DEFAULT 0
  123. #define FILAMENT_FLEX 1
  124. #define FILAMENT_PVA 2
  125. #define FILAMENT_UNDEFINED 255
  126. //Stepper Movement Variables
  127. //===========================================================================
  128. //=============================imported variables============================
  129. //===========================================================================
  130. //===========================================================================
  131. //=============================public variables=============================
  132. //===========================================================================
  133. #ifdef SDSUPPORT
  134. CardReader card;
  135. #endif
  136. unsigned long PingTime = _millis();
  137. unsigned long NcTime;
  138. uint8_t mbl_z_probe_nr = 3; //numer of Z measurements for each point in mesh bed leveling calibration
  139. //used for PINDA temp calibration and pause print
  140. #define DEFAULT_RETRACTION 1
  141. #define DEFAULT_RETRACTION_MM 4 //MM
  142. float default_retraction = DEFAULT_RETRACTION;
  143. float homing_feedrate[] = HOMING_FEEDRATE;
  144. // Currently only the extruder axis may be switched to a relative mode.
  145. // Other axes are always absolute or relative based on the common relative_mode flag.
  146. bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
  147. int feedmultiply=100; //100->1 200->2
  148. int extrudemultiply=100; //100->1 200->2
  149. int extruder_multiply[EXTRUDERS] = {100
  150. #if EXTRUDERS > 1
  151. , 100
  152. #if EXTRUDERS > 2
  153. , 100
  154. #endif
  155. #endif
  156. };
  157. int bowden_length[4] = {385, 385, 385, 385};
  158. bool is_usb_printing = false;
  159. bool homing_flag = false;
  160. bool temp_cal_active = false;
  161. unsigned long kicktime = _millis()+100000;
  162. unsigned int usb_printing_counter;
  163. int8_t lcd_change_fil_state = 0;
  164. unsigned long pause_time = 0;
  165. unsigned long start_pause_print = _millis();
  166. unsigned long t_fan_rising_edge = _millis();
  167. LongTimer safetyTimer;
  168. static LongTimer crashDetTimer;
  169. //unsigned long load_filament_time;
  170. bool mesh_bed_leveling_flag = false;
  171. bool mesh_bed_run_from_menu = false;
  172. bool prusa_sd_card_upload = false;
  173. unsigned int status_number = 0;
  174. unsigned long total_filament_used;
  175. unsigned int heating_status;
  176. unsigned int heating_status_counter;
  177. bool loading_flag = false;
  178. char snmm_filaments_used = 0;
  179. bool fan_state[2];
  180. int fan_edge_counter[2];
  181. int fan_speed[2];
  182. char dir_names[3][9];
  183. bool sortAlpha = false;
  184. float extruder_multiplier[EXTRUDERS] = {1.0
  185. #if EXTRUDERS > 1
  186. , 1.0
  187. #if EXTRUDERS > 2
  188. , 1.0
  189. #endif
  190. #endif
  191. };
  192. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  193. //shortcuts for more readable code
  194. #define _x current_position[X_AXIS]
  195. #define _y current_position[Y_AXIS]
  196. #define _z current_position[Z_AXIS]
  197. #define _e current_position[E_AXIS]
  198. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  199. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  200. bool axis_known_position[3] = {false, false, false};
  201. // Extruder offset
  202. #if EXTRUDERS > 1
  203. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  204. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  205. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  206. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  207. #endif
  208. };
  209. #endif
  210. uint8_t active_extruder = 0;
  211. int fanSpeed=0;
  212. #ifdef FWRETRACT
  213. bool retracted[EXTRUDERS]={false
  214. #if EXTRUDERS > 1
  215. , false
  216. #if EXTRUDERS > 2
  217. , false
  218. #endif
  219. #endif
  220. };
  221. bool retracted_swap[EXTRUDERS]={false
  222. #if EXTRUDERS > 1
  223. , false
  224. #if EXTRUDERS > 2
  225. , false
  226. #endif
  227. #endif
  228. };
  229. float retract_length_swap = RETRACT_LENGTH_SWAP;
  230. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  231. #endif
  232. #ifdef PS_DEFAULT_OFF
  233. bool powersupply = false;
  234. #else
  235. bool powersupply = true;
  236. #endif
  237. bool cancel_heatup = false ;
  238. int8_t busy_state = NOT_BUSY;
  239. static long prev_busy_signal_ms = -1;
  240. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  241. const char errormagic[] PROGMEM = "Error:";
  242. const char echomagic[] PROGMEM = "echo:";
  243. bool no_response = false;
  244. uint8_t important_status;
  245. uint8_t saved_filament_type;
  246. #define SAVED_TARGET_UNSET (X_MIN_POS-1)
  247. float saved_target[NUM_AXIS] = {SAVED_TARGET_UNSET, 0, 0, 0};
  248. // save/restore printing in case that mmu was not responding
  249. bool mmu_print_saved = false;
  250. // storing estimated time to end of print counted by slicer
  251. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  252. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  253. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  254. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  255. //===========================================================================
  256. //=============================Private Variables=============================
  257. //===========================================================================
  258. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  259. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  260. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  261. // For tracing an arc
  262. static float offset[3] = {0.0, 0.0, 0.0};
  263. // Current feedrate
  264. float feedrate = 1500.0;
  265. // Feedrate for the next move
  266. static float next_feedrate;
  267. // Original feedrate saved during homing moves
  268. static float saved_feedrate;
  269. const int sensitive_pins[] = SENSITIVE_PINS; // Sensitive pin list for M42
  270. //static float tt = 0;
  271. //static float bt = 0;
  272. //Inactivity shutdown variables
  273. static unsigned long previous_millis_cmd = 0;
  274. unsigned long max_inactive_time = 0;
  275. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  276. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  277. unsigned long starttime=0;
  278. unsigned long stoptime=0;
  279. unsigned long _usb_timer = 0;
  280. bool Stopped=false;
  281. #if NUM_SERVOS > 0
  282. Servo servos[NUM_SERVOS];
  283. #endif
  284. bool target_direction;
  285. //Insert variables if CHDK is defined
  286. #ifdef CHDK
  287. unsigned long chdkHigh = 0;
  288. boolean chdkActive = false;
  289. #endif
  290. //! @name RAM save/restore printing
  291. //! @{
  292. bool saved_printing = false; //!< Print is paused and saved in RAM
  293. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  294. uint8_t saved_printing_type = PRINTING_TYPE_SD;
  295. static float saved_pos[4] = { 0, 0, 0, 0 };
  296. static uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
  297. static int saved_feedmultiply2 = 0;
  298. static uint8_t saved_active_extruder = 0;
  299. static float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  300. static bool saved_extruder_relative_mode = false;
  301. static int saved_fanSpeed = 0; //!< Print fan speed
  302. //! @}
  303. static int saved_feedmultiply_mm = 100;
  304. //===========================================================================
  305. //=============================Routines======================================
  306. //===========================================================================
  307. static void get_arc_coordinates();
  308. static bool setTargetedHotend(int code, uint8_t &extruder);
  309. static void print_time_remaining_init();
  310. static void wait_for_heater(long codenum, uint8_t extruder);
  311. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
  312. static void temp_compensation_start();
  313. static void temp_compensation_apply();
  314. uint16_t gcode_in_progress = 0;
  315. uint16_t mcode_in_progress = 0;
  316. void serial_echopair_P(const char *s_P, float v)
  317. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  318. void serial_echopair_P(const char *s_P, double v)
  319. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  320. void serial_echopair_P(const char *s_P, unsigned long v)
  321. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  322. /*FORCE_INLINE*/ void serialprintPGM(const char *str)
  323. {
  324. #if 0
  325. char ch=pgm_read_byte(str);
  326. while(ch)
  327. {
  328. MYSERIAL.write(ch);
  329. ch=pgm_read_byte(++str);
  330. }
  331. #else
  332. // hmm, same size as the above version, the compiler did a good job optimizing the above
  333. while( uint8_t ch = pgm_read_byte(str) ){
  334. MYSERIAL.write((char)ch);
  335. ++str;
  336. }
  337. #endif
  338. }
  339. #ifdef SDSUPPORT
  340. #include "SdFatUtil.h"
  341. int freeMemory() { return SdFatUtil::FreeRam(); }
  342. #else
  343. extern "C" {
  344. extern unsigned int __bss_end;
  345. extern unsigned int __heap_start;
  346. extern void *__brkval;
  347. int freeMemory() {
  348. int free_memory;
  349. if ((int)__brkval == 0)
  350. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  351. else
  352. free_memory = ((int)&free_memory) - ((int)__brkval);
  353. return free_memory;
  354. }
  355. }
  356. #endif //!SDSUPPORT
  357. void setup_killpin()
  358. {
  359. #if defined(KILL_PIN) && KILL_PIN > -1
  360. SET_INPUT(KILL_PIN);
  361. WRITE(KILL_PIN,HIGH);
  362. #endif
  363. }
  364. // Set home pin
  365. void setup_homepin(void)
  366. {
  367. #if defined(HOME_PIN) && HOME_PIN > -1
  368. SET_INPUT(HOME_PIN);
  369. WRITE(HOME_PIN,HIGH);
  370. #endif
  371. }
  372. void setup_photpin()
  373. {
  374. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  375. SET_OUTPUT(PHOTOGRAPH_PIN);
  376. WRITE(PHOTOGRAPH_PIN, LOW);
  377. #endif
  378. }
  379. void setup_powerhold()
  380. {
  381. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  382. SET_OUTPUT(SUICIDE_PIN);
  383. WRITE(SUICIDE_PIN, HIGH);
  384. #endif
  385. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  386. SET_OUTPUT(PS_ON_PIN);
  387. #if defined(PS_DEFAULT_OFF)
  388. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  389. #else
  390. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  391. #endif
  392. #endif
  393. }
  394. void suicide()
  395. {
  396. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  397. SET_OUTPUT(SUICIDE_PIN);
  398. WRITE(SUICIDE_PIN, LOW);
  399. #endif
  400. }
  401. void servo_init()
  402. {
  403. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  404. servos[0].attach(SERVO0_PIN);
  405. #endif
  406. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  407. servos[1].attach(SERVO1_PIN);
  408. #endif
  409. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  410. servos[2].attach(SERVO2_PIN);
  411. #endif
  412. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  413. servos[3].attach(SERVO3_PIN);
  414. #endif
  415. #if (NUM_SERVOS >= 5)
  416. #error "TODO: enter initalisation code for more servos"
  417. #endif
  418. }
  419. bool fans_check_enabled = true;
  420. #ifdef TMC2130
  421. void crashdet_stop_and_save_print()
  422. {
  423. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  424. }
  425. void crashdet_restore_print_and_continue()
  426. {
  427. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  428. // babystep_apply();
  429. }
  430. void crashdet_stop_and_save_print2()
  431. {
  432. cli();
  433. planner_abort_hard(); //abort printing
  434. cmdqueue_reset(); //empty cmdqueue
  435. card.sdprinting = false;
  436. card.closefile();
  437. // Reset and re-enable the stepper timer just before the global interrupts are enabled.
  438. st_reset_timer();
  439. sei();
  440. }
  441. void crashdet_detected(uint8_t mask)
  442. {
  443. st_synchronize();
  444. static uint8_t crashDet_counter = 0;
  445. bool automatic_recovery_after_crash = true;
  446. if (crashDet_counter++ == 0) {
  447. crashDetTimer.start();
  448. }
  449. else if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)){
  450. crashDetTimer.stop();
  451. crashDet_counter = 0;
  452. }
  453. else if(crashDet_counter == CRASHDET_COUNTER_MAX){
  454. automatic_recovery_after_crash = false;
  455. crashDetTimer.stop();
  456. crashDet_counter = 0;
  457. }
  458. else {
  459. crashDetTimer.start();
  460. }
  461. lcd_update_enable(true);
  462. lcd_clear();
  463. lcd_update(2);
  464. if (mask & X_AXIS_MASK)
  465. {
  466. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_X, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_X) + 1);
  467. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT) + 1);
  468. }
  469. if (mask & Y_AXIS_MASK)
  470. {
  471. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_Y, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_Y) + 1);
  472. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT) + 1);
  473. }
  474. lcd_update_enable(true);
  475. lcd_update(2);
  476. lcd_setstatuspgm(_T(MSG_CRASH_DETECTED));
  477. gcode_G28(true, true, false); //home X and Y
  478. st_synchronize();
  479. if (automatic_recovery_after_crash) {
  480. enquecommand_P(PSTR("CRASH_RECOVER"));
  481. }else{
  482. setTargetHotend(0, active_extruder);
  483. bool yesno = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Crash detected. Resume print?"), false);
  484. lcd_update_enable(true);
  485. if (yesno)
  486. {
  487. enquecommand_P(PSTR("CRASH_RECOVER"));
  488. }
  489. else
  490. {
  491. enquecommand_P(PSTR("CRASH_CANCEL"));
  492. }
  493. }
  494. }
  495. void crashdet_recover()
  496. {
  497. crashdet_restore_print_and_continue();
  498. if (lcd_crash_detect_enabled()) tmc2130_sg_stop_on_crash = true;
  499. }
  500. void crashdet_cancel()
  501. {
  502. saved_printing = false;
  503. tmc2130_sg_stop_on_crash = true;
  504. if (saved_printing_type == PRINTING_TYPE_SD) {
  505. lcd_print_stop();
  506. }else if(saved_printing_type == PRINTING_TYPE_USB){
  507. SERIAL_ECHOLNRPGM(MSG_OCTOPRINT_CANCEL); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  508. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  509. }
  510. }
  511. #endif //TMC2130
  512. void failstats_reset_print()
  513. {
  514. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  515. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  516. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  517. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  518. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  519. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  520. }
  521. #ifdef MESH_BED_LEVELING
  522. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  523. #endif
  524. // Factory reset function
  525. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  526. // Level input parameter sets depth of reset
  527. int er_progress = 0;
  528. static void factory_reset(char level)
  529. {
  530. lcd_clear();
  531. switch (level) {
  532. // Level 0: Language reset
  533. case 0:
  534. Sound_MakeCustom(100,0,false);
  535. lang_reset();
  536. break;
  537. //Level 1: Reset statistics
  538. case 1:
  539. Sound_MakeCustom(100,0,false);
  540. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  541. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  542. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  543. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  544. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  545. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  546. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  547. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  548. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  549. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  550. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  551. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  552. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  553. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  554. lcd_menu_statistics();
  555. break;
  556. // Level 2: Prepare for shipping
  557. case 2:
  558. //lcd_puts_P(PSTR("Factory RESET"));
  559. //lcd_puts_at_P(1,2,PSTR("Shipping prep"));
  560. // Force language selection at the next boot up.
  561. lang_reset();
  562. // Force the "Follow calibration flow" message at the next boot up.
  563. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  564. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  565. farm_no = 0;
  566. farm_mode = false;
  567. eeprom_update_byte((uint8_t*)EEPROM_FARM_MODE, farm_mode);
  568. EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
  569. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  570. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  571. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  572. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  573. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  574. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  575. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  576. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  577. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  578. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  579. #ifdef FILAMENT_SENSOR
  580. fsensor_enable();
  581. fsensor_autoload_set(true);
  582. #endif //FILAMENT_SENSOR
  583. Sound_MakeCustom(100,0,false);
  584. //_delay_ms(2000);
  585. break;
  586. // Level 3: erase everything, whole EEPROM will be set to 0xFF
  587. case 3:
  588. lcd_puts_P(PSTR("Factory RESET"));
  589. lcd_puts_at_P(1, 2, PSTR("ERASING all data"));
  590. Sound_MakeCustom(100,0,false);
  591. er_progress = 0;
  592. lcd_puts_at_P(3, 3, PSTR(" "));
  593. lcd_set_cursor(3, 3);
  594. lcd_print(er_progress);
  595. // Erase EEPROM
  596. for (int i = 0; i < 4096; i++) {
  597. eeprom_update_byte((uint8_t*)i, 0xFF);
  598. if (i % 41 == 0) {
  599. er_progress++;
  600. lcd_puts_at_P(3, 3, PSTR(" "));
  601. lcd_set_cursor(3, 3);
  602. lcd_print(er_progress);
  603. lcd_puts_P(PSTR("%"));
  604. }
  605. }
  606. break;
  607. case 4:
  608. bowden_menu();
  609. break;
  610. default:
  611. break;
  612. }
  613. }
  614. extern "C" {
  615. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  616. }
  617. int uart_putchar(char c, FILE *)
  618. {
  619. MYSERIAL.write(c);
  620. return 0;
  621. }
  622. void lcd_splash()
  623. {
  624. lcd_clear(); // clears display and homes screen
  625. lcd_puts_P(PSTR("\n Original Prusa i3\n Prusa Research"));
  626. }
  627. void factory_reset()
  628. {
  629. KEEPALIVE_STATE(PAUSED_FOR_USER);
  630. if (!READ(BTN_ENC))
  631. {
  632. _delay_ms(1000);
  633. if (!READ(BTN_ENC))
  634. {
  635. lcd_clear();
  636. lcd_puts_P(PSTR("Factory RESET"));
  637. SET_OUTPUT(BEEPER);
  638. if(eSoundMode!=e_SOUND_MODE_SILENT)
  639. WRITE(BEEPER, HIGH);
  640. while (!READ(BTN_ENC));
  641. WRITE(BEEPER, LOW);
  642. _delay_ms(2000);
  643. char level = reset_menu();
  644. factory_reset(level);
  645. switch (level) {
  646. case 0: _delay_ms(0); break;
  647. case 1: _delay_ms(0); break;
  648. case 2: _delay_ms(0); break;
  649. case 3: _delay_ms(0); break;
  650. }
  651. }
  652. }
  653. KEEPALIVE_STATE(IN_HANDLER);
  654. }
  655. void show_fw_version_warnings() {
  656. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  657. switch (FW_DEV_VERSION) {
  658. 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
  659. 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
  660. case(FW_VERSION_DEVEL):
  661. case(FW_VERSION_DEBUG):
  662. lcd_update_enable(false);
  663. lcd_clear();
  664. #if FW_DEV_VERSION == FW_VERSION_DEVEL
  665. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  666. #else
  667. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  668. #endif
  669. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  670. lcd_puts_at_P(0, 2, PSTR("ver ")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  671. lcd_puts_at_P(0, 3, PSTR(FW_REPOSITORY));
  672. lcd_wait_for_click();
  673. break;
  674. // 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
  675. }
  676. lcd_update_enable(true);
  677. }
  678. //! @brief try to check if firmware is on right type of printer
  679. static void check_if_fw_is_on_right_printer(){
  680. #ifdef FILAMENT_SENSOR
  681. if((PRINTER_TYPE == PRINTER_MK3) || (PRINTER_TYPE == PRINTER_MK3S)){
  682. #ifdef IR_SENSOR
  683. swi2c_init();
  684. const uint8_t pat9125_detected = swi2c_readByte_A8(PAT9125_I2C_ADDR,0x00,NULL);
  685. if (pat9125_detected){
  686. lcd_show_fullscreen_message_and_wait_P(_i("MK3S firmware detected on MK3 printer"));}
  687. #endif //IR_SENSOR
  688. #ifdef PAT9125
  689. //will return 1 only if IR can detect filament in bondtech extruder so this may fail even when we have IR sensor
  690. const uint8_t ir_detected = !(PIN_GET(IR_SENSOR_PIN));
  691. if (ir_detected){
  692. lcd_show_fullscreen_message_and_wait_P(_i("MK3 firmware detected on MK3S printer"));}
  693. #endif //PAT9125
  694. }
  695. #endif //FILAMENT_SENSOR
  696. }
  697. uint8_t check_printer_version()
  698. {
  699. uint8_t version_changed = 0;
  700. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  701. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  702. if (printer_type != PRINTER_TYPE) {
  703. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  704. else version_changed |= 0b10;
  705. }
  706. if (motherboard != MOTHERBOARD) {
  707. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  708. else version_changed |= 0b01;
  709. }
  710. return version_changed;
  711. }
  712. #ifdef BOOTAPP
  713. #include "bootapp.h" //bootloader support
  714. #endif //BOOTAPP
  715. #if (LANG_MODE != 0) //secondary language support
  716. #ifdef W25X20CL
  717. // language update from external flash
  718. #define LANGBOOT_BLOCKSIZE 0x1000u
  719. #define LANGBOOT_RAMBUFFER 0x0800
  720. void update_sec_lang_from_external_flash()
  721. {
  722. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  723. {
  724. uint8_t lang = boot_reserved >> 4;
  725. uint8_t state = boot_reserved & 0xf;
  726. lang_table_header_t header;
  727. uint32_t src_addr;
  728. if (lang_get_header(lang, &header, &src_addr))
  729. {
  730. lcd_puts_at_P(1,3,PSTR("Language update."));
  731. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  732. _delay(100);
  733. boot_reserved = (state + 1) | (lang << 4);
  734. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  735. {
  736. cli();
  737. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  738. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  739. w25x20cl_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  740. if (state == 0)
  741. {
  742. //TODO - check header integrity
  743. }
  744. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  745. }
  746. else
  747. {
  748. //TODO - check sec lang data integrity
  749. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  750. }
  751. }
  752. }
  753. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  754. }
  755. #ifdef DEBUG_W25X20CL
  756. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  757. {
  758. lang_table_header_t header;
  759. uint8_t count = 0;
  760. uint32_t addr = 0x00000;
  761. while (1)
  762. {
  763. printf_P(_n("LANGTABLE%d:"), count);
  764. w25x20cl_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  765. if (header.magic != LANG_MAGIC)
  766. {
  767. printf_P(_n("NG!\n"));
  768. break;
  769. }
  770. printf_P(_n("OK\n"));
  771. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  772. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  773. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  774. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  775. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  776. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  777. addr += header.size;
  778. codes[count] = header.code;
  779. count ++;
  780. }
  781. return count;
  782. }
  783. void list_sec_lang_from_external_flash()
  784. {
  785. uint16_t codes[8];
  786. uint8_t count = lang_xflash_enum_codes(codes);
  787. printf_P(_n("XFlash lang count = %hhd\n"), count);
  788. }
  789. #endif //DEBUG_W25X20CL
  790. #endif //W25X20CL
  791. #endif //(LANG_MODE != 0)
  792. static void w25x20cl_err_msg()
  793. {
  794. lcd_clear();
  795. lcd_puts_P(_n("External SPI flash\nW25X20CL is not res-\nponding. Language\nswitch unavailable."));
  796. }
  797. // "Setup" function is called by the Arduino framework on startup.
  798. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  799. // are initialized by the main() routine provided by the Arduino framework.
  800. void setup()
  801. {
  802. mmu_init();
  803. ultralcd_init();
  804. spi_init();
  805. lcd_splash();
  806. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  807. #ifdef W25X20CL
  808. bool w25x20cl_success = w25x20cl_init();
  809. if (w25x20cl_success)
  810. {
  811. optiboot_w25x20cl_enter();
  812. #if (LANG_MODE != 0) //secondary language support
  813. update_sec_lang_from_external_flash();
  814. #endif //(LANG_MODE != 0)
  815. }
  816. else
  817. {
  818. w25x20cl_err_msg();
  819. }
  820. #else
  821. const bool w25x20cl_success = true;
  822. #endif //W25X20CL
  823. setup_killpin();
  824. setup_powerhold();
  825. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  826. EEPROM_read_B(EEPROM_FARM_NUMBER, &farm_no);
  827. if ((farm_mode == 0xFF && farm_no == 0) || ((uint16_t)farm_no == 0xFFFF))
  828. farm_mode = false; //if farm_mode has not been stored to eeprom yet and farm number is set to zero or EEPROM is fresh, deactivate farm mode
  829. if ((uint16_t)farm_no == 0xFFFF) farm_no = 0;
  830. selectedSerialPort = eeprom_read_byte((uint8_t*)EEPROM_SECOND_SERIAL_ACTIVE);
  831. if (selectedSerialPort == 0xFF) selectedSerialPort = 0;
  832. if (farm_mode)
  833. {
  834. no_response = true; //we need confirmation by recieving PRUSA thx
  835. important_status = 8;
  836. prusa_statistics(8);
  837. selectedSerialPort = 1;
  838. #ifdef TMC2130
  839. //increased extruder current (PFW363)
  840. tmc2130_current_h[E_AXIS] = 36;
  841. tmc2130_current_r[E_AXIS] = 36;
  842. #endif //TMC2130
  843. #ifdef FILAMENT_SENSOR
  844. //disabled filament autoload (PFW360)
  845. fsensor_autoload_set(false);
  846. #endif //FILAMENT_SENSOR
  847. // ~ FanCheck -> on
  848. if(!(eeprom_read_byte((uint8_t*)EEPROM_FAN_CHECK_ENABLED)))
  849. eeprom_update_byte((unsigned char *)EEPROM_FAN_CHECK_ENABLED,true);
  850. }
  851. MYSERIAL.begin(BAUDRATE);
  852. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  853. #ifndef W25X20CL
  854. SERIAL_PROTOCOLLNPGM("start");
  855. #endif //W25X20CL
  856. stdout = uartout;
  857. SERIAL_ECHO_START;
  858. printf_P(PSTR(" " FW_VERSION_FULL "\n"));
  859. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  860. #ifdef DEBUG_SEC_LANG
  861. lang_table_header_t header;
  862. uint32_t src_addr = 0x00000;
  863. if (lang_get_header(1, &header, &src_addr))
  864. {
  865. //this is comparsion of some printing-methods regarding to flash space usage and code size/readability
  866. #define LT_PRINT_TEST 2
  867. // flash usage
  868. // total p.test
  869. //0 252718 t+c text code
  870. //1 253142 424 170 254
  871. //2 253040 322 164 158
  872. //3 253248 530 135 395
  873. #if (LT_PRINT_TEST==1) //not optimized printf
  874. printf_P(_n(" _src_addr = 0x%08lx\n"), src_addr);
  875. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  876. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  877. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  878. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  879. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  880. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  881. #elif (LT_PRINT_TEST==2) //optimized printf
  882. printf_P(
  883. _n(
  884. " _src_addr = 0x%08lx\n"
  885. " _lt_magic = 0x%08lx %S\n"
  886. " _lt_size = 0x%04x (%d)\n"
  887. " _lt_count = 0x%04x (%d)\n"
  888. " _lt_chsum = 0x%04x\n"
  889. " _lt_code = 0x%04x (%c%c)\n"
  890. " _lt_resv1 = 0x%08lx\n"
  891. ),
  892. src_addr,
  893. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  894. header.size, header.size,
  895. header.count, header.count,
  896. header.checksum,
  897. header.code, header.code >> 8, header.code & 0xff,
  898. header.signature
  899. );
  900. #elif (LT_PRINT_TEST==3) //arduino print/println (leading zeros not solved)
  901. MYSERIAL.print(" _src_addr = 0x");
  902. MYSERIAL.println(src_addr, 16);
  903. MYSERIAL.print(" _lt_magic = 0x");
  904. MYSERIAL.print(header.magic, 16);
  905. MYSERIAL.println((header.magic==LANG_MAGIC)?" OK":" NA");
  906. MYSERIAL.print(" _lt_size = 0x");
  907. MYSERIAL.print(header.size, 16);
  908. MYSERIAL.print(" (");
  909. MYSERIAL.print(header.size, 10);
  910. MYSERIAL.println(")");
  911. MYSERIAL.print(" _lt_count = 0x");
  912. MYSERIAL.print(header.count, 16);
  913. MYSERIAL.print(" (");
  914. MYSERIAL.print(header.count, 10);
  915. MYSERIAL.println(")");
  916. MYSERIAL.print(" _lt_chsum = 0x");
  917. MYSERIAL.println(header.checksum, 16);
  918. MYSERIAL.print(" _lt_code = 0x");
  919. MYSERIAL.print(header.code, 16);
  920. MYSERIAL.print(" (");
  921. MYSERIAL.print((char)(header.code >> 8), 0);
  922. MYSERIAL.print((char)(header.code & 0xff), 0);
  923. MYSERIAL.println(")");
  924. MYSERIAL.print(" _lt_resv1 = 0x");
  925. MYSERIAL.println(header.signature, 16);
  926. #endif //(LT_PRINT_TEST==)
  927. #undef LT_PRINT_TEST
  928. #if 0
  929. w25x20cl_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  930. for (uint16_t i = 0; i < 1024; i++)
  931. {
  932. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  933. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  934. if ((i % 16) == 15) putchar('\n');
  935. }
  936. #endif
  937. uint16_t sum = 0;
  938. for (uint16_t i = 0; i < header.size; i++)
  939. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  940. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  941. sum -= header.checksum; //subtract checksum
  942. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  943. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  944. if (sum == header.checksum)
  945. printf_P(_n("Checksum OK\n"), sum);
  946. else
  947. printf_P(_n("Checksum NG\n"), sum);
  948. }
  949. else
  950. printf_P(_n("lang_get_header failed!\n"));
  951. #if 0
  952. for (uint16_t i = 0; i < 1024*10; i++)
  953. {
  954. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  955. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  956. if ((i % 16) == 15) putchar('\n');
  957. }
  958. #endif
  959. #if 0
  960. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  961. for (int i = 0; i < 4096; ++i) {
  962. int b = eeprom_read_byte((unsigned char*)i);
  963. if (b != 255) {
  964. SERIAL_ECHO(i);
  965. SERIAL_ECHO(":");
  966. SERIAL_ECHO(b);
  967. SERIAL_ECHOLN("");
  968. }
  969. }
  970. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  971. #endif
  972. #endif //DEBUG_SEC_LANG
  973. // Check startup - does nothing if bootloader sets MCUSR to 0
  974. byte mcu = MCUSR;
  975. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  976. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  977. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  978. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  979. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  980. if (mcu & 1) puts_P(MSG_POWERUP);
  981. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  982. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  983. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  984. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  985. MCUSR = 0;
  986. //SERIAL_ECHORPGM(MSG_MARLIN);
  987. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  988. #ifdef STRING_VERSION_CONFIG_H
  989. #ifdef STRING_CONFIG_H_AUTHOR
  990. SERIAL_ECHO_START;
  991. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  992. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  993. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  994. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  995. SERIAL_ECHOPGM("Compiled: ");
  996. SERIAL_ECHOLNPGM(__DATE__);
  997. #endif
  998. #endif
  999. SERIAL_ECHO_START;
  1000. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1001. SERIAL_ECHO(freeMemory());
  1002. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1003. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1004. //lcd_update_enable(false); // why do we need this?? - andre
  1005. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1006. bool previous_settings_retrieved = false;
  1007. uint8_t hw_changed = check_printer_version();
  1008. 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
  1009. previous_settings_retrieved = Config_RetrieveSettings();
  1010. }
  1011. else { //printer version was changed so use default settings
  1012. Config_ResetDefault();
  1013. }
  1014. SdFatUtil::set_stack_guard(); //writes magic number at the end of static variables to protect against overwriting static memory by stack
  1015. tp_init(); // Initialize temperature loop
  1016. if (w25x20cl_success) lcd_splash(); // we need to do this again, because tp_init() kills lcd
  1017. else
  1018. {
  1019. w25x20cl_err_msg();
  1020. printf_P(_n("W25X20CL not responding.\n"));
  1021. }
  1022. plan_init(); // Initialize planner;
  1023. factory_reset();
  1024. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  1025. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff)
  1026. {
  1027. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  1028. // where all the EEPROM entries are set to 0x0ff.
  1029. // Once a firmware boots up, it forces at least a language selection, which changes
  1030. // EEPROM_LANG to number lower than 0x0ff.
  1031. // 1) Set a high power mode.
  1032. eeprom_update_byte((uint8_t*)EEPROM_SILENT, SILENT_MODE_OFF);
  1033. #ifdef TMC2130
  1034. tmc2130_mode = TMC2130_MODE_NORMAL;
  1035. #endif //TMC2130
  1036. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  1037. }
  1038. lcd_encoder_diff=0;
  1039. #ifdef TMC2130
  1040. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1041. if (silentMode == 0xff) silentMode = 0;
  1042. tmc2130_mode = TMC2130_MODE_NORMAL;
  1043. if (lcd_crash_detect_enabled() && !farm_mode)
  1044. {
  1045. lcd_crash_detect_enable();
  1046. puts_P(_N("CrashDetect ENABLED!"));
  1047. }
  1048. else
  1049. {
  1050. lcd_crash_detect_disable();
  1051. puts_P(_N("CrashDetect DISABLED"));
  1052. }
  1053. #ifdef TMC2130_LINEARITY_CORRECTION
  1054. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1055. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1056. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1057. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1058. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1059. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1060. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1061. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1062. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1063. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1064. #endif //TMC2130_LINEARITY_CORRECTION
  1065. #ifdef TMC2130_VARIABLE_RESOLUTION
  1066. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1067. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1068. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1069. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1070. #else //TMC2130_VARIABLE_RESOLUTION
  1071. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1072. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1073. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1074. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1075. #endif //TMC2130_VARIABLE_RESOLUTION
  1076. #endif //TMC2130
  1077. st_init(); // Initialize stepper, this enables interrupts!
  1078. #ifdef UVLO_SUPPORT
  1079. setup_uvlo_interrupt();
  1080. #endif //UVLO_SUPPORT
  1081. #ifdef TMC2130
  1082. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1083. update_mode_profile();
  1084. tmc2130_init();
  1085. #endif //TMC2130
  1086. #ifdef PSU_Delta
  1087. init_force_z(); // ! important for correct Z-axis initialization
  1088. #endif // PSU_Delta
  1089. setup_photpin();
  1090. servo_init();
  1091. // Reset the machine correction matrix.
  1092. // It does not make sense to load the correction matrix until the machine is homed.
  1093. world2machine_reset();
  1094. #ifdef FILAMENT_SENSOR
  1095. fsensor_init();
  1096. #endif //FILAMENT_SENSOR
  1097. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1098. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1099. #endif
  1100. setup_homepin();
  1101. #ifdef TMC2130
  1102. if (1) {
  1103. // try to run to zero phase before powering the Z motor.
  1104. // Move in negative direction
  1105. WRITE(Z_DIR_PIN,INVERT_Z_DIR);
  1106. // Round the current micro-micro steps to micro steps.
  1107. for (uint16_t phase = (tmc2130_rd_MSCNT(Z_AXIS) + 8) >> 4; phase > 0; -- phase) {
  1108. // Until the phase counter is reset to zero.
  1109. WRITE(Z_STEP_PIN, !INVERT_Z_STEP_PIN);
  1110. _delay(2);
  1111. WRITE(Z_STEP_PIN, INVERT_Z_STEP_PIN);
  1112. _delay(2);
  1113. }
  1114. }
  1115. #endif //TMC2130
  1116. #if defined(Z_AXIS_ALWAYS_ON) && !defined(PSU_Delta)
  1117. enable_z();
  1118. #endif
  1119. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  1120. EEPROM_read_B(EEPROM_FARM_NUMBER, &farm_no);
  1121. if ((farm_mode == 0xFF && farm_no == 0) || (farm_no == static_cast<int>(0xFFFF))) farm_mode = false; //if farm_mode has not been stored to eeprom yet and farm number is set to zero or EEPROM is fresh, deactivate farm mode
  1122. if (farm_no == static_cast<int>(0xFFFF)) farm_no = 0;
  1123. if (farm_mode)
  1124. {
  1125. prusa_statistics(8);
  1126. }
  1127. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1128. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1129. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1130. // but this times out if a blocking dialog is shown in setup().
  1131. card.initsd();
  1132. #ifdef DEBUG_SD_SPEED_TEST
  1133. if (card.cardOK)
  1134. {
  1135. uint8_t* buff = (uint8_t*)block_buffer;
  1136. uint32_t block = 0;
  1137. uint32_t sumr = 0;
  1138. uint32_t sumw = 0;
  1139. for (int i = 0; i < 1024; i++)
  1140. {
  1141. uint32_t u = _micros();
  1142. bool res = card.card.readBlock(i, buff);
  1143. u = _micros() - u;
  1144. if (res)
  1145. {
  1146. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1147. sumr += u;
  1148. u = _micros();
  1149. res = card.card.writeBlock(i, buff);
  1150. u = _micros() - u;
  1151. if (res)
  1152. {
  1153. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1154. sumw += u;
  1155. }
  1156. else
  1157. {
  1158. printf_P(PSTR("writeBlock %4d error\n"), i);
  1159. break;
  1160. }
  1161. }
  1162. else
  1163. {
  1164. printf_P(PSTR("readBlock %4d error\n"), i);
  1165. break;
  1166. }
  1167. }
  1168. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1169. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1170. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1171. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1172. }
  1173. else
  1174. printf_P(PSTR("Card NG!\n"));
  1175. #endif //DEBUG_SD_SPEED_TEST
  1176. eeprom_init();
  1177. #ifdef SNMM
  1178. if (eeprom_read_dword((uint32_t*)EEPROM_BOWDEN_LENGTH) == 0x0ffffffff) { //bowden length used for SNMM
  1179. int _z = BOWDEN_LENGTH;
  1180. for(int i = 0; i<4; i++) EEPROM_save_B(EEPROM_BOWDEN_LENGTH + i * 2, &_z);
  1181. }
  1182. #endif
  1183. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1184. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1185. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1186. #if (LANG_MODE != 0) //secondary language support
  1187. #ifdef DEBUG_W25X20CL
  1188. W25X20CL_SPI_ENTER();
  1189. uint8_t uid[8]; // 64bit unique id
  1190. w25x20cl_rd_uid(uid);
  1191. puts_P(_n("W25X20CL UID="));
  1192. for (uint8_t i = 0; i < 8; i ++)
  1193. printf_P(PSTR("%02hhx"), uid[i]);
  1194. putchar('\n');
  1195. list_sec_lang_from_external_flash();
  1196. #endif //DEBUG_W25X20CL
  1197. // lang_reset();
  1198. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1199. lcd_language();
  1200. #ifdef DEBUG_SEC_LANG
  1201. uint16_t sec_lang_code = lang_get_code(1);
  1202. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1203. 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);
  1204. lang_print_sec_lang(uartout);
  1205. #endif //DEBUG_SEC_LANG
  1206. #endif //(LANG_MODE != 0)
  1207. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  1208. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1209. temp_cal_active = false;
  1210. } else temp_cal_active = eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE);
  1211. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1212. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1213. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1214. int16_t z_shift = 0;
  1215. for (uint8_t i = 0; i < 5; i++) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  1216. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1217. temp_cal_active = false;
  1218. }
  1219. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 255) {
  1220. eeprom_write_byte((uint8_t*)EEPROM_UVLO, 0);
  1221. }
  1222. if (eeprom_read_byte((uint8_t*)EEPROM_SD_SORT) == 255) {
  1223. eeprom_write_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1224. }
  1225. //mbl_mode_init();
  1226. mbl_settings_init();
  1227. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1228. if (SilentModeMenu_MMU == 255) {
  1229. SilentModeMenu_MMU = 1;
  1230. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1231. }
  1232. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1233. setup_fan_interrupt();
  1234. #endif //DEBUG_DISABLE_FANCHECK
  1235. #ifdef PAT9125
  1236. fsensor_setup_interrupt();
  1237. #endif //PAT9125
  1238. for (int i = 0; i<4; i++) EEPROM_read_B(EEPROM_BOWDEN_LENGTH + i * 2, &bowden_length[i]);
  1239. #ifndef DEBUG_DISABLE_STARTMSGS
  1240. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1241. if (!farm_mode) {
  1242. check_if_fw_is_on_right_printer();
  1243. show_fw_version_warnings();
  1244. }
  1245. switch (hw_changed) {
  1246. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1247. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1248. case(0b01):
  1249. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1250. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1251. break;
  1252. case(0b10):
  1253. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1254. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1255. break;
  1256. case(0b11):
  1257. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1258. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1259. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1260. break;
  1261. default: break; //no change, show no message
  1262. }
  1263. if (!previous_settings_retrieved) {
  1264. lcd_show_fullscreen_message_and_wait_P(_i("Old settings found. Default PID, Esteps etc. will be set.")); //if EEPROM version or printer type was changed, inform user that default setting were loaded////MSG_DEFAULT_SETTINGS_LOADED c=20 r=4
  1265. Config_StoreSettings();
  1266. }
  1267. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 1) {
  1268. lcd_wizard(WizState::Run);
  1269. }
  1270. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1271. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1272. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1273. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1274. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1275. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  1276. // Show the message.
  1277. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1278. }
  1279. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1280. // Show the message.
  1281. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1282. lcd_update_enable(true);
  1283. }
  1284. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && temp_cal_active == true && calibration_status_pinda() == false) {
  1285. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1286. lcd_update_enable(true);
  1287. }
  1288. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1289. // Show the message.
  1290. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1291. }
  1292. }
  1293. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1294. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1295. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1296. update_current_firmware_version_to_eeprom();
  1297. lcd_selftest();
  1298. }
  1299. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1300. KEEPALIVE_STATE(IN_PROCESS);
  1301. #endif //DEBUG_DISABLE_STARTMSGS
  1302. lcd_update_enable(true);
  1303. lcd_clear();
  1304. lcd_update(2);
  1305. // Store the currently running firmware into an eeprom,
  1306. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1307. update_current_firmware_version_to_eeprom();
  1308. #ifdef TMC2130
  1309. tmc2130_home_origin[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN);
  1310. tmc2130_home_bsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS);
  1311. tmc2130_home_fsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS);
  1312. if (tmc2130_home_origin[X_AXIS] == 0xff) tmc2130_home_origin[X_AXIS] = 0;
  1313. if (tmc2130_home_bsteps[X_AXIS] == 0xff) tmc2130_home_bsteps[X_AXIS] = 48;
  1314. if (tmc2130_home_fsteps[X_AXIS] == 0xff) tmc2130_home_fsteps[X_AXIS] = 48;
  1315. tmc2130_home_origin[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN);
  1316. tmc2130_home_bsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS);
  1317. tmc2130_home_fsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS);
  1318. if (tmc2130_home_origin[Y_AXIS] == 0xff) tmc2130_home_origin[Y_AXIS] = 0;
  1319. if (tmc2130_home_bsteps[Y_AXIS] == 0xff) tmc2130_home_bsteps[Y_AXIS] = 48;
  1320. if (tmc2130_home_fsteps[Y_AXIS] == 0xff) tmc2130_home_fsteps[Y_AXIS] = 48;
  1321. tmc2130_home_enabled = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED);
  1322. if (tmc2130_home_enabled == 0xff) tmc2130_home_enabled = 0;
  1323. #endif //TMC2130
  1324. #ifdef UVLO_SUPPORT
  1325. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1326. /*
  1327. if (lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1328. else {
  1329. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1330. lcd_update_enable(true);
  1331. lcd_update(2);
  1332. lcd_setstatuspgm(_T(WELCOME_MSG));
  1333. }
  1334. */
  1335. manage_heater(); // Update temperatures
  1336. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1337. 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));
  1338. #endif
  1339. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1340. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1341. puts_P(_N("Automatic recovery!"));
  1342. #endif
  1343. recover_print(1);
  1344. }
  1345. else{
  1346. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1347. puts_P(_N("Normal recovery!"));
  1348. #endif
  1349. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) ) recover_print(0);
  1350. else {
  1351. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1352. lcd_update_enable(true);
  1353. lcd_update(2);
  1354. lcd_setstatuspgm(_T(WELCOME_MSG));
  1355. }
  1356. }
  1357. }
  1358. #endif //UVLO_SUPPORT
  1359. fCheckModeInit();
  1360. fSetMmuMode(mmu_enabled);
  1361. KEEPALIVE_STATE(NOT_BUSY);
  1362. #ifdef WATCHDOG
  1363. wdt_enable(WDTO_4S);
  1364. #endif //WATCHDOG
  1365. }
  1366. void trace();
  1367. #define CHUNK_SIZE 64 // bytes
  1368. #define SAFETY_MARGIN 1
  1369. char chunk[CHUNK_SIZE+SAFETY_MARGIN];
  1370. int chunkHead = 0;
  1371. void serial_read_stream() {
  1372. setAllTargetHotends(0);
  1373. setTargetBed(0);
  1374. lcd_clear();
  1375. lcd_puts_P(PSTR(" Upload in progress"));
  1376. // first wait for how many bytes we will receive
  1377. uint32_t bytesToReceive;
  1378. // receive the four bytes
  1379. char bytesToReceiveBuffer[4];
  1380. for (int i=0; i<4; i++) {
  1381. int data;
  1382. while ((data = MYSERIAL.read()) == -1) {};
  1383. bytesToReceiveBuffer[i] = data;
  1384. }
  1385. // make it a uint32
  1386. memcpy(&bytesToReceive, &bytesToReceiveBuffer, 4);
  1387. // we're ready, notify the sender
  1388. MYSERIAL.write('+');
  1389. // lock in the routine
  1390. uint32_t receivedBytes = 0;
  1391. while (prusa_sd_card_upload) {
  1392. int i;
  1393. for (i=0; i<CHUNK_SIZE; i++) {
  1394. int data;
  1395. // check if we're not done
  1396. if (receivedBytes == bytesToReceive) {
  1397. break;
  1398. }
  1399. // read the next byte
  1400. while ((data = MYSERIAL.read()) == -1) {};
  1401. receivedBytes++;
  1402. // save it to the chunk
  1403. chunk[i] = data;
  1404. }
  1405. // write the chunk to SD
  1406. card.write_command_no_newline(&chunk[0]);
  1407. // notify the sender we're ready for more data
  1408. MYSERIAL.write('+');
  1409. // for safety
  1410. manage_heater();
  1411. // check if we're done
  1412. if(receivedBytes == bytesToReceive) {
  1413. trace(); // beep
  1414. card.closefile();
  1415. prusa_sd_card_upload = false;
  1416. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1417. }
  1418. }
  1419. }
  1420. /**
  1421. * Output a "busy" message at regular intervals
  1422. * while the machine is not accepting commands.
  1423. */
  1424. void host_keepalive() {
  1425. #ifndef HOST_KEEPALIVE_FEATURE
  1426. return;
  1427. #endif //HOST_KEEPALIVE_FEATURE
  1428. if (farm_mode) return;
  1429. long ms = _millis();
  1430. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1431. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1432. switch (busy_state) {
  1433. case IN_HANDLER:
  1434. case IN_PROCESS:
  1435. SERIAL_ECHO_START;
  1436. SERIAL_ECHOLNPGM("busy: processing");
  1437. break;
  1438. case PAUSED_FOR_USER:
  1439. SERIAL_ECHO_START;
  1440. SERIAL_ECHOLNPGM("busy: paused for user");
  1441. break;
  1442. case PAUSED_FOR_INPUT:
  1443. SERIAL_ECHO_START;
  1444. SERIAL_ECHOLNPGM("busy: paused for input");
  1445. break;
  1446. default:
  1447. break;
  1448. }
  1449. }
  1450. prev_busy_signal_ms = ms;
  1451. }
  1452. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1453. // Before loop(), the setup() function is called by the main() routine.
  1454. void loop()
  1455. {
  1456. KEEPALIVE_STATE(NOT_BUSY);
  1457. if ((usb_printing_counter > 0) && ((_millis()-_usb_timer) > 1000))
  1458. {
  1459. is_usb_printing = true;
  1460. usb_printing_counter--;
  1461. _usb_timer = _millis();
  1462. }
  1463. if (usb_printing_counter == 0)
  1464. {
  1465. is_usb_printing = false;
  1466. }
  1467. if (isPrintPaused && saved_printing_type == PRINTING_TYPE_USB) //keep believing that usb is being printed. Prevents accessing dangerous menus while pausing.
  1468. {
  1469. is_usb_printing = true;
  1470. }
  1471. #ifdef FANCHECK
  1472. if (fan_check_error && isPrintPaused)
  1473. {
  1474. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1475. host_keepalive(); //prevent timeouts since usb processing is disabled until print is resumed. This is for a crude way of pausing a print on all hosts.
  1476. }
  1477. #endif
  1478. if (prusa_sd_card_upload)
  1479. {
  1480. //we read byte-by byte
  1481. serial_read_stream();
  1482. }
  1483. else
  1484. {
  1485. get_command();
  1486. #ifdef SDSUPPORT
  1487. card.checkautostart(false);
  1488. #endif
  1489. if(buflen)
  1490. {
  1491. cmdbuffer_front_already_processed = false;
  1492. #ifdef SDSUPPORT
  1493. if(card.saving)
  1494. {
  1495. // Saving a G-code file onto an SD-card is in progress.
  1496. // Saving starts with M28, saving until M29 is seen.
  1497. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1498. card.write_command(CMDBUFFER_CURRENT_STRING);
  1499. if(card.logging)
  1500. process_commands();
  1501. else
  1502. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1503. } else {
  1504. card.closefile();
  1505. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1506. }
  1507. } else {
  1508. process_commands();
  1509. }
  1510. #else
  1511. process_commands();
  1512. #endif //SDSUPPORT
  1513. if (! cmdbuffer_front_already_processed && buflen)
  1514. {
  1515. // ptr points to the start of the block currently being processed.
  1516. // The first character in the block is the block type.
  1517. char *ptr = cmdbuffer + bufindr;
  1518. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1519. // To support power panic, move the lenght of the command on the SD card to a planner buffer.
  1520. union {
  1521. struct {
  1522. char lo;
  1523. char hi;
  1524. } lohi;
  1525. uint16_t value;
  1526. } sdlen;
  1527. sdlen.value = 0;
  1528. {
  1529. // This block locks the interrupts globally for 3.25 us,
  1530. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1531. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1532. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1533. cli();
  1534. // Reset the command to something, which will be ignored by the power panic routine,
  1535. // so this buffer length will not be counted twice.
  1536. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1537. // Extract the current buffer length.
  1538. sdlen.lohi.lo = *ptr ++;
  1539. sdlen.lohi.hi = *ptr;
  1540. // and pass it to the planner queue.
  1541. planner_add_sd_length(sdlen.value);
  1542. sei();
  1543. }
  1544. }
  1545. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1546. cli();
  1547. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1548. // and one for each command to previous block in the planner queue.
  1549. planner_add_sd_length(1);
  1550. sei();
  1551. }
  1552. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1553. // this block's SD card length will not be counted twice as its command type has been replaced
  1554. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1555. cmdqueue_pop_front();
  1556. }
  1557. host_keepalive();
  1558. }
  1559. }
  1560. //check heater every n milliseconds
  1561. manage_heater();
  1562. isPrintPaused ? manage_inactivity(true) : manage_inactivity(false);
  1563. checkHitEndstops();
  1564. lcd_update(0);
  1565. #ifdef TMC2130
  1566. tmc2130_check_overtemp();
  1567. if (tmc2130_sg_crash)
  1568. {
  1569. uint8_t crash = tmc2130_sg_crash;
  1570. tmc2130_sg_crash = 0;
  1571. // crashdet_stop_and_save_print();
  1572. switch (crash)
  1573. {
  1574. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1575. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1576. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1577. }
  1578. }
  1579. #endif //TMC2130
  1580. mmu_loop();
  1581. }
  1582. #define DEFINE_PGM_READ_ANY(type, reader) \
  1583. static inline type pgm_read_any(const type *p) \
  1584. { return pgm_read_##reader##_near(p); }
  1585. DEFINE_PGM_READ_ANY(float, float);
  1586. DEFINE_PGM_READ_ANY(signed char, byte);
  1587. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1588. static const PROGMEM type array##_P[3] = \
  1589. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1590. static inline type array(int axis) \
  1591. { return pgm_read_any(&array##_P[axis]); } \
  1592. type array##_ext(int axis) \
  1593. { return pgm_read_any(&array##_P[axis]); }
  1594. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1595. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1596. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1597. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1598. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1599. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1600. static void axis_is_at_home(int axis) {
  1601. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1602. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1603. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1604. }
  1605. inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); }
  1606. inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); }
  1607. //! @return original feedmultiply
  1608. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1609. saved_feedrate = feedrate;
  1610. int l_feedmultiply = feedmultiply;
  1611. feedmultiply = 100;
  1612. previous_millis_cmd = _millis();
  1613. enable_endstops(enable_endstops_now);
  1614. return l_feedmultiply;
  1615. }
  1616. //! @param original_feedmultiply feedmultiply to restore
  1617. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1618. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1619. enable_endstops(false);
  1620. #endif
  1621. feedrate = saved_feedrate;
  1622. feedmultiply = original_feedmultiply;
  1623. previous_millis_cmd = _millis();
  1624. }
  1625. #ifdef ENABLE_AUTO_BED_LEVELING
  1626. #ifdef AUTO_BED_LEVELING_GRID
  1627. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1628. {
  1629. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1630. planeNormal.debug("planeNormal");
  1631. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1632. //bedLevel.debug("bedLevel");
  1633. //plan_bed_level_matrix.debug("bed level before");
  1634. //vector_3 uncorrected_position = plan_get_position_mm();
  1635. //uncorrected_position.debug("position before");
  1636. vector_3 corrected_position = plan_get_position();
  1637. // corrected_position.debug("position after");
  1638. current_position[X_AXIS] = corrected_position.x;
  1639. current_position[Y_AXIS] = corrected_position.y;
  1640. current_position[Z_AXIS] = corrected_position.z;
  1641. // put the bed at 0 so we don't go below it.
  1642. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1643. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1644. }
  1645. #else // not AUTO_BED_LEVELING_GRID
  1646. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1647. plan_bed_level_matrix.set_to_identity();
  1648. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1649. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1650. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1651. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1652. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1653. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1654. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1655. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1656. vector_3 corrected_position = plan_get_position();
  1657. current_position[X_AXIS] = corrected_position.x;
  1658. current_position[Y_AXIS] = corrected_position.y;
  1659. current_position[Z_AXIS] = corrected_position.z;
  1660. // put the bed at 0 so we don't go below it.
  1661. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1662. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1663. }
  1664. #endif // AUTO_BED_LEVELING_GRID
  1665. static void run_z_probe() {
  1666. plan_bed_level_matrix.set_to_identity();
  1667. feedrate = homing_feedrate[Z_AXIS];
  1668. // move down until you find the bed
  1669. float zPosition = -10;
  1670. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1671. st_synchronize();
  1672. // we have to let the planner know where we are right now as it is not where we said to go.
  1673. zPosition = st_get_position_mm(Z_AXIS);
  1674. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1675. // move up the retract distance
  1676. zPosition += home_retract_mm(Z_AXIS);
  1677. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1678. st_synchronize();
  1679. // move back down slowly to find bed
  1680. feedrate = homing_feedrate[Z_AXIS]/4;
  1681. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1682. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1683. st_synchronize();
  1684. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1685. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1686. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1687. }
  1688. static void do_blocking_move_to(float x, float y, float z) {
  1689. float oldFeedRate = feedrate;
  1690. feedrate = homing_feedrate[Z_AXIS];
  1691. current_position[Z_AXIS] = z;
  1692. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1693. st_synchronize();
  1694. feedrate = XY_TRAVEL_SPEED;
  1695. current_position[X_AXIS] = x;
  1696. current_position[Y_AXIS] = y;
  1697. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1698. st_synchronize();
  1699. feedrate = oldFeedRate;
  1700. }
  1701. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1702. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1703. }
  1704. /// Probe bed height at position (x,y), returns the measured z value
  1705. static float probe_pt(float x, float y, float z_before) {
  1706. // move to right place
  1707. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1708. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1709. run_z_probe();
  1710. float measured_z = current_position[Z_AXIS];
  1711. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1712. SERIAL_PROTOCOLPGM(" x: ");
  1713. SERIAL_PROTOCOL(x);
  1714. SERIAL_PROTOCOLPGM(" y: ");
  1715. SERIAL_PROTOCOL(y);
  1716. SERIAL_PROTOCOLPGM(" z: ");
  1717. SERIAL_PROTOCOL(measured_z);
  1718. SERIAL_PROTOCOLPGM("\n");
  1719. return measured_z;
  1720. }
  1721. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1722. #ifdef LIN_ADVANCE
  1723. /**
  1724. * M900: Set and/or Get advance K factor
  1725. *
  1726. * K<factor> Set advance K factor
  1727. */
  1728. inline void gcode_M900() {
  1729. float newK = code_seen('K') ? code_value_float() : -2;
  1730. #ifdef LA_NOCOMPAT
  1731. if (newK >= 0 && newK < 10)
  1732. extruder_advance_K = newK;
  1733. else
  1734. SERIAL_ECHOLNPGM("K out of allowed range!");
  1735. #else
  1736. if (newK == 0)
  1737. extruder_advance_K = 0;
  1738. else if (newK == -1)
  1739. la10c_reset();
  1740. else
  1741. {
  1742. newK = la10c_value(newK);
  1743. if (newK < 0)
  1744. SERIAL_ECHOLNPGM("K out of allowed range!");
  1745. else
  1746. extruder_advance_K = newK;
  1747. }
  1748. #endif
  1749. SERIAL_ECHO_START;
  1750. SERIAL_ECHOPGM("Advance K=");
  1751. SERIAL_ECHOLN(extruder_advance_K);
  1752. }
  1753. #endif // LIN_ADVANCE
  1754. bool check_commands() {
  1755. bool end_command_found = false;
  1756. while (buflen)
  1757. {
  1758. if ((code_seen("M84")) || (code_seen("M 84"))) end_command_found = true;
  1759. if (!cmdbuffer_front_already_processed)
  1760. cmdqueue_pop_front();
  1761. cmdbuffer_front_already_processed = false;
  1762. }
  1763. return end_command_found;
  1764. }
  1765. // raise_z_above: slowly raise Z to the requested height
  1766. //
  1767. // contrarily to a simple move, this function will carefully plan a move
  1768. // when the current Z position is unknown. In such cases, stallguard is
  1769. // enabled and will prevent prolonged pushing against the Z tops
  1770. void raise_z_above(float target, bool plan)
  1771. {
  1772. if (current_position[Z_AXIS] >= target)
  1773. return;
  1774. // Z needs raising
  1775. current_position[Z_AXIS] = target;
  1776. #if defined(Z_MIN_PIN) && (Z_MIN_PIN > -1) && !defined(DEBUG_DISABLE_ZMINLIMIT)
  1777. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1778. #else
  1779. bool z_min_endstop = false;
  1780. #endif
  1781. if (axis_known_position[Z_AXIS] || z_min_endstop)
  1782. {
  1783. // current position is known or very low, it's safe to raise Z
  1784. if(plan) plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS], active_extruder);
  1785. return;
  1786. }
  1787. // ensure Z is powered in normal mode to overcome initial load
  1788. enable_z();
  1789. st_synchronize();
  1790. // rely on crashguard to limit damage
  1791. bool z_endstop_enabled = enable_z_endstop(true);
  1792. #ifdef TMC2130
  1793. tmc2130_home_enter(Z_AXIS_MASK);
  1794. #endif //TMC2130
  1795. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  1796. st_synchronize();
  1797. #ifdef TMC2130
  1798. if (endstop_z_hit_on_purpose())
  1799. {
  1800. // not necessarily exact, but will avoid further vertical moves
  1801. current_position[Z_AXIS] = max_pos[Z_AXIS];
  1802. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS],
  1803. current_position[Z_AXIS], current_position[E_AXIS]);
  1804. }
  1805. tmc2130_home_exit();
  1806. #endif //TMC2130
  1807. enable_z_endstop(z_endstop_enabled);
  1808. }
  1809. #ifdef TMC2130
  1810. bool calibrate_z_auto()
  1811. {
  1812. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1813. lcd_clear();
  1814. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1815. bool endstops_enabled = enable_endstops(true);
  1816. int axis_up_dir = -home_dir(Z_AXIS);
  1817. tmc2130_home_enter(Z_AXIS_MASK);
  1818. current_position[Z_AXIS] = 0;
  1819. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1820. set_destination_to_current();
  1821. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1822. feedrate = homing_feedrate[Z_AXIS];
  1823. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / 60, active_extruder);
  1824. st_synchronize();
  1825. // current_position[axis] = 0;
  1826. // plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1827. tmc2130_home_exit();
  1828. enable_endstops(false);
  1829. current_position[Z_AXIS] = 0;
  1830. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1831. set_destination_to_current();
  1832. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1833. feedrate = homing_feedrate[Z_AXIS] / 2;
  1834. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / 60, active_extruder);
  1835. st_synchronize();
  1836. enable_endstops(endstops_enabled);
  1837. if (PRINTER_TYPE == PRINTER_MK3) {
  1838. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1839. }
  1840. else {
  1841. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1842. }
  1843. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1844. return true;
  1845. }
  1846. #endif //TMC2130
  1847. #ifdef TMC2130
  1848. void homeaxis(int axis, uint8_t cnt, uint8_t* pstep)
  1849. #else
  1850. void homeaxis(int axis, uint8_t cnt)
  1851. #endif //TMC2130
  1852. {
  1853. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1854. #define HOMEAXIS_DO(LETTER) \
  1855. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1856. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1857. {
  1858. int axis_home_dir = home_dir(axis);
  1859. feedrate = homing_feedrate[axis];
  1860. #ifdef TMC2130
  1861. tmc2130_home_enter(X_AXIS_MASK << axis);
  1862. #endif //TMC2130
  1863. // Move away a bit, so that the print head does not touch the end position,
  1864. // and the following movement to endstop has a chance to achieve the required velocity
  1865. // for the stall guard to work.
  1866. current_position[axis] = 0;
  1867. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1868. set_destination_to_current();
  1869. // destination[axis] = 11.f;
  1870. destination[axis] = -3.f * axis_home_dir;
  1871. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1872. st_synchronize();
  1873. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1874. endstops_hit_on_purpose();
  1875. enable_endstops(false);
  1876. current_position[axis] = 0;
  1877. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1878. destination[axis] = 1. * axis_home_dir;
  1879. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1880. st_synchronize();
  1881. // Now continue to move up to the left end stop with the collision detection enabled.
  1882. enable_endstops(true);
  1883. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1884. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1885. st_synchronize();
  1886. for (uint8_t i = 0; i < cnt; i++)
  1887. {
  1888. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1889. endstops_hit_on_purpose();
  1890. enable_endstops(false);
  1891. current_position[axis] = 0;
  1892. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1893. destination[axis] = -10.f * axis_home_dir;
  1894. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1895. st_synchronize();
  1896. endstops_hit_on_purpose();
  1897. // Now move left up to the collision, this time with a repeatable velocity.
  1898. enable_endstops(true);
  1899. destination[axis] = 11.f * axis_home_dir;
  1900. #ifdef TMC2130
  1901. feedrate = homing_feedrate[axis];
  1902. #else //TMC2130
  1903. feedrate = homing_feedrate[axis] / 2;
  1904. #endif //TMC2130
  1905. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1906. st_synchronize();
  1907. #ifdef TMC2130
  1908. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1909. if (pstep) pstep[i] = mscnt >> 4;
  1910. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1911. #endif //TMC2130
  1912. }
  1913. endstops_hit_on_purpose();
  1914. enable_endstops(false);
  1915. #ifdef TMC2130
  1916. uint8_t orig = tmc2130_home_origin[axis];
  1917. uint8_t back = tmc2130_home_bsteps[axis];
  1918. if (tmc2130_home_enabled && (orig <= 63))
  1919. {
  1920. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1921. if (back > 0)
  1922. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1923. }
  1924. else
  1925. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1926. tmc2130_home_exit();
  1927. #endif //TMC2130
  1928. axis_is_at_home(axis);
  1929. axis_known_position[axis] = true;
  1930. // Move from minimum
  1931. #ifdef TMC2130
  1932. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1933. #else //TMC2130
  1934. float dist = - axis_home_dir * 0.01f * 64;
  1935. #endif //TMC2130
  1936. current_position[axis] -= dist;
  1937. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1938. current_position[axis] += dist;
  1939. destination[axis] = current_position[axis];
  1940. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], 0.5f*feedrate/60, active_extruder);
  1941. st_synchronize();
  1942. feedrate = 0.0;
  1943. }
  1944. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1945. {
  1946. #ifdef TMC2130
  1947. FORCE_HIGH_POWER_START;
  1948. #endif
  1949. int axis_home_dir = home_dir(axis);
  1950. current_position[axis] = 0;
  1951. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1952. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1953. feedrate = homing_feedrate[axis];
  1954. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1955. st_synchronize();
  1956. #ifdef TMC2130
  1957. if (READ(Z_TMC2130_DIAG) != 0) { //Z crash
  1958. FORCE_HIGH_POWER_END;
  1959. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1960. return;
  1961. }
  1962. #endif //TMC2130
  1963. current_position[axis] = 0;
  1964. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1965. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1966. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1967. st_synchronize();
  1968. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1969. feedrate = homing_feedrate[axis]/2 ;
  1970. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1971. st_synchronize();
  1972. #ifdef TMC2130
  1973. if (READ(Z_TMC2130_DIAG) != 0) { //Z crash
  1974. FORCE_HIGH_POWER_END;
  1975. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1976. return;
  1977. }
  1978. #endif //TMC2130
  1979. axis_is_at_home(axis);
  1980. destination[axis] = current_position[axis];
  1981. feedrate = 0.0;
  1982. endstops_hit_on_purpose();
  1983. axis_known_position[axis] = true;
  1984. #ifdef TMC2130
  1985. FORCE_HIGH_POWER_END;
  1986. #endif
  1987. }
  1988. enable_endstops(endstops_enabled);
  1989. }
  1990. /**/
  1991. void home_xy()
  1992. {
  1993. set_destination_to_current();
  1994. homeaxis(X_AXIS);
  1995. homeaxis(Y_AXIS);
  1996. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1997. endstops_hit_on_purpose();
  1998. }
  1999. void refresh_cmd_timeout(void)
  2000. {
  2001. previous_millis_cmd = _millis();
  2002. }
  2003. #ifdef FWRETRACT
  2004. void retract(bool retracting, bool swapretract = false) {
  2005. if(retracting && !retracted[active_extruder]) {
  2006. destination[X_AXIS]=current_position[X_AXIS];
  2007. destination[Y_AXIS]=current_position[Y_AXIS];
  2008. destination[Z_AXIS]=current_position[Z_AXIS];
  2009. destination[E_AXIS]=current_position[E_AXIS];
  2010. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  2011. plan_set_e_position(current_position[E_AXIS]);
  2012. float oldFeedrate = feedrate;
  2013. feedrate=cs.retract_feedrate*60;
  2014. retracted[active_extruder]=true;
  2015. prepare_move();
  2016. current_position[Z_AXIS]-=cs.retract_zlift;
  2017. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2018. prepare_move();
  2019. feedrate = oldFeedrate;
  2020. } else if(!retracting && retracted[active_extruder]) {
  2021. destination[X_AXIS]=current_position[X_AXIS];
  2022. destination[Y_AXIS]=current_position[Y_AXIS];
  2023. destination[Z_AXIS]=current_position[Z_AXIS];
  2024. destination[E_AXIS]=current_position[E_AXIS];
  2025. current_position[Z_AXIS]+=cs.retract_zlift;
  2026. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2027. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  2028. plan_set_e_position(current_position[E_AXIS]);
  2029. float oldFeedrate = feedrate;
  2030. feedrate=cs.retract_recover_feedrate*60;
  2031. retracted[active_extruder]=false;
  2032. prepare_move();
  2033. feedrate = oldFeedrate;
  2034. }
  2035. } //retract
  2036. #endif //FWRETRACT
  2037. void trace() {
  2038. Sound_MakeCustom(25,440,true);
  2039. }
  2040. /*
  2041. void ramming() {
  2042. // float tmp[4] = DEFAULT_MAX_FEEDRATE;
  2043. if (current_temperature[0] < 230) {
  2044. //PLA
  2045. max_feedrate[E_AXIS] = 50;
  2046. //current_position[E_AXIS] -= 8;
  2047. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2048. //current_position[E_AXIS] += 8;
  2049. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2050. current_position[E_AXIS] += 5.4;
  2051. plan_buffer_line_curposXYZE(2800 / 60, active_extruder);
  2052. current_position[E_AXIS] += 3.2;
  2053. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  2054. current_position[E_AXIS] += 3;
  2055. plan_buffer_line_curposXYZE(3400 / 60, active_extruder);
  2056. st_synchronize();
  2057. max_feedrate[E_AXIS] = 80;
  2058. current_position[E_AXIS] -= 82;
  2059. plan_buffer_line_curposXYZE(9500 / 60, active_extruder);
  2060. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  2061. current_position[E_AXIS] -= 20;
  2062. plan_buffer_line_curposXYZE(1200 / 60, active_extruder);
  2063. current_position[E_AXIS] += 5;
  2064. plan_buffer_line_curposXYZE(400 / 60, active_extruder);
  2065. current_position[E_AXIS] += 5;
  2066. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2067. current_position[E_AXIS] -= 10;
  2068. st_synchronize();
  2069. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2070. current_position[E_AXIS] += 10;
  2071. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2072. current_position[E_AXIS] -= 10;
  2073. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2074. current_position[E_AXIS] += 10;
  2075. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2076. current_position[E_AXIS] -= 10;
  2077. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2078. st_synchronize();
  2079. }
  2080. else {
  2081. //ABS
  2082. max_feedrate[E_AXIS] = 50;
  2083. //current_position[E_AXIS] -= 8;
  2084. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2085. //current_position[E_AXIS] += 8;
  2086. //plan_buffer_line_curposXYZE(2100 / 60, active_extruder);
  2087. current_position[E_AXIS] += 3.1;
  2088. plan_buffer_line_curposXYZE(2000 / 60, active_extruder);
  2089. current_position[E_AXIS] += 3.1;
  2090. plan_buffer_line_curposXYZE(2500 / 60, active_extruder);
  2091. current_position[E_AXIS] += 4;
  2092. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  2093. st_synchronize();
  2094. //current_position[X_AXIS] += 23; //delay
  2095. //plan_buffer_line_curposXYZE(600/60, active_extruder); //delay
  2096. //current_position[X_AXIS] -= 23; //delay
  2097. //plan_buffer_line_curposXYZE(600/60, active_extruder); //delay
  2098. _delay(4700);
  2099. max_feedrate[E_AXIS] = 80;
  2100. current_position[E_AXIS] -= 92;
  2101. plan_buffer_line_curposXYZE(9900 / 60, active_extruder);
  2102. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  2103. current_position[E_AXIS] -= 5;
  2104. plan_buffer_line_curposXYZE(800 / 60, active_extruder);
  2105. current_position[E_AXIS] += 5;
  2106. plan_buffer_line_curposXYZE(400 / 60, active_extruder);
  2107. current_position[E_AXIS] -= 5;
  2108. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2109. st_synchronize();
  2110. current_position[E_AXIS] += 5;
  2111. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2112. current_position[E_AXIS] -= 5;
  2113. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2114. current_position[E_AXIS] += 5;
  2115. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2116. current_position[E_AXIS] -= 5;
  2117. plan_buffer_line_curposXYZE(600 / 60, active_extruder);
  2118. st_synchronize();
  2119. }
  2120. }
  2121. */
  2122. #ifdef TMC2130
  2123. void force_high_power_mode(bool start_high_power_section) {
  2124. #ifdef PSU_Delta
  2125. if (start_high_power_section == true) enable_force_z();
  2126. #endif //PSU_Delta
  2127. uint8_t silent;
  2128. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2129. if (silent == 1) {
  2130. //we are in silent mode, set to normal mode to enable crash detection
  2131. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2132. st_synchronize();
  2133. cli();
  2134. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2135. update_mode_profile();
  2136. tmc2130_init();
  2137. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2138. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2139. st_reset_timer();
  2140. sei();
  2141. }
  2142. }
  2143. #endif //TMC2130
  2144. #ifdef TMC2130
  2145. 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)
  2146. #else
  2147. 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)
  2148. #endif //TMC2130
  2149. {
  2150. st_synchronize();
  2151. #if 0
  2152. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2153. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2154. #endif
  2155. // Flag for the display update routine and to disable the print cancelation during homing.
  2156. homing_flag = true;
  2157. // Which axes should be homed?
  2158. bool home_x = home_x_axis;
  2159. bool home_y = home_y_axis;
  2160. bool home_z = home_z_axis;
  2161. // Either all X,Y,Z codes are present, or none of them.
  2162. bool home_all_axes = home_x == home_y && home_x == home_z;
  2163. if (home_all_axes)
  2164. // No X/Y/Z code provided means to home all axes.
  2165. home_x = home_y = home_z = true;
  2166. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2167. if (home_all_axes) {
  2168. raise_z_above(MESH_HOME_Z_SEARCH);
  2169. st_synchronize();
  2170. }
  2171. #ifdef ENABLE_AUTO_BED_LEVELING
  2172. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2173. #endif //ENABLE_AUTO_BED_LEVELING
  2174. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2175. // the planner will not perform any adjustments in the XY plane.
  2176. // Wait for the motors to stop and update the current position with the absolute values.
  2177. world2machine_revert_to_uncorrected();
  2178. // For mesh bed leveling deactivate the matrix temporarily.
  2179. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2180. // in a single axis only.
  2181. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2182. #ifdef MESH_BED_LEVELING
  2183. uint8_t mbl_was_active = mbl.active;
  2184. mbl.active = 0;
  2185. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2186. #endif
  2187. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  2188. // consumed during the first movements following this statement.
  2189. if (home_z)
  2190. babystep_undo();
  2191. saved_feedrate = feedrate;
  2192. int l_feedmultiply = feedmultiply;
  2193. feedmultiply = 100;
  2194. previous_millis_cmd = _millis();
  2195. enable_endstops(true);
  2196. memcpy(destination, current_position, sizeof(destination));
  2197. feedrate = 0.0;
  2198. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2199. if(home_z)
  2200. homeaxis(Z_AXIS);
  2201. #endif
  2202. #ifdef QUICK_HOME
  2203. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2204. if(home_x && home_y) //first diagonal move
  2205. {
  2206. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2207. int x_axis_home_dir = home_dir(X_AXIS);
  2208. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2209. destination[X_AXIS] = 1.5 * max_length(X_AXIS) * x_axis_home_dir;destination[Y_AXIS] = 1.5 * max_length(Y_AXIS) * home_dir(Y_AXIS);
  2210. feedrate = homing_feedrate[X_AXIS];
  2211. if(homing_feedrate[Y_AXIS]<feedrate)
  2212. feedrate = homing_feedrate[Y_AXIS];
  2213. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2214. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2215. } else {
  2216. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2217. }
  2218. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  2219. st_synchronize();
  2220. axis_is_at_home(X_AXIS);
  2221. axis_is_at_home(Y_AXIS);
  2222. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2223. destination[X_AXIS] = current_position[X_AXIS];
  2224. destination[Y_AXIS] = current_position[Y_AXIS];
  2225. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  2226. feedrate = 0.0;
  2227. st_synchronize();
  2228. endstops_hit_on_purpose();
  2229. current_position[X_AXIS] = destination[X_AXIS];
  2230. current_position[Y_AXIS] = destination[Y_AXIS];
  2231. current_position[Z_AXIS] = destination[Z_AXIS];
  2232. }
  2233. #endif /* QUICK_HOME */
  2234. #ifdef TMC2130
  2235. if(home_x)
  2236. {
  2237. if (!calib)
  2238. homeaxis(X_AXIS);
  2239. else
  2240. tmc2130_home_calibrate(X_AXIS);
  2241. }
  2242. if(home_y)
  2243. {
  2244. if (!calib)
  2245. homeaxis(Y_AXIS);
  2246. else
  2247. tmc2130_home_calibrate(Y_AXIS);
  2248. }
  2249. #else //TMC2130
  2250. if(home_x) homeaxis(X_AXIS);
  2251. if(home_y) homeaxis(Y_AXIS);
  2252. #endif //TMC2130
  2253. if(home_x_axis && home_x_value != 0)
  2254. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2255. if(home_y_axis && home_y_value != 0)
  2256. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2257. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2258. #ifndef Z_SAFE_HOMING
  2259. if(home_z) {
  2260. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2261. raise_z_above(Z_RAISE_BEFORE_HOMING);
  2262. st_synchronize();
  2263. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2264. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP)) // If Mesh bed leveling, move X&Y to safe position for home
  2265. raise_z_above(MESH_HOME_Z_SEARCH);
  2266. st_synchronize();
  2267. if (!axis_known_position[X_AXIS]) homeaxis(X_AXIS);
  2268. if (!axis_known_position[Y_AXIS]) homeaxis(Y_AXIS);
  2269. // 1st mesh bed leveling measurement point, corrected.
  2270. world2machine_initialize();
  2271. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2272. world2machine_reset();
  2273. if (destination[Y_AXIS] < Y_MIN_POS)
  2274. destination[Y_AXIS] = Y_MIN_POS;
  2275. feedrate = homing_feedrate[X_AXIS] / 20;
  2276. enable_endstops(false);
  2277. #ifdef DEBUG_BUILD
  2278. SERIAL_ECHOLNPGM("plan_set_position()");
  2279. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2280. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2281. #endif
  2282. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2283. #ifdef DEBUG_BUILD
  2284. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2285. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2286. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2287. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2288. #endif
  2289. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2290. st_synchronize();
  2291. current_position[X_AXIS] = destination[X_AXIS];
  2292. current_position[Y_AXIS] = destination[Y_AXIS];
  2293. enable_endstops(true);
  2294. endstops_hit_on_purpose();
  2295. homeaxis(Z_AXIS);
  2296. #else // MESH_BED_LEVELING
  2297. homeaxis(Z_AXIS);
  2298. #endif // MESH_BED_LEVELING
  2299. }
  2300. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2301. if(home_all_axes) {
  2302. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2303. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2304. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2305. feedrate = XY_TRAVEL_SPEED/60;
  2306. current_position[Z_AXIS] = 0;
  2307. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2308. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2309. st_synchronize();
  2310. current_position[X_AXIS] = destination[X_AXIS];
  2311. current_position[Y_AXIS] = destination[Y_AXIS];
  2312. homeaxis(Z_AXIS);
  2313. }
  2314. // Let's see if X and Y are homed and probe is inside bed area.
  2315. if(home_z) {
  2316. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2317. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2318. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2319. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2320. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2321. current_position[Z_AXIS] = 0;
  2322. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2323. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2324. feedrate = max_feedrate[Z_AXIS];
  2325. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2326. st_synchronize();
  2327. homeaxis(Z_AXIS);
  2328. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2329. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2330. SERIAL_ECHO_START;
  2331. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2332. } else {
  2333. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2334. SERIAL_ECHO_START;
  2335. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2336. }
  2337. }
  2338. #endif // Z_SAFE_HOMING
  2339. #endif // Z_HOME_DIR < 0
  2340. if(home_z_axis && home_z_value != 0)
  2341. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2342. #ifdef ENABLE_AUTO_BED_LEVELING
  2343. if(home_z)
  2344. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2345. #endif
  2346. // Set the planner and stepper routine positions.
  2347. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2348. // contains the machine coordinates.
  2349. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2350. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  2351. enable_endstops(false);
  2352. #endif
  2353. feedrate = saved_feedrate;
  2354. feedmultiply = l_feedmultiply;
  2355. previous_millis_cmd = _millis();
  2356. endstops_hit_on_purpose();
  2357. #ifndef MESH_BED_LEVELING
  2358. //-// Oct 2019 :: this part of code is (from) now probably un-compilable
  2359. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  2360. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  2361. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  2362. lcd_adjust_z();
  2363. #endif
  2364. // Load the machine correction matrix
  2365. world2machine_initialize();
  2366. // and correct the current_position XY axes to match the transformed coordinate system.
  2367. world2machine_update_current();
  2368. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP))
  2369. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2370. {
  2371. if (! home_z && mbl_was_active) {
  2372. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2373. mbl.active = true;
  2374. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2375. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2376. }
  2377. }
  2378. else
  2379. {
  2380. st_synchronize();
  2381. homing_flag = false;
  2382. }
  2383. #endif
  2384. if (farm_mode) { prusa_statistics(20); };
  2385. homing_flag = false;
  2386. #if 0
  2387. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2388. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2389. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2390. #endif
  2391. }
  2392. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2393. {
  2394. #ifdef TMC2130
  2395. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2396. #else
  2397. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2398. #endif //TMC2130
  2399. }
  2400. void adjust_bed_reset()
  2401. {
  2402. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2403. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2404. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2405. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2406. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2407. }
  2408. //! @brief Calibrate XYZ
  2409. //! @param onlyZ if true, calibrate only Z axis
  2410. //! @param verbosity_level
  2411. //! @retval true Succeeded
  2412. //! @retval false Failed
  2413. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2414. {
  2415. bool final_result = false;
  2416. #ifdef TMC2130
  2417. FORCE_HIGH_POWER_START;
  2418. #endif // TMC2130
  2419. FORCE_BL_ON_START;
  2420. // Only Z calibration?
  2421. if (!onlyZ)
  2422. {
  2423. setTargetBed(0);
  2424. setAllTargetHotends(0);
  2425. adjust_bed_reset(); //reset bed level correction
  2426. }
  2427. // Disable the default update procedure of the display. We will do a modal dialog.
  2428. lcd_update_enable(false);
  2429. // Let the planner use the uncorrected coordinates.
  2430. mbl.reset();
  2431. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2432. // the planner will not perform any adjustments in the XY plane.
  2433. // Wait for the motors to stop and update the current position with the absolute values.
  2434. world2machine_revert_to_uncorrected();
  2435. // Reset the baby step value applied without moving the axes.
  2436. babystep_reset();
  2437. // Mark all axes as in a need for homing.
  2438. memset(axis_known_position, 0, sizeof(axis_known_position));
  2439. // Home in the XY plane.
  2440. //set_destination_to_current();
  2441. int l_feedmultiply = setup_for_endstop_move();
  2442. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2443. home_xy();
  2444. enable_endstops(false);
  2445. current_position[X_AXIS] += 5;
  2446. current_position[Y_AXIS] += 5;
  2447. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40, active_extruder);
  2448. st_synchronize();
  2449. // Let the user move the Z axes up to the end stoppers.
  2450. #ifdef TMC2130
  2451. if (calibrate_z_auto())
  2452. {
  2453. #else //TMC2130
  2454. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2455. {
  2456. #endif //TMC2130
  2457. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2458. if(onlyZ){
  2459. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2460. lcd_set_cursor(0, 3);
  2461. lcd_print(1);
  2462. lcd_puts_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE2));
  2463. }else{
  2464. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2465. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2466. lcd_set_cursor(0, 2);
  2467. lcd_print(1);
  2468. lcd_puts_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE2));
  2469. }
  2470. refresh_cmd_timeout();
  2471. #ifndef STEEL_SHEET
  2472. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2473. {
  2474. lcd_wait_for_cool_down();
  2475. }
  2476. #endif //STEEL_SHEET
  2477. if(!onlyZ)
  2478. {
  2479. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2480. #ifdef STEEL_SHEET
  2481. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  2482. if(result) lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2483. #endif //STEEL_SHEET
  2484. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2485. KEEPALIVE_STATE(IN_HANDLER);
  2486. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2487. lcd_set_cursor(0, 2);
  2488. lcd_print(1);
  2489. lcd_puts_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE2));
  2490. }
  2491. bool endstops_enabled = enable_endstops(false);
  2492. current_position[Z_AXIS] -= 1; //move 1mm down with disabled endstop
  2493. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40, active_extruder);
  2494. st_synchronize();
  2495. // Move the print head close to the bed.
  2496. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2497. enable_endstops(true);
  2498. #ifdef TMC2130
  2499. tmc2130_home_enter(Z_AXIS_MASK);
  2500. #endif //TMC2130
  2501. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40, active_extruder);
  2502. st_synchronize();
  2503. #ifdef TMC2130
  2504. tmc2130_home_exit();
  2505. #endif //TMC2130
  2506. enable_endstops(endstops_enabled);
  2507. if ((st_get_position_mm(Z_AXIS) <= (MESH_HOME_Z_SEARCH + HOME_Z_SEARCH_THRESHOLD)) &&
  2508. (st_get_position_mm(Z_AXIS) >= (MESH_HOME_Z_SEARCH - HOME_Z_SEARCH_THRESHOLD)))
  2509. {
  2510. if (onlyZ)
  2511. {
  2512. clean_up_after_endstop_move(l_feedmultiply);
  2513. // Z only calibration.
  2514. // Load the machine correction matrix
  2515. world2machine_initialize();
  2516. // and correct the current_position to match the transformed coordinate system.
  2517. world2machine_update_current();
  2518. //FIXME
  2519. bool result = sample_mesh_and_store_reference();
  2520. if (result)
  2521. {
  2522. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2523. // Shipped, the nozzle height has been set already. The user can start printing now.
  2524. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2525. final_result = true;
  2526. // babystep_apply();
  2527. }
  2528. }
  2529. else
  2530. {
  2531. // Reset the baby step value and the baby step applied flag.
  2532. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2533. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  2534. // Complete XYZ calibration.
  2535. uint8_t point_too_far_mask = 0;
  2536. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2537. clean_up_after_endstop_move(l_feedmultiply);
  2538. // Print head up.
  2539. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2540. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40, active_extruder);
  2541. st_synchronize();
  2542. //#ifndef NEW_XYZCAL
  2543. if (result >= 0)
  2544. {
  2545. #ifdef HEATBED_V2
  2546. sample_z();
  2547. #else //HEATBED_V2
  2548. point_too_far_mask = 0;
  2549. // Second half: The fine adjustment.
  2550. // Let the planner use the uncorrected coordinates.
  2551. mbl.reset();
  2552. world2machine_reset();
  2553. // Home in the XY plane.
  2554. int l_feedmultiply = setup_for_endstop_move();
  2555. home_xy();
  2556. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2557. clean_up_after_endstop_move(l_feedmultiply);
  2558. // Print head up.
  2559. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2560. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40, active_extruder);
  2561. st_synchronize();
  2562. // if (result >= 0) babystep_apply();
  2563. #endif //HEATBED_V2
  2564. }
  2565. //#endif //NEW_XYZCAL
  2566. lcd_update_enable(true);
  2567. lcd_update(2);
  2568. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2569. if (result >= 0)
  2570. {
  2571. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2572. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2573. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2574. final_result = true;
  2575. }
  2576. }
  2577. #ifdef TMC2130
  2578. tmc2130_home_exit();
  2579. #endif
  2580. }
  2581. else
  2582. {
  2583. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2584. final_result = false;
  2585. }
  2586. }
  2587. else
  2588. {
  2589. // Timeouted.
  2590. }
  2591. lcd_update_enable(true);
  2592. #ifdef TMC2130
  2593. FORCE_HIGH_POWER_END;
  2594. #endif // TMC2130
  2595. FORCE_BL_ON_END;
  2596. return final_result;
  2597. }
  2598. void gcode_M114()
  2599. {
  2600. SERIAL_PROTOCOLPGM("X:");
  2601. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2602. SERIAL_PROTOCOLPGM(" Y:");
  2603. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2604. SERIAL_PROTOCOLPGM(" Z:");
  2605. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2606. SERIAL_PROTOCOLPGM(" E:");
  2607. SERIAL_PROTOCOL(current_position[E_AXIS]);
  2608. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  2609. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  2610. SERIAL_PROTOCOLPGM(" Y:");
  2611. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  2612. SERIAL_PROTOCOLPGM(" Z:");
  2613. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  2614. SERIAL_PROTOCOLPGM(" E:");
  2615. SERIAL_PROTOCOL(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  2616. SERIAL_PROTOCOLLN("");
  2617. }
  2618. //! extracted code to compute z_shift for M600 in case of filament change operation
  2619. //! requested from fsensors.
  2620. //! The function ensures, that the printhead lifts to at least 25mm above the heat bed
  2621. //! unlike the previous implementation, which was adding 25mm even when the head was
  2622. //! printing at e.g. 24mm height.
  2623. //! A safety margin of FILAMENTCHANGE_ZADD is added in all cases to avoid touching
  2624. //! the printout.
  2625. //! This function is templated to enable fast change of computation data type.
  2626. //! @return new z_shift value
  2627. template<typename T>
  2628. static T gcode_M600_filament_change_z_shift()
  2629. {
  2630. #ifdef FILAMENTCHANGE_ZADD
  2631. static_assert(Z_MAX_POS < (255 - FILAMENTCHANGE_ZADD), "Z-range too high, change the T type from uint8_t to uint16_t");
  2632. // avoid floating point arithmetics when not necessary - results in shorter code
  2633. T ztmp = T( current_position[Z_AXIS] );
  2634. T z_shift = 0;
  2635. if(ztmp < T(25)){
  2636. z_shift = T(25) - ztmp; // make sure to be at least 25mm above the heat bed
  2637. }
  2638. return z_shift + T(FILAMENTCHANGE_ZADD); // always move above printout
  2639. #else
  2640. return T(0);
  2641. #endif
  2642. }
  2643. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/)
  2644. {
  2645. st_synchronize();
  2646. float lastpos[4];
  2647. if (farm_mode)
  2648. {
  2649. prusa_statistics(22);
  2650. }
  2651. //First backup current position and settings
  2652. int feedmultiplyBckp = feedmultiply;
  2653. float HotendTempBckp = degTargetHotend(active_extruder);
  2654. int fanSpeedBckp = fanSpeed;
  2655. lastpos[X_AXIS] = current_position[X_AXIS];
  2656. lastpos[Y_AXIS] = current_position[Y_AXIS];
  2657. lastpos[Z_AXIS] = current_position[Z_AXIS];
  2658. lastpos[E_AXIS] = current_position[E_AXIS];
  2659. //Retract E
  2660. current_position[E_AXIS] += e_shift;
  2661. plan_buffer_line_curposXYZE(FILAMENTCHANGE_RFEED, active_extruder);
  2662. st_synchronize();
  2663. //Lift Z
  2664. current_position[Z_AXIS] += z_shift;
  2665. plan_buffer_line_curposXYZE(FILAMENTCHANGE_ZFEED, active_extruder);
  2666. st_synchronize();
  2667. //Move XY to side
  2668. current_position[X_AXIS] = x_position;
  2669. current_position[Y_AXIS] = y_position;
  2670. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED, active_extruder);
  2671. st_synchronize();
  2672. //Beep, manage nozzle heater and wait for user to start unload filament
  2673. if(!mmu_enabled) M600_wait_for_user(HotendTempBckp);
  2674. lcd_change_fil_state = 0;
  2675. // Unload filament
  2676. if (mmu_enabled) extr_unload(); //unload just current filament for multimaterial printers (used also in M702)
  2677. else unload_filament(); //unload filament for single material (used also in M702)
  2678. //finish moves
  2679. st_synchronize();
  2680. if (!mmu_enabled)
  2681. {
  2682. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2683. lcd_change_fil_state = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Was filament unload successful?"),
  2684. false, true); ////MSG_UNLOAD_SUCCESSFUL c=20 r=2
  2685. if (lcd_change_fil_state == 0)
  2686. {
  2687. lcd_clear();
  2688. lcd_set_cursor(0, 2);
  2689. lcd_puts_P(_T(MSG_PLEASE_WAIT));
  2690. current_position[X_AXIS] -= 100;
  2691. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED, active_extruder);
  2692. st_synchronize();
  2693. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually."));////MSG_CHECK_IDLER c=20 r=4
  2694. }
  2695. }
  2696. if (mmu_enabled)
  2697. {
  2698. if (!automatic) {
  2699. if (saved_printing) mmu_eject_filament(mmu_extruder, false); //if M600 was invoked by filament senzor (FINDA) eject filament so user can easily remove it
  2700. mmu_M600_wait_and_beep();
  2701. if (saved_printing) {
  2702. lcd_clear();
  2703. lcd_set_cursor(0, 2);
  2704. lcd_puts_P(_T(MSG_PLEASE_WAIT));
  2705. mmu_command(MmuCmd::R0);
  2706. manage_response(false, false);
  2707. }
  2708. }
  2709. mmu_M600_load_filament(automatic, HotendTempBckp);
  2710. }
  2711. else
  2712. M600_load_filament();
  2713. if (!automatic) M600_check_state(HotendTempBckp);
  2714. lcd_update_enable(true);
  2715. //Not let's go back to print
  2716. fanSpeed = fanSpeedBckp;
  2717. //Feed a little of filament to stabilize pressure
  2718. if (!automatic)
  2719. {
  2720. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  2721. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EXFEED, active_extruder);
  2722. }
  2723. //Move XY back
  2724. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  2725. FILAMENTCHANGE_XYFEED, active_extruder);
  2726. st_synchronize();
  2727. //Move Z back
  2728. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS],
  2729. FILAMENTCHANGE_ZFEED, active_extruder);
  2730. st_synchronize();
  2731. //Set E position to original
  2732. plan_set_e_position(lastpos[E_AXIS]);
  2733. memcpy(current_position, lastpos, sizeof(lastpos));
  2734. memcpy(destination, current_position, sizeof(current_position));
  2735. //Recover feed rate
  2736. feedmultiply = feedmultiplyBckp;
  2737. char cmd[9];
  2738. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  2739. enquecommand(cmd);
  2740. #ifdef IR_SENSOR
  2741. //this will set fsensor_watch_autoload to correct value and prevent possible M701 gcode enqueuing when M600 is finished
  2742. fsensor_check_autoload();
  2743. #endif //IR_SENSOR
  2744. lcd_setstatuspgm(_T(WELCOME_MSG));
  2745. custom_message_type = CustomMsg::Status;
  2746. }
  2747. void gcode_M701()
  2748. {
  2749. printf_P(PSTR("gcode_M701 begin\n"));
  2750. if (farm_mode)
  2751. {
  2752. prusa_statistics(22);
  2753. }
  2754. if (mmu_enabled)
  2755. {
  2756. extr_adj(tmp_extruder);//loads current extruder
  2757. mmu_extruder = tmp_extruder;
  2758. }
  2759. else
  2760. {
  2761. enable_z();
  2762. custom_message_type = CustomMsg::FilamentLoading;
  2763. #ifdef FSENSOR_QUALITY
  2764. fsensor_oq_meassure_start(40);
  2765. #endif //FSENSOR_QUALITY
  2766. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  2767. current_position[E_AXIS] += 40;
  2768. plan_buffer_line_curposXYZE(400 / 60, active_extruder); //fast sequence
  2769. st_synchronize();
  2770. raise_z_above(MIN_Z_FOR_LOAD, false);
  2771. current_position[E_AXIS] += 30;
  2772. plan_buffer_line_curposXYZE(400 / 60, active_extruder); //fast sequence
  2773. load_filament_final_feed(); //slow sequence
  2774. st_synchronize();
  2775. Sound_MakeCustom(50,500,false);
  2776. if (!farm_mode && loading_flag) {
  2777. lcd_load_filament_color_check();
  2778. }
  2779. lcd_update_enable(true);
  2780. lcd_update(2);
  2781. lcd_setstatuspgm(_T(WELCOME_MSG));
  2782. disable_z();
  2783. loading_flag = false;
  2784. custom_message_type = CustomMsg::Status;
  2785. #ifdef FSENSOR_QUALITY
  2786. fsensor_oq_meassure_stop();
  2787. if (!fsensor_oq_result())
  2788. {
  2789. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Fil. sensor response is poor, disable it?"), false, true);
  2790. lcd_update_enable(true);
  2791. lcd_update(2);
  2792. if (disable)
  2793. fsensor_disable();
  2794. }
  2795. #endif //FSENSOR_QUALITY
  2796. }
  2797. }
  2798. /**
  2799. * @brief Get serial number from 32U2 processor
  2800. *
  2801. * Typical format of S/N is:CZPX0917X003XC13518
  2802. *
  2803. * Command operates only in farm mode, if not in farm mode, "Not in farm mode." is written to MYSERIAL.
  2804. *
  2805. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  2806. * reply is transmitted to serial port 1 character by character.
  2807. * Operation takes typically 23 ms. If the retransmit is not finished until 100 ms,
  2808. * it is interrupted, so less, or no characters are retransmitted, only newline character is send
  2809. * in any case.
  2810. */
  2811. static void gcode_PRUSA_SN()
  2812. {
  2813. if (farm_mode) {
  2814. selectedSerialPort = 0;
  2815. putchar(';');
  2816. putchar('S');
  2817. int numbersRead = 0;
  2818. ShortTimer timeout;
  2819. timeout.start();
  2820. while (numbersRead < 19) {
  2821. while (MSerial.available() > 0) {
  2822. uint8_t serial_char = MSerial.read();
  2823. selectedSerialPort = 1;
  2824. putchar(serial_char);
  2825. numbersRead++;
  2826. selectedSerialPort = 0;
  2827. }
  2828. if (timeout.expired(100u)) break;
  2829. }
  2830. selectedSerialPort = 1;
  2831. putchar('\n');
  2832. #if 0
  2833. for (int b = 0; b < 3; b++) {
  2834. _tone(BEEPER, 110);
  2835. _delay(50);
  2836. _noTone(BEEPER);
  2837. _delay(50);
  2838. }
  2839. #endif
  2840. } else {
  2841. puts_P(_N("Not in farm mode."));
  2842. }
  2843. }
  2844. //! Detection of faulty RAMBo 1.1b boards equipped with bigger capacitors
  2845. //! at the TACH_1 pin, which causes bad detection of print fan speed.
  2846. //! Warning: This function is not to be used by ordinary users, it is here only for automated testing purposes,
  2847. //! it may even interfere with other functions of the printer! You have been warned!
  2848. //! The test idea is to measure the time necessary to charge the capacitor.
  2849. //! So the algorithm is as follows:
  2850. //! 1. Set TACH_1 pin to INPUT mode and LOW
  2851. //! 2. Wait a few ms
  2852. //! 3. disable interrupts and measure the time until the TACH_1 pin reaches HIGH
  2853. //! Repeat 1.-3. several times
  2854. //! Good RAMBo's times are in the range of approx. 260-320 us
  2855. //! Bad RAMBo's times are approx. 260-1200 us
  2856. //! So basically we are interested in maximum time, the minima are mostly the same.
  2857. //! May be that's why the bad RAMBo's still produce some fan RPM reading, but not corresponding to reality
  2858. static void gcode_PRUSA_BadRAMBoFanTest(){
  2859. //printf_P(PSTR("Enter fan pin test\n"));
  2860. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  2861. fan_measuring = false; // prevent EXTINT7 breaking into the measurement
  2862. unsigned long tach1max = 0;
  2863. uint8_t tach1cntr = 0;
  2864. for( /* nothing */; tach1cntr < 100; ++tach1cntr){
  2865. //printf_P(PSTR("TACH_1: %d\n"), tach1cntr);
  2866. SET_OUTPUT(TACH_1);
  2867. WRITE(TACH_1, LOW);
  2868. _delay(20); // the delay may be lower
  2869. unsigned long tachMeasure = _micros();
  2870. cli();
  2871. SET_INPUT(TACH_1);
  2872. // just wait brutally in an endless cycle until we reach HIGH
  2873. // if this becomes a problem it may be improved to non-endless cycle
  2874. while( READ(TACH_1) == 0 ) ;
  2875. sei();
  2876. tachMeasure = _micros() - tachMeasure;
  2877. if( tach1max < tachMeasure )
  2878. tach1max = tachMeasure;
  2879. //printf_P(PSTR("TACH_1: %d: capacitor check time=%lu us\n"), (int)tach1cntr, tachMeasure);
  2880. }
  2881. //printf_P(PSTR("TACH_1: max=%lu us\n"), tach1max);
  2882. SERIAL_PROTOCOLPGM("RAMBo FAN ");
  2883. if( tach1max > 500 ){
  2884. // bad RAMBo
  2885. SERIAL_PROTOCOLLNPGM("BAD");
  2886. } else {
  2887. SERIAL_PROTOCOLLNPGM("OK");
  2888. }
  2889. // cleanup after the test function
  2890. SET_INPUT(TACH_1);
  2891. WRITE(TACH_1, HIGH);
  2892. #endif
  2893. }
  2894. // G92 - Set current position to coordinates given
  2895. static void gcode_G92()
  2896. {
  2897. bool codes[NUM_AXIS];
  2898. float values[NUM_AXIS];
  2899. // Check which axes need to be set
  2900. for(uint8_t i = 0; i < NUM_AXIS; ++i)
  2901. {
  2902. codes[i] = code_seen(axis_codes[i]);
  2903. if(codes[i])
  2904. values[i] = code_value();
  2905. }
  2906. if((codes[E_AXIS] && values[E_AXIS] == 0) &&
  2907. (!codes[X_AXIS] && !codes[Y_AXIS] && !codes[Z_AXIS]))
  2908. {
  2909. // As a special optimization, when _just_ clearing the E position
  2910. // we schedule a flag asynchronously along with the next block to
  2911. // reset the starting E position instead of stopping the planner
  2912. current_position[E_AXIS] = 0;
  2913. plan_reset_next_e();
  2914. }
  2915. else
  2916. {
  2917. // In any other case we're forced to synchronize
  2918. st_synchronize();
  2919. for(uint8_t i = 0; i < 3; ++i)
  2920. {
  2921. if(codes[i])
  2922. current_position[i] = values[i] + cs.add_homing[i];
  2923. }
  2924. if(codes[E_AXIS])
  2925. current_position[E_AXIS] = values[E_AXIS];
  2926. // Set all at once
  2927. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS],
  2928. current_position[Z_AXIS], current_position[E_AXIS]);
  2929. }
  2930. }
  2931. #ifdef BACKLASH_X
  2932. extern uint8_t st_backlash_x;
  2933. #endif //BACKLASH_X
  2934. #ifdef BACKLASH_Y
  2935. extern uint8_t st_backlash_y;
  2936. #endif //BACKLASH_Y
  2937. //! \ingroup marlin_main
  2938. //! @brief Parse and process commands
  2939. //!
  2940. //! look here for descriptions of G-codes: http://linuxcnc.org/handbook/gcode/g-code.html
  2941. //! http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  2942. //!
  2943. //!
  2944. //! Implemented Codes
  2945. //! -------------------
  2946. //!
  2947. //! * _This list is not updated. Current documentation is maintained inside the process_cmd function._
  2948. //!
  2949. //!@n PRUSA CODES
  2950. //!@n P F - Returns FW versions
  2951. //!@n P R - Returns revision of printer
  2952. //!
  2953. //!@n G0 -> G1
  2954. //!@n G1 - Coordinated Movement X Y Z E
  2955. //!@n G2 - CW ARC
  2956. //!@n G3 - CCW ARC
  2957. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  2958. //!@n G10 - retract filament according to settings of M207
  2959. //!@n G11 - retract recover filament according to settings of M208
  2960. //!@n G28 - Home all Axis
  2961. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  2962. //!@n G30 - Single Z Probe, probes bed at current XY location.
  2963. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  2964. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  2965. //!@n G80 - Automatic mesh bed leveling
  2966. //!@n G81 - Print bed profile
  2967. //!@n G90 - Use Absolute Coordinates
  2968. //!@n G91 - Use Relative Coordinates
  2969. //!@n G92 - Set current position to coordinates given
  2970. //!
  2971. //!@n M Codes
  2972. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  2973. //!@n M1 - Same as M0
  2974. //!@n M17 - Enable/Power all stepper motors
  2975. //!@n M18 - Disable all stepper motors; same as M84
  2976. //!@n M20 - List SD card
  2977. //!@n M21 - Init SD card
  2978. //!@n M22 - Release SD card
  2979. //!@n M23 - Select SD file (M23 filename.g)
  2980. //!@n M24 - Start/resume SD print
  2981. //!@n M25 - Pause SD print
  2982. //!@n M26 - Set SD position in bytes (M26 S12345)
  2983. //!@n M27 - Report SD print status
  2984. //!@n M28 - Start SD write (M28 filename.g)
  2985. //!@n M29 - Stop SD write
  2986. //!@n M30 - Delete file from SD (M30 filename.g)
  2987. //!@n M31 - Output time since last M109 or SD card start to serial
  2988. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  2989. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  2990. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  2991. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  2992. //!@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.
  2993. //!@n M73 - Show percent done and print time remaining
  2994. //!@n M80 - Turn on Power Supply
  2995. //!@n M81 - Turn off Power Supply
  2996. //!@n M82 - Set E codes absolute (default)
  2997. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  2998. //!@n M84 - Disable steppers until next move,
  2999. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  3000. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3001. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  3002. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  3003. //!@n M104 - Set extruder target temp
  3004. //!@n M105 - Read current temp
  3005. //!@n M106 - Fan on
  3006. //!@n M107 - Fan off
  3007. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  3008. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  3009. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  3010. //!@n M112 - Emergency stop
  3011. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  3012. //!@n M114 - Output current position to serial port
  3013. //!@n M115 - Capabilities string
  3014. //!@n M117 - display message
  3015. //!@n M119 - Output Endstop status to serial port
  3016. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  3017. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  3018. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3019. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3020. //!@n M140 - Set bed target temp
  3021. //!@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.
  3022. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3023. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3024. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3025. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3026. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  3027. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3028. //!@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
  3029. //!@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
  3030. //!@n M206 - set additional homing offset
  3031. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  3032. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  3033. //!@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.
  3034. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3035. //!@n M220 S<factor in percent>- set speed factor override percentage
  3036. //!@n M221 S<factor in percent>- set extrude factor override percentage
  3037. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3038. //!@n M240 - Trigger a camera to take a photograph
  3039. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  3040. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3041. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  3042. //!@n M301 - Set PID parameters P I and D
  3043. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  3044. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  3045. //!@n M304 - Set bed PID parameters P I and D
  3046. //!@n M400 - Finish all moves
  3047. //!@n M401 - Lower z-probe if present
  3048. //!@n M402 - Raise z-probe if present
  3049. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  3050. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  3051. //!@n M406 - Turn off Filament Sensor extrusion control
  3052. //!@n M407 - Displays measured filament diameter
  3053. //!@n M500 - stores parameters in EEPROM
  3054. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  3055. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  3056. //!@n M503 - print the current settings (from memory not from EEPROM)
  3057. //!@n M509 - force language selection on next restart
  3058. //!@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)
  3059. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3060. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  3061. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  3062. //!@n M861 - Set / Read PINDA temperature compensation offsets
  3063. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  3064. //!@n M907 - Set digital trimpot motor current using axis codes.
  3065. //!@n M908 - Control digital trimpot directly.
  3066. //!@n M350 - Set microstepping mode.
  3067. //!@n M351 - Toggle MS1 MS2 pins directly.
  3068. //!
  3069. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  3070. //!@n M999 - Restart after being stopped by error
  3071. //! <br><br>
  3072. /** @defgroup marlin_main Marlin main */
  3073. /** \ingroup GCodes */
  3074. //! _This is a list of currently implemented G Codes in Prusa firmware (dynamically generated from doxygen)_
  3075. void process_commands()
  3076. {
  3077. #ifdef FANCHECK
  3078. if(fan_check_error){
  3079. if(fan_check_error == EFCE_DETECTED){
  3080. fan_check_error = EFCE_REPORTED;
  3081. // SERIAL_PROTOCOLLNRPGM(MSG_OCTOPRINT_PAUSED);
  3082. lcd_pause_print();
  3083. } // otherwise it has already been reported, so just ignore further processing
  3084. return; //ignore usb stream. It is reenabled by selecting resume from the lcd.
  3085. }
  3086. #endif
  3087. if (!buflen) return; //empty command
  3088. #ifdef FILAMENT_RUNOUT_SUPPORT
  3089. SET_INPUT(FR_SENS);
  3090. #endif
  3091. #ifdef CMDBUFFER_DEBUG
  3092. SERIAL_ECHOPGM("Processing a GCODE command: ");
  3093. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  3094. SERIAL_ECHOLNPGM("");
  3095. SERIAL_ECHOPGM("In cmdqueue: ");
  3096. SERIAL_ECHO(buflen);
  3097. SERIAL_ECHOLNPGM("");
  3098. #endif /* CMDBUFFER_DEBUG */
  3099. unsigned long codenum; //throw away variable
  3100. char *starpos = NULL;
  3101. #ifdef ENABLE_AUTO_BED_LEVELING
  3102. float x_tmp, y_tmp, z_tmp, real_z;
  3103. #endif
  3104. // PRUSA GCODES
  3105. KEEPALIVE_STATE(IN_HANDLER);
  3106. #ifdef SNMM
  3107. float tmp_motor[3] = DEFAULT_PWM_MOTOR_CURRENT;
  3108. float tmp_motor_loud[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  3109. int8_t SilentMode;
  3110. #endif
  3111. if (code_seen("M117")) { //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  3112. starpos = (strchr(strchr_pointer + 5, '*'));
  3113. if (starpos != NULL)
  3114. *(starpos) = '\0';
  3115. lcd_setstatus(strchr_pointer + 5);
  3116. }
  3117. #ifdef TMC2130
  3118. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  3119. {
  3120. //! ### CRASH_DETECTED - TMC2130
  3121. // ---------------------------------
  3122. if(code_seen("CRASH_DETECTED"))
  3123. {
  3124. uint8_t mask = 0;
  3125. if (code_seen('X')) mask |= X_AXIS_MASK;
  3126. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  3127. crashdet_detected(mask);
  3128. }
  3129. //! ### CRASH_RECOVER - TMC2130
  3130. // ----------------------------------
  3131. else if(code_seen("CRASH_RECOVER"))
  3132. crashdet_recover();
  3133. //! ### CRASH_CANCEL - TMC2130
  3134. // ----------------------------------
  3135. else if(code_seen("CRASH_CANCEL"))
  3136. crashdet_cancel();
  3137. }
  3138. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3139. {
  3140. //! ### TMC_SET_WAVE_
  3141. // --------------------
  3142. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0)
  3143. {
  3144. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3145. axis = (axis == 'E')?3:(axis - 'X');
  3146. if (axis < 4)
  3147. {
  3148. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3149. tmc2130_set_wave(axis, 247, fac);
  3150. }
  3151. }
  3152. //! ### TMC_SET_STEP_
  3153. // ------------------
  3154. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0)
  3155. {
  3156. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3157. axis = (axis == 'E')?3:(axis - 'X');
  3158. if (axis < 4)
  3159. {
  3160. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3161. uint16_t res = tmc2130_get_res(axis);
  3162. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3163. }
  3164. }
  3165. //! ### TMC_SET_CHOP_
  3166. // -------------------
  3167. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0)
  3168. {
  3169. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3170. axis = (axis == 'E')?3:(axis - 'X');
  3171. if (axis < 4)
  3172. {
  3173. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  3174. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3175. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3176. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3177. char* str_end = 0;
  3178. if (CMDBUFFER_CURRENT_STRING[14])
  3179. {
  3180. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3181. if (str_end && *str_end)
  3182. {
  3183. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3184. if (str_end && *str_end)
  3185. {
  3186. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3187. if (str_end && *str_end)
  3188. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3189. }
  3190. }
  3191. }
  3192. tmc2130_chopper_config[axis].toff = chop0;
  3193. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3194. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3195. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3196. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3197. //printf_P(_N("TMC_SET_CHOP_%c %hhd %hhd %hhd %hhd\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3198. }
  3199. }
  3200. }
  3201. #ifdef BACKLASH_X
  3202. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3203. {
  3204. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3205. st_backlash_x = bl;
  3206. printf_P(_N("st_backlash_x = %hhd\n"), st_backlash_x);
  3207. }
  3208. #endif //BACKLASH_X
  3209. #ifdef BACKLASH_Y
  3210. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3211. {
  3212. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3213. st_backlash_y = bl;
  3214. printf_P(_N("st_backlash_y = %hhd\n"), st_backlash_y);
  3215. }
  3216. #endif //BACKLASH_Y
  3217. #endif //TMC2130
  3218. else if(code_seen("PRUSA")){
  3219. /*!
  3220. *
  3221. ### PRUSA - Internal command set
  3222. Set of internal PRUSA commands
  3223. PRUSA [ Ping | PRN | FAN | fn | thx | uvlo | MMURES | RESET | fv | M28 | SN | Fir | Rev | Lang | Lz | Beat | FR ]
  3224. - `Ping`
  3225. - `PRN` - Prints revision of the printer
  3226. - `FAN` - Prints fan details
  3227. - `fn` - Prints farm no.
  3228. - `thx`
  3229. - `uvlo`
  3230. - `MMURES` - Reset MMU
  3231. - `RESET` - (Careful!)
  3232. - `fv` - ?
  3233. - `M28`
  3234. - `SN`
  3235. - `Fir` - Prints firmware version
  3236. - `Rev`- Prints filament size, elelectronics, nozzle type
  3237. - `Lang` - Reset the language
  3238. - `Lz`
  3239. - `Beat` - Kick farm link timer
  3240. - `FR` - Full factory reset
  3241. - `nozzle set <diameter>` - set nozzle diameter (farm mode only), e.g. `PRUSA nozzle set 0.4`
  3242. - `nozzle D<diameter>` - check the nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle D0.4`
  3243. - `nozzle` - prints nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle`
  3244. *
  3245. */
  3246. if (code_seen("Ping")) { // PRUSA Ping
  3247. if (farm_mode) {
  3248. PingTime = _millis();
  3249. //MYSERIAL.print(farm_no); MYSERIAL.println(": OK");
  3250. }
  3251. }
  3252. else if (code_seen("PRN")) { // PRUSA PRN
  3253. printf_P(_N("%d"), status_number);
  3254. } else if( code_seen("FANPINTST") ){
  3255. gcode_PRUSA_BadRAMBoFanTest();
  3256. }else if (code_seen("FAN")) { //! PRUSA FAN
  3257. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3258. }else if (code_seen("fn")) { // PRUSA fn
  3259. if (farm_mode) {
  3260. printf_P(_N("%d"), farm_no);
  3261. }
  3262. else {
  3263. puts_P(_N("Not in farm mode."));
  3264. }
  3265. }
  3266. else if (code_seen("thx")) // PRUSA thx
  3267. {
  3268. no_response = false;
  3269. }
  3270. else if (code_seen("uvlo")) // PRUSA uvlo
  3271. {
  3272. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3273. enquecommand_P(PSTR("M24"));
  3274. }
  3275. else if (code_seen("MMURES")) // PRUSA MMURES
  3276. {
  3277. mmu_reset();
  3278. }
  3279. else if (code_seen("RESET")) { // PRUSA RESET
  3280. // careful!
  3281. if (farm_mode) {
  3282. #if (defined(WATCHDOG) && (MOTHERBOARD == BOARD_EINSY_1_0a))
  3283. boot_app_magic = BOOT_APP_MAGIC;
  3284. boot_app_flags = BOOT_APP_FLG_RUN;
  3285. wdt_enable(WDTO_15MS);
  3286. cli();
  3287. while(1);
  3288. #else //WATCHDOG
  3289. asm volatile("jmp 0x3E000");
  3290. #endif //WATCHDOG
  3291. }
  3292. else {
  3293. MYSERIAL.println("Not in farm mode.");
  3294. }
  3295. }else if (code_seen("fv")) { // PRUSA fv
  3296. // get file version
  3297. #ifdef SDSUPPORT
  3298. card.openFile(strchr_pointer + 3,true);
  3299. while (true) {
  3300. uint16_t readByte = card.get();
  3301. MYSERIAL.write(readByte);
  3302. if (readByte=='\n') {
  3303. break;
  3304. }
  3305. }
  3306. card.closefile();
  3307. #endif // SDSUPPORT
  3308. } else if (code_seen("M28")) { // PRUSA M28
  3309. trace();
  3310. prusa_sd_card_upload = true;
  3311. card.openFile(strchr_pointer+4,false);
  3312. } else if (code_seen("SN")) { // PRUSA SN
  3313. gcode_PRUSA_SN();
  3314. } else if(code_seen("Fir")){ // PRUSA Fir
  3315. SERIAL_PROTOCOLLN(FW_VERSION_FULL);
  3316. } else if(code_seen("Rev")){ // PRUSA Rev
  3317. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3318. } else if(code_seen("Lang")) { // PRUSA Lang
  3319. lang_reset();
  3320. } else if(code_seen("Lz")) { // PRUSA Lz
  3321. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  3322. } else if(code_seen("Beat")) { // PRUSA Beat
  3323. // Kick farm link timer
  3324. kicktime = _millis();
  3325. } else if(code_seen("FR")) { // PRUSA FR
  3326. // Factory full reset
  3327. factory_reset(0);
  3328. //-//
  3329. /*
  3330. } else if(code_seen("rrr")) {
  3331. MYSERIAL.println("=== checking ===");
  3332. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_CHECK_MODE),DEC);
  3333. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER),DEC);
  3334. MYSERIAL.println(eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM),DEC);
  3335. MYSERIAL.println(farm_mode,DEC);
  3336. MYSERIAL.println(eCheckMode,DEC);
  3337. } else if(code_seen("www")) {
  3338. MYSERIAL.println("=== @ FF ===");
  3339. eeprom_update_byte((uint8_t*)EEPROM_CHECK_MODE,0xFF);
  3340. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,0xFF);
  3341. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,0xFFFF);
  3342. */
  3343. } else if (code_seen("nozzle")) { // PRUSA nozzle
  3344. uint16_t nDiameter;
  3345. if(code_seen('D'))
  3346. {
  3347. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3348. nozzle_diameter_check(nDiameter);
  3349. }
  3350. else if(code_seen("set") && farm_mode)
  3351. {
  3352. strchr_pointer++; // skip 1st char (~ 's')
  3353. strchr_pointer++; // skip 2nd char (~ 'e')
  3354. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3355. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  3356. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  3357. }
  3358. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  3359. //-// !!! SupportMenu
  3360. /*
  3361. // musi byt PRED "PRUSA model"
  3362. } else if (code_seen("smodel")) { //! PRUSA smodel
  3363. size_t nOffset;
  3364. // ! -> "l"
  3365. strchr_pointer+=5*sizeof(*strchr_pointer); // skip 1st - 5th char (~ 'smode')
  3366. nOffset=strspn(strchr_pointer+1," \t\n\r\v\f");
  3367. if(*(strchr_pointer+1+nOffset))
  3368. printer_smodel_check(strchr_pointer);
  3369. else SERIAL_PROTOCOLLN(PRINTER_NAME);
  3370. } else if (code_seen("model")) { //! PRUSA model
  3371. uint16_t nPrinterModel;
  3372. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'mode')
  3373. nPrinterModel=(uint16_t)code_value_long();
  3374. if(nPrinterModel!=0)
  3375. printer_model_check(nPrinterModel);
  3376. else SERIAL_PROTOCOLLN(PRINTER_TYPE);
  3377. } else if (code_seen("version")) { //! PRUSA version
  3378. strchr_pointer+=7*sizeof(*strchr_pointer); // skip 1st - 7th char (~ 'version')
  3379. while(*strchr_pointer==' ') // skip leading spaces
  3380. strchr_pointer++;
  3381. if(*strchr_pointer!=0)
  3382. fw_version_check(strchr_pointer);
  3383. else SERIAL_PROTOCOLLN(FW_VERSION);
  3384. } else if (code_seen("gcode")) { //! PRUSA gcode
  3385. uint16_t nGcodeLevel;
  3386. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'gcod')
  3387. nGcodeLevel=(uint16_t)code_value_long();
  3388. if(nGcodeLevel!=0)
  3389. gcode_level_check(nGcodeLevel);
  3390. else SERIAL_PROTOCOLLN(GCODE_LEVEL);
  3391. */
  3392. }
  3393. //else if (code_seen('Cal')) {
  3394. // lcd_calibration();
  3395. // }
  3396. }
  3397. // This prevents reading files with "^" in their names.
  3398. // Since it is unclear, if there is some usage of this construct,
  3399. // it will be deprecated in 3.9 alpha a possibly completely removed in the future:
  3400. // else if (code_seen('^')) {
  3401. // // nothing, this is a version line
  3402. // }
  3403. else if(code_seen('G'))
  3404. {
  3405. gcode_in_progress = (int)code_value();
  3406. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3407. switch (gcode_in_progress)
  3408. {
  3409. //! ### G0, G1 - Coordinated movement X Y Z E
  3410. // --------------------------------------
  3411. case 0: // G0 -> G1
  3412. case 1: // G1
  3413. if(Stopped == false) {
  3414. #ifdef FILAMENT_RUNOUT_SUPPORT
  3415. if(READ(FR_SENS)){
  3416. int feedmultiplyBckp=feedmultiply;
  3417. float target[4];
  3418. float lastpos[4];
  3419. target[X_AXIS]=current_position[X_AXIS];
  3420. target[Y_AXIS]=current_position[Y_AXIS];
  3421. target[Z_AXIS]=current_position[Z_AXIS];
  3422. target[E_AXIS]=current_position[E_AXIS];
  3423. lastpos[X_AXIS]=current_position[X_AXIS];
  3424. lastpos[Y_AXIS]=current_position[Y_AXIS];
  3425. lastpos[Z_AXIS]=current_position[Z_AXIS];
  3426. lastpos[E_AXIS]=current_position[E_AXIS];
  3427. //retract by E
  3428. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT ;
  3429. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  3430. target[Z_AXIS]+= FILAMENTCHANGE_ZADD ;
  3431. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 300, active_extruder);
  3432. target[X_AXIS]= FILAMENTCHANGE_XPOS ;
  3433. target[Y_AXIS]= FILAMENTCHANGE_YPOS ;
  3434. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder);
  3435. target[E_AXIS]+= FILAMENTCHANGE_FINALRETRACT ;
  3436. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3437. //finish moves
  3438. st_synchronize();
  3439. //disable extruder steppers so filament can be removed
  3440. disable_e0();
  3441. disable_e1();
  3442. disable_e2();
  3443. _delay(100);
  3444. //LCD_ALERTMESSAGEPGM(_T(MSG_FILAMENTCHANGE));
  3445. uint8_t cnt=0;
  3446. int counterBeep = 0;
  3447. lcd_wait_interact();
  3448. while(!lcd_clicked()){
  3449. cnt++;
  3450. manage_heater();
  3451. manage_inactivity(true);
  3452. //lcd_update(0);
  3453. if(cnt==0)
  3454. {
  3455. #if BEEPER > 0
  3456. if (counterBeep== 500){
  3457. counterBeep = 0;
  3458. }
  3459. SET_OUTPUT(BEEPER);
  3460. if (counterBeep== 0){
  3461. if(eSoundMode!=e_SOUND_MODE_SILENT)
  3462. WRITE(BEEPER,HIGH);
  3463. }
  3464. if (counterBeep== 20){
  3465. WRITE(BEEPER,LOW);
  3466. }
  3467. counterBeep++;
  3468. #else
  3469. #endif
  3470. }
  3471. }
  3472. WRITE(BEEPER,LOW);
  3473. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3474. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3475. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3476. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3477. lcd_change_fil_state = 0;
  3478. lcd_loading_filament();
  3479. while ((lcd_change_fil_state == 0)||(lcd_change_fil_state != 1)){
  3480. lcd_change_fil_state = 0;
  3481. lcd_alright();
  3482. switch(lcd_change_fil_state){
  3483. case 2:
  3484. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3485. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3486. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3487. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3488. lcd_loading_filament();
  3489. break;
  3490. case 3:
  3491. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3492. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3493. lcd_loading_color();
  3494. break;
  3495. default:
  3496. lcd_change_success();
  3497. break;
  3498. }
  3499. }
  3500. target[E_AXIS]+= 5;
  3501. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3502. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT;
  3503. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  3504. //current_position[E_AXIS]=target[E_AXIS]; //the long retract of L is compensated by manual filament feeding
  3505. //plan_set_e_position(current_position[E_AXIS]);
  3506. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //should do nothing
  3507. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //move xy back
  3508. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 200, active_extruder); //move z back
  3509. target[E_AXIS]= target[E_AXIS] - FILAMENTCHANGE_FIRSTRETRACT;
  3510. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 5, active_extruder); //final untretract
  3511. plan_set_e_position(lastpos[E_AXIS]);
  3512. feedmultiply=feedmultiplyBckp;
  3513. char cmd[9];
  3514. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3515. enquecommand(cmd);
  3516. }
  3517. #endif
  3518. get_coordinates(); // For X Y Z E F
  3519. // When recovering from a previous print move, restore the originally
  3520. // calculated target position on the first USB/SD command. This accounts
  3521. // properly for relative moves
  3522. if ((saved_target[0] != SAVED_TARGET_UNSET) &&
  3523. ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) ||
  3524. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  3525. {
  3526. memcpy(destination, saved_target, sizeof(destination));
  3527. saved_target[0] = SAVED_TARGET_UNSET;
  3528. }
  3529. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3530. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3531. }
  3532. #ifdef FWRETRACT
  3533. if(cs.autoretract_enabled)
  3534. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3535. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3536. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3537. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3538. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3539. retract(!retracted[active_extruder]);
  3540. return;
  3541. }
  3542. }
  3543. #endif //FWRETRACT
  3544. prepare_move();
  3545. //ClearToSend();
  3546. }
  3547. break;
  3548. //! ### G2 - CW ARC
  3549. // ------------------------------
  3550. case 2:
  3551. if(Stopped == false) {
  3552. get_arc_coordinates();
  3553. prepare_arc_move(true);
  3554. }
  3555. break;
  3556. //! ### G3 - CCW ARC
  3557. // -------------------------------
  3558. case 3:
  3559. if(Stopped == false) {
  3560. get_arc_coordinates();
  3561. prepare_arc_move(false);
  3562. }
  3563. break;
  3564. //! ### G4 - Dwell
  3565. // -------------------------------
  3566. case 4:
  3567. codenum = 0;
  3568. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3569. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3570. if(codenum != 0) LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  3571. st_synchronize();
  3572. codenum += _millis(); // keep track of when we started waiting
  3573. previous_millis_cmd = _millis();
  3574. while(_millis() < codenum) {
  3575. manage_heater();
  3576. manage_inactivity();
  3577. lcd_update(0);
  3578. }
  3579. break;
  3580. #ifdef FWRETRACT
  3581. //! ### G10 Retract
  3582. // ------------------------------
  3583. case 10:
  3584. #if EXTRUDERS > 1
  3585. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  3586. retract(true,retracted_swap[active_extruder]);
  3587. #else
  3588. retract(true);
  3589. #endif
  3590. break;
  3591. //! ### G11 - Retract recover
  3592. // -----------------------------
  3593. case 11:
  3594. #if EXTRUDERS > 1
  3595. retract(false,retracted_swap[active_extruder]);
  3596. #else
  3597. retract(false);
  3598. #endif
  3599. break;
  3600. #endif //FWRETRACT
  3601. //! ### G28 - Home all Axis one at a time
  3602. // --------------------------------------------
  3603. case 28:
  3604. {
  3605. long home_x_value = 0;
  3606. long home_y_value = 0;
  3607. long home_z_value = 0;
  3608. // Which axes should be homed?
  3609. bool home_x = code_seen(axis_codes[X_AXIS]);
  3610. home_x_value = code_value_long();
  3611. bool home_y = code_seen(axis_codes[Y_AXIS]);
  3612. home_y_value = code_value_long();
  3613. bool home_z = code_seen(axis_codes[Z_AXIS]);
  3614. home_z_value = code_value_long();
  3615. bool without_mbl = code_seen('W');
  3616. // calibrate?
  3617. #ifdef TMC2130
  3618. bool calib = code_seen('C');
  3619. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  3620. #else
  3621. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  3622. #endif //TMC2130
  3623. if ((home_x || home_y || without_mbl || home_z) == false) {
  3624. // Push the commands to the front of the message queue in the reverse order!
  3625. // There shall be always enough space reserved for these commands.
  3626. goto case_G80;
  3627. }
  3628. break;
  3629. }
  3630. #ifdef ENABLE_AUTO_BED_LEVELING
  3631. //! ### G29 - Detailed Z-Probe
  3632. // --------------------------------
  3633. case 29:
  3634. {
  3635. #if Z_MIN_PIN == -1
  3636. #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."
  3637. #endif
  3638. // Prevent user from running a G29 without first homing in X and Y
  3639. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  3640. {
  3641. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  3642. SERIAL_ECHO_START;
  3643. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  3644. break; // abort G29, since we don't know where we are
  3645. }
  3646. st_synchronize();
  3647. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  3648. //vector_3 corrected_position = plan_get_position_mm();
  3649. //corrected_position.debug("position before G29");
  3650. plan_bed_level_matrix.set_to_identity();
  3651. vector_3 uncorrected_position = plan_get_position();
  3652. //uncorrected_position.debug("position durring G29");
  3653. current_position[X_AXIS] = uncorrected_position.x;
  3654. current_position[Y_AXIS] = uncorrected_position.y;
  3655. current_position[Z_AXIS] = uncorrected_position.z;
  3656. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  3657. int l_feedmultiply = setup_for_endstop_move();
  3658. feedrate = homing_feedrate[Z_AXIS];
  3659. #ifdef AUTO_BED_LEVELING_GRID
  3660. // probe at the points of a lattice grid
  3661. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  3662. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  3663. // solve the plane equation ax + by + d = z
  3664. // A is the matrix with rows [x y 1] for all the probed points
  3665. // B is the vector of the Z positions
  3666. // 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
  3667. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  3668. // "A" matrix of the linear system of equations
  3669. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  3670. // "B" vector of Z points
  3671. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  3672. int probePointCounter = 0;
  3673. bool zig = true;
  3674. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  3675. {
  3676. int xProbe, xInc;
  3677. if (zig)
  3678. {
  3679. xProbe = LEFT_PROBE_BED_POSITION;
  3680. //xEnd = RIGHT_PROBE_BED_POSITION;
  3681. xInc = xGridSpacing;
  3682. zig = false;
  3683. } else // zag
  3684. {
  3685. xProbe = RIGHT_PROBE_BED_POSITION;
  3686. //xEnd = LEFT_PROBE_BED_POSITION;
  3687. xInc = -xGridSpacing;
  3688. zig = true;
  3689. }
  3690. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  3691. {
  3692. float z_before;
  3693. if (probePointCounter == 0)
  3694. {
  3695. // raise before probing
  3696. z_before = Z_RAISE_BEFORE_PROBING;
  3697. } else
  3698. {
  3699. // raise extruder
  3700. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  3701. }
  3702. float measured_z = probe_pt(xProbe, yProbe, z_before);
  3703. eqnBVector[probePointCounter] = measured_z;
  3704. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  3705. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  3706. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  3707. probePointCounter++;
  3708. xProbe += xInc;
  3709. }
  3710. }
  3711. clean_up_after_endstop_move(l_feedmultiply);
  3712. // solve lsq problem
  3713. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  3714. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  3715. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  3716. SERIAL_PROTOCOLPGM(" b: ");
  3717. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  3718. SERIAL_PROTOCOLPGM(" d: ");
  3719. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  3720. set_bed_level_equation_lsq(plane_equation_coefficients);
  3721. free(plane_equation_coefficients);
  3722. #else // AUTO_BED_LEVELING_GRID not defined
  3723. // Probe at 3 arbitrary points
  3724. // probe 1
  3725. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  3726. // probe 2
  3727. 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);
  3728. // probe 3
  3729. 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);
  3730. clean_up_after_endstop_move(l_feedmultiply);
  3731. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  3732. #endif // AUTO_BED_LEVELING_GRID
  3733. st_synchronize();
  3734. // The following code correct the Z height difference from z-probe position and hotend tip position.
  3735. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  3736. // When the bed is uneven, this height must be corrected.
  3737. 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)
  3738. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  3739. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  3740. z_tmp = current_position[Z_AXIS];
  3741. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  3742. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  3743. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  3744. }
  3745. break;
  3746. #ifndef Z_PROBE_SLED
  3747. //! ### G30 - Single Z Probe
  3748. // ------------------------------------
  3749. case 30:
  3750. {
  3751. st_synchronize();
  3752. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  3753. int l_feedmultiply = setup_for_endstop_move();
  3754. feedrate = homing_feedrate[Z_AXIS];
  3755. run_z_probe();
  3756. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  3757. SERIAL_PROTOCOLPGM(" X: ");
  3758. SERIAL_PROTOCOL(current_position[X_AXIS]);
  3759. SERIAL_PROTOCOLPGM(" Y: ");
  3760. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3761. SERIAL_PROTOCOLPGM(" Z: ");
  3762. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3763. SERIAL_PROTOCOLPGM("\n");
  3764. clean_up_after_endstop_move(l_feedmultiply);
  3765. }
  3766. break;
  3767. #else
  3768. //! ### G31 - Dock the sled
  3769. // ---------------------------
  3770. case 31:
  3771. dock_sled(true);
  3772. break;
  3773. //! ### G32 - Undock the sled
  3774. // ----------------------------
  3775. case 32:
  3776. dock_sled(false);
  3777. break;
  3778. #endif // Z_PROBE_SLED
  3779. #endif // ENABLE_AUTO_BED_LEVELING
  3780. #ifdef MESH_BED_LEVELING
  3781. //! ### G30 - Single Z Probe
  3782. // ----------------------------
  3783. case 30:
  3784. {
  3785. st_synchronize();
  3786. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  3787. int l_feedmultiply = setup_for_endstop_move();
  3788. feedrate = homing_feedrate[Z_AXIS];
  3789. find_bed_induction_sensor_point_z(-10.f, 3);
  3790. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  3791. clean_up_after_endstop_move(l_feedmultiply);
  3792. }
  3793. break;
  3794. //! ### G75 - Print temperature interpolation
  3795. // ---------------------------------------------
  3796. case 75:
  3797. {
  3798. for (int i = 40; i <= 110; i++)
  3799. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  3800. }
  3801. break;
  3802. //! ### G76 - PINDA probe temperature calibration
  3803. // ------------------------------------------------
  3804. case 76:
  3805. {
  3806. #ifdef PINDA_THERMISTOR
  3807. if (true)
  3808. {
  3809. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  3810. //we need to know accurate position of first calibration point
  3811. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  3812. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first."));
  3813. break;
  3814. }
  3815. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  3816. {
  3817. // We don't know where we are! HOME!
  3818. // Push the commands to the front of the message queue in the reverse order!
  3819. // There shall be always enough space reserved for these commands.
  3820. repeatcommand_front(); // repeat G76 with all its parameters
  3821. enquecommand_front_P((PSTR("G28 W0")));
  3822. break;
  3823. }
  3824. 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
  3825. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  3826. if (result)
  3827. {
  3828. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3829. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3830. current_position[Z_AXIS] = 50;
  3831. current_position[Y_AXIS] = 180;
  3832. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3833. st_synchronize();
  3834. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  3835. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  3836. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  3837. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3838. st_synchronize();
  3839. gcode_G28(false, false, true);
  3840. }
  3841. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  3842. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  3843. current_position[Z_AXIS] = 100;
  3844. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3845. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  3846. lcd_temp_cal_show_result(false);
  3847. break;
  3848. }
  3849. }
  3850. lcd_update_enable(true);
  3851. KEEPALIVE_STATE(NOT_BUSY); //no need to print busy messages as we print current temperatures periodicaly
  3852. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  3853. float zero_z;
  3854. int z_shift = 0; //unit: steps
  3855. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  3856. if (start_temp < 35) start_temp = 35;
  3857. if (start_temp < current_temperature_pinda) start_temp += 5;
  3858. printf_P(_N("start temperature: %.1f\n"), start_temp);
  3859. // setTargetHotend(200, 0);
  3860. setTargetBed(70 + (start_temp - 30));
  3861. custom_message_type = CustomMsg::TempCal;
  3862. custom_message_state = 1;
  3863. lcd_setstatuspgm(_T(MSG_TEMP_CALIBRATION));
  3864. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3865. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3866. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3867. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3868. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3869. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3870. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3871. st_synchronize();
  3872. while (current_temperature_pinda < start_temp)
  3873. {
  3874. delay_keep_alive(1000);
  3875. serialecho_temperatures();
  3876. }
  3877. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  3878. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3879. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3880. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  3881. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  3882. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3883. st_synchronize();
  3884. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  3885. if (find_z_result == false) {
  3886. lcd_temp_cal_show_result(find_z_result);
  3887. break;
  3888. }
  3889. zero_z = current_position[Z_AXIS];
  3890. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  3891. int i = -1; for (; i < 5; i++)
  3892. {
  3893. float temp = (40 + i * 5);
  3894. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  3895. if (i >= 0) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  3896. if (start_temp <= temp) break;
  3897. }
  3898. for (i++; i < 5; i++)
  3899. {
  3900. float temp = (40 + i * 5);
  3901. printf_P(_N("\nStep: %d/6\n"), i + 2);
  3902. custom_message_state = i + 2;
  3903. setTargetBed(50 + 10 * (temp - 30) / 5);
  3904. // setTargetHotend(255, 0);
  3905. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3906. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3907. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3908. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3909. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3910. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3911. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3912. st_synchronize();
  3913. while (current_temperature_pinda < temp)
  3914. {
  3915. delay_keep_alive(1000);
  3916. serialecho_temperatures();
  3917. }
  3918. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3919. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3920. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  3921. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  3922. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3923. st_synchronize();
  3924. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  3925. if (find_z_result == false) {
  3926. lcd_temp_cal_show_result(find_z_result);
  3927. break;
  3928. }
  3929. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  3930. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  3931. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  3932. }
  3933. lcd_temp_cal_show_result(true);
  3934. break;
  3935. }
  3936. #endif //PINDA_THERMISTOR
  3937. setTargetBed(PINDA_MIN_T);
  3938. float zero_z;
  3939. int z_shift = 0; //unit: steps
  3940. int t_c; // temperature
  3941. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  3942. // We don't know where we are! HOME!
  3943. // Push the commands to the front of the message queue in the reverse order!
  3944. // There shall be always enough space reserved for these commands.
  3945. repeatcommand_front(); // repeat G76 with all its parameters
  3946. enquecommand_front_P((PSTR("G28 W0")));
  3947. break;
  3948. }
  3949. puts_P(_N("PINDA probe calibration start"));
  3950. custom_message_type = CustomMsg::TempCal;
  3951. custom_message_state = 1;
  3952. lcd_setstatuspgm(_T(MSG_TEMP_CALIBRATION));
  3953. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3954. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3955. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3956. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3957. st_synchronize();
  3958. while (abs(degBed() - PINDA_MIN_T) > 1) {
  3959. delay_keep_alive(1000);
  3960. serialecho_temperatures();
  3961. }
  3962. //enquecommand_P(PSTR("M190 S50"));
  3963. for (int i = 0; i < PINDA_HEAT_T; i++) {
  3964. delay_keep_alive(1000);
  3965. serialecho_temperatures();
  3966. }
  3967. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  3968. current_position[Z_AXIS] = 5;
  3969. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3970. current_position[X_AXIS] = BED_X0;
  3971. current_position[Y_AXIS] = BED_Y0;
  3972. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3973. st_synchronize();
  3974. find_bed_induction_sensor_point_z(-1.f);
  3975. zero_z = current_position[Z_AXIS];
  3976. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  3977. for (int i = 0; i<5; i++) {
  3978. printf_P(_N("\nStep: %d/6\n"), i + 2);
  3979. custom_message_state = i + 2;
  3980. t_c = 60 + i * 10;
  3981. setTargetBed(t_c);
  3982. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3983. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3984. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3985. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3986. st_synchronize();
  3987. while (degBed() < t_c) {
  3988. delay_keep_alive(1000);
  3989. serialecho_temperatures();
  3990. }
  3991. for (int i = 0; i < PINDA_HEAT_T; i++) {
  3992. delay_keep_alive(1000);
  3993. serialecho_temperatures();
  3994. }
  3995. current_position[Z_AXIS] = 5;
  3996. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  3997. current_position[X_AXIS] = BED_X0;
  3998. current_position[Y_AXIS] = BED_Y0;
  3999. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  4000. st_synchronize();
  4001. find_bed_induction_sensor_point_z(-1.f);
  4002. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4003. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  4004. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i*2, &z_shift);
  4005. }
  4006. custom_message_type = CustomMsg::Status;
  4007. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  4008. puts_P(_N("Temperature calibration done."));
  4009. disable_x();
  4010. disable_y();
  4011. disable_z();
  4012. disable_e0();
  4013. disable_e1();
  4014. disable_e2();
  4015. setTargetBed(0); //set bed target temperature back to 0
  4016. lcd_show_fullscreen_message_and_wait_P(_T(MSG_TEMP_CALIBRATION_DONE));
  4017. temp_cal_active = true;
  4018. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  4019. lcd_update_enable(true);
  4020. lcd_update(2);
  4021. }
  4022. break;
  4023. //! ### G80 - Mesh-based Z probe
  4024. // -----------------------------------
  4025. /*
  4026. * Probes a grid and produces a mesh to compensate for variable bed height
  4027. * The S0 report the points as below
  4028. * +----> X-axis
  4029. * |
  4030. * |
  4031. * v Y-axis
  4032. */
  4033. case 80:
  4034. #ifdef MK1BP
  4035. break;
  4036. #endif //MK1BP
  4037. case_G80:
  4038. {
  4039. mesh_bed_leveling_flag = true;
  4040. #ifndef LA_NOCOMPAT
  4041. // When printing via USB there's no clear boundary between prints. Abuse MBL to indicate
  4042. // the beginning of a new print, allowing a new autodetected setting just after G80.
  4043. la10c_reset();
  4044. #endif
  4045. #ifndef PINDA_THERMISTOR
  4046. static bool run = false; // thermistor-less PINDA temperature compensation is running
  4047. #endif // ndef PINDA_THERMISTOR
  4048. #ifdef SUPPORT_VERBOSITY
  4049. int8_t verbosity_level = 0;
  4050. if (code_seen('V')) {
  4051. // Just 'V' without a number counts as V1.
  4052. char c = strchr_pointer[1];
  4053. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4054. }
  4055. #endif //SUPPORT_VERBOSITY
  4056. // Firstly check if we know where we are
  4057. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4058. // We don't know where we are! HOME!
  4059. // Push the commands to the front of the message queue in the reverse order!
  4060. // There shall be always enough space reserved for these commands.
  4061. repeatcommand_front(); // repeat G80 with all its parameters
  4062. enquecommand_front_P((PSTR("G28 W0")));
  4063. break;
  4064. }
  4065. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  4066. if (code_seen('N')) {
  4067. nMeasPoints = code_value_uint8();
  4068. if (nMeasPoints != 7) {
  4069. nMeasPoints = 3;
  4070. }
  4071. }
  4072. else {
  4073. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  4074. }
  4075. uint8_t nProbeRetry = 3;
  4076. if (code_seen('R')) {
  4077. nProbeRetry = code_value_uint8();
  4078. if (nProbeRetry > 10) {
  4079. nProbeRetry = 10;
  4080. }
  4081. }
  4082. else {
  4083. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  4084. }
  4085. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  4086. #ifndef PINDA_THERMISTOR
  4087. if (run == false && temp_cal_active == true && calibration_status_pinda() == true && target_temperature_bed >= 50)
  4088. {
  4089. temp_compensation_start();
  4090. run = true;
  4091. repeatcommand_front(); // repeat G80 with all its parameters
  4092. enquecommand_front_P((PSTR("G28 W0")));
  4093. break;
  4094. }
  4095. run = false;
  4096. #endif //PINDA_THERMISTOR
  4097. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  4098. CustomMsg custom_message_type_old = custom_message_type;
  4099. unsigned int custom_message_state_old = custom_message_state;
  4100. custom_message_type = CustomMsg::MeshBedLeveling;
  4101. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  4102. lcd_update(1);
  4103. mbl.reset(); //reset mesh bed leveling
  4104. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  4105. // consumed during the first movements following this statement.
  4106. babystep_undo();
  4107. // Cycle through all points and probe them
  4108. // First move up. During this first movement, the babystepping will be reverted.
  4109. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4110. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  4111. // The move to the first calibration point.
  4112. current_position[X_AXIS] = BED_X0;
  4113. current_position[Y_AXIS] = BED_Y0;
  4114. #ifdef SUPPORT_VERBOSITY
  4115. if (verbosity_level >= 1)
  4116. {
  4117. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4118. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  4119. }
  4120. #else //SUPPORT_VERBOSITY
  4121. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4122. #endif //SUPPORT_VERBOSITY
  4123. plan_buffer_line_curposXYZE(homing_feedrate[X_AXIS] / 30, active_extruder);
  4124. // Wait until the move is finished.
  4125. st_synchronize();
  4126. uint8_t mesh_point = 0; //index number of calibration point
  4127. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  4128. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  4129. 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)
  4130. #ifdef SUPPORT_VERBOSITY
  4131. if (verbosity_level >= 1) {
  4132. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  4133. }
  4134. #endif // SUPPORT_VERBOSITY
  4135. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  4136. const char *kill_message = NULL;
  4137. while (mesh_point != nMeasPoints * nMeasPoints) {
  4138. // Get coords of a measuring point.
  4139. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  4140. uint8_t iy = mesh_point / nMeasPoints;
  4141. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  4142. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  4143. custom_message_state--;
  4144. mesh_point++;
  4145. continue; //skip
  4146. }*/
  4147. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  4148. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  4149. {
  4150. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  4151. }
  4152. float z0 = 0.f;
  4153. if (has_z && (mesh_point > 0)) {
  4154. uint16_t z_offset_u = 0;
  4155. if (nMeasPoints == 7) {
  4156. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  4157. }
  4158. else {
  4159. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  4160. }
  4161. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  4162. #ifdef SUPPORT_VERBOSITY
  4163. if (verbosity_level >= 1) {
  4164. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  4165. }
  4166. #endif // SUPPORT_VERBOSITY
  4167. }
  4168. // Move Z up to MESH_HOME_Z_SEARCH.
  4169. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4170. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  4171. float init_z_bckp = current_position[Z_AXIS];
  4172. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  4173. st_synchronize();
  4174. // Move to XY position of the sensor point.
  4175. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  4176. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  4177. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  4178. #ifdef SUPPORT_VERBOSITY
  4179. if (verbosity_level >= 1) {
  4180. clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4181. SERIAL_PROTOCOL(mesh_point);
  4182. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  4183. }
  4184. #else //SUPPORT_VERBOSITY
  4185. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  4186. #endif // SUPPORT_VERBOSITY
  4187. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  4188. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  4189. st_synchronize();
  4190. // Go down until endstop is hit
  4191. const float Z_CALIBRATION_THRESHOLD = 1.f;
  4192. 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
  4193. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  4194. break;
  4195. }
  4196. 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.
  4197. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  4198. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4199. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  4200. st_synchronize();
  4201. 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
  4202. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  4203. break;
  4204. }
  4205. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  4206. printf_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken.\n"));
  4207. break;
  4208. }
  4209. }
  4210. 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
  4211. printf_P(PSTR("Bed leveling failed. Sensor triggered too high.\n"));
  4212. break;
  4213. }
  4214. #ifdef SUPPORT_VERBOSITY
  4215. if (verbosity_level >= 10) {
  4216. SERIAL_ECHOPGM("X: ");
  4217. MYSERIAL.print(current_position[X_AXIS], 5);
  4218. SERIAL_ECHOLNPGM("");
  4219. SERIAL_ECHOPGM("Y: ");
  4220. MYSERIAL.print(current_position[Y_AXIS], 5);
  4221. SERIAL_PROTOCOLPGM("\n");
  4222. }
  4223. #endif // SUPPORT_VERBOSITY
  4224. float offset_z = 0;
  4225. #ifdef PINDA_THERMISTOR
  4226. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  4227. #endif //PINDA_THERMISTOR
  4228. // #ifdef SUPPORT_VERBOSITY
  4229. /* if (verbosity_level >= 1)
  4230. {
  4231. SERIAL_ECHOPGM("mesh bed leveling: ");
  4232. MYSERIAL.print(current_position[Z_AXIS], 5);
  4233. SERIAL_ECHOPGM(" offset: ");
  4234. MYSERIAL.print(offset_z, 5);
  4235. SERIAL_ECHOLNPGM("");
  4236. }*/
  4237. // #endif // SUPPORT_VERBOSITY
  4238. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  4239. custom_message_state--;
  4240. mesh_point++;
  4241. lcd_update(1);
  4242. }
  4243. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4244. #ifdef SUPPORT_VERBOSITY
  4245. if (verbosity_level >= 20) {
  4246. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  4247. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  4248. MYSERIAL.print(current_position[Z_AXIS], 5);
  4249. }
  4250. #endif // SUPPORT_VERBOSITY
  4251. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  4252. st_synchronize();
  4253. if (mesh_point != nMeasPoints * nMeasPoints) {
  4254. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  4255. bool bState;
  4256. do { // repeat until Z-leveling o.k.
  4257. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ..."));
  4258. #ifdef TMC2130
  4259. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  4260. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  4261. #else // TMC2130
  4262. lcd_wait_for_click_delay(0); // ~ no timeout
  4263. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  4264. #endif // TMC2130
  4265. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  4266. bState=enable_z_endstop(false);
  4267. current_position[Z_AXIS] -= 1;
  4268. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40, active_extruder);
  4269. st_synchronize();
  4270. enable_z_endstop(true);
  4271. #ifdef TMC2130
  4272. tmc2130_home_enter(Z_AXIS_MASK);
  4273. #endif // TMC2130
  4274. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4275. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40, active_extruder);
  4276. st_synchronize();
  4277. #ifdef TMC2130
  4278. tmc2130_home_exit();
  4279. #endif // TMC2130
  4280. enable_z_endstop(bState);
  4281. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  4282. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  4283. custom_message_type=CustomMsg::Status; // display / status-line recovery
  4284. lcd_update_enable(true); // display / status-line recovery
  4285. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  4286. repeatcommand_front(); // re-run (i.e. of "G80")
  4287. break;
  4288. }
  4289. clean_up_after_endstop_move(l_feedmultiply);
  4290. // SERIAL_ECHOLNPGM("clean up finished ");
  4291. #ifndef PINDA_THERMISTOR
  4292. if(temp_cal_active == true && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  4293. #endif
  4294. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  4295. // SERIAL_ECHOLNPGM("babystep applied");
  4296. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  4297. #ifdef SUPPORT_VERBOSITY
  4298. if (verbosity_level >= 1) {
  4299. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  4300. }
  4301. #endif // SUPPORT_VERBOSITY
  4302. for (uint8_t i = 0; i < 4; ++i) {
  4303. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  4304. long correction = 0;
  4305. if (code_seen(codes[i]))
  4306. correction = code_value_long();
  4307. else if (eeprom_bed_correction_valid) {
  4308. unsigned char *addr = (i < 2) ?
  4309. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  4310. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  4311. correction = eeprom_read_int8(addr);
  4312. }
  4313. if (correction == 0)
  4314. continue;
  4315. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  4316. SERIAL_ERROR_START;
  4317. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  4318. SERIAL_ECHO(correction);
  4319. SERIAL_ECHOLNPGM(" microns");
  4320. }
  4321. else {
  4322. float offset = float(correction) * 0.001f;
  4323. switch (i) {
  4324. case 0:
  4325. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  4326. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  4327. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  4328. }
  4329. }
  4330. break;
  4331. case 1:
  4332. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  4333. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  4334. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  4335. }
  4336. }
  4337. break;
  4338. case 2:
  4339. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  4340. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  4341. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  4342. }
  4343. }
  4344. break;
  4345. case 3:
  4346. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  4347. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  4348. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  4349. }
  4350. }
  4351. break;
  4352. }
  4353. }
  4354. }
  4355. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  4356. if (nMeasPoints == 3) {
  4357. 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)
  4358. }
  4359. /*
  4360. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4361. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4362. SERIAL_PROTOCOLPGM(",");
  4363. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4364. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4365. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4366. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4367. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4368. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4369. SERIAL_PROTOCOLPGM(" ");
  4370. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4371. }
  4372. SERIAL_PROTOCOLPGM("\n");
  4373. }
  4374. */
  4375. if (nMeasPoints == 7 && magnet_elimination) {
  4376. mbl_interpolation(nMeasPoints);
  4377. }
  4378. /*
  4379. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4380. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4381. SERIAL_PROTOCOLPGM(",");
  4382. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4383. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4384. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4385. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4386. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4387. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4388. SERIAL_PROTOCOLPGM(" ");
  4389. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4390. }
  4391. SERIAL_PROTOCOLPGM("\n");
  4392. }
  4393. */
  4394. // SERIAL_ECHOLNPGM("Upsample finished");
  4395. mbl.active = 1; //activate mesh bed leveling
  4396. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  4397. go_home_with_z_lift();
  4398. // SERIAL_ECHOLNPGM("Go home finished");
  4399. //unretract (after PINDA preheat retraction)
  4400. if (degHotend(active_extruder) > EXTRUDE_MINTEMP && temp_cal_active == true && calibration_status_pinda() == true && target_temperature_bed >= 50) {
  4401. current_position[E_AXIS] += default_retraction;
  4402. plan_buffer_line_curposXYZE(400, active_extruder);
  4403. }
  4404. KEEPALIVE_STATE(NOT_BUSY);
  4405. // Restore custom message state
  4406. lcd_setstatuspgm(_T(WELCOME_MSG));
  4407. custom_message_type = custom_message_type_old;
  4408. custom_message_state = custom_message_state_old;
  4409. mesh_bed_leveling_flag = false;
  4410. mesh_bed_run_from_menu = false;
  4411. lcd_update(2);
  4412. }
  4413. break;
  4414. //! ### G81 - Mesh bed leveling status
  4415. // -----------------------------------------
  4416. /*
  4417. * Prints mesh bed leveling status and bed profile if activated
  4418. */
  4419. case 81:
  4420. if (mbl.active) {
  4421. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4422. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4423. SERIAL_PROTOCOLPGM(",");
  4424. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4425. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4426. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4427. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4428. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4429. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4430. SERIAL_PROTOCOLPGM(" ");
  4431. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4432. }
  4433. SERIAL_PROTOCOLPGM("\n");
  4434. }
  4435. }
  4436. else
  4437. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4438. break;
  4439. #if 0
  4440. /*
  4441. * G82: Single Z probe at current location
  4442. *
  4443. * WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4444. *
  4445. */
  4446. case 82:
  4447. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4448. int l_feedmultiply = setup_for_endstop_move();
  4449. find_bed_induction_sensor_point_z();
  4450. clean_up_after_endstop_move(l_feedmultiply);
  4451. SERIAL_PROTOCOLPGM("Bed found at: ");
  4452. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4453. SERIAL_PROTOCOLPGM("\n");
  4454. break;
  4455. /*
  4456. * G83: Prusa3D specific: Babystep in Z and store to EEPROM
  4457. */
  4458. case 83:
  4459. {
  4460. int babystepz = code_seen('S') ? code_value() : 0;
  4461. int BabyPosition = code_seen('P') ? code_value() : 0;
  4462. if (babystepz != 0) {
  4463. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4464. // Is the axis indexed starting with zero or one?
  4465. if (BabyPosition > 4) {
  4466. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4467. }else{
  4468. // Save it to the eeprom
  4469. babystepLoadZ = babystepz;
  4470. EEPROM_save_B(EEPROM_BABYSTEP_Z0+(BabyPosition*2),&babystepLoadZ);
  4471. // adjust the Z
  4472. babystepsTodoZadd(babystepLoadZ);
  4473. }
  4474. }
  4475. }
  4476. break;
  4477. /*
  4478. * G84: Prusa3D specific: UNDO Babystep Z (move Z axis back)
  4479. */
  4480. case 84:
  4481. babystepsTodoZsubtract(babystepLoadZ);
  4482. // babystepLoadZ = 0;
  4483. break;
  4484. /*
  4485. * G85: Prusa3D specific: Pick best babystep
  4486. */
  4487. case 85:
  4488. lcd_pick_babystep();
  4489. break;
  4490. #endif
  4491. /**
  4492. * ### G86 - Disable babystep correction after home
  4493. *
  4494. * This G-code will be performed at the start of a calibration script.
  4495. * (Prusa3D specific)
  4496. */
  4497. case 86:
  4498. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4499. break;
  4500. /**
  4501. * ### G87 - Enable babystep correction after home
  4502. *
  4503. *
  4504. * This G-code will be performed at the end of a calibration script.
  4505. * (Prusa3D specific)
  4506. */
  4507. case 87:
  4508. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4509. break;
  4510. /**
  4511. * ### G88 - Reserved
  4512. *
  4513. * Currently has no effect.
  4514. */
  4515. // Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4516. case 88:
  4517. break;
  4518. #endif // ENABLE_MESH_BED_LEVELING
  4519. //! ### G90 - Switch off relative mode
  4520. // -------------------------------
  4521. case 90: {
  4522. for(uint8_t i = 0; i != NUM_AXIS; ++i)
  4523. axis_relative_modes[i] = false;
  4524. }
  4525. break;
  4526. //! ### G91 - Switch on relative mode
  4527. // -------------------------------
  4528. case 91: {
  4529. for(uint8_t i = 0; i != NUM_AXIS; ++i)
  4530. axis_relative_modes[i] = true;
  4531. }
  4532. break;
  4533. //! ### G92 - Set position
  4534. // -----------------------------
  4535. case 92: {
  4536. gcode_G92();
  4537. }
  4538. break;
  4539. //! ### G98 - Activate farm mode
  4540. // -----------------------------------
  4541. case 98:
  4542. farm_mode = 1;
  4543. PingTime = _millis();
  4544. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  4545. EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
  4546. SilentModeMenu = SILENT_MODE_OFF;
  4547. eeprom_update_byte((unsigned char *)EEPROM_SILENT, SilentModeMenu);
  4548. fCheckModeInit(); // alternatively invoke printer reset
  4549. break;
  4550. //! ### G99 - Deactivate farm mode
  4551. // -------------------------------------
  4552. case 99:
  4553. farm_mode = 0;
  4554. lcd_printer_connected();
  4555. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  4556. lcd_update(2);
  4557. fCheckModeInit(); // alternatively invoke printer reset
  4558. break;
  4559. default:
  4560. printf_P(PSTR("Unknown G code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4561. }
  4562. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4563. gcode_in_progress = 0;
  4564. } // end if(code_seen('G'))
  4565. //! ---------------------------------------------------------------------------------
  4566. else if(code_seen('M'))
  4567. {
  4568. int index;
  4569. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4570. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4571. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4572. printf_P(PSTR("Invalid M code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4573. } else
  4574. {
  4575. mcode_in_progress = (int)code_value();
  4576. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4577. switch(mcode_in_progress)
  4578. {
  4579. //! ### M0, M1 - Stop the printer
  4580. // ---------------------------------------------------------------
  4581. case 0: // M0 - Unconditional stop - Wait for user button press on LCD
  4582. case 1: // M1 - Conditional stop - Wait for user button press on LCD
  4583. {
  4584. char *src = strchr_pointer + 2;
  4585. codenum = 0;
  4586. bool hasP = false, hasS = false;
  4587. if (code_seen('P')) {
  4588. codenum = code_value(); // milliseconds to wait
  4589. hasP = codenum > 0;
  4590. }
  4591. if (code_seen('S')) {
  4592. codenum = code_value() * 1000; // seconds to wait
  4593. hasS = codenum > 0;
  4594. }
  4595. starpos = strchr(src, '*');
  4596. if (starpos != NULL) *(starpos) = '\0';
  4597. while (*src == ' ') ++src;
  4598. if (!hasP && !hasS && *src != '\0') {
  4599. lcd_setstatus(src);
  4600. } else {
  4601. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT
  4602. }
  4603. lcd_ignore_click(); //call lcd_ignore_click aslo for else ???
  4604. st_synchronize();
  4605. previous_millis_cmd = _millis();
  4606. if (codenum > 0){
  4607. codenum += _millis(); // keep track of when we started waiting
  4608. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4609. while(_millis() < codenum && !lcd_clicked()){
  4610. manage_heater();
  4611. manage_inactivity(true);
  4612. lcd_update(0);
  4613. }
  4614. KEEPALIVE_STATE(IN_HANDLER);
  4615. lcd_ignore_click(false);
  4616. }else{
  4617. marlin_wait_for_click();
  4618. }
  4619. if (IS_SD_PRINTING)
  4620. LCD_MESSAGERPGM(_T(MSG_RESUMING_PRINT));
  4621. else
  4622. LCD_MESSAGERPGM(_T(WELCOME_MSG));
  4623. }
  4624. break;
  4625. //! ### M17 - Enable axes
  4626. // ---------------------------------
  4627. case 17:
  4628. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE
  4629. enable_x();
  4630. enable_y();
  4631. enable_z();
  4632. enable_e0();
  4633. enable_e1();
  4634. enable_e2();
  4635. break;
  4636. #ifdef SDSUPPORT
  4637. //! ### M20 - SD Card file list
  4638. // -----------------------------------
  4639. case 20:
  4640. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4641. card.ls();
  4642. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4643. break;
  4644. //! ### M21 - Init SD card
  4645. // ------------------------------------
  4646. case 21:
  4647. card.initsd();
  4648. break;
  4649. //! ### M22 - Release SD card
  4650. // -----------------------------------
  4651. case 22:
  4652. card.release();
  4653. break;
  4654. //! ### M23 - Select file
  4655. // -----------------------------------
  4656. case 23:
  4657. starpos = (strchr(strchr_pointer + 4,'*'));
  4658. if(starpos!=NULL)
  4659. *(starpos)='\0';
  4660. card.openFile(strchr_pointer + 4,true);
  4661. break;
  4662. //! ### M24 - Start/resume SD print
  4663. // ----------------------------------
  4664. case 24:
  4665. if (isPrintPaused)
  4666. lcd_resume_print();
  4667. else
  4668. {
  4669. failstats_reset_print();
  4670. #ifndef LA_NOCOMPAT
  4671. la10c_reset();
  4672. #endif
  4673. card.startFileprint();
  4674. starttime=_millis();
  4675. }
  4676. break;
  4677. //! ### M26 S\<index\> - Set SD index
  4678. //! Set position in SD card file to index in bytes.
  4679. //! This command is expected to be called after M23 and before M24.
  4680. //! Otherwise effect of this command is undefined.
  4681. // ----------------------------------
  4682. case 26:
  4683. if(card.cardOK && code_seen('S')) {
  4684. long index = code_value_long();
  4685. card.setIndex(index);
  4686. // We don't disable interrupt during update of sdpos_atomic
  4687. // as we expect, that SD card print is not active in this moment
  4688. sdpos_atomic = index;
  4689. }
  4690. break;
  4691. //! ### M27 - Get SD status
  4692. // ----------------------------------
  4693. case 27:
  4694. card.getStatus();
  4695. break;
  4696. //! ### M28 - Start SD write
  4697. // ---------------------------------
  4698. case 28:
  4699. starpos = (strchr(strchr_pointer + 4,'*'));
  4700. if(starpos != NULL){
  4701. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4702. strchr_pointer = strchr(npos,' ') + 1;
  4703. *(starpos) = '\0';
  4704. }
  4705. card.openFile(strchr_pointer+4,false);
  4706. break;
  4707. //! ### M29 - Stop SD write
  4708. // -------------------------------------
  4709. //! Currently has no effect.
  4710. case 29:
  4711. //processed in write to file routine above
  4712. //card,saving = false;
  4713. break;
  4714. //! ### M30 - Delete file <filename>
  4715. // ----------------------------------
  4716. case 30:
  4717. if (card.cardOK){
  4718. card.closefile();
  4719. starpos = (strchr(strchr_pointer + 4,'*'));
  4720. if(starpos != NULL){
  4721. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4722. strchr_pointer = strchr(npos,' ') + 1;
  4723. *(starpos) = '\0';
  4724. }
  4725. card.removeFile(strchr_pointer + 4);
  4726. }
  4727. break;
  4728. //! ### M32 - Select file and start SD print
  4729. // ------------------------------------
  4730. case 32:
  4731. {
  4732. if(card.sdprinting) {
  4733. st_synchronize();
  4734. }
  4735. starpos = (strchr(strchr_pointer + 4,'*'));
  4736. char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4737. if(namestartpos==NULL)
  4738. {
  4739. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4740. }
  4741. else
  4742. namestartpos++; //to skip the '!'
  4743. if(starpos!=NULL)
  4744. *(starpos)='\0';
  4745. bool call_procedure=(code_seen('P'));
  4746. if(strchr_pointer>namestartpos)
  4747. call_procedure=false; //false alert, 'P' found within filename
  4748. if( card.cardOK )
  4749. {
  4750. card.openFile(namestartpos,true,!call_procedure);
  4751. if(code_seen('S'))
  4752. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4753. card.setIndex(code_value_long());
  4754. #ifndef LA_NOCOMPAT
  4755. la10c_reset();
  4756. #endif
  4757. card.startFileprint();
  4758. if(!call_procedure)
  4759. starttime=_millis(); //procedure calls count as normal print time.
  4760. }
  4761. } break;
  4762. //! ### M982 - Start SD write
  4763. // ---------------------------------
  4764. case 928:
  4765. starpos = (strchr(strchr_pointer + 5,'*'));
  4766. if(starpos != NULL){
  4767. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4768. strchr_pointer = strchr(npos,' ') + 1;
  4769. *(starpos) = '\0';
  4770. }
  4771. card.openLogFile(strchr_pointer+5);
  4772. break;
  4773. #endif //SDSUPPORT
  4774. //! ### M31 - Report current print time
  4775. // --------------------------------------------------
  4776. case 31: //M31 take time since the start of the SD print or an M109 command
  4777. {
  4778. stoptime=_millis();
  4779. char time[30];
  4780. unsigned long t=(stoptime-starttime)/1000;
  4781. int sec,min;
  4782. min=t/60;
  4783. sec=t%60;
  4784. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4785. SERIAL_ECHO_START;
  4786. SERIAL_ECHOLN(time);
  4787. lcd_setstatus(time);
  4788. autotempShutdown();
  4789. }
  4790. break;
  4791. //! ### M42 - Set pin state
  4792. // -----------------------------
  4793. case 42:
  4794. if (code_seen('S'))
  4795. {
  4796. int pin_status = code_value();
  4797. int pin_number = LED_PIN;
  4798. if (code_seen('P') && pin_status >= 0 && pin_status <= 255)
  4799. pin_number = code_value();
  4800. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  4801. {
  4802. if (sensitive_pins[i] == pin_number)
  4803. {
  4804. pin_number = -1;
  4805. break;
  4806. }
  4807. }
  4808. #if defined(FAN_PIN) && FAN_PIN > -1
  4809. if (pin_number == FAN_PIN)
  4810. fanSpeed = pin_status;
  4811. #endif
  4812. if (pin_number > -1)
  4813. {
  4814. pinMode(pin_number, OUTPUT);
  4815. digitalWrite(pin_number, pin_status);
  4816. analogWrite(pin_number, pin_status);
  4817. }
  4818. }
  4819. break;
  4820. //! ### M44 - Reset the bed skew and offset calibration (Prusa specific)
  4821. // --------------------------------------------------------------------
  4822. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  4823. // Reset the baby step value and the baby step applied flag.
  4824. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4825. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  4826. // Reset the skew and offset in both RAM and EEPROM.
  4827. reset_bed_offset_and_skew();
  4828. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4829. // the planner will not perform any adjustments in the XY plane.
  4830. // Wait for the motors to stop and update the current position with the absolute values.
  4831. world2machine_revert_to_uncorrected();
  4832. break;
  4833. //! ### M45 - Bed skew and offset with manual Z up (Prusa specific)
  4834. // ------------------------------------------------------
  4835. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  4836. {
  4837. int8_t verbosity_level = 0;
  4838. bool only_Z = code_seen('Z');
  4839. #ifdef SUPPORT_VERBOSITY
  4840. if (code_seen('V'))
  4841. {
  4842. // Just 'V' without a number counts as V1.
  4843. char c = strchr_pointer[1];
  4844. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4845. }
  4846. #endif //SUPPORT_VERBOSITY
  4847. gcode_M45(only_Z, verbosity_level);
  4848. }
  4849. break;
  4850. /*
  4851. case 46:
  4852. {
  4853. // M46: Prusa3D: Show the assigned IP address.
  4854. uint8_t ip[4];
  4855. bool hasIP = card.ToshibaFlashAir_GetIP(ip);
  4856. if (hasIP) {
  4857. SERIAL_ECHOPGM("Toshiba FlashAir current IP: ");
  4858. SERIAL_ECHO(int(ip[0]));
  4859. SERIAL_ECHOPGM(".");
  4860. SERIAL_ECHO(int(ip[1]));
  4861. SERIAL_ECHOPGM(".");
  4862. SERIAL_ECHO(int(ip[2]));
  4863. SERIAL_ECHOPGM(".");
  4864. SERIAL_ECHO(int(ip[3]));
  4865. SERIAL_ECHOLNPGM("");
  4866. } else {
  4867. SERIAL_ECHOLNPGM("Toshiba FlashAir GetIP failed");
  4868. }
  4869. break;
  4870. }
  4871. */
  4872. //! ### M47 - Show end stops dialog on the display (Prusa specific)
  4873. // ----------------------------------------------------
  4874. case 47:
  4875. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4876. lcd_diag_show_end_stops();
  4877. KEEPALIVE_STATE(IN_HANDLER);
  4878. break;
  4879. #if 0
  4880. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  4881. {
  4882. // Disable the default update procedure of the display. We will do a modal dialog.
  4883. lcd_update_enable(false);
  4884. // Let the planner use the uncorrected coordinates.
  4885. mbl.reset();
  4886. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4887. // the planner will not perform any adjustments in the XY plane.
  4888. // Wait for the motors to stop and update the current position with the absolute values.
  4889. world2machine_revert_to_uncorrected();
  4890. // Move the print head close to the bed.
  4891. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4892. 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);
  4893. st_synchronize();
  4894. // Home in the XY plane.
  4895. set_destination_to_current();
  4896. int l_feedmultiply = setup_for_endstop_move();
  4897. home_xy();
  4898. int8_t verbosity_level = 0;
  4899. if (code_seen('V')) {
  4900. // Just 'V' without a number counts as V1.
  4901. char c = strchr_pointer[1];
  4902. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4903. }
  4904. bool success = scan_bed_induction_points(verbosity_level);
  4905. clean_up_after_endstop_move(l_feedmultiply);
  4906. // Print head up.
  4907. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4908. 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);
  4909. st_synchronize();
  4910. lcd_update_enable(true);
  4911. break;
  4912. }
  4913. #endif
  4914. #ifdef ENABLE_AUTO_BED_LEVELING
  4915. #ifdef Z_PROBE_REPEATABILITY_TEST
  4916. //! ### M48 - Z-Probe repeatability measurement function.
  4917. // ------------------------------------------------------
  4918. //!
  4919. //! _Usage:_
  4920. //!
  4921. //! M48 <n #_samples> <X X_position_for_samples> <Y Y_position_for_samples> <V Verbose_Level> <L legs_of_movement_prior_to_doing_probe>
  4922. //!
  4923. //! This function assumes the bed has been homed. Specifically, that a G28 command
  4924. //! as been issued prior to invoking the M48 Z-Probe repeatability measurement function.
  4925. //! Any information generated by a prior G29 Bed leveling command will be lost and need to be
  4926. //! regenerated.
  4927. //!
  4928. //! The number of samples will default to 10 if not specified. You can use upper or lower case
  4929. //! letters for any of the options EXCEPT n. n must be in lower case because Marlin uses a capital
  4930. //! N for its communication protocol and will get horribly confused if you send it a capital N.
  4931. //!
  4932. case 48: // M48 Z-Probe repeatability
  4933. {
  4934. #if Z_MIN_PIN == -1
  4935. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  4936. #endif
  4937. double sum=0.0;
  4938. double mean=0.0;
  4939. double sigma=0.0;
  4940. double sample_set[50];
  4941. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  4942. double X_current, Y_current, Z_current;
  4943. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  4944. if (code_seen('V') || code_seen('v')) {
  4945. verbose_level = code_value();
  4946. if (verbose_level<0 || verbose_level>4 ) {
  4947. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  4948. goto Sigma_Exit;
  4949. }
  4950. }
  4951. if (verbose_level > 0) {
  4952. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  4953. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  4954. }
  4955. if (code_seen('n')) {
  4956. n_samples = code_value();
  4957. if (n_samples<4 || n_samples>50 ) {
  4958. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  4959. goto Sigma_Exit;
  4960. }
  4961. }
  4962. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  4963. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  4964. Z_current = st_get_position_mm(Z_AXIS);
  4965. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  4966. ext_position = st_get_position_mm(E_AXIS);
  4967. if (code_seen('X') || code_seen('x') ) {
  4968. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  4969. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  4970. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  4971. goto Sigma_Exit;
  4972. }
  4973. }
  4974. if (code_seen('Y') || code_seen('y') ) {
  4975. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  4976. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  4977. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  4978. goto Sigma_Exit;
  4979. }
  4980. }
  4981. if (code_seen('L') || code_seen('l') ) {
  4982. n_legs = code_value();
  4983. if ( n_legs==1 )
  4984. n_legs = 2;
  4985. if ( n_legs<0 || n_legs>15 ) {
  4986. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  4987. goto Sigma_Exit;
  4988. }
  4989. }
  4990. //
  4991. // Do all the preliminary setup work. First raise the probe.
  4992. //
  4993. st_synchronize();
  4994. plan_bed_level_matrix.set_to_identity();
  4995. plan_buffer_line( X_current, Y_current, Z_start_location,
  4996. ext_position,
  4997. homing_feedrate[Z_AXIS]/60,
  4998. active_extruder);
  4999. st_synchronize();
  5000. //
  5001. // Now get everything to the specified probe point So we can safely do a probe to
  5002. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  5003. // use that as a starting point for each probe.
  5004. //
  5005. if (verbose_level > 2)
  5006. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  5007. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5008. ext_position,
  5009. homing_feedrate[X_AXIS]/60,
  5010. active_extruder);
  5011. st_synchronize();
  5012. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  5013. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  5014. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5015. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  5016. //
  5017. // OK, do the inital probe to get us close to the bed.
  5018. // Then retrace the right amount and use that in subsequent probes
  5019. //
  5020. int l_feedmultiply = setup_for_endstop_move();
  5021. run_z_probe();
  5022. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5023. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5024. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5025. ext_position,
  5026. homing_feedrate[X_AXIS]/60,
  5027. active_extruder);
  5028. st_synchronize();
  5029. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5030. for( n=0; n<n_samples; n++) {
  5031. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  5032. if ( n_legs) {
  5033. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  5034. int rotational_direction, l;
  5035. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  5036. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  5037. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  5038. //SERIAL_ECHOPAIR("starting radius: ",radius);
  5039. //SERIAL_ECHOPAIR(" theta: ",theta);
  5040. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  5041. //SERIAL_PROTOCOLLNPGM("");
  5042. for( l=0; l<n_legs-1; l++) {
  5043. if (rotational_direction==1)
  5044. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5045. else
  5046. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5047. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  5048. if ( radius<0.0 )
  5049. radius = -radius;
  5050. X_current = X_probe_location + cos(theta) * radius;
  5051. Y_current = Y_probe_location + sin(theta) * radius;
  5052. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  5053. X_current = X_MIN_POS;
  5054. if ( X_current>X_MAX_POS)
  5055. X_current = X_MAX_POS;
  5056. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  5057. Y_current = Y_MIN_POS;
  5058. if ( Y_current>Y_MAX_POS)
  5059. Y_current = Y_MAX_POS;
  5060. if (verbose_level>3 ) {
  5061. SERIAL_ECHOPAIR("x: ", X_current);
  5062. SERIAL_ECHOPAIR("y: ", Y_current);
  5063. SERIAL_PROTOCOLLNPGM("");
  5064. }
  5065. do_blocking_move_to( X_current, Y_current, Z_current );
  5066. }
  5067. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5068. }
  5069. int l_feedmultiply = setup_for_endstop_move();
  5070. run_z_probe();
  5071. sample_set[n] = current_position[Z_AXIS];
  5072. //
  5073. // Get the current mean for the data points we have so far
  5074. //
  5075. sum=0.0;
  5076. for( j=0; j<=n; j++) {
  5077. sum = sum + sample_set[j];
  5078. }
  5079. mean = sum / (double (n+1));
  5080. //
  5081. // Now, use that mean to calculate the standard deviation for the
  5082. // data points we have so far
  5083. //
  5084. sum=0.0;
  5085. for( j=0; j<=n; j++) {
  5086. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5087. }
  5088. sigma = sqrt( sum / (double (n+1)) );
  5089. if (verbose_level > 1) {
  5090. SERIAL_PROTOCOL(n+1);
  5091. SERIAL_PROTOCOL(" of ");
  5092. SERIAL_PROTOCOL(n_samples);
  5093. SERIAL_PROTOCOLPGM(" z: ");
  5094. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5095. }
  5096. if (verbose_level > 2) {
  5097. SERIAL_PROTOCOL(" mean: ");
  5098. SERIAL_PROTOCOL_F(mean,6);
  5099. SERIAL_PROTOCOL(" sigma: ");
  5100. SERIAL_PROTOCOL_F(sigma,6);
  5101. }
  5102. if (verbose_level > 0)
  5103. SERIAL_PROTOCOLPGM("\n");
  5104. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5105. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5106. st_synchronize();
  5107. }
  5108. _delay(1000);
  5109. clean_up_after_endstop_move(l_feedmultiply);
  5110. // enable_endstops(true);
  5111. if (verbose_level > 0) {
  5112. SERIAL_PROTOCOLPGM("Mean: ");
  5113. SERIAL_PROTOCOL_F(mean, 6);
  5114. SERIAL_PROTOCOLPGM("\n");
  5115. }
  5116. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5117. SERIAL_PROTOCOL_F(sigma, 6);
  5118. SERIAL_PROTOCOLPGM("\n\n");
  5119. Sigma_Exit:
  5120. break;
  5121. }
  5122. #endif // Z_PROBE_REPEATABILITY_TEST
  5123. #endif // ENABLE_AUTO_BED_LEVELING
  5124. //! ### M73 - Set/get print progress
  5125. // -------------------------------------
  5126. //! _Usage:_
  5127. //!
  5128. //! M73 P<percent> R<time_remaining> Q<percent_silent> S<time_remaining_silent>
  5129. //!
  5130. case 73: //M73 show percent done and time remaining
  5131. if(code_seen('P')) print_percent_done_normal = code_value();
  5132. if(code_seen('R')) print_time_remaining_normal = code_value();
  5133. if(code_seen('Q')) print_percent_done_silent = code_value();
  5134. if(code_seen('S')) print_time_remaining_silent = code_value();
  5135. {
  5136. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %d; print time remaining in mins: %d\n");
  5137. printf_P(_msg_mode_done_remain, _N("NORMAL"), int(print_percent_done_normal), print_time_remaining_normal);
  5138. printf_P(_msg_mode_done_remain, _N("SILENT"), int(print_percent_done_silent), print_time_remaining_silent);
  5139. }
  5140. break;
  5141. //! ### M104 - Set hotend temperature
  5142. // -----------------------------------------
  5143. case 104: // M104
  5144. {
  5145. uint8_t extruder;
  5146. if(setTargetedHotend(104,extruder)){
  5147. break;
  5148. }
  5149. if (code_seen('S'))
  5150. {
  5151. setTargetHotendSafe(code_value(), extruder);
  5152. }
  5153. break;
  5154. }
  5155. //! ### M112 - Emergency stop
  5156. // -----------------------------------------
  5157. case 112:
  5158. kill(MSG_M112_KILL, 3);
  5159. break;
  5160. //! ### M140 - Set bed temperature
  5161. // -----------------------------------------
  5162. case 140:
  5163. if (code_seen('S')) setTargetBed(code_value());
  5164. break;
  5165. //! ### M105 - Report temperatures
  5166. // -----------------------------------------
  5167. case 105:
  5168. {
  5169. uint8_t extruder;
  5170. if(setTargetedHotend(105, extruder)){
  5171. break;
  5172. }
  5173. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  5174. SERIAL_PROTOCOLPGM("ok T:");
  5175. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  5176. SERIAL_PROTOCOLPGM(" /");
  5177. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  5178. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5179. SERIAL_PROTOCOLPGM(" B:");
  5180. SERIAL_PROTOCOL_F(degBed(),1);
  5181. SERIAL_PROTOCOLPGM(" /");
  5182. SERIAL_PROTOCOL_F(degTargetBed(),1);
  5183. #endif //TEMP_BED_PIN
  5184. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  5185. SERIAL_PROTOCOLPGM(" T");
  5186. SERIAL_PROTOCOL(cur_extruder);
  5187. SERIAL_PROTOCOLPGM(":");
  5188. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  5189. SERIAL_PROTOCOLPGM(" /");
  5190. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  5191. }
  5192. #else
  5193. SERIAL_ERROR_START;
  5194. SERIAL_ERRORLNRPGM(_i("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  5195. #endif
  5196. SERIAL_PROTOCOLPGM(" @:");
  5197. #ifdef EXTRUDER_WATTS
  5198. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  5199. SERIAL_PROTOCOLPGM("W");
  5200. #else
  5201. SERIAL_PROTOCOL(getHeaterPower(extruder));
  5202. #endif
  5203. SERIAL_PROTOCOLPGM(" B@:");
  5204. #ifdef BED_WATTS
  5205. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  5206. SERIAL_PROTOCOLPGM("W");
  5207. #else
  5208. SERIAL_PROTOCOL(getHeaterPower(-1));
  5209. #endif
  5210. #ifdef PINDA_THERMISTOR
  5211. SERIAL_PROTOCOLPGM(" P:");
  5212. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  5213. #endif //PINDA_THERMISTOR
  5214. #ifdef AMBIENT_THERMISTOR
  5215. SERIAL_PROTOCOLPGM(" A:");
  5216. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  5217. #endif //AMBIENT_THERMISTOR
  5218. #ifdef SHOW_TEMP_ADC_VALUES
  5219. {float raw = 0.0;
  5220. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5221. SERIAL_PROTOCOLPGM(" ADC B:");
  5222. SERIAL_PROTOCOL_F(degBed(),1);
  5223. SERIAL_PROTOCOLPGM("C->");
  5224. raw = rawBedTemp();
  5225. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  5226. SERIAL_PROTOCOLPGM(" Rb->");
  5227. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  5228. SERIAL_PROTOCOLPGM(" Rxb->");
  5229. SERIAL_PROTOCOL_F(raw, 5);
  5230. #endif
  5231. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  5232. SERIAL_PROTOCOLPGM(" T");
  5233. SERIAL_PROTOCOL(cur_extruder);
  5234. SERIAL_PROTOCOLPGM(":");
  5235. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  5236. SERIAL_PROTOCOLPGM("C->");
  5237. raw = rawHotendTemp(cur_extruder);
  5238. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  5239. SERIAL_PROTOCOLPGM(" Rt");
  5240. SERIAL_PROTOCOL(cur_extruder);
  5241. SERIAL_PROTOCOLPGM("->");
  5242. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  5243. SERIAL_PROTOCOLPGM(" Rx");
  5244. SERIAL_PROTOCOL(cur_extruder);
  5245. SERIAL_PROTOCOLPGM("->");
  5246. SERIAL_PROTOCOL_F(raw, 5);
  5247. }}
  5248. #endif
  5249. SERIAL_PROTOCOLLN("");
  5250. KEEPALIVE_STATE(NOT_BUSY);
  5251. return;
  5252. break;
  5253. }
  5254. //! ### M109 - Wait for extruder temperature
  5255. //! Parameters (not mandatory):
  5256. //! * S \<temp\> set extruder temperature
  5257. //! * R \<temp\> set extruder temperature
  5258. //!
  5259. //! Parameters S and R are treated identically.
  5260. //! Command always waits for both cool down and heat up.
  5261. //! If no parameters are supplied waits for previously
  5262. //! set extruder temperature.
  5263. // -------------------------------------------------
  5264. case 109:
  5265. {
  5266. uint8_t extruder;
  5267. if(setTargetedHotend(109, extruder)){
  5268. break;
  5269. }
  5270. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5271. heating_status = 1;
  5272. if (farm_mode) { prusa_statistics(1); };
  5273. #ifdef AUTOTEMP
  5274. autotemp_enabled=false;
  5275. #endif
  5276. if (code_seen('S')) {
  5277. setTargetHotendSafe(code_value(), extruder);
  5278. } else if (code_seen('R')) {
  5279. setTargetHotendSafe(code_value(), extruder);
  5280. }
  5281. #ifdef AUTOTEMP
  5282. if (code_seen('S')) autotemp_min=code_value();
  5283. if (code_seen('B')) autotemp_max=code_value();
  5284. if (code_seen('F'))
  5285. {
  5286. autotemp_factor=code_value();
  5287. autotemp_enabled=true;
  5288. }
  5289. #endif
  5290. codenum = _millis();
  5291. /* See if we are heating up or cooling down */
  5292. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5293. KEEPALIVE_STATE(NOT_BUSY);
  5294. cancel_heatup = false;
  5295. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5296. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5297. KEEPALIVE_STATE(IN_HANDLER);
  5298. heating_status = 2;
  5299. if (farm_mode) { prusa_statistics(2); };
  5300. //starttime=_millis();
  5301. previous_millis_cmd = _millis();
  5302. }
  5303. break;
  5304. //! ### M190 - Wait for bed temperature
  5305. //! Parameters (not mandatory):
  5306. //! * S \<temp\> set extruder temperature and wait for heating
  5307. //! * R \<temp\> set extruder temperature and wait for heating or cooling
  5308. //!
  5309. //! If no parameter is supplied, waits for heating or cooling to previously set temperature.
  5310. case 190:
  5311. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5312. {
  5313. bool CooldownNoWait = false;
  5314. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5315. heating_status = 3;
  5316. if (farm_mode) { prusa_statistics(1); };
  5317. if (code_seen('S'))
  5318. {
  5319. setTargetBed(code_value());
  5320. CooldownNoWait = true;
  5321. }
  5322. else if (code_seen('R'))
  5323. {
  5324. setTargetBed(code_value());
  5325. }
  5326. codenum = _millis();
  5327. cancel_heatup = false;
  5328. target_direction = isHeatingBed(); // true if heating, false if cooling
  5329. KEEPALIVE_STATE(NOT_BUSY);
  5330. while ( (target_direction)&&(!cancel_heatup) ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false)) )
  5331. {
  5332. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5333. {
  5334. if (!farm_mode) {
  5335. float tt = degHotend(active_extruder);
  5336. SERIAL_PROTOCOLPGM("T:");
  5337. SERIAL_PROTOCOL(tt);
  5338. SERIAL_PROTOCOLPGM(" E:");
  5339. SERIAL_PROTOCOL((int)active_extruder);
  5340. SERIAL_PROTOCOLPGM(" B:");
  5341. SERIAL_PROTOCOL_F(degBed(), 1);
  5342. SERIAL_PROTOCOLLN("");
  5343. }
  5344. codenum = _millis();
  5345. }
  5346. manage_heater();
  5347. manage_inactivity();
  5348. lcd_update(0);
  5349. }
  5350. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5351. KEEPALIVE_STATE(IN_HANDLER);
  5352. heating_status = 4;
  5353. previous_millis_cmd = _millis();
  5354. }
  5355. #endif
  5356. break;
  5357. #if defined(FAN_PIN) && FAN_PIN > -1
  5358. //! ### M106 - Set fan speed
  5359. // -------------------------------------------
  5360. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5361. if (code_seen('S')){
  5362. fanSpeed=constrain(code_value(),0,255);
  5363. }
  5364. else {
  5365. fanSpeed=255;
  5366. }
  5367. break;
  5368. //! ### M107 - Fan off
  5369. // -------------------------------
  5370. case 107:
  5371. fanSpeed = 0;
  5372. break;
  5373. #endif //FAN_PIN
  5374. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5375. //! ### M80 - Turn on the Power Supply
  5376. // -------------------------------
  5377. case 80:
  5378. SET_OUTPUT(PS_ON_PIN); //GND
  5379. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5380. // If you have a switch on suicide pin, this is useful
  5381. // if you want to start another print with suicide feature after
  5382. // a print without suicide...
  5383. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5384. SET_OUTPUT(SUICIDE_PIN);
  5385. WRITE(SUICIDE_PIN, HIGH);
  5386. #endif
  5387. powersupply = true;
  5388. LCD_MESSAGERPGM(_T(WELCOME_MSG));
  5389. lcd_update(0);
  5390. break;
  5391. //! ### M81 - Turn off Power Supply
  5392. // --------------------------------------
  5393. case 81:
  5394. disable_heater();
  5395. st_synchronize();
  5396. disable_e0();
  5397. disable_e1();
  5398. disable_e2();
  5399. finishAndDisableSteppers();
  5400. fanSpeed = 0;
  5401. _delay(1000); // Wait a little before to switch off
  5402. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5403. st_synchronize();
  5404. suicide();
  5405. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5406. SET_OUTPUT(PS_ON_PIN);
  5407. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5408. #endif
  5409. powersupply = false;
  5410. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5411. lcd_update(0);
  5412. break;
  5413. #endif
  5414. //! ### M82 - Set E axis to absolute mode
  5415. // ---------------------------------------
  5416. case 82:
  5417. axis_relative_modes[E_AXIS] = false;
  5418. break;
  5419. //! ### M83 - Set E axis to relative mode
  5420. // ---------------------------------------
  5421. case 83:
  5422. axis_relative_modes[E_AXIS] = true;
  5423. break;
  5424. //! ### M84, M18 - Disable steppers
  5425. //---------------------------------------
  5426. //! This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5427. //!
  5428. //! M84 [E<flag>] [S<seconds>] [X<flag>] [Y<flag>] [Z<flag>]
  5429. //!
  5430. case 18: //compatibility
  5431. case 84: // M84
  5432. if(code_seen('S')){
  5433. stepper_inactive_time = code_value() * 1000;
  5434. }
  5435. else
  5436. {
  5437. 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])));
  5438. if(all_axis)
  5439. {
  5440. st_synchronize();
  5441. disable_e0();
  5442. disable_e1();
  5443. disable_e2();
  5444. finishAndDisableSteppers();
  5445. }
  5446. else
  5447. {
  5448. st_synchronize();
  5449. if (code_seen('X')) disable_x();
  5450. if (code_seen('Y')) disable_y();
  5451. if (code_seen('Z')) disable_z();
  5452. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5453. if (code_seen('E')) {
  5454. disable_e0();
  5455. disable_e1();
  5456. disable_e2();
  5457. }
  5458. #endif
  5459. }
  5460. }
  5461. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  5462. print_time_remaining_init();
  5463. snmm_filaments_used = 0;
  5464. break;
  5465. //! ### M85 - Set max inactive time
  5466. // ---------------------------------------
  5467. case 85: // M85
  5468. if(code_seen('S')) {
  5469. max_inactive_time = code_value() * 1000;
  5470. }
  5471. break;
  5472. #ifdef SAFETYTIMER
  5473. //! ### M86 - Set safety timer expiration time
  5474. //!
  5475. //! _Usage:_
  5476. //! M86 S<seconds>
  5477. //!
  5478. //! Sets the safety timer expiration time in seconds. M86 S0 will disable safety timer.
  5479. //! When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5480. case 86:
  5481. if (code_seen('S')) {
  5482. safetytimer_inactive_time = code_value() * 1000;
  5483. safetyTimer.start();
  5484. }
  5485. break;
  5486. #endif
  5487. //! ### M92 Set Axis steps-per-unit
  5488. // ---------------------------------------
  5489. //! Same syntax as G92
  5490. case 92:
  5491. for(int8_t i=0; i < NUM_AXIS; i++)
  5492. {
  5493. if(code_seen(axis_codes[i]))
  5494. {
  5495. if(i == 3) { // E
  5496. float value = code_value();
  5497. if(value < 20.0) {
  5498. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5499. cs.max_jerk[E_AXIS] *= factor;
  5500. max_feedrate[i] *= factor;
  5501. axis_steps_per_sqr_second[i] *= factor;
  5502. }
  5503. cs.axis_steps_per_unit[i] = value;
  5504. }
  5505. else {
  5506. cs.axis_steps_per_unit[i] = code_value();
  5507. }
  5508. }
  5509. }
  5510. break;
  5511. //! ### M110 - Set Line number
  5512. // ---------------------------------------
  5513. case 110:
  5514. if (code_seen('N'))
  5515. gcode_LastN = code_value_long();
  5516. break;
  5517. //! ### M113 - Get or set host keep-alive interval
  5518. // ------------------------------------------
  5519. case 113:
  5520. if (code_seen('S')) {
  5521. host_keepalive_interval = (uint8_t)code_value_short();
  5522. // NOMORE(host_keepalive_interval, 60);
  5523. }
  5524. else {
  5525. SERIAL_ECHO_START;
  5526. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5527. SERIAL_PROTOCOLLN("");
  5528. }
  5529. break;
  5530. //! ### M115 - Firmware info
  5531. // --------------------------------------
  5532. //! Print the firmware info and capabilities
  5533. //!
  5534. //! M115 [V] [U<version>]
  5535. //!
  5536. //! Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5537. //! `M115 U` Checks the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5538. //! pause the print for 30s and ask the user to upgrade the firmware.
  5539. case 115: // M115
  5540. if (code_seen('V')) {
  5541. // Report the Prusa version number.
  5542. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5543. } else if (code_seen('U')) {
  5544. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5545. // pause the print for 30s and ask the user to upgrade the firmware.
  5546. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5547. } else {
  5548. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5549. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5550. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5551. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5552. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5553. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5554. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5555. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5556. SERIAL_ECHOPGM(" UUID:");
  5557. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5558. }
  5559. break;
  5560. //! ### M114 - Get current position
  5561. // -------------------------------------
  5562. case 114:
  5563. gcode_M114();
  5564. break;
  5565. //! ### M117 - Set LCD Message
  5566. // --------------------------------------
  5567. /*
  5568. M117 moved up to get the high priority
  5569. case 117: // M117 display message
  5570. starpos = (strchr(strchr_pointer + 5,'*'));
  5571. if(starpos!=NULL)
  5572. *(starpos)='\0';
  5573. lcd_setstatus(strchr_pointer + 5);
  5574. break;*/
  5575. //! ### M120 - Disable endstops
  5576. // ----------------------------------------
  5577. case 120:
  5578. enable_endstops(false) ;
  5579. break;
  5580. //! ### M121 - Enable endstops
  5581. // ----------------------------------------
  5582. case 121:
  5583. enable_endstops(true) ;
  5584. break;
  5585. //! ### M119 - Get endstop states
  5586. // ----------------------------------------
  5587. case 119:
  5588. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5589. SERIAL_PROTOCOLLN("");
  5590. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5591. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5592. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5593. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5594. }else{
  5595. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5596. }
  5597. SERIAL_PROTOCOLLN("");
  5598. #endif
  5599. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5600. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5601. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5602. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5603. }else{
  5604. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5605. }
  5606. SERIAL_PROTOCOLLN("");
  5607. #endif
  5608. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5609. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5610. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5611. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5612. }else{
  5613. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5614. }
  5615. SERIAL_PROTOCOLLN("");
  5616. #endif
  5617. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5618. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5619. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5620. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5621. }else{
  5622. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5623. }
  5624. SERIAL_PROTOCOLLN("");
  5625. #endif
  5626. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5627. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5628. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5629. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5630. }else{
  5631. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5632. }
  5633. SERIAL_PROTOCOLLN("");
  5634. #endif
  5635. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5636. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5637. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5638. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5639. }else{
  5640. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5641. }
  5642. SERIAL_PROTOCOLLN("");
  5643. #endif
  5644. break;
  5645. //TODO: update for all axis, use for loop
  5646. #ifdef BLINKM
  5647. //! ### M150 - Set RGB(W) Color
  5648. // -------------------------------------------
  5649. case 150:
  5650. {
  5651. byte red;
  5652. byte grn;
  5653. byte blu;
  5654. if(code_seen('R')) red = code_value();
  5655. if(code_seen('U')) grn = code_value();
  5656. if(code_seen('B')) blu = code_value();
  5657. SendColors(red,grn,blu);
  5658. }
  5659. break;
  5660. #endif //BLINKM
  5661. //! ### M200 - Set filament diameter
  5662. // ----------------------------------------
  5663. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5664. {
  5665. uint8_t extruder = active_extruder;
  5666. if(code_seen('T')) {
  5667. extruder = code_value();
  5668. if(extruder >= EXTRUDERS) {
  5669. SERIAL_ECHO_START;
  5670. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  5671. break;
  5672. }
  5673. }
  5674. if(code_seen('D')) {
  5675. float diameter = (float)code_value();
  5676. if (diameter == 0.0) {
  5677. // setting any extruder filament size disables volumetric on the assumption that
  5678. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5679. // for all extruders
  5680. cs.volumetric_enabled = false;
  5681. } else {
  5682. cs.filament_size[extruder] = (float)code_value();
  5683. // make sure all extruders have some sane value for the filament size
  5684. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5685. #if EXTRUDERS > 1
  5686. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5687. #if EXTRUDERS > 2
  5688. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5689. #endif
  5690. #endif
  5691. cs.volumetric_enabled = true;
  5692. }
  5693. } else {
  5694. //reserved for setting filament diameter via UFID or filament measuring device
  5695. break;
  5696. }
  5697. calculate_extruder_multipliers();
  5698. }
  5699. break;
  5700. //! ### M201 - Set Print Max Acceleration
  5701. // -------------------------------------------
  5702. case 201:
  5703. for (int8_t i = 0; i < NUM_AXIS; i++)
  5704. {
  5705. if (code_seen(axis_codes[i]))
  5706. {
  5707. unsigned long val = code_value();
  5708. #ifdef TMC2130
  5709. unsigned long val_silent = val;
  5710. if ((i == X_AXIS) || (i == Y_AXIS))
  5711. {
  5712. if (val > NORMAL_MAX_ACCEL_XY)
  5713. val = NORMAL_MAX_ACCEL_XY;
  5714. if (val_silent > SILENT_MAX_ACCEL_XY)
  5715. val_silent = SILENT_MAX_ACCEL_XY;
  5716. }
  5717. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  5718. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  5719. #else //TMC2130
  5720. max_acceleration_units_per_sq_second[i] = val;
  5721. #endif //TMC2130
  5722. }
  5723. }
  5724. // 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)
  5725. reset_acceleration_rates();
  5726. break;
  5727. #if 0 // Not used for Sprinter/grbl gen6
  5728. case 202: // M202
  5729. for(int8_t i=0; i < NUM_AXIS; i++) {
  5730. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  5731. }
  5732. break;
  5733. #endif
  5734. //! ### M203 - Set Max Feedrate
  5735. // ---------------------------------------
  5736. case 203: // M203 max feedrate mm/sec
  5737. for (int8_t i = 0; i < NUM_AXIS; i++)
  5738. {
  5739. if (code_seen(axis_codes[i]))
  5740. {
  5741. float val = code_value();
  5742. #ifdef TMC2130
  5743. float val_silent = val;
  5744. if ((i == X_AXIS) || (i == Y_AXIS))
  5745. {
  5746. if (val > NORMAL_MAX_FEEDRATE_XY)
  5747. val = NORMAL_MAX_FEEDRATE_XY;
  5748. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  5749. val_silent = SILENT_MAX_FEEDRATE_XY;
  5750. }
  5751. cs.max_feedrate_normal[i] = val;
  5752. cs.max_feedrate_silent[i] = val_silent;
  5753. #else //TMC2130
  5754. max_feedrate[i] = val;
  5755. #endif //TMC2130
  5756. }
  5757. }
  5758. break;
  5759. //! ### M204 - Acceleration settings
  5760. // ------------------------------------------
  5761. //! Supporting old format:
  5762. //!
  5763. //! M204 S[normal moves] T[filmanent only moves]
  5764. //!
  5765. //! and new format:
  5766. //!
  5767. //! M204 P[printing moves] R[filmanent only moves] T[travel moves] (as of now T is ignored)
  5768. case 204:
  5769. {
  5770. if(code_seen('S')) {
  5771. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  5772. // and it is also generated by Slic3r to control acceleration per extrusion type
  5773. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  5774. cs.acceleration = code_value();
  5775. // Interpret the T value as retract acceleration in the old Marlin format.
  5776. if(code_seen('T'))
  5777. cs.retract_acceleration = code_value();
  5778. } else {
  5779. // New acceleration format, compatible with the upstream Marlin.
  5780. if(code_seen('P'))
  5781. cs.acceleration = code_value();
  5782. if(code_seen('R'))
  5783. cs.retract_acceleration = code_value();
  5784. if(code_seen('T')) {
  5785. // Interpret the T value as the travel acceleration in the new Marlin format.
  5786. //FIXME Prusa3D firmware currently does not support travel acceleration value independent from the extruding acceleration value.
  5787. // travel_acceleration = code_value();
  5788. }
  5789. }
  5790. }
  5791. break;
  5792. //! ### M205 - Set advanced settings
  5793. // ---------------------------------------------
  5794. //! Set some advanced settings related to movement.
  5795. //!
  5796. //! M205 [S] [T] [B] [X] [Y] [Z] [E]
  5797. /*!
  5798. - `S` - Minimum feedrate for print moves (unit/s)
  5799. - `T` - Minimum feedrate for travel moves (units/s)
  5800. - `B` - Minimum segment time (us)
  5801. - `X` - Maximum X jerk (units/s), similarly for other axes
  5802. */
  5803. case 205:
  5804. {
  5805. if(code_seen('S')) cs.minimumfeedrate = code_value();
  5806. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  5807. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  5808. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  5809. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  5810. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  5811. if(code_seen('E')) cs.max_jerk[E_AXIS] = code_value();
  5812. if (cs.max_jerk[X_AXIS] > DEFAULT_XJERK) cs.max_jerk[X_AXIS] = DEFAULT_XJERK;
  5813. if (cs.max_jerk[Y_AXIS] > DEFAULT_YJERK) cs.max_jerk[Y_AXIS] = DEFAULT_YJERK;
  5814. }
  5815. break;
  5816. //! ### M206 - Set additional homing offsets
  5817. // ----------------------------------------------
  5818. case 206:
  5819. for(int8_t i=0; i < 3; i++)
  5820. {
  5821. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  5822. }
  5823. break;
  5824. #ifdef FWRETRACT
  5825. //! ### M207 - Set firmware retraction
  5826. // --------------------------------------------------
  5827. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  5828. {
  5829. if(code_seen('S'))
  5830. {
  5831. cs.retract_length = code_value() ;
  5832. }
  5833. if(code_seen('F'))
  5834. {
  5835. cs.retract_feedrate = code_value()/60 ;
  5836. }
  5837. if(code_seen('Z'))
  5838. {
  5839. cs.retract_zlift = code_value() ;
  5840. }
  5841. }break;
  5842. //! ### M208 - Set retract recover length
  5843. // --------------------------------------------
  5844. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  5845. {
  5846. if(code_seen('S'))
  5847. {
  5848. cs.retract_recover_length = code_value() ;
  5849. }
  5850. if(code_seen('F'))
  5851. {
  5852. cs.retract_recover_feedrate = code_value()/60 ;
  5853. }
  5854. }break;
  5855. //! ### M209 - Enable/disable automatict retract
  5856. // ---------------------------------------------
  5857. 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.
  5858. {
  5859. if(code_seen('S'))
  5860. {
  5861. int t= code_value() ;
  5862. switch(t)
  5863. {
  5864. case 0:
  5865. {
  5866. cs.autoretract_enabled=false;
  5867. retracted[0]=false;
  5868. #if EXTRUDERS > 1
  5869. retracted[1]=false;
  5870. #endif
  5871. #if EXTRUDERS > 2
  5872. retracted[2]=false;
  5873. #endif
  5874. }break;
  5875. case 1:
  5876. {
  5877. cs.autoretract_enabled=true;
  5878. retracted[0]=false;
  5879. #if EXTRUDERS > 1
  5880. retracted[1]=false;
  5881. #endif
  5882. #if EXTRUDERS > 2
  5883. retracted[2]=false;
  5884. #endif
  5885. }break;
  5886. default:
  5887. SERIAL_ECHO_START;
  5888. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  5889. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  5890. SERIAL_ECHOLNPGM("\"(1)");
  5891. }
  5892. }
  5893. }break;
  5894. #endif // FWRETRACT
  5895. #if EXTRUDERS > 1
  5896. // ### M218 - Set hotend offset
  5897. // ----------------------------------------
  5898. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  5899. {
  5900. uint8_t extruder;
  5901. if(setTargetedHotend(218, extruder)){
  5902. break;
  5903. }
  5904. if(code_seen('X'))
  5905. {
  5906. extruder_offset[X_AXIS][extruder] = code_value();
  5907. }
  5908. if(code_seen('Y'))
  5909. {
  5910. extruder_offset[Y_AXIS][extruder] = code_value();
  5911. }
  5912. SERIAL_ECHO_START;
  5913. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  5914. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  5915. {
  5916. SERIAL_ECHO(" ");
  5917. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  5918. SERIAL_ECHO(",");
  5919. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  5920. }
  5921. SERIAL_ECHOLN("");
  5922. }break;
  5923. #endif
  5924. //! ### M220 Set feedrate percentage
  5925. // -----------------------------------------------
  5926. case 220: // M220 S<factor in percent>- set speed factor override percentage
  5927. {
  5928. if (code_seen('B')) //backup current speed factor
  5929. {
  5930. saved_feedmultiply_mm = feedmultiply;
  5931. }
  5932. if(code_seen('S'))
  5933. {
  5934. feedmultiply = code_value() ;
  5935. }
  5936. if (code_seen('R')) { //restore previous feedmultiply
  5937. feedmultiply = saved_feedmultiply_mm;
  5938. }
  5939. }
  5940. break;
  5941. //! ### M221 - Set extrude factor override percentage
  5942. // ----------------------------------------------------
  5943. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  5944. {
  5945. if(code_seen('S'))
  5946. {
  5947. int tmp_code = code_value();
  5948. if (code_seen('T'))
  5949. {
  5950. uint8_t extruder;
  5951. if(setTargetedHotend(221, extruder)){
  5952. break;
  5953. }
  5954. extruder_multiply[extruder] = tmp_code;
  5955. }
  5956. else
  5957. {
  5958. extrudemultiply = tmp_code ;
  5959. }
  5960. }
  5961. calculate_extruder_multipliers();
  5962. }
  5963. break;
  5964. //! ### M226 - Wait for Pin state
  5965. // ------------------------------------------
  5966. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  5967. {
  5968. if(code_seen('P')){
  5969. int pin_number = code_value(); // pin number
  5970. int pin_state = -1; // required pin state - default is inverted
  5971. if(code_seen('S')) pin_state = code_value(); // required pin state
  5972. if(pin_state >= -1 && pin_state <= 1){
  5973. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  5974. {
  5975. if (sensitive_pins[i] == pin_number)
  5976. {
  5977. pin_number = -1;
  5978. break;
  5979. }
  5980. }
  5981. if (pin_number > -1)
  5982. {
  5983. int target = LOW;
  5984. st_synchronize();
  5985. pinMode(pin_number, INPUT);
  5986. switch(pin_state){
  5987. case 1:
  5988. target = HIGH;
  5989. break;
  5990. case 0:
  5991. target = LOW;
  5992. break;
  5993. case -1:
  5994. target = !digitalRead(pin_number);
  5995. break;
  5996. }
  5997. while(digitalRead(pin_number) != target){
  5998. manage_heater();
  5999. manage_inactivity();
  6000. lcd_update(0);
  6001. }
  6002. }
  6003. }
  6004. }
  6005. }
  6006. break;
  6007. #if NUM_SERVOS > 0
  6008. //! ### M280 - Set/Get servo position
  6009. // --------------------------------------------
  6010. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6011. {
  6012. int servo_index = -1;
  6013. int servo_position = 0;
  6014. if (code_seen('P'))
  6015. servo_index = code_value();
  6016. if (code_seen('S')) {
  6017. servo_position = code_value();
  6018. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  6019. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6020. servos[servo_index].attach(0);
  6021. #endif
  6022. servos[servo_index].write(servo_position);
  6023. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6024. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  6025. servos[servo_index].detach();
  6026. #endif
  6027. }
  6028. else {
  6029. SERIAL_ECHO_START;
  6030. SERIAL_ECHO("Servo ");
  6031. SERIAL_ECHO(servo_index);
  6032. SERIAL_ECHOLN(" out of range");
  6033. }
  6034. }
  6035. else if (servo_index >= 0) {
  6036. SERIAL_PROTOCOL(MSG_OK);
  6037. SERIAL_PROTOCOL(" Servo ");
  6038. SERIAL_PROTOCOL(servo_index);
  6039. SERIAL_PROTOCOL(": ");
  6040. SERIAL_PROTOCOL(servos[servo_index].read());
  6041. SERIAL_PROTOCOLLN("");
  6042. }
  6043. }
  6044. break;
  6045. #endif // NUM_SERVOS > 0
  6046. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  6047. //! ### M300 - Play tone
  6048. // -----------------------
  6049. case 300: // M300
  6050. {
  6051. int beepS = code_seen('S') ? code_value() : 110;
  6052. int beepP = code_seen('P') ? code_value() : 1000;
  6053. if (beepS > 0)
  6054. {
  6055. #if BEEPER > 0
  6056. Sound_MakeCustom(beepP,beepS,false);
  6057. #endif
  6058. }
  6059. else
  6060. {
  6061. _delay(beepP);
  6062. }
  6063. }
  6064. break;
  6065. #endif // M300
  6066. #ifdef PIDTEMP
  6067. //! ### M301 - Set hotend PID
  6068. // ---------------------------------------
  6069. case 301:
  6070. {
  6071. if(code_seen('P')) cs.Kp = code_value();
  6072. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  6073. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6074. #ifdef PID_ADD_EXTRUSION_RATE
  6075. if(code_seen('C')) Kc = code_value();
  6076. #endif
  6077. updatePID();
  6078. SERIAL_PROTOCOLRPGM(MSG_OK);
  6079. SERIAL_PROTOCOL(" p:");
  6080. SERIAL_PROTOCOL(cs.Kp);
  6081. SERIAL_PROTOCOL(" i:");
  6082. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6083. SERIAL_PROTOCOL(" d:");
  6084. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6085. #ifdef PID_ADD_EXTRUSION_RATE
  6086. SERIAL_PROTOCOL(" c:");
  6087. //Kc does not have scaling applied above, or in resetting defaults
  6088. SERIAL_PROTOCOL(Kc);
  6089. #endif
  6090. SERIAL_PROTOCOLLN("");
  6091. }
  6092. break;
  6093. #endif //PIDTEMP
  6094. #ifdef PIDTEMPBED
  6095. //! ### M304 - Set bed PID
  6096. // --------------------------------------
  6097. case 304:
  6098. {
  6099. if(code_seen('P')) cs.bedKp = code_value();
  6100. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6101. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6102. updatePID();
  6103. SERIAL_PROTOCOLRPGM(MSG_OK);
  6104. SERIAL_PROTOCOL(" p:");
  6105. SERIAL_PROTOCOL(cs.bedKp);
  6106. SERIAL_PROTOCOL(" i:");
  6107. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6108. SERIAL_PROTOCOL(" d:");
  6109. SERIAL_PROTOCOL(unscalePID_d(cs.bedKd));
  6110. SERIAL_PROTOCOLLN("");
  6111. }
  6112. break;
  6113. #endif //PIDTEMP
  6114. //! ### M240 - Trigger camera
  6115. // --------------------------------------------
  6116. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6117. {
  6118. #ifdef CHDK
  6119. SET_OUTPUT(CHDK);
  6120. WRITE(CHDK, HIGH);
  6121. chdkHigh = _millis();
  6122. chdkActive = true;
  6123. #else
  6124. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6125. const uint8_t NUM_PULSES=16;
  6126. const float PULSE_LENGTH=0.01524;
  6127. for(int i=0; i < NUM_PULSES; i++) {
  6128. WRITE(PHOTOGRAPH_PIN, HIGH);
  6129. _delay_ms(PULSE_LENGTH);
  6130. WRITE(PHOTOGRAPH_PIN, LOW);
  6131. _delay_ms(PULSE_LENGTH);
  6132. }
  6133. _delay(7.33);
  6134. for(int i=0; i < NUM_PULSES; i++) {
  6135. WRITE(PHOTOGRAPH_PIN, HIGH);
  6136. _delay_ms(PULSE_LENGTH);
  6137. WRITE(PHOTOGRAPH_PIN, LOW);
  6138. _delay_ms(PULSE_LENGTH);
  6139. }
  6140. #endif
  6141. #endif //chdk end if
  6142. }
  6143. break;
  6144. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6145. //! ### M302 - Allow cold extrude, or set minimum extrude temperature
  6146. // -------------------------------------------------------------------
  6147. case 302:
  6148. {
  6149. float temp = .0;
  6150. if (code_seen('S')) temp=code_value();
  6151. set_extrude_min_temp(temp);
  6152. }
  6153. break;
  6154. #endif
  6155. //! ### M303 - PID autotune
  6156. // -------------------------------------
  6157. case 303:
  6158. {
  6159. float temp = 150.0;
  6160. int e=0;
  6161. int c=5;
  6162. if (code_seen('E')) e=code_value();
  6163. if (e<0)
  6164. temp=70;
  6165. if (code_seen('S')) temp=code_value();
  6166. if (code_seen('C')) c=code_value();
  6167. PID_autotune(temp, e, c);
  6168. }
  6169. break;
  6170. //! ### M400 - Wait for all moves to finish
  6171. // -----------------------------------------
  6172. case 400:
  6173. {
  6174. st_synchronize();
  6175. }
  6176. break;
  6177. //! ### M403 - Set filament type (material) for particular extruder and notify the MMU
  6178. // ----------------------------------------------
  6179. case 403:
  6180. {
  6181. // currently three different materials are needed (default, flex and PVA)
  6182. // add storing this information for different load/unload profiles etc. in the future
  6183. // firmware does not wait for "ok" from mmu
  6184. if (mmu_enabled)
  6185. {
  6186. uint8_t extruder = 255;
  6187. uint8_t filament = FILAMENT_UNDEFINED;
  6188. if(code_seen('E')) extruder = code_value();
  6189. if(code_seen('F')) filament = code_value();
  6190. mmu_set_filament_type(extruder, filament);
  6191. }
  6192. }
  6193. break;
  6194. //! ### M500 - Store settings in EEPROM
  6195. // -----------------------------------------
  6196. case 500:
  6197. {
  6198. Config_StoreSettings();
  6199. }
  6200. break;
  6201. //! ### M501 - Read settings from EEPROM
  6202. // ----------------------------------------
  6203. case 501:
  6204. {
  6205. Config_RetrieveSettings();
  6206. }
  6207. break;
  6208. //! ### M502 - Revert all settings to factory default
  6209. // -------------------------------------------------
  6210. case 502:
  6211. {
  6212. Config_ResetDefault();
  6213. }
  6214. break;
  6215. //! ### M503 - Repport all settings currently in memory
  6216. // -------------------------------------------------
  6217. case 503:
  6218. {
  6219. Config_PrintSettings();
  6220. }
  6221. break;
  6222. //! ### M509 - Force language selection
  6223. // ------------------------------------------------
  6224. case 509:
  6225. {
  6226. lang_reset();
  6227. SERIAL_ECHO_START;
  6228. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6229. }
  6230. break;
  6231. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6232. //! ### M540 - Abort print on endstop hit (enable/disable)
  6233. // -----------------------------------------------------
  6234. case 540:
  6235. {
  6236. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6237. }
  6238. break;
  6239. #endif
  6240. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6241. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6242. {
  6243. float value;
  6244. if (code_seen('Z'))
  6245. {
  6246. value = code_value();
  6247. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6248. {
  6249. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6250. SERIAL_ECHO_START;
  6251. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6252. SERIAL_PROTOCOLLN("");
  6253. }
  6254. else
  6255. {
  6256. SERIAL_ECHO_START;
  6257. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6258. SERIAL_ECHORPGM(MSG_Z_MIN);
  6259. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6260. SERIAL_ECHORPGM(MSG_Z_MAX);
  6261. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6262. SERIAL_PROTOCOLLN("");
  6263. }
  6264. }
  6265. else
  6266. {
  6267. SERIAL_ECHO_START;
  6268. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6269. SERIAL_ECHO(-cs.zprobe_zoffset);
  6270. SERIAL_PROTOCOLLN("");
  6271. }
  6272. break;
  6273. }
  6274. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6275. #ifdef FILAMENTCHANGEENABLE
  6276. //! ### M600 - Initiate Filament change procedure
  6277. // --------------------------------------
  6278. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6279. {
  6280. st_synchronize();
  6281. float x_position = current_position[X_AXIS];
  6282. float y_position = current_position[Y_AXIS];
  6283. float z_shift = 0; // is it necessary to be a float?
  6284. float e_shift_init = 0;
  6285. float e_shift_late = 0;
  6286. bool automatic = false;
  6287. //Retract extruder
  6288. if(code_seen('E'))
  6289. {
  6290. e_shift_init = code_value();
  6291. }
  6292. else
  6293. {
  6294. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6295. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6296. #endif
  6297. }
  6298. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6299. if (code_seen('L'))
  6300. {
  6301. e_shift_late = code_value();
  6302. }
  6303. else
  6304. {
  6305. #ifdef FILAMENTCHANGE_FINALRETRACT
  6306. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6307. #endif
  6308. }
  6309. //Lift Z
  6310. if(code_seen('Z'))
  6311. {
  6312. z_shift = code_value();
  6313. }
  6314. else
  6315. {
  6316. z_shift = gcode_M600_filament_change_z_shift<uint8_t>();
  6317. }
  6318. //Move XY to side
  6319. if(code_seen('X'))
  6320. {
  6321. x_position = code_value();
  6322. }
  6323. else
  6324. {
  6325. #ifdef FILAMENTCHANGE_XPOS
  6326. x_position = FILAMENTCHANGE_XPOS;
  6327. #endif
  6328. }
  6329. if(code_seen('Y'))
  6330. {
  6331. y_position = code_value();
  6332. }
  6333. else
  6334. {
  6335. #ifdef FILAMENTCHANGE_YPOS
  6336. y_position = FILAMENTCHANGE_YPOS ;
  6337. #endif
  6338. }
  6339. if (mmu_enabled && code_seen("AUTO"))
  6340. automatic = true;
  6341. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6342. }
  6343. break;
  6344. #endif //FILAMENTCHANGEENABLE
  6345. //! ### M25 - Pause SD print
  6346. //! ### M601 - Pause print
  6347. //! ### M125 - Pause print (TODO: not implemented)
  6348. // -------------------------------
  6349. case 25:
  6350. case 601:
  6351. {
  6352. if (!isPrintPaused)
  6353. {
  6354. st_synchronize();
  6355. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  6356. lcd_pause_print();
  6357. }
  6358. }
  6359. break;
  6360. //! ### M602 - Resume print
  6361. // -------------------------------
  6362. case 602: {
  6363. if (isPrintPaused)
  6364. lcd_resume_print();
  6365. }
  6366. break;
  6367. //! ### M603 - Stop print
  6368. // -------------------------------
  6369. case 603: {
  6370. lcd_print_stop();
  6371. }
  6372. break;
  6373. #ifdef PINDA_THERMISTOR
  6374. //! ### M860 - Wait for extruder temperature (PINDA)
  6375. // --------------------------------------------------------------
  6376. /*!
  6377. Wait for PINDA thermistor to reach target temperature
  6378. M860 [S<target_temperature>]
  6379. */
  6380. case 860:
  6381. {
  6382. int set_target_pinda = 0;
  6383. if (code_seen('S')) {
  6384. set_target_pinda = code_value();
  6385. }
  6386. else {
  6387. break;
  6388. }
  6389. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  6390. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  6391. SERIAL_PROTOCOL(set_target_pinda);
  6392. SERIAL_PROTOCOLLN("");
  6393. codenum = _millis();
  6394. cancel_heatup = false;
  6395. bool is_pinda_cooling = false;
  6396. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  6397. is_pinda_cooling = true;
  6398. }
  6399. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  6400. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  6401. {
  6402. SERIAL_PROTOCOLPGM("P:");
  6403. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  6404. SERIAL_PROTOCOLPGM("/");
  6405. SERIAL_PROTOCOL(set_target_pinda);
  6406. SERIAL_PROTOCOLLN("");
  6407. codenum = _millis();
  6408. }
  6409. manage_heater();
  6410. manage_inactivity();
  6411. lcd_update(0);
  6412. }
  6413. LCD_MESSAGERPGM(MSG_OK);
  6414. break;
  6415. }
  6416. //! ### M861 - Set/Get PINDA temperature compensation offsets
  6417. // -----------------------------------------------------------
  6418. /*!
  6419. M861 [ ? | ! | Z | S<microsteps> [I<table_index>] ]
  6420. - `?` - Print current EEPROM offset values
  6421. - `!` - Set factory default values
  6422. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6423. - `S<microsteps>` `I<table_index>` - Set compensation ustep value S for compensation table index I
  6424. */
  6425. case 861:
  6426. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  6427. uint8_t cal_status = calibration_status_pinda();
  6428. int16_t usteps = 0;
  6429. cal_status ? SERIAL_PROTOCOLLN("PINDA cal status: 1") : SERIAL_PROTOCOLLN("PINDA cal status: 0");
  6430. SERIAL_PROTOCOLLN("index, temp, ustep, um");
  6431. for (uint8_t i = 0; i < 6; i++)
  6432. {
  6433. if(i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i-1) * 2, &usteps);
  6434. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6435. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6436. SERIAL_PROTOCOLPGM(", ");
  6437. SERIAL_PROTOCOL(35 + (i * 5));
  6438. SERIAL_PROTOCOLPGM(", ");
  6439. SERIAL_PROTOCOL(usteps);
  6440. SERIAL_PROTOCOLPGM(", ");
  6441. SERIAL_PROTOCOL(mm * 1000);
  6442. SERIAL_PROTOCOLLN("");
  6443. }
  6444. }
  6445. else if (code_seen('!')) { // ! - Set factory default values
  6446. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6447. int16_t z_shift = 8; //40C - 20um - 8usteps
  6448. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT, &z_shift);
  6449. z_shift = 24; //45C - 60um - 24usteps
  6450. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 2, &z_shift);
  6451. z_shift = 48; //50C - 120um - 48usteps
  6452. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 4, &z_shift);
  6453. z_shift = 80; //55C - 200um - 80usteps
  6454. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 6, &z_shift);
  6455. z_shift = 120; //60C - 300um - 120usteps
  6456. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 8, &z_shift);
  6457. SERIAL_PROTOCOLLN("factory restored");
  6458. }
  6459. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6460. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6461. int16_t z_shift = 0;
  6462. for (uint8_t i = 0; i < 5; i++) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  6463. SERIAL_PROTOCOLLN("zerorized");
  6464. }
  6465. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  6466. int16_t usteps = code_value();
  6467. if (code_seen('I')) {
  6468. uint8_t index = code_value();
  6469. if (index < 5) {
  6470. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + index * 2, &usteps);
  6471. SERIAL_PROTOCOLLN("OK");
  6472. SERIAL_PROTOCOLLN("index, temp, ustep, um");
  6473. for (uint8_t i = 0; i < 6; i++)
  6474. {
  6475. usteps = 0;
  6476. if (i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i - 1) * 2, &usteps);
  6477. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6478. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6479. SERIAL_PROTOCOLPGM(", ");
  6480. SERIAL_PROTOCOL(35 + (i * 5));
  6481. SERIAL_PROTOCOLPGM(", ");
  6482. SERIAL_PROTOCOL(usteps);
  6483. SERIAL_PROTOCOLPGM(", ");
  6484. SERIAL_PROTOCOL(mm * 1000);
  6485. SERIAL_PROTOCOLLN("");
  6486. }
  6487. }
  6488. }
  6489. }
  6490. else {
  6491. SERIAL_PROTOCOLPGM("no valid command");
  6492. }
  6493. break;
  6494. #endif //PINDA_THERMISTOR
  6495. //! ### M862 - Print checking
  6496. // ----------------------------------------------
  6497. /*!
  6498. Checks the parameters of the printer and gcode and performs compatibility check
  6499. - M862.1 { P<nozzle_diameter> | Q }
  6500. - M862.2 { P<model_code> | Q }
  6501. - M862.3 { P"<model_name>" | Q }
  6502. - M862.4 { P<fw_version> | Q }
  6503. - M862.5 { P<gcode_level> | Q }
  6504. When run with P<> argument, the check is performed against the input value.
  6505. When run with Q argument, the current value is shown.
  6506. M862.3 accepts text identifiers of printer types too.
  6507. The syntax of M862.3 is (note the quotes around the type):
  6508. M862.3 P "MK3S"
  6509. Accepted printer type identifiers and their numeric counterparts:
  6510. - MK1 (100)
  6511. - MK2 (200)
  6512. - MK2MM (201)
  6513. - MK2S (202)
  6514. - MK2SMM (203)
  6515. - MK2.5 (250)
  6516. - MK2.5MMU2 (20250)
  6517. - MK2.5S (252)
  6518. - MK2.5SMMU2S (20252)
  6519. - MK3 (300)
  6520. - MK3MMU2 (20300)
  6521. - MK3S (302)
  6522. - MK3SMMU2S (20302)
  6523. */
  6524. case 862: // M862: print checking
  6525. float nDummy;
  6526. uint8_t nCommand;
  6527. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  6528. switch((ClPrintChecking)nCommand)
  6529. {
  6530. case ClPrintChecking::_Nozzle: // ~ .1
  6531. uint16_t nDiameter;
  6532. if(code_seen('P'))
  6533. {
  6534. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  6535. nozzle_diameter_check(nDiameter);
  6536. }
  6537. /*
  6538. else if(code_seen('S')&&farm_mode)
  6539. {
  6540. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  6541. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  6542. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  6543. }
  6544. */
  6545. else if(code_seen('Q'))
  6546. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  6547. break;
  6548. case ClPrintChecking::_Model: // ~ .2
  6549. if(code_seen('P'))
  6550. {
  6551. uint16_t nPrinterModel;
  6552. nPrinterModel=(uint16_t)code_value_long();
  6553. printer_model_check(nPrinterModel);
  6554. }
  6555. else if(code_seen('Q'))
  6556. SERIAL_PROTOCOLLN(nPrinterType);
  6557. break;
  6558. case ClPrintChecking::_Smodel: // ~ .3
  6559. if(code_seen('P'))
  6560. printer_smodel_check(strchr_pointer);
  6561. else if(code_seen('Q'))
  6562. SERIAL_PROTOCOLLNRPGM(sPrinterName);
  6563. break;
  6564. case ClPrintChecking::_Version: // ~ .4
  6565. if(code_seen('P'))
  6566. fw_version_check(++strchr_pointer);
  6567. else if(code_seen('Q'))
  6568. SERIAL_PROTOCOLLN(FW_VERSION);
  6569. break;
  6570. case ClPrintChecking::_Gcode: // ~ .5
  6571. if(code_seen('P'))
  6572. {
  6573. uint16_t nGcodeLevel;
  6574. nGcodeLevel=(uint16_t)code_value_long();
  6575. gcode_level_check(nGcodeLevel);
  6576. }
  6577. else if(code_seen('Q'))
  6578. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  6579. break;
  6580. }
  6581. break;
  6582. #ifdef LIN_ADVANCE
  6583. //! ### M900 - Set Linear advance options
  6584. // ----------------------------------------------
  6585. case 900:
  6586. gcode_M900();
  6587. break;
  6588. #endif
  6589. //! ### M907 - Set digital trimpot motor current in mA using axis codes
  6590. // ---------------------------------------------------------------
  6591. case 907:
  6592. {
  6593. #ifdef TMC2130
  6594. //! See tmc2130_cur2val() for translation to 0 .. 63 range
  6595. for (int i = 0; i < NUM_AXIS; i++)
  6596. if(code_seen(axis_codes[i]))
  6597. {
  6598. long cur_mA = code_value_long();
  6599. uint8_t val = tmc2130_cur2val(cur_mA);
  6600. tmc2130_set_current_h(i, val);
  6601. tmc2130_set_current_r(i, val);
  6602. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  6603. }
  6604. #else //TMC2130
  6605. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  6606. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  6607. if(code_seen('B')) st_current_set(4,code_value());
  6608. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  6609. #endif
  6610. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  6611. if(code_seen('X')) st_current_set(0, code_value());
  6612. #endif
  6613. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  6614. if(code_seen('Z')) st_current_set(1, code_value());
  6615. #endif
  6616. #ifdef MOTOR_CURRENT_PWM_E_PIN
  6617. if(code_seen('E')) st_current_set(2, code_value());
  6618. #endif
  6619. #endif //TMC2130
  6620. }
  6621. break;
  6622. //! ### M908 - Control digital trimpot directly
  6623. // ---------------------------------------------------------
  6624. case 908:
  6625. {
  6626. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  6627. uint8_t channel,current;
  6628. if(code_seen('P')) channel=code_value();
  6629. if(code_seen('S')) current=code_value();
  6630. digitalPotWrite(channel, current);
  6631. #endif
  6632. }
  6633. break;
  6634. #ifdef TMC2130_SERVICE_CODES_M910_M918
  6635. //! ### M910 - TMC2130 init
  6636. // -----------------------------------------------
  6637. case 910:
  6638. {
  6639. tmc2130_init();
  6640. }
  6641. break;
  6642. //! ### M911 - Set TMC2130 holding currents
  6643. // -------------------------------------------------
  6644. case 911:
  6645. {
  6646. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  6647. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  6648. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  6649. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  6650. }
  6651. break;
  6652. //! ### M912 - Set TMC2130 running currents
  6653. // -----------------------------------------------
  6654. case 912:
  6655. {
  6656. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  6657. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  6658. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  6659. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  6660. }
  6661. break;
  6662. //! ### M913 - Print TMC2130 currents
  6663. // -----------------------------
  6664. case 913:
  6665. {
  6666. tmc2130_print_currents();
  6667. }
  6668. break;
  6669. //! ### M914 - Set TMC2130 normal mode
  6670. // ------------------------------
  6671. case 914:
  6672. {
  6673. tmc2130_mode = TMC2130_MODE_NORMAL;
  6674. update_mode_profile();
  6675. tmc2130_init();
  6676. }
  6677. break;
  6678. //! ### M95 - Set TMC2130 silent mode
  6679. // ------------------------------
  6680. case 915:
  6681. {
  6682. tmc2130_mode = TMC2130_MODE_SILENT;
  6683. update_mode_profile();
  6684. tmc2130_init();
  6685. }
  6686. break;
  6687. //! ### M916 - Set TMC2130 Stallguard sensitivity threshold
  6688. // -------------------------------------------------------
  6689. case 916:
  6690. {
  6691. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  6692. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  6693. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  6694. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  6695. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  6696. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  6697. }
  6698. break;
  6699. //! ### M917 - Set TMC2130 PWM amplitude offset (pwm_ampl)
  6700. // --------------------------------------------------------------
  6701. case 917:
  6702. {
  6703. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  6704. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  6705. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  6706. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  6707. }
  6708. break;
  6709. //! ### M918 - Set TMC2130 PWM amplitude gradient (pwm_grad)
  6710. // -------------------------------------------------------------
  6711. case 918:
  6712. {
  6713. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  6714. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  6715. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  6716. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  6717. }
  6718. break;
  6719. #endif //TMC2130_SERVICE_CODES_M910_M918
  6720. //! ### M350 - Set microstepping mode
  6721. // ---------------------------------------------------
  6722. //! Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  6723. case 350:
  6724. {
  6725. #ifdef TMC2130
  6726. for (int i=0; i<NUM_AXIS; i++)
  6727. {
  6728. if(code_seen(axis_codes[i]))
  6729. {
  6730. uint16_t res_new = code_value();
  6731. bool res_valid = (res_new == 8) || (res_new == 16) || (res_new == 32); // resolutions valid for all axis
  6732. res_valid |= (i != E_AXIS) && ((res_new == 1) || (res_new == 2) || (res_new == 4)); // resolutions valid for X Y Z only
  6733. res_valid |= (i == E_AXIS) && ((res_new == 64) || (res_new == 128)); // resolutions valid for E only
  6734. if (res_valid)
  6735. {
  6736. st_synchronize();
  6737. uint16_t res = tmc2130_get_res(i);
  6738. tmc2130_set_res(i, res_new);
  6739. cs.axis_ustep_resolution[i] = res_new;
  6740. if (res_new > res)
  6741. {
  6742. uint16_t fac = (res_new / res);
  6743. cs.axis_steps_per_unit[i] *= fac;
  6744. position[i] *= fac;
  6745. }
  6746. else
  6747. {
  6748. uint16_t fac = (res / res_new);
  6749. cs.axis_steps_per_unit[i] /= fac;
  6750. position[i] /= fac;
  6751. }
  6752. }
  6753. }
  6754. }
  6755. #else //TMC2130
  6756. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  6757. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  6758. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  6759. if(code_seen('B')) microstep_mode(4,code_value());
  6760. microstep_readings();
  6761. #endif
  6762. #endif //TMC2130
  6763. }
  6764. break;
  6765. //! ### M351 - Toggle Microstep Pins
  6766. // -----------------------------------
  6767. //! Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  6768. //!
  6769. //! M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  6770. case 351:
  6771. {
  6772. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  6773. if(code_seen('S')) switch((int)code_value())
  6774. {
  6775. case 1:
  6776. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  6777. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  6778. break;
  6779. case 2:
  6780. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  6781. if(code_seen('B')) microstep_ms(4,-1,code_value());
  6782. break;
  6783. }
  6784. microstep_readings();
  6785. #endif
  6786. }
  6787. break;
  6788. //! ### M701 - Load filament
  6789. // -------------------------
  6790. case 701:
  6791. {
  6792. if (mmu_enabled && code_seen('E'))
  6793. tmp_extruder = code_value();
  6794. gcode_M701();
  6795. }
  6796. break;
  6797. //! ### M702 - Unload filament
  6798. // ------------------------
  6799. /*!
  6800. M702 [U C]
  6801. - `U` Unload all filaments used in current print
  6802. - `C` Unload just current filament
  6803. - without any parameters unload all filaments
  6804. */
  6805. case 702:
  6806. {
  6807. #ifdef SNMM
  6808. if (code_seen('U'))
  6809. extr_unload_used(); //! if "U" unload all filaments which were used in current print
  6810. else if (code_seen('C'))
  6811. extr_unload(); //! if "C" unload just current filament
  6812. else
  6813. extr_unload_all(); //! otherwise unload all filaments
  6814. #else
  6815. if (code_seen('C')) {
  6816. if(mmu_enabled) extr_unload(); //! if "C" unload current filament; if mmu is not present no action is performed
  6817. }
  6818. else {
  6819. if(mmu_enabled) extr_unload(); //! unload current filament
  6820. else unload_filament();
  6821. }
  6822. #endif //SNMM
  6823. }
  6824. break;
  6825. //! ### M999 - Restart after being stopped
  6826. // ------------------------------------
  6827. case 999:
  6828. Stopped = false;
  6829. lcd_reset_alert_level();
  6830. gcode_LastN = Stopped_gcode_LastN;
  6831. FlushSerialRequestResend();
  6832. break;
  6833. default:
  6834. printf_P(PSTR("Unknown M code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  6835. }
  6836. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  6837. mcode_in_progress = 0;
  6838. }
  6839. }
  6840. // end if(code_seen('M')) (end of M codes)
  6841. //! -----------------------------------------------------------------------------------------
  6842. //! T Codes
  6843. //!
  6844. //! T<extruder nr.> - select extruder in case of multi extruder printer
  6845. //! select filament in case of MMU_V2
  6846. //! if extruder is "?", open menu to let the user select extruder/filament
  6847. //!
  6848. //! For MMU_V2:
  6849. //! @n T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  6850. //! @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  6851. //! @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.
  6852. //! @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  6853. else if(code_seen('T'))
  6854. {
  6855. int index;
  6856. bool load_to_nozzle = false;
  6857. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  6858. *(strchr_pointer + index) = tolower(*(strchr_pointer + index));
  6859. if ((*(strchr_pointer + index) < '0' || *(strchr_pointer + index) > '4') && *(strchr_pointer + index) != '?' && *(strchr_pointer + index) != 'x' && *(strchr_pointer + index) != 'c') {
  6860. SERIAL_ECHOLNPGM("Invalid T code.");
  6861. }
  6862. else if (*(strchr_pointer + index) == 'x'){ //load to bondtech gears; if mmu is not present do nothing
  6863. if (mmu_enabled)
  6864. {
  6865. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_FILAMENT), _T(MSG_FILAMENT));
  6866. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  6867. {
  6868. printf_P(PSTR("Duplicate T-code ignored.\n"));
  6869. }
  6870. else
  6871. {
  6872. st_synchronize();
  6873. mmu_command(MmuCmd::T0 + tmp_extruder);
  6874. manage_response(true, true, MMU_TCODE_MOVE);
  6875. }
  6876. }
  6877. }
  6878. else if (*(strchr_pointer + index) == 'c') { //load to from bondtech gears to nozzle (nozzle should be preheated)
  6879. if (mmu_enabled)
  6880. {
  6881. st_synchronize();
  6882. mmu_continue_loading(is_usb_printing || (lcd_commands_type == LcdCommands::Layer1Cal));
  6883. mmu_extruder = tmp_extruder; //filament change is finished
  6884. mmu_load_to_nozzle();
  6885. }
  6886. }
  6887. else {
  6888. if (*(strchr_pointer + index) == '?')
  6889. {
  6890. if(mmu_enabled)
  6891. {
  6892. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_FILAMENT), _T(MSG_FILAMENT));
  6893. load_to_nozzle = true;
  6894. } else
  6895. {
  6896. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_EXTRUDER), _T(MSG_EXTRUDER));
  6897. }
  6898. }
  6899. else {
  6900. tmp_extruder = code_value();
  6901. if (mmu_enabled && lcd_autoDepleteEnabled())
  6902. {
  6903. tmp_extruder = ad_getAlternative(tmp_extruder);
  6904. }
  6905. }
  6906. st_synchronize();
  6907. snmm_filaments_used |= (1 << tmp_extruder); //for stop print
  6908. if (mmu_enabled)
  6909. {
  6910. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  6911. {
  6912. printf_P(PSTR("Duplicate T-code ignored.\n"));
  6913. }
  6914. else
  6915. {
  6916. #if defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  6917. if (EEPROM_MMU_CUTTER_ENABLED_always == eeprom_read_byte((uint8_t*)EEPROM_MMU_CUTTER_ENABLED))
  6918. {
  6919. mmu_command(MmuCmd::K0 + tmp_extruder);
  6920. manage_response(true, true, MMU_UNLOAD_MOVE);
  6921. }
  6922. #endif //defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  6923. mmu_command(MmuCmd::T0 + tmp_extruder);
  6924. manage_response(true, true, MMU_TCODE_MOVE);
  6925. mmu_continue_loading(is_usb_printing || (lcd_commands_type == LcdCommands::Layer1Cal));
  6926. mmu_extruder = tmp_extruder; //filament change is finished
  6927. if (load_to_nozzle)// for single material usage with mmu
  6928. {
  6929. mmu_load_to_nozzle();
  6930. }
  6931. }
  6932. }
  6933. else
  6934. {
  6935. #ifdef SNMM
  6936. mmu_extruder = tmp_extruder;
  6937. _delay(100);
  6938. disable_e0();
  6939. disable_e1();
  6940. disable_e2();
  6941. pinMode(E_MUX0_PIN, OUTPUT);
  6942. pinMode(E_MUX1_PIN, OUTPUT);
  6943. _delay(100);
  6944. SERIAL_ECHO_START;
  6945. SERIAL_ECHO("T:");
  6946. SERIAL_ECHOLN((int)tmp_extruder);
  6947. switch (tmp_extruder) {
  6948. case 1:
  6949. WRITE(E_MUX0_PIN, HIGH);
  6950. WRITE(E_MUX1_PIN, LOW);
  6951. break;
  6952. case 2:
  6953. WRITE(E_MUX0_PIN, LOW);
  6954. WRITE(E_MUX1_PIN, HIGH);
  6955. break;
  6956. case 3:
  6957. WRITE(E_MUX0_PIN, HIGH);
  6958. WRITE(E_MUX1_PIN, HIGH);
  6959. break;
  6960. default:
  6961. WRITE(E_MUX0_PIN, LOW);
  6962. WRITE(E_MUX1_PIN, LOW);
  6963. break;
  6964. }
  6965. _delay(100);
  6966. #else //SNMM
  6967. if (tmp_extruder >= EXTRUDERS) {
  6968. SERIAL_ECHO_START;
  6969. SERIAL_ECHOPGM("T");
  6970. SERIAL_PROTOCOLLN((int)tmp_extruder);
  6971. SERIAL_ECHOLNRPGM(_n("Invalid extruder"));////MSG_INVALID_EXTRUDER
  6972. }
  6973. else {
  6974. #if EXTRUDERS > 1
  6975. boolean make_move = false;
  6976. #endif
  6977. if (code_seen('F')) {
  6978. #if EXTRUDERS > 1
  6979. make_move = true;
  6980. #endif
  6981. next_feedrate = code_value();
  6982. if (next_feedrate > 0.0) {
  6983. feedrate = next_feedrate;
  6984. }
  6985. }
  6986. #if EXTRUDERS > 1
  6987. if (tmp_extruder != active_extruder) {
  6988. // Save current position to return to after applying extruder offset
  6989. memcpy(destination, current_position, sizeof(destination));
  6990. // Offset extruder (only by XY)
  6991. int i;
  6992. for (i = 0; i < 2; i++) {
  6993. current_position[i] = current_position[i] -
  6994. extruder_offset[i][active_extruder] +
  6995. extruder_offset[i][tmp_extruder];
  6996. }
  6997. // Set the new active extruder and position
  6998. active_extruder = tmp_extruder;
  6999. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  7000. // Move to the old position if 'F' was in the parameters
  7001. if (make_move && Stopped == false) {
  7002. prepare_move();
  7003. }
  7004. }
  7005. #endif
  7006. SERIAL_ECHO_START;
  7007. SERIAL_ECHORPGM(_n("Active Extruder: "));////MSG_ACTIVE_EXTRUDER
  7008. SERIAL_PROTOCOLLN((int)active_extruder);
  7009. }
  7010. #endif //SNMM
  7011. }
  7012. }
  7013. } // end if(code_seen('T')) (end of T codes)
  7014. //! ----------------------------------------------------------------------------------------------
  7015. else if (code_seen('D')) // D codes (debug)
  7016. {
  7017. switch((int)code_value())
  7018. {
  7019. //! ### D-1 - Endless loop
  7020. // -------------------
  7021. case -1:
  7022. dcode__1(); break;
  7023. #ifdef DEBUG_DCODES
  7024. //! ### D0 - Reset
  7025. // --------------
  7026. case 0:
  7027. dcode_0(); break;
  7028. //! ### D1 - Clear EEPROM
  7029. // ------------------
  7030. case 1:
  7031. dcode_1(); break;
  7032. //! ### D2 - Read/Write RAM
  7033. // --------------------
  7034. case 2:
  7035. dcode_2(); break;
  7036. #endif //DEBUG_DCODES
  7037. #ifdef DEBUG_DCODE3
  7038. //! ### D3 - Read/Write EEPROM
  7039. // -----------------------
  7040. case 3:
  7041. dcode_3(); break;
  7042. #endif //DEBUG_DCODE3
  7043. #ifdef DEBUG_DCODES
  7044. //! ### D4 - Read/Write PIN
  7045. // ---------------------
  7046. case 4:
  7047. dcode_4(); break;
  7048. #endif //DEBUG_DCODES
  7049. #ifdef DEBUG_DCODE5
  7050. //! ### D5 - Read/Write FLASH
  7051. // ------------------------
  7052. case 5:
  7053. dcode_5(); break;
  7054. break;
  7055. #endif //DEBUG_DCODE5
  7056. #ifdef DEBUG_DCODES
  7057. //! ### D6 - Read/Write external FLASH
  7058. // ---------------------------------------
  7059. case 6:
  7060. dcode_6(); break;
  7061. //! ### D7 - Read/Write Bootloader
  7062. // -------------------------------
  7063. case 7:
  7064. dcode_7(); break;
  7065. //! ### D8 - Read/Write PINDA
  7066. // ---------------------------
  7067. case 8:
  7068. dcode_8(); break;
  7069. // ### D9 - Read/Write ADC
  7070. // ------------------------
  7071. case 9:
  7072. dcode_9(); break;
  7073. //! ### D10 - XYZ calibration = OK
  7074. // ------------------------------
  7075. case 10:
  7076. dcode_10(); break;
  7077. #endif //DEBUG_DCODES
  7078. #ifdef HEATBED_ANALYSIS
  7079. //! ### D80 - Bed check
  7080. // ---------------------
  7081. /*!
  7082. - `E` - dimension x
  7083. - `F` - dimention y
  7084. - `G` - points_x
  7085. - `H` - points_y
  7086. - `I` - offset_x
  7087. - `J` - offset_y
  7088. */
  7089. case 80:
  7090. {
  7091. float dimension_x = 40;
  7092. float dimension_y = 40;
  7093. int points_x = 40;
  7094. int points_y = 40;
  7095. float offset_x = 74;
  7096. float offset_y = 33;
  7097. if (code_seen('E')) dimension_x = code_value();
  7098. if (code_seen('F')) dimension_y = code_value();
  7099. if (code_seen('G')) {points_x = code_value(); }
  7100. if (code_seen('H')) {points_y = code_value(); }
  7101. if (code_seen('I')) {offset_x = code_value(); }
  7102. if (code_seen('J')) {offset_y = code_value(); }
  7103. printf_P(PSTR("DIM X: %f\n"), dimension_x);
  7104. printf_P(PSTR("DIM Y: %f\n"), dimension_y);
  7105. printf_P(PSTR("POINTS X: %d\n"), points_x);
  7106. printf_P(PSTR("POINTS Y: %d\n"), points_y);
  7107. printf_P(PSTR("OFFSET X: %f\n"), offset_x);
  7108. printf_P(PSTR("OFFSET Y: %f\n"), offset_y);
  7109. bed_check(dimension_x,dimension_y,points_x,points_y,offset_x,offset_y);
  7110. }break;
  7111. //! ### D81 - Bed analysis
  7112. // -----------------------------
  7113. /*!
  7114. - `E` - dimension x
  7115. - `F` - dimention y
  7116. - `G` - points_x
  7117. - `H` - points_y
  7118. - `I` - offset_x
  7119. - `J` - offset_y
  7120. */
  7121. case 81:
  7122. {
  7123. float dimension_x = 40;
  7124. float dimension_y = 40;
  7125. int points_x = 40;
  7126. int points_y = 40;
  7127. float offset_x = 74;
  7128. float offset_y = 33;
  7129. if (code_seen('E')) dimension_x = code_value();
  7130. if (code_seen('F')) dimension_y = code_value();
  7131. if (code_seen("G")) { strchr_pointer+=1; points_x = code_value(); }
  7132. if (code_seen("H")) { strchr_pointer+=1; points_y = code_value(); }
  7133. if (code_seen("I")) { strchr_pointer+=1; offset_x = code_value(); }
  7134. if (code_seen("J")) { strchr_pointer+=1; offset_y = code_value(); }
  7135. bed_analysis(dimension_x,dimension_y,points_x,points_y,offset_x,offset_y);
  7136. } break;
  7137. #endif //HEATBED_ANALYSIS
  7138. #ifdef DEBUG_DCODES
  7139. //! ### D106 print measured fan speed for different pwm values
  7140. // --------------------------------------------------------------
  7141. case 106:
  7142. {
  7143. for (int i = 255; i > 0; i = i - 5) {
  7144. fanSpeed = i;
  7145. //delay_keep_alive(2000);
  7146. for (int j = 0; j < 100; j++) {
  7147. delay_keep_alive(100);
  7148. }
  7149. printf_P(_N("%d: %d\n"), i, fan_speed[1]);
  7150. }
  7151. }break;
  7152. #ifdef TMC2130
  7153. //! ### D2130 - TMC2130 Trinamic stepper controller
  7154. // ---------------------------
  7155. /*!
  7156. D2130<axis><command>[subcommand][value]
  7157. - <command>:
  7158. - '0' current off
  7159. - '1' current on
  7160. - '+' single step
  7161. - * value sereval steps
  7162. - '-' dtto oposite direction
  7163. - '?' read register
  7164. - * "mres"
  7165. - * "step"
  7166. - * "mscnt"
  7167. - * "mscuract"
  7168. - * "wave"
  7169. - '!' set register
  7170. - * "mres"
  7171. - * "step"
  7172. - * "wave"
  7173. - '@' home calibrate axis
  7174. Example:
  7175. D2130E?wave ... print extruder microstep linearity compensation curve
  7176. D2130E!wave0 ... disable extruder linearity compensation curve, (sine curve is used)
  7177. D2130E!wave220 ... (sin(x))^1.1 extruder microstep compensation curve used
  7178. */
  7179. case 2130:
  7180. dcode_2130(); break;
  7181. #endif //TMC2130
  7182. #if (defined (FILAMENT_SENSOR) && defined(PAT9125))
  7183. //! ### D9125 - FILAMENT_SENSOR
  7184. // ---------------------------------
  7185. case 9125:
  7186. dcode_9125(); break;
  7187. #endif //FILAMENT_SENSOR
  7188. #endif //DEBUG_DCODES
  7189. }
  7190. }
  7191. else
  7192. {
  7193. SERIAL_ECHO_START;
  7194. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  7195. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  7196. SERIAL_ECHOLNPGM("\"(2)");
  7197. }
  7198. KEEPALIVE_STATE(NOT_BUSY);
  7199. ClearToSend();
  7200. }
  7201. /** @defgroup GCodes G-Code List
  7202. */
  7203. // ---------------------------------------------------
  7204. void FlushSerialRequestResend()
  7205. {
  7206. //char cmdbuffer[bufindr][100]="Resend:";
  7207. MYSERIAL.flush();
  7208. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  7209. }
  7210. // Confirm the execution of a command, if sent from a serial line.
  7211. // Execution of a command from a SD card will not be confirmed.
  7212. void ClearToSend()
  7213. {
  7214. previous_millis_cmd = _millis();
  7215. if ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR))
  7216. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7217. }
  7218. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7219. void update_currents() {
  7220. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  7221. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  7222. float tmp_motor[3];
  7223. //SERIAL_ECHOLNPGM("Currents updated: ");
  7224. if (destination[Z_AXIS] < Z_SILENT) {
  7225. //SERIAL_ECHOLNPGM("LOW");
  7226. for (uint8_t i = 0; i < 3; i++) {
  7227. st_current_set(i, current_low[i]);
  7228. /*MYSERIAL.print(int(i));
  7229. SERIAL_ECHOPGM(": ");
  7230. MYSERIAL.println(current_low[i]);*/
  7231. }
  7232. }
  7233. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  7234. //SERIAL_ECHOLNPGM("HIGH");
  7235. for (uint8_t i = 0; i < 3; i++) {
  7236. st_current_set(i, current_high[i]);
  7237. /*MYSERIAL.print(int(i));
  7238. SERIAL_ECHOPGM(": ");
  7239. MYSERIAL.println(current_high[i]);*/
  7240. }
  7241. }
  7242. else {
  7243. for (uint8_t i = 0; i < 3; i++) {
  7244. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  7245. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  7246. st_current_set(i, tmp_motor[i]);
  7247. /*MYSERIAL.print(int(i));
  7248. SERIAL_ECHOPGM(": ");
  7249. MYSERIAL.println(tmp_motor[i]);*/
  7250. }
  7251. }
  7252. }
  7253. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7254. void get_coordinates()
  7255. {
  7256. bool seen[4]={false,false,false,false};
  7257. for(int8_t i=0; i < NUM_AXIS; i++) {
  7258. if(code_seen(axis_codes[i]))
  7259. {
  7260. bool relative = axis_relative_modes[i];
  7261. destination[i] = (float)code_value();
  7262. if (i == E_AXIS) {
  7263. float emult = extruder_multiplier[active_extruder];
  7264. if (emult != 1.) {
  7265. if (! relative) {
  7266. destination[i] -= current_position[i];
  7267. relative = true;
  7268. }
  7269. destination[i] *= emult;
  7270. }
  7271. }
  7272. if (relative)
  7273. destination[i] += current_position[i];
  7274. seen[i]=true;
  7275. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7276. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  7277. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7278. }
  7279. else destination[i] = current_position[i]; //Are these else lines really needed?
  7280. }
  7281. if(code_seen('F')) {
  7282. next_feedrate = code_value();
  7283. #ifdef MAX_SILENT_FEEDRATE
  7284. if (tmc2130_mode == TMC2130_MODE_SILENT)
  7285. if (next_feedrate > MAX_SILENT_FEEDRATE) next_feedrate = MAX_SILENT_FEEDRATE;
  7286. #endif //MAX_SILENT_FEEDRATE
  7287. if(next_feedrate > 0.0) feedrate = next_feedrate;
  7288. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  7289. {
  7290. // float e_max_speed =
  7291. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  7292. }
  7293. }
  7294. }
  7295. void get_arc_coordinates()
  7296. {
  7297. #ifdef SF_ARC_FIX
  7298. bool relative_mode_backup = relative_mode;
  7299. relative_mode = true;
  7300. #endif
  7301. get_coordinates();
  7302. #ifdef SF_ARC_FIX
  7303. relative_mode=relative_mode_backup;
  7304. #endif
  7305. if(code_seen('I')) {
  7306. offset[0] = code_value();
  7307. }
  7308. else {
  7309. offset[0] = 0.0;
  7310. }
  7311. if(code_seen('J')) {
  7312. offset[1] = code_value();
  7313. }
  7314. else {
  7315. offset[1] = 0.0;
  7316. }
  7317. }
  7318. void clamp_to_software_endstops(float target[3])
  7319. {
  7320. #ifdef DEBUG_DISABLE_SWLIMITS
  7321. return;
  7322. #endif //DEBUG_DISABLE_SWLIMITS
  7323. world2machine_clamp(target[0], target[1]);
  7324. // Clamp the Z coordinate.
  7325. if (min_software_endstops) {
  7326. float negative_z_offset = 0;
  7327. #ifdef ENABLE_AUTO_BED_LEVELING
  7328. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  7329. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  7330. #endif
  7331. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  7332. }
  7333. if (max_software_endstops) {
  7334. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  7335. }
  7336. }
  7337. #ifdef MESH_BED_LEVELING
  7338. 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) {
  7339. float dx = x - current_position[X_AXIS];
  7340. float dy = y - current_position[Y_AXIS];
  7341. int n_segments = 0;
  7342. if (mbl.active) {
  7343. float len = abs(dx) + abs(dy);
  7344. if (len > 0)
  7345. // Split to 3cm segments or shorter.
  7346. n_segments = int(ceil(len / 30.f));
  7347. }
  7348. if (n_segments > 1) {
  7349. // In a multi-segment move explicitly set the final target in the plan
  7350. // as the move will be recalculated in it's entirety
  7351. float gcode_target[NUM_AXIS];
  7352. gcode_target[X_AXIS] = x;
  7353. gcode_target[Y_AXIS] = y;
  7354. gcode_target[Z_AXIS] = z;
  7355. gcode_target[E_AXIS] = e;
  7356. float dz = z - current_position[Z_AXIS];
  7357. float de = e - current_position[E_AXIS];
  7358. for (int i = 1; i < n_segments; ++ i) {
  7359. float t = float(i) / float(n_segments);
  7360. plan_buffer_line(current_position[X_AXIS] + t * dx,
  7361. current_position[Y_AXIS] + t * dy,
  7362. current_position[Z_AXIS] + t * dz,
  7363. current_position[E_AXIS] + t * de,
  7364. feed_rate, extruder, gcode_target);
  7365. if (waiting_inside_plan_buffer_line_print_aborted)
  7366. return;
  7367. }
  7368. }
  7369. // The rest of the path.
  7370. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  7371. }
  7372. #endif // MESH_BED_LEVELING
  7373. void prepare_move()
  7374. {
  7375. clamp_to_software_endstops(destination);
  7376. previous_millis_cmd = _millis();
  7377. // Do not use feedmultiply for E or Z only moves
  7378. if( (current_position[X_AXIS] == destination [X_AXIS]) && (current_position[Y_AXIS] == destination [Y_AXIS])) {
  7379. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  7380. }
  7381. else {
  7382. #ifdef MESH_BED_LEVELING
  7383. 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);
  7384. #else
  7385. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate*feedmultiply*(1./(60.f*100.f)), active_extruder);
  7386. #endif
  7387. }
  7388. set_current_to_destination();
  7389. }
  7390. void prepare_arc_move(char isclockwise) {
  7391. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  7392. // Trace the arc
  7393. mc_arc(current_position, destination, offset, X_AXIS, Y_AXIS, Z_AXIS, feedrate*feedmultiply/60/100.0, r, isclockwise, active_extruder);
  7394. // As far as the parser is concerned, the position is now == target. In reality the
  7395. // motion control system might still be processing the action and the real tool position
  7396. // in any intermediate location.
  7397. for(int8_t i=0; i < NUM_AXIS; i++) {
  7398. current_position[i] = destination[i];
  7399. }
  7400. previous_millis_cmd = _millis();
  7401. }
  7402. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  7403. #if defined(FAN_PIN)
  7404. #if CONTROLLERFAN_PIN == FAN_PIN
  7405. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  7406. #endif
  7407. #endif
  7408. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  7409. unsigned long lastMotorCheck = 0;
  7410. void controllerFan()
  7411. {
  7412. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  7413. {
  7414. lastMotorCheck = _millis();
  7415. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  7416. #if EXTRUDERS > 2
  7417. || !READ(E2_ENABLE_PIN)
  7418. #endif
  7419. #if EXTRUDER > 1
  7420. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  7421. || !READ(X2_ENABLE_PIN)
  7422. #endif
  7423. || !READ(E1_ENABLE_PIN)
  7424. #endif
  7425. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  7426. {
  7427. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  7428. }
  7429. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  7430. {
  7431. digitalWrite(CONTROLLERFAN_PIN, 0);
  7432. analogWrite(CONTROLLERFAN_PIN, 0);
  7433. }
  7434. else
  7435. {
  7436. // allows digital or PWM fan output to be used (see M42 handling)
  7437. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  7438. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  7439. }
  7440. }
  7441. }
  7442. #endif
  7443. #ifdef TEMP_STAT_LEDS
  7444. static bool blue_led = false;
  7445. static bool red_led = false;
  7446. static uint32_t stat_update = 0;
  7447. void handle_status_leds(void) {
  7448. float max_temp = 0.0;
  7449. if(_millis() > stat_update) {
  7450. stat_update += 500; // Update every 0.5s
  7451. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  7452. max_temp = max(max_temp, degHotend(cur_extruder));
  7453. max_temp = max(max_temp, degTargetHotend(cur_extruder));
  7454. }
  7455. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  7456. max_temp = max(max_temp, degTargetBed());
  7457. max_temp = max(max_temp, degBed());
  7458. #endif
  7459. if((max_temp > 55.0) && (red_led == false)) {
  7460. digitalWrite(STAT_LED_RED, 1);
  7461. digitalWrite(STAT_LED_BLUE, 0);
  7462. red_led = true;
  7463. blue_led = false;
  7464. }
  7465. if((max_temp < 54.0) && (blue_led == false)) {
  7466. digitalWrite(STAT_LED_RED, 0);
  7467. digitalWrite(STAT_LED_BLUE, 1);
  7468. red_led = false;
  7469. blue_led = true;
  7470. }
  7471. }
  7472. }
  7473. #endif
  7474. #ifdef SAFETYTIMER
  7475. /**
  7476. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  7477. *
  7478. * Full screen blocking notification message is shown after heater turning off.
  7479. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  7480. * damage print.
  7481. *
  7482. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  7483. */
  7484. static void handleSafetyTimer()
  7485. {
  7486. #if (EXTRUDERS > 1)
  7487. #error Implemented only for one extruder.
  7488. #endif //(EXTRUDERS > 1)
  7489. if ((PRINTER_ACTIVE) || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  7490. {
  7491. safetyTimer.stop();
  7492. }
  7493. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  7494. {
  7495. safetyTimer.start();
  7496. }
  7497. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  7498. {
  7499. setTargetBed(0);
  7500. setAllTargetHotends(0);
  7501. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED
  7502. }
  7503. }
  7504. #endif //SAFETYTIMER
  7505. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  7506. {
  7507. bool bInhibitFlag;
  7508. #ifdef FILAMENT_SENSOR
  7509. if (mmu_enabled == false)
  7510. {
  7511. //-// if (mcode_in_progress != 600) //M600 not in progress
  7512. #ifdef PAT9125
  7513. bInhibitFlag=(menu_menu==lcd_menu_extruder_info); // Support::ExtruderInfo menu active
  7514. #endif // PAT9125
  7515. #ifdef IR_SENSOR
  7516. bInhibitFlag=(menu_menu==lcd_menu_show_sensors_state); // Support::SensorInfo menu active
  7517. #endif // IR_SENSOR
  7518. if ((mcode_in_progress != 600) && (eFilamentAction != FilamentAction::AutoLoad) && (!bInhibitFlag)) //M600 not in progress, preHeat @ autoLoad menu not active, Support::ExtruderInfo/SensorInfo menu not active
  7519. {
  7520. if (!moves_planned() && !IS_SD_PRINTING && !is_usb_printing && (lcd_commands_type != LcdCommands::Layer1Cal) && ! eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE))
  7521. {
  7522. if (fsensor_check_autoload())
  7523. {
  7524. #ifdef PAT9125
  7525. fsensor_autoload_check_stop();
  7526. #endif //PAT9125
  7527. //-// if (degHotend0() > EXTRUDE_MINTEMP)
  7528. if(0)
  7529. {
  7530. Sound_MakeCustom(50,1000,false);
  7531. loading_flag = true;
  7532. enquecommand_front_P((PSTR("M701")));
  7533. }
  7534. else
  7535. {
  7536. /*
  7537. lcd_update_enable(false);
  7538. show_preheat_nozzle_warning();
  7539. lcd_update_enable(true);
  7540. */
  7541. eFilamentAction=FilamentAction::AutoLoad;
  7542. bFilamentFirstRun=false;
  7543. if(target_temperature[0]>=EXTRUDE_MINTEMP)
  7544. {
  7545. bFilamentPreheatState=true;
  7546. // mFilamentItem(target_temperature[0],target_temperature_bed);
  7547. menu_submenu(mFilamentItemForce);
  7548. }
  7549. else
  7550. {
  7551. menu_submenu(lcd_generic_preheat_menu);
  7552. lcd_timeoutToStatus.start();
  7553. }
  7554. }
  7555. }
  7556. }
  7557. else
  7558. {
  7559. #ifdef PAT9125
  7560. fsensor_autoload_check_stop();
  7561. #endif //PAT9125
  7562. fsensor_update();
  7563. }
  7564. }
  7565. }
  7566. #endif //FILAMENT_SENSOR
  7567. #ifdef SAFETYTIMER
  7568. handleSafetyTimer();
  7569. #endif //SAFETYTIMER
  7570. #if defined(KILL_PIN) && KILL_PIN > -1
  7571. static int killCount = 0; // make the inactivity button a bit less responsive
  7572. const int KILL_DELAY = 10000;
  7573. #endif
  7574. if(buflen < (BUFSIZE-1)){
  7575. get_command();
  7576. }
  7577. if( (_millis() - previous_millis_cmd) > max_inactive_time )
  7578. if(max_inactive_time)
  7579. kill(_n("Inactivity Shutdown"), 4);
  7580. if(stepper_inactive_time) {
  7581. if( (_millis() - previous_millis_cmd) > stepper_inactive_time )
  7582. {
  7583. if(blocks_queued() == false && ignore_stepper_queue == false) {
  7584. disable_x();
  7585. disable_y();
  7586. disable_z();
  7587. disable_e0();
  7588. disable_e1();
  7589. disable_e2();
  7590. }
  7591. }
  7592. }
  7593. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  7594. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  7595. {
  7596. chdkActive = false;
  7597. WRITE(CHDK, LOW);
  7598. }
  7599. #endif
  7600. #if defined(KILL_PIN) && KILL_PIN > -1
  7601. // Check if the kill button was pressed and wait just in case it was an accidental
  7602. // key kill key press
  7603. // -------------------------------------------------------------------------------
  7604. if( 0 == READ(KILL_PIN) )
  7605. {
  7606. killCount++;
  7607. }
  7608. else if (killCount > 0)
  7609. {
  7610. killCount--;
  7611. }
  7612. // Exceeded threshold and we can confirm that it was not accidental
  7613. // KILL the machine
  7614. // ----------------------------------------------------------------
  7615. if ( killCount >= KILL_DELAY)
  7616. {
  7617. kill(NULL, 5);
  7618. }
  7619. #endif
  7620. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  7621. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  7622. #endif
  7623. #ifdef EXTRUDER_RUNOUT_PREVENT
  7624. if( (_millis() - previous_millis_cmd) > EXTRUDER_RUNOUT_SECONDS*1000 )
  7625. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  7626. {
  7627. bool oldstatus=READ(E0_ENABLE_PIN);
  7628. enable_e0();
  7629. float oldepos=current_position[E_AXIS];
  7630. float oldedes=destination[E_AXIS];
  7631. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  7632. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  7633. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  7634. current_position[E_AXIS]=oldepos;
  7635. destination[E_AXIS]=oldedes;
  7636. plan_set_e_position(oldepos);
  7637. previous_millis_cmd=_millis();
  7638. st_synchronize();
  7639. WRITE(E0_ENABLE_PIN,oldstatus);
  7640. }
  7641. #endif
  7642. #ifdef TEMP_STAT_LEDS
  7643. handle_status_leds();
  7644. #endif
  7645. check_axes_activity();
  7646. mmu_loop();
  7647. }
  7648. void kill(const char *full_screen_message, unsigned char id)
  7649. {
  7650. printf_P(_N("KILL: %d\n"), id);
  7651. //return;
  7652. cli(); // Stop interrupts
  7653. disable_heater();
  7654. disable_x();
  7655. // SERIAL_ECHOLNPGM("kill - disable Y");
  7656. disable_y();
  7657. disable_z();
  7658. disable_e0();
  7659. disable_e1();
  7660. disable_e2();
  7661. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  7662. pinMode(PS_ON_PIN,INPUT);
  7663. #endif
  7664. SERIAL_ERROR_START;
  7665. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  7666. if (full_screen_message != NULL) {
  7667. SERIAL_ERRORLNRPGM(full_screen_message);
  7668. lcd_display_message_fullscreen_P(full_screen_message);
  7669. } else {
  7670. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  7671. }
  7672. // FMC small patch to update the LCD before ending
  7673. sei(); // enable interrupts
  7674. for ( int i=5; i--; lcd_update(0))
  7675. {
  7676. _delay(200);
  7677. }
  7678. cli(); // disable interrupts
  7679. suicide();
  7680. while(1)
  7681. {
  7682. #ifdef WATCHDOG
  7683. wdt_reset();
  7684. #endif //WATCHDOG
  7685. /* Intentionally left empty */
  7686. } // Wait for reset
  7687. }
  7688. // Stop: Emergency stop used by overtemp functions which allows recovery
  7689. //
  7690. // In addition to stopping the print, this prevents subsequent G[0-3] commands to be
  7691. // processed via USB (using "Stopped") until the print is resumed via M999 or
  7692. // manually started from scratch with the LCD.
  7693. //
  7694. // Note that the current instruction is completely discarded, so resuming from Stop()
  7695. // will introduce either over/under extrusion on the current segment, and will not
  7696. // survive a power panic. Switching Stop() to use the pause machinery instead (with
  7697. // the addition of disabling the headers) could allow true recovery in the future.
  7698. void Stop()
  7699. {
  7700. disable_heater();
  7701. if(Stopped == false) {
  7702. Stopped = true;
  7703. lcd_print_stop();
  7704. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  7705. SERIAL_ERROR_START;
  7706. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  7707. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  7708. }
  7709. }
  7710. bool IsStopped() { return Stopped; };
  7711. #ifdef FAST_PWM_FAN
  7712. void setPwmFrequency(uint8_t pin, int val)
  7713. {
  7714. val &= 0x07;
  7715. switch(digitalPinToTimer(pin))
  7716. {
  7717. #if defined(TCCR0A)
  7718. case TIMER0A:
  7719. case TIMER0B:
  7720. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  7721. // TCCR0B |= val;
  7722. break;
  7723. #endif
  7724. #if defined(TCCR1A)
  7725. case TIMER1A:
  7726. case TIMER1B:
  7727. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  7728. // TCCR1B |= val;
  7729. break;
  7730. #endif
  7731. #if defined(TCCR2)
  7732. case TIMER2:
  7733. case TIMER2:
  7734. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  7735. TCCR2 |= val;
  7736. break;
  7737. #endif
  7738. #if defined(TCCR2A)
  7739. case TIMER2A:
  7740. case TIMER2B:
  7741. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  7742. TCCR2B |= val;
  7743. break;
  7744. #endif
  7745. #if defined(TCCR3A)
  7746. case TIMER3A:
  7747. case TIMER3B:
  7748. case TIMER3C:
  7749. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  7750. TCCR3B |= val;
  7751. break;
  7752. #endif
  7753. #if defined(TCCR4A)
  7754. case TIMER4A:
  7755. case TIMER4B:
  7756. case TIMER4C:
  7757. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  7758. TCCR4B |= val;
  7759. break;
  7760. #endif
  7761. #if defined(TCCR5A)
  7762. case TIMER5A:
  7763. case TIMER5B:
  7764. case TIMER5C:
  7765. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  7766. TCCR5B |= val;
  7767. break;
  7768. #endif
  7769. }
  7770. }
  7771. #endif //FAST_PWM_FAN
  7772. //! @brief Get and validate extruder number
  7773. //!
  7774. //! If it is not specified, active_extruder is returned in parameter extruder.
  7775. //! @param [in] code M code number
  7776. //! @param [out] extruder
  7777. //! @return error
  7778. //! @retval true Invalid extruder specified in T code
  7779. //! @retval false Valid extruder specified in T code, or not specifiead
  7780. bool setTargetedHotend(int code, uint8_t &extruder)
  7781. {
  7782. extruder = active_extruder;
  7783. if(code_seen('T')) {
  7784. extruder = code_value();
  7785. if(extruder >= EXTRUDERS) {
  7786. SERIAL_ECHO_START;
  7787. switch(code){
  7788. case 104:
  7789. SERIAL_ECHORPGM(_n("M104 Invalid extruder "));////MSG_M104_INVALID_EXTRUDER
  7790. break;
  7791. case 105:
  7792. SERIAL_ECHO(_n("M105 Invalid extruder "));////MSG_M105_INVALID_EXTRUDER
  7793. break;
  7794. case 109:
  7795. SERIAL_ECHO(_n("M109 Invalid extruder "));////MSG_M109_INVALID_EXTRUDER
  7796. break;
  7797. case 218:
  7798. SERIAL_ECHO(_n("M218 Invalid extruder "));////MSG_M218_INVALID_EXTRUDER
  7799. break;
  7800. case 221:
  7801. SERIAL_ECHO(_n("M221 Invalid extruder "));////MSG_M221_INVALID_EXTRUDER
  7802. break;
  7803. }
  7804. SERIAL_PROTOCOLLN((int)extruder);
  7805. return true;
  7806. }
  7807. }
  7808. return false;
  7809. }
  7810. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  7811. {
  7812. 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)
  7813. {
  7814. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  7815. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  7816. }
  7817. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  7818. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  7819. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  7820. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  7821. total_filament_used = 0;
  7822. }
  7823. float calculate_extruder_multiplier(float diameter) {
  7824. float out = 1.f;
  7825. if (cs.volumetric_enabled && diameter > 0.f) {
  7826. float area = M_PI * diameter * diameter * 0.25;
  7827. out = 1.f / area;
  7828. }
  7829. if (extrudemultiply != 100)
  7830. out *= float(extrudemultiply) * 0.01f;
  7831. return out;
  7832. }
  7833. void calculate_extruder_multipliers() {
  7834. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  7835. #if EXTRUDERS > 1
  7836. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  7837. #if EXTRUDERS > 2
  7838. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  7839. #endif
  7840. #endif
  7841. }
  7842. void delay_keep_alive(unsigned int ms)
  7843. {
  7844. for (;;) {
  7845. manage_heater();
  7846. // Manage inactivity, but don't disable steppers on timeout.
  7847. manage_inactivity(true);
  7848. lcd_update(0);
  7849. if (ms == 0)
  7850. break;
  7851. else if (ms >= 50) {
  7852. _delay(50);
  7853. ms -= 50;
  7854. } else {
  7855. _delay(ms);
  7856. ms = 0;
  7857. }
  7858. }
  7859. }
  7860. static void wait_for_heater(long codenum, uint8_t extruder) {
  7861. if (!degTargetHotend(extruder))
  7862. return;
  7863. #ifdef TEMP_RESIDENCY_TIME
  7864. long residencyStart;
  7865. residencyStart = -1;
  7866. /* continue to loop until we have reached the target temp
  7867. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  7868. cancel_heatup = false;
  7869. while ((!cancel_heatup) && ((residencyStart == -1) ||
  7870. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  7871. #else
  7872. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  7873. #endif //TEMP_RESIDENCY_TIME
  7874. if ((_millis() - codenum) > 1000UL)
  7875. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  7876. if (!farm_mode) {
  7877. SERIAL_PROTOCOLPGM("T:");
  7878. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  7879. SERIAL_PROTOCOLPGM(" E:");
  7880. SERIAL_PROTOCOL((int)extruder);
  7881. #ifdef TEMP_RESIDENCY_TIME
  7882. SERIAL_PROTOCOLPGM(" W:");
  7883. if (residencyStart > -1)
  7884. {
  7885. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  7886. SERIAL_PROTOCOLLN(codenum);
  7887. }
  7888. else
  7889. {
  7890. SERIAL_PROTOCOLLN("?");
  7891. }
  7892. }
  7893. #else
  7894. SERIAL_PROTOCOLLN("");
  7895. #endif
  7896. codenum = _millis();
  7897. }
  7898. manage_heater();
  7899. manage_inactivity(true); //do not disable steppers
  7900. lcd_update(0);
  7901. #ifdef TEMP_RESIDENCY_TIME
  7902. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  7903. or when current temp falls outside the hysteresis after target temp was reached */
  7904. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  7905. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  7906. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  7907. {
  7908. residencyStart = _millis();
  7909. }
  7910. #endif //TEMP_RESIDENCY_TIME
  7911. }
  7912. }
  7913. void check_babystep()
  7914. {
  7915. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  7916. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  7917. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  7918. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  7919. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  7920. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  7921. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  7922. babystep_z);
  7923. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  7924. lcd_update_enable(true);
  7925. }
  7926. }
  7927. #ifdef HEATBED_ANALYSIS
  7928. void d_setup()
  7929. {
  7930. pinMode(D_DATACLOCK, INPUT_PULLUP);
  7931. pinMode(D_DATA, INPUT_PULLUP);
  7932. pinMode(D_REQUIRE, OUTPUT);
  7933. digitalWrite(D_REQUIRE, HIGH);
  7934. }
  7935. float d_ReadData()
  7936. {
  7937. int digit[13];
  7938. String mergeOutput;
  7939. float output;
  7940. digitalWrite(D_REQUIRE, HIGH);
  7941. for (int i = 0; i<13; i++)
  7942. {
  7943. for (int j = 0; j < 4; j++)
  7944. {
  7945. while (digitalRead(D_DATACLOCK) == LOW) {}
  7946. while (digitalRead(D_DATACLOCK) == HIGH) {}
  7947. bitWrite(digit[i], j, digitalRead(D_DATA));
  7948. }
  7949. }
  7950. digitalWrite(D_REQUIRE, LOW);
  7951. mergeOutput = "";
  7952. output = 0;
  7953. for (int r = 5; r <= 10; r++) //Merge digits
  7954. {
  7955. mergeOutput += digit[r];
  7956. }
  7957. output = mergeOutput.toFloat();
  7958. if (digit[4] == 8) //Handle sign
  7959. {
  7960. output *= -1;
  7961. }
  7962. for (int i = digit[11]; i > 0; i--) //Handle floating point
  7963. {
  7964. output /= 10;
  7965. }
  7966. return output;
  7967. }
  7968. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  7969. int t1 = 0;
  7970. int t_delay = 0;
  7971. int digit[13];
  7972. int m;
  7973. char str[3];
  7974. //String mergeOutput;
  7975. char mergeOutput[15];
  7976. float output;
  7977. int mesh_point = 0; //index number of calibration point
  7978. 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
  7979. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  7980. float mesh_home_z_search = 4;
  7981. float measure_z_height = 0.2f;
  7982. float row[x_points_num];
  7983. int ix = 0;
  7984. int iy = 0;
  7985. const char* filename_wldsd = "mesh.txt";
  7986. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  7987. char numb_wldsd[8]; // (" -A.BCD" + null)
  7988. #ifdef MICROMETER_LOGGING
  7989. d_setup();
  7990. #endif //MICROMETER_LOGGING
  7991. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  7992. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  7993. unsigned int custom_message_type_old = custom_message_type;
  7994. unsigned int custom_message_state_old = custom_message_state;
  7995. custom_message_type = CustomMsg::MeshBedLeveling;
  7996. custom_message_state = (x_points_num * y_points_num) + 10;
  7997. lcd_update(1);
  7998. //mbl.reset();
  7999. babystep_undo();
  8000. card.openFile(filename_wldsd, false);
  8001. /*destination[Z_AXIS] = mesh_home_z_search;
  8002. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8003. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  8004. for(int8_t i=0; i < NUM_AXIS; i++) {
  8005. current_position[i] = destination[i];
  8006. }
  8007. st_synchronize();
  8008. */
  8009. destination[Z_AXIS] = measure_z_height;
  8010. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  8011. for(int8_t i=0; i < NUM_AXIS; i++) {
  8012. current_position[i] = destination[i];
  8013. }
  8014. st_synchronize();
  8015. /*int l_feedmultiply = */setup_for_endstop_move(false);
  8016. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8017. SERIAL_PROTOCOL(x_points_num);
  8018. SERIAL_PROTOCOLPGM(",");
  8019. SERIAL_PROTOCOL(y_points_num);
  8020. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8021. SERIAL_PROTOCOL(mesh_home_z_search);
  8022. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8023. SERIAL_PROTOCOL(x_dimension);
  8024. SERIAL_PROTOCOLPGM(",");
  8025. SERIAL_PROTOCOL(y_dimension);
  8026. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8027. while (mesh_point != x_points_num * y_points_num) {
  8028. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8029. iy = mesh_point / x_points_num;
  8030. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8031. float z0 = 0.f;
  8032. /*destination[Z_AXIS] = mesh_home_z_search;
  8033. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8034. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  8035. for(int8_t i=0; i < NUM_AXIS; i++) {
  8036. current_position[i] = destination[i];
  8037. }
  8038. st_synchronize();*/
  8039. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8040. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8041. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  8042. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  8043. mesh_plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], XY_AXIS_FEEDRATE/6, active_extruder);
  8044. set_current_to_destination();
  8045. st_synchronize();
  8046. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  8047. delay_keep_alive(1000);
  8048. #ifdef MICROMETER_LOGGING
  8049. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8050. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8051. //strcat(data_wldsd, numb_wldsd);
  8052. //MYSERIAL.println(data_wldsd);
  8053. //delay(1000);
  8054. //delay(3000);
  8055. //t1 = millis();
  8056. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8057. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8058. memset(digit, 0, sizeof(digit));
  8059. //cli();
  8060. digitalWrite(D_REQUIRE, LOW);
  8061. for (int i = 0; i<13; i++)
  8062. {
  8063. //t1 = millis();
  8064. for (int j = 0; j < 4; j++)
  8065. {
  8066. while (digitalRead(D_DATACLOCK) == LOW) {}
  8067. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8068. //printf_P(PSTR("Done %d\n"), j);
  8069. bitWrite(digit[i], j, digitalRead(D_DATA));
  8070. }
  8071. //t_delay = (millis() - t1);
  8072. //SERIAL_PROTOCOLPGM(" ");
  8073. //SERIAL_PROTOCOL_F(t_delay, 5);
  8074. //SERIAL_PROTOCOLPGM(" ");
  8075. }
  8076. //sei();
  8077. digitalWrite(D_REQUIRE, HIGH);
  8078. mergeOutput[0] = '\0';
  8079. output = 0;
  8080. for (int r = 5; r <= 10; r++) //Merge digits
  8081. {
  8082. sprintf(str, "%d", digit[r]);
  8083. strcat(mergeOutput, str);
  8084. }
  8085. output = atof(mergeOutput);
  8086. if (digit[4] == 8) //Handle sign
  8087. {
  8088. output *= -1;
  8089. }
  8090. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8091. {
  8092. output *= 0.1;
  8093. }
  8094. //output = d_ReadData();
  8095. //row[ix] = current_position[Z_AXIS];
  8096. //row[ix] = d_ReadData();
  8097. row[ix] = output;
  8098. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8099. memset(data_wldsd, 0, sizeof(data_wldsd));
  8100. for (int i = 0; i < x_points_num; i++) {
  8101. SERIAL_PROTOCOLPGM(" ");
  8102. SERIAL_PROTOCOL_F(row[i], 5);
  8103. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8104. dtostrf(row[i], 7, 3, numb_wldsd);
  8105. strcat(data_wldsd, numb_wldsd);
  8106. }
  8107. card.write_command(data_wldsd);
  8108. SERIAL_PROTOCOLPGM("\n");
  8109. }
  8110. custom_message_state--;
  8111. mesh_point++;
  8112. lcd_update(1);
  8113. }
  8114. #endif //MICROMETER_LOGGING
  8115. card.closefile();
  8116. //clean_up_after_endstop_move(l_feedmultiply);
  8117. }
  8118. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8119. int t1 = 0;
  8120. int t_delay = 0;
  8121. int digit[13];
  8122. int m;
  8123. char str[3];
  8124. //String mergeOutput;
  8125. char mergeOutput[15];
  8126. float output;
  8127. int mesh_point = 0; //index number of calibration point
  8128. 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
  8129. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8130. float mesh_home_z_search = 4;
  8131. float row[x_points_num];
  8132. int ix = 0;
  8133. int iy = 0;
  8134. const char* filename_wldsd = "wldsd.txt";
  8135. char data_wldsd[70];
  8136. char numb_wldsd[10];
  8137. d_setup();
  8138. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  8139. // We don't know where we are! HOME!
  8140. // Push the commands to the front of the message queue in the reverse order!
  8141. // There shall be always enough space reserved for these commands.
  8142. repeatcommand_front(); // repeat G80 with all its parameters
  8143. enquecommand_front_P((PSTR("G28 W0")));
  8144. enquecommand_front_P((PSTR("G1 Z5")));
  8145. return;
  8146. }
  8147. unsigned int custom_message_type_old = custom_message_type;
  8148. unsigned int custom_message_state_old = custom_message_state;
  8149. custom_message_type = CustomMsg::MeshBedLeveling;
  8150. custom_message_state = (x_points_num * y_points_num) + 10;
  8151. lcd_update(1);
  8152. mbl.reset();
  8153. babystep_undo();
  8154. card.openFile(filename_wldsd, false);
  8155. current_position[Z_AXIS] = mesh_home_z_search;
  8156. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  8157. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8158. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8159. int l_feedmultiply = setup_for_endstop_move(false);
  8160. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8161. SERIAL_PROTOCOL(x_points_num);
  8162. SERIAL_PROTOCOLPGM(",");
  8163. SERIAL_PROTOCOL(y_points_num);
  8164. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8165. SERIAL_PROTOCOL(mesh_home_z_search);
  8166. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8167. SERIAL_PROTOCOL(x_dimension);
  8168. SERIAL_PROTOCOLPGM(",");
  8169. SERIAL_PROTOCOL(y_dimension);
  8170. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8171. while (mesh_point != x_points_num * y_points_num) {
  8172. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8173. iy = mesh_point / x_points_num;
  8174. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8175. float z0 = 0.f;
  8176. current_position[Z_AXIS] = mesh_home_z_search;
  8177. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8178. st_synchronize();
  8179. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8180. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8181. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  8182. st_synchronize();
  8183. 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
  8184. break;
  8185. card.closefile();
  8186. }
  8187. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8188. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8189. //strcat(data_wldsd, numb_wldsd);
  8190. //MYSERIAL.println(data_wldsd);
  8191. //_delay(1000);
  8192. //_delay(3000);
  8193. //t1 = _millis();
  8194. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8195. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8196. memset(digit, 0, sizeof(digit));
  8197. //cli();
  8198. digitalWrite(D_REQUIRE, LOW);
  8199. for (int i = 0; i<13; i++)
  8200. {
  8201. //t1 = _millis();
  8202. for (int j = 0; j < 4; j++)
  8203. {
  8204. while (digitalRead(D_DATACLOCK) == LOW) {}
  8205. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8206. bitWrite(digit[i], j, digitalRead(D_DATA));
  8207. }
  8208. //t_delay = (_millis() - t1);
  8209. //SERIAL_PROTOCOLPGM(" ");
  8210. //SERIAL_PROTOCOL_F(t_delay, 5);
  8211. //SERIAL_PROTOCOLPGM(" ");
  8212. }
  8213. //sei();
  8214. digitalWrite(D_REQUIRE, HIGH);
  8215. mergeOutput[0] = '\0';
  8216. output = 0;
  8217. for (int r = 5; r <= 10; r++) //Merge digits
  8218. {
  8219. sprintf(str, "%d", digit[r]);
  8220. strcat(mergeOutput, str);
  8221. }
  8222. output = atof(mergeOutput);
  8223. if (digit[4] == 8) //Handle sign
  8224. {
  8225. output *= -1;
  8226. }
  8227. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8228. {
  8229. output *= 0.1;
  8230. }
  8231. //output = d_ReadData();
  8232. //row[ix] = current_position[Z_AXIS];
  8233. memset(data_wldsd, 0, sizeof(data_wldsd));
  8234. for (int i = 0; i <3; i++) {
  8235. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8236. dtostrf(current_position[i], 8, 5, numb_wldsd);
  8237. strcat(data_wldsd, numb_wldsd);
  8238. strcat(data_wldsd, ";");
  8239. }
  8240. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8241. dtostrf(output, 8, 5, numb_wldsd);
  8242. strcat(data_wldsd, numb_wldsd);
  8243. //strcat(data_wldsd, ";");
  8244. card.write_command(data_wldsd);
  8245. //row[ix] = d_ReadData();
  8246. row[ix] = output; // current_position[Z_AXIS];
  8247. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8248. for (int i = 0; i < x_points_num; i++) {
  8249. SERIAL_PROTOCOLPGM(" ");
  8250. SERIAL_PROTOCOL_F(row[i], 5);
  8251. }
  8252. SERIAL_PROTOCOLPGM("\n");
  8253. }
  8254. custom_message_state--;
  8255. mesh_point++;
  8256. lcd_update(1);
  8257. }
  8258. card.closefile();
  8259. clean_up_after_endstop_move(l_feedmultiply);
  8260. }
  8261. #endif //HEATBED_ANALYSIS
  8262. #ifndef PINDA_THERMISTOR
  8263. static void temp_compensation_start() {
  8264. custom_message_type = CustomMsg::TempCompPreheat;
  8265. custom_message_state = PINDA_HEAT_T + 1;
  8266. lcd_update(2);
  8267. if (degHotend(active_extruder) > EXTRUDE_MINTEMP) {
  8268. current_position[E_AXIS] -= default_retraction;
  8269. }
  8270. plan_buffer_line_curposXYZE(400, active_extruder);
  8271. current_position[X_AXIS] = PINDA_PREHEAT_X;
  8272. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  8273. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  8274. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  8275. st_synchronize();
  8276. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  8277. for (int i = 0; i < PINDA_HEAT_T; i++) {
  8278. delay_keep_alive(1000);
  8279. custom_message_state = PINDA_HEAT_T - i;
  8280. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  8281. else lcd_update(1);
  8282. }
  8283. custom_message_type = CustomMsg::Status;
  8284. custom_message_state = 0;
  8285. }
  8286. static void temp_compensation_apply() {
  8287. int i_add;
  8288. int z_shift = 0;
  8289. float z_shift_mm;
  8290. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  8291. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  8292. i_add = (target_temperature_bed - 60) / 10;
  8293. EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + i_add * 2, &z_shift);
  8294. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  8295. }else {
  8296. //interpolation
  8297. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  8298. }
  8299. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  8300. 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);
  8301. st_synchronize();
  8302. plan_set_z_position(current_position[Z_AXIS]);
  8303. }
  8304. else {
  8305. //we have no temp compensation data
  8306. }
  8307. }
  8308. #endif //ndef PINDA_THERMISTOR
  8309. float temp_comp_interpolation(float inp_temperature) {
  8310. //cubic spline interpolation
  8311. int n, i, j;
  8312. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  8313. int shift[10];
  8314. int temp_C[10];
  8315. n = 6; //number of measured points
  8316. shift[0] = 0;
  8317. for (i = 0; i < n; i++) {
  8318. if (i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i-1) * 2, &shift[i]); //read shift in steps from EEPROM
  8319. temp_C[i] = 50 + i * 10; //temperature in C
  8320. #ifdef PINDA_THERMISTOR
  8321. temp_C[i] = 35 + i * 5; //temperature in C
  8322. #else
  8323. temp_C[i] = 50 + i * 10; //temperature in C
  8324. #endif
  8325. x[i] = (float)temp_C[i];
  8326. f[i] = (float)shift[i];
  8327. }
  8328. if (inp_temperature < x[0]) return 0;
  8329. for (i = n - 1; i>0; i--) {
  8330. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  8331. h[i - 1] = x[i] - x[i - 1];
  8332. }
  8333. //*********** formation of h, s , f matrix **************
  8334. for (i = 1; i<n - 1; i++) {
  8335. m[i][i] = 2 * (h[i - 1] + h[i]);
  8336. if (i != 1) {
  8337. m[i][i - 1] = h[i - 1];
  8338. m[i - 1][i] = h[i - 1];
  8339. }
  8340. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  8341. }
  8342. //*********** forward elimination **************
  8343. for (i = 1; i<n - 2; i++) {
  8344. temp = (m[i + 1][i] / m[i][i]);
  8345. for (j = 1; j <= n - 1; j++)
  8346. m[i + 1][j] -= temp*m[i][j];
  8347. }
  8348. //*********** backward substitution *********
  8349. for (i = n - 2; i>0; i--) {
  8350. sum = 0;
  8351. for (j = i; j <= n - 2; j++)
  8352. sum += m[i][j] * s[j];
  8353. s[i] = (m[i][n - 1] - sum) / m[i][i];
  8354. }
  8355. for (i = 0; i<n - 1; i++)
  8356. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  8357. a = (s[i + 1] - s[i]) / (6 * h[i]);
  8358. b = s[i] / 2;
  8359. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  8360. d = f[i];
  8361. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  8362. }
  8363. return sum;
  8364. }
  8365. #ifdef PINDA_THERMISTOR
  8366. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  8367. {
  8368. if (!temp_cal_active) return 0;
  8369. if (!calibration_status_pinda()) return 0;
  8370. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  8371. }
  8372. #endif //PINDA_THERMISTOR
  8373. void long_pause() //long pause print
  8374. {
  8375. st_synchronize();
  8376. start_pause_print = _millis();
  8377. // Stop heaters
  8378. setAllTargetHotends(0);
  8379. //lift z
  8380. current_position[Z_AXIS] += Z_PAUSE_LIFT;
  8381. if (current_position[Z_AXIS] > Z_MAX_POS) current_position[Z_AXIS] = Z_MAX_POS;
  8382. plan_buffer_line_curposXYZE(15, active_extruder);
  8383. //Move XY to side
  8384. current_position[X_AXIS] = X_PAUSE_POS;
  8385. current_position[Y_AXIS] = Y_PAUSE_POS;
  8386. plan_buffer_line_curposXYZE(50, active_extruder);
  8387. // Turn off the print fan
  8388. fanSpeed = 0;
  8389. }
  8390. void serialecho_temperatures() {
  8391. float tt = degHotend(active_extruder);
  8392. SERIAL_PROTOCOLPGM("T:");
  8393. SERIAL_PROTOCOL(tt);
  8394. SERIAL_PROTOCOLPGM(" E:");
  8395. SERIAL_PROTOCOL((int)active_extruder);
  8396. SERIAL_PROTOCOLPGM(" B:");
  8397. SERIAL_PROTOCOL_F(degBed(), 1);
  8398. SERIAL_PROTOCOLLN("");
  8399. }
  8400. #ifdef UVLO_SUPPORT
  8401. void uvlo_()
  8402. {
  8403. unsigned long time_start = _millis();
  8404. bool sd_print = card.sdprinting;
  8405. // Conserve power as soon as possible.
  8406. #ifdef LCD_BL_PIN
  8407. backlightMode = BACKLIGHT_MODE_DIM;
  8408. backlightLevel_LOW = 0;
  8409. backlight_update();
  8410. #endif //LCD_BL_PIN
  8411. disable_x();
  8412. disable_y();
  8413. #ifdef TMC2130
  8414. tmc2130_set_current_h(Z_AXIS, 20);
  8415. tmc2130_set_current_r(Z_AXIS, 20);
  8416. tmc2130_set_current_h(E_AXIS, 20);
  8417. tmc2130_set_current_r(E_AXIS, 20);
  8418. #endif //TMC2130
  8419. // Indicate that the interrupt has been triggered.
  8420. // SERIAL_ECHOLNPGM("UVLO");
  8421. // Read out the current Z motor microstep counter. This will be later used
  8422. // for reaching the zero full step before powering off.
  8423. uint16_t z_microsteps = 0;
  8424. #ifdef TMC2130
  8425. z_microsteps = tmc2130_rd_MSCNT(Z_TMC2130_CS);
  8426. #endif //TMC2130
  8427. // Calculate the file position, from which to resume this print.
  8428. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  8429. {
  8430. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  8431. sd_position -= sdlen_planner;
  8432. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  8433. sd_position -= sdlen_cmdqueue;
  8434. if (sd_position < 0) sd_position = 0;
  8435. }
  8436. // save the global state at planning time
  8437. uint16_t feedrate_bckp;
  8438. if (blocks_queued())
  8439. {
  8440. memcpy(saved_target, current_block->gcode_target, sizeof(saved_target));
  8441. feedrate_bckp = current_block->gcode_feedrate;
  8442. }
  8443. else
  8444. {
  8445. saved_target[0] = SAVED_TARGET_UNSET;
  8446. feedrate_bckp = feedrate;
  8447. }
  8448. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  8449. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  8450. // are in action.
  8451. planner_abort_hard();
  8452. // Store the current extruder position.
  8453. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), st_get_position_mm(E_AXIS));
  8454. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, axis_relative_modes[3]?0:1);
  8455. // Clean the input command queue.
  8456. cmdqueue_reset();
  8457. card.sdprinting = false;
  8458. // card.closefile();
  8459. // Enable stepper driver interrupt to move Z axis.
  8460. // This should be fine as the planner and command queues are empty and the SD card printing is disabled.
  8461. //FIXME one may want to disable serial lines at this point of time to avoid interfering with the command queue,
  8462. // though it should not happen that the command queue is touched as the plan_buffer_line always succeed without blocking.
  8463. sei();
  8464. plan_buffer_line(
  8465. current_position[X_AXIS],
  8466. current_position[Y_AXIS],
  8467. current_position[Z_AXIS],
  8468. current_position[E_AXIS] - default_retraction,
  8469. 95, active_extruder);
  8470. st_synchronize();
  8471. disable_e0();
  8472. plan_buffer_line(
  8473. current_position[X_AXIS],
  8474. current_position[Y_AXIS],
  8475. current_position[Z_AXIS] + UVLO_Z_AXIS_SHIFT + float((1024 - z_microsteps + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS],
  8476. current_position[E_AXIS] - default_retraction,
  8477. 40, active_extruder);
  8478. st_synchronize();
  8479. disable_e0();
  8480. plan_buffer_line(
  8481. current_position[X_AXIS],
  8482. current_position[Y_AXIS],
  8483. current_position[Z_AXIS] + UVLO_Z_AXIS_SHIFT + float((1024 - z_microsteps + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS],
  8484. current_position[E_AXIS] - default_retraction,
  8485. 40, active_extruder);
  8486. st_synchronize();
  8487. disable_e0();
  8488. // Move Z up to the next 0th full step.
  8489. // Write the file position.
  8490. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  8491. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  8492. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  8493. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  8494. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  8495. // Scale the z value to 1u resolution.
  8496. int16_t v = mbl.active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  8497. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  8498. }
  8499. // Read out the current Z motor microstep counter. This will be later used
  8500. // for reaching the zero full step before powering off.
  8501. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  8502. // Store the current position.
  8503. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  8504. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  8505. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z , current_position[Z_AXIS]);
  8506. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  8507. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDRATE, feedrate_bckp);
  8508. EEPROM_save_B(EEPROM_UVLO_FEEDMULTIPLY, &feedmultiply);
  8509. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_HOTEND, target_temperature[active_extruder]);
  8510. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, target_temperature_bed);
  8511. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  8512. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  8513. #if EXTRUDERS > 1
  8514. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  8515. #if EXTRUDERS > 2
  8516. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  8517. #endif
  8518. #endif
  8519. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  8520. // Store the saved target
  8521. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+0*4), saved_target[X_AXIS]);
  8522. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+1*4), saved_target[Y_AXIS]);
  8523. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+2*4), saved_target[Z_AXIS]);
  8524. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_TARGET+3*4), saved_target[E_AXIS]);
  8525. #ifdef LIN_ADVANCE
  8526. eeprom_update_float((float*)(EEPROM_UVLO_LA_K), extruder_advance_K);
  8527. #endif
  8528. // Finaly store the "power outage" flag.
  8529. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  8530. st_synchronize();
  8531. printf_P(_N("stps%d\n"), tmc2130_rd_MSCNT(Z_AXIS));
  8532. // Increment power failure counter
  8533. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  8534. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  8535. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  8536. #if 0
  8537. // Move the print head to the side of the print until all the power stored in the power supply capacitors is depleted.
  8538. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  8539. plan_buffer_line_curposXYZE(500, active_extruder);
  8540. st_synchronize();
  8541. #endif
  8542. wdt_enable(WDTO_500MS);
  8543. WRITE(BEEPER,HIGH);
  8544. while(1)
  8545. ;
  8546. }
  8547. void uvlo_tiny()
  8548. {
  8549. uint16_t z_microsteps=0;
  8550. // Conserve power as soon as possible.
  8551. disable_x();
  8552. disable_y();
  8553. disable_e0();
  8554. #ifdef TMC2130
  8555. tmc2130_set_current_h(Z_AXIS, 20);
  8556. tmc2130_set_current_r(Z_AXIS, 20);
  8557. #endif //TMC2130
  8558. // Read out the current Z motor microstep counter
  8559. #ifdef TMC2130
  8560. z_microsteps=tmc2130_rd_MSCNT(Z_TMC2130_CS);
  8561. #endif //TMC2130
  8562. planner_abort_hard();
  8563. //save current position only in case, where the printer is moving on Z axis, which is only when EEPROM_UVLO is 1
  8564. //EEPROM_UVLO is 1 after normal uvlo or after recover_print(), when the extruder is moving on Z axis after rehome
  8565. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)!=2){
  8566. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  8567. eeprom_update_word((uint16_t*)(EEPROM_UVLO_TINY_Z_MICROSTEPS),z_microsteps);
  8568. }
  8569. //after multiple power panics current Z axis is unknow
  8570. //in this case we set EEPROM_UVLO_TINY_CURRENT_POSITION_Z to last know position which is EEPROM_UVLO_CURRENT_POSITION_Z
  8571. if(eeprom_read_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z) < 0.001f){
  8572. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), eeprom_read_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z));
  8573. eeprom_update_word((uint16_t*)(EEPROM_UVLO_TINY_Z_MICROSTEPS), eeprom_read_word((uint16_t*)EEPROM_UVLO_Z_MICROSTEPS));
  8574. }
  8575. // Finaly store the "power outage" flag.
  8576. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  8577. // Increment power failure counter
  8578. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  8579. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  8580. wdt_enable(WDTO_500MS);
  8581. WRITE(BEEPER,HIGH);
  8582. while(1)
  8583. ;
  8584. }
  8585. #endif //UVLO_SUPPORT
  8586. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  8587. void setup_fan_interrupt() {
  8588. //INT7
  8589. DDRE &= ~(1 << 7); //input pin
  8590. PORTE &= ~(1 << 7); //no internal pull-up
  8591. //start with sensing rising edge
  8592. EICRB &= ~(1 << 6);
  8593. EICRB |= (1 << 7);
  8594. //enable INT7 interrupt
  8595. EIMSK |= (1 << 7);
  8596. }
  8597. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  8598. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  8599. ISR(INT7_vect) {
  8600. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  8601. #ifdef FAN_SOFT_PWM
  8602. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  8603. #else //FAN_SOFT_PWM
  8604. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  8605. #endif //FAN_SOFT_PWM
  8606. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  8607. t_fan_rising_edge = millis_nc();
  8608. }
  8609. else { //interrupt was triggered by falling edge
  8610. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  8611. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  8612. }
  8613. }
  8614. EICRB ^= (1 << 6); //change edge
  8615. }
  8616. #endif
  8617. #ifdef UVLO_SUPPORT
  8618. void setup_uvlo_interrupt() {
  8619. DDRE &= ~(1 << 4); //input pin
  8620. PORTE &= ~(1 << 4); //no internal pull-up
  8621. //sensing falling edge
  8622. EICRB |= (1 << 0);
  8623. EICRB &= ~(1 << 1);
  8624. //enable INT4 interrupt
  8625. EIMSK |= (1 << 4);
  8626. }
  8627. ISR(INT4_vect) {
  8628. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  8629. SERIAL_ECHOLNPGM("INT4");
  8630. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  8631. if(PRINTER_ACTIVE && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  8632. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  8633. }
  8634. void recover_print(uint8_t automatic) {
  8635. char cmd[30];
  8636. lcd_update_enable(true);
  8637. lcd_update(2);
  8638. lcd_setstatuspgm(_i("Recovering print "));////MSG_RECOVERING_PRINT c=20 r=1
  8639. bool bTiny=(eeprom_read_byte((uint8_t*)EEPROM_UVLO)==2);
  8640. recover_machine_state_after_power_panic(bTiny); //recover position, temperatures and extrude_multipliers
  8641. // Lift the print head, so one may remove the excess priming material.
  8642. if(!bTiny&&(current_position[Z_AXIS]<25))
  8643. enquecommand_P(PSTR("G1 Z25 F800"));
  8644. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine transformation status.
  8645. enquecommand_P(PSTR("G28 X Y"));
  8646. // Set the target bed and nozzle temperatures and wait.
  8647. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  8648. enquecommand(cmd);
  8649. sprintf_P(cmd, PSTR("M190 S%d"), target_temperature_bed);
  8650. enquecommand(cmd);
  8651. enquecommand_P(PSTR("M83")); //E axis relative mode
  8652. //enquecommand_P(PSTR("G1 E5 F120")); //Extrude some filament to stabilize pessure
  8653. // If not automatically recoreverd (long power loss), extrude extra filament to stabilize
  8654. if(automatic == 0){
  8655. enquecommand_P(PSTR("G1 E5 F120")); //Extrude some filament to stabilize pessure
  8656. }
  8657. enquecommand_P(PSTR("G1 E" STRINGIFY(-default_retraction)" F480"));
  8658. 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]);
  8659. // Restart the print.
  8660. restore_print_from_eeprom();
  8661. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  8662. }
  8663. void recover_machine_state_after_power_panic(bool bTiny)
  8664. {
  8665. char cmd[30];
  8666. // 1) Recover the logical cordinates at the time of the power panic.
  8667. // The logical XY coordinates are needed to recover the machine Z coordinate corrected by the mesh bed leveling.
  8668. current_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  8669. current_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  8670. // 2) Restore the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  8671. mbl.active = false;
  8672. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  8673. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  8674. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  8675. // Scale the z value to 10u resolution.
  8676. int16_t v;
  8677. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  8678. if (v != 0)
  8679. mbl.active = true;
  8680. mbl.z_values[iy][ix] = float(v) * 0.001f;
  8681. }
  8682. // Recover the logical coordinate of the Z axis at the time of the power panic.
  8683. // The current position after power panic is moved to the next closest 0th full step.
  8684. if(bTiny){
  8685. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z))
  8686. + float((1024 - eeprom_read_word((uint16_t*)(EEPROM_UVLO_TINY_Z_MICROSTEPS))
  8687. + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS];
  8688. //after multiple power panics the print is slightly in the air so get it little bit down.
  8689. //Not exactly sure why is this happening, but it has something to do with bed leveling and world2machine coordinates
  8690. current_position[Z_AXIS] -= 0.4*mbl.get_z(current_position[X_AXIS], current_position[Y_AXIS]);
  8691. }
  8692. else{
  8693. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)) +
  8694. UVLO_Z_AXIS_SHIFT + float((1024 - eeprom_read_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS))
  8695. + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS];
  8696. }
  8697. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS)) {
  8698. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  8699. sprintf_P(cmd, PSTR("G92 E"));
  8700. dtostrf(current_position[E_AXIS], 6, 3, cmd + strlen(cmd));
  8701. enquecommand(cmd);
  8702. }
  8703. memcpy(destination, current_position, sizeof(destination));
  8704. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  8705. print_world_coordinates();
  8706. // 3) Initialize the logical to physical coordinate system transformation.
  8707. world2machine_initialize();
  8708. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  8709. // print_mesh_bed_leveling_table();
  8710. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  8711. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  8712. babystep_load();
  8713. // 5) Set the physical positions from the logical positions using the world2machine transformation and the active bed leveling.
  8714. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  8715. // 6) Power up the motors, mark their positions as known.
  8716. //FIXME Verfiy, whether the X and Y axes should be powered up here, as they will later be re-homed anyway.
  8717. axis_known_position[X_AXIS] = true; enable_x();
  8718. axis_known_position[Y_AXIS] = true; enable_y();
  8719. axis_known_position[Z_AXIS] = true; enable_z();
  8720. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  8721. print_physical_coordinates();
  8722. // 7) Recover the target temperatures.
  8723. target_temperature[active_extruder] = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_HOTEND);
  8724. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  8725. // 8) Recover extruder multipilers
  8726. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  8727. #if EXTRUDERS > 1
  8728. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  8729. #if EXTRUDERS > 2
  8730. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  8731. #endif
  8732. #endif
  8733. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  8734. // 9) Recover the saved target
  8735. saved_target[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+0*4));
  8736. saved_target[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+1*4));
  8737. saved_target[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+2*4));
  8738. saved_target[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_TARGET+3*4));
  8739. #ifdef LIN_ADVANCE
  8740. extruder_advance_K = eeprom_read_float((float*)EEPROM_UVLO_LA_K);
  8741. #endif
  8742. }
  8743. void restore_print_from_eeprom() {
  8744. int feedrate_rec;
  8745. int feedmultiply_rec;
  8746. uint8_t fan_speed_rec;
  8747. char cmd[30];
  8748. char filename[13];
  8749. uint8_t depth = 0;
  8750. char dir_name[9];
  8751. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  8752. feedrate_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDRATE);
  8753. EEPROM_read_B(EEPROM_UVLO_FEEDMULTIPLY, &feedmultiply_rec);
  8754. SERIAL_ECHOPGM("Feedrate:");
  8755. MYSERIAL.print(feedrate_rec);
  8756. SERIAL_ECHOPGM(", feedmultiply:");
  8757. MYSERIAL.println(feedmultiply_rec);
  8758. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  8759. MYSERIAL.println(int(depth));
  8760. for (int i = 0; i < depth; i++) {
  8761. for (int j = 0; j < 8; j++) {
  8762. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  8763. }
  8764. dir_name[8] = '\0';
  8765. MYSERIAL.println(dir_name);
  8766. strcpy(dir_names[i], dir_name);
  8767. card.chdir(dir_name);
  8768. }
  8769. for (int i = 0; i < 8; i++) {
  8770. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  8771. }
  8772. filename[8] = '\0';
  8773. MYSERIAL.print(filename);
  8774. strcat_P(filename, PSTR(".gco"));
  8775. sprintf_P(cmd, PSTR("M23 %s"), filename);
  8776. enquecommand(cmd);
  8777. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  8778. SERIAL_ECHOPGM("Position read from eeprom:");
  8779. MYSERIAL.println(position);
  8780. // E axis relative mode.
  8781. enquecommand_P(PSTR("M83"));
  8782. // Move to the XY print position in logical coordinates, where the print has been killed.
  8783. strcpy_P(cmd, PSTR("G1 X")); strcat(cmd, ftostr32(eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0))));
  8784. strcat_P(cmd, PSTR(" Y")); strcat(cmd, ftostr32(eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4))));
  8785. strcat_P(cmd, PSTR(" F2000"));
  8786. enquecommand(cmd);
  8787. //moving on Z axis ahead, set EEPROM_UVLO to 1, so normal uvlo can fire
  8788. eeprom_update_byte((uint8_t*)EEPROM_UVLO,1);
  8789. // Move the Z axis down to the print, in logical coordinates.
  8790. strcpy_P(cmd, PSTR("G1 Z")); strcat(cmd, ftostr32(eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z))));
  8791. enquecommand(cmd);
  8792. // Unretract.
  8793. enquecommand_P(PSTR("G1 E" STRINGIFY(2*default_retraction)" F480"));
  8794. // Set the feedrates saved at the power panic.
  8795. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  8796. enquecommand(cmd);
  8797. sprintf_P(cmd, PSTR("M220 S%d"), feedmultiply_rec);
  8798. enquecommand(cmd);
  8799. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  8800. {
  8801. enquecommand_P(PSTR("M82")); //E axis abslute mode
  8802. }
  8803. // Set the fan speed saved at the power panic.
  8804. strcpy_P(cmd, PSTR("M106 S"));
  8805. strcat(cmd, itostr3(int(fan_speed_rec)));
  8806. enquecommand(cmd);
  8807. // Set a position in the file.
  8808. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  8809. enquecommand(cmd);
  8810. enquecommand_P(PSTR("G4 S0"));
  8811. enquecommand_P(PSTR("PRUSA uvlo"));
  8812. }
  8813. #endif //UVLO_SUPPORT
  8814. //! @brief Immediately stop print moves
  8815. //!
  8816. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  8817. //! If printing from sd card, position in file is saved.
  8818. //! If printing from USB, line number is saved.
  8819. //!
  8820. //! @param z_move
  8821. //! @param e_move
  8822. void stop_and_save_print_to_ram(float z_move, float e_move)
  8823. {
  8824. if (saved_printing) return;
  8825. #if 0
  8826. unsigned char nplanner_blocks;
  8827. #endif
  8828. unsigned char nlines;
  8829. uint16_t sdlen_planner;
  8830. uint16_t sdlen_cmdqueue;
  8831. cli();
  8832. if (card.sdprinting) {
  8833. #if 0
  8834. nplanner_blocks = number_of_blocks();
  8835. #endif
  8836. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  8837. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  8838. saved_sdpos -= sdlen_planner;
  8839. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  8840. saved_sdpos -= sdlen_cmdqueue;
  8841. saved_printing_type = PRINTING_TYPE_SD;
  8842. }
  8843. else if (is_usb_printing) { //reuse saved_sdpos for storing line number
  8844. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  8845. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  8846. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  8847. saved_sdpos -= nlines;
  8848. saved_sdpos -= buflen; //number of blocks in cmd buffer
  8849. saved_printing_type = PRINTING_TYPE_USB;
  8850. }
  8851. else {
  8852. saved_printing_type = PRINTING_TYPE_NONE;
  8853. //not sd printing nor usb printing
  8854. }
  8855. #if 0
  8856. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  8857. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  8858. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  8859. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  8860. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  8861. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  8862. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  8863. {
  8864. card.setIndex(saved_sdpos);
  8865. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  8866. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  8867. MYSERIAL.print(char(card.get()));
  8868. SERIAL_ECHOLNPGM("Content of command buffer: ");
  8869. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  8870. MYSERIAL.print(char(card.get()));
  8871. SERIAL_ECHOLNPGM("End of command buffer");
  8872. }
  8873. {
  8874. // Print the content of the planner buffer, line by line:
  8875. card.setIndex(saved_sdpos);
  8876. int8_t iline = 0;
  8877. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  8878. SERIAL_ECHOPGM("Planner line (from file): ");
  8879. MYSERIAL.print(int(iline), DEC);
  8880. SERIAL_ECHOPGM(", length: ");
  8881. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  8882. SERIAL_ECHOPGM(", steps: (");
  8883. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  8884. SERIAL_ECHOPGM(",");
  8885. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  8886. SERIAL_ECHOPGM(",");
  8887. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  8888. SERIAL_ECHOPGM(",");
  8889. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  8890. SERIAL_ECHOPGM("), events: ");
  8891. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  8892. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  8893. MYSERIAL.print(char(card.get()));
  8894. }
  8895. }
  8896. {
  8897. // Print the content of the command buffer, line by line:
  8898. int8_t iline = 0;
  8899. union {
  8900. struct {
  8901. char lo;
  8902. char hi;
  8903. } lohi;
  8904. uint16_t value;
  8905. } sdlen_single;
  8906. int _bufindr = bufindr;
  8907. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  8908. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  8909. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  8910. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  8911. }
  8912. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  8913. MYSERIAL.print(int(iline), DEC);
  8914. SERIAL_ECHOPGM(", type: ");
  8915. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  8916. SERIAL_ECHOPGM(", len: ");
  8917. MYSERIAL.println(sdlen_single.value, DEC);
  8918. // Print the content of the buffer line.
  8919. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  8920. SERIAL_ECHOPGM("Buffer line (from file): ");
  8921. MYSERIAL.println(int(iline), DEC);
  8922. for (; sdlen_single.value > 0; -- sdlen_single.value)
  8923. MYSERIAL.print(char(card.get()));
  8924. if (-- _buflen == 0)
  8925. break;
  8926. // First skip the current command ID and iterate up to the end of the string.
  8927. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  8928. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  8929. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  8930. // If the end of the buffer was empty,
  8931. if (_bufindr == sizeof(cmdbuffer)) {
  8932. // skip to the start and find the nonzero command.
  8933. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  8934. }
  8935. }
  8936. }
  8937. #endif
  8938. // save the global state at planning time
  8939. if (blocks_queued())
  8940. {
  8941. memcpy(saved_target, current_block->gcode_target, sizeof(saved_target));
  8942. saved_feedrate2 = current_block->gcode_feedrate;
  8943. }
  8944. else
  8945. {
  8946. saved_target[0] = SAVED_TARGET_UNSET;
  8947. saved_feedrate2 = feedrate;
  8948. }
  8949. planner_abort_hard(); //abort printing
  8950. memcpy(saved_pos, current_position, sizeof(saved_pos));
  8951. saved_feedmultiply2 = feedmultiply; //save feedmultiply
  8952. saved_active_extruder = active_extruder; //save active_extruder
  8953. saved_extruder_temperature = degTargetHotend(active_extruder);
  8954. saved_extruder_relative_mode = axis_relative_modes[E_AXIS];
  8955. saved_fanSpeed = fanSpeed;
  8956. cmdqueue_reset(); //empty cmdqueue
  8957. card.sdprinting = false;
  8958. // card.closefile();
  8959. saved_printing = true;
  8960. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  8961. st_reset_timer();
  8962. sei();
  8963. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  8964. #if 1
  8965. // Rather than calling plan_buffer_line directly, push the move into the command queue so that
  8966. // the caller can continue processing. This is used during powerpanic to save the state as we
  8967. // move away from the print.
  8968. char buf[48];
  8969. if(e_move)
  8970. {
  8971. // First unretract (relative extrusion)
  8972. if(!saved_extruder_relative_mode){
  8973. enquecommand(PSTR("M83"), true);
  8974. }
  8975. //retract 45mm/s
  8976. // A single sprintf may not be faster, but is definitely 20B shorter
  8977. // than a sequence of commands building the string piece by piece
  8978. // A snprintf would have been a safer call, but since it is not used
  8979. // in the whole program, its implementation would bring more bytes to the total size
  8980. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  8981. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  8982. enquecommand(buf, false);
  8983. }
  8984. if(z_move)
  8985. {
  8986. // Then lift Z axis
  8987. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  8988. enquecommand(buf, false);
  8989. }
  8990. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  8991. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  8992. repeatcommand_front();
  8993. #else
  8994. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS] + z_move, saved_pos[E_AXIS] + e_move, homing_feedrate[Z_AXIS], active_extruder);
  8995. st_synchronize(); //wait moving
  8996. memcpy(current_position, saved_pos, sizeof(saved_pos));
  8997. memcpy(destination, current_position, sizeof(destination));
  8998. #endif
  8999. waiting_inside_plan_buffer_line_print_aborted = true; //unroll the stack
  9000. }
  9001. }
  9002. //! @brief Restore print from ram
  9003. //!
  9004. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  9005. //! print fan speed, waits for extruder temperature restore, then restores
  9006. //! position and continues print moves.
  9007. //!
  9008. //! Internally lcd_update() is called by wait_for_heater().
  9009. //!
  9010. //! @param e_move
  9011. void restore_print_from_ram_and_continue(float e_move)
  9012. {
  9013. if (!saved_printing) return;
  9014. #ifdef FANCHECK
  9015. // Do not allow resume printing if fans are still not ok
  9016. if ((fan_check_error != EFCE_OK) && (fan_check_error != EFCE_FIXED)) return;
  9017. if (fan_check_error == EFCE_FIXED) fan_check_error = EFCE_OK; //reenable serial stream processing if printing from usb
  9018. #endif
  9019. // for (int axis = X_AXIS; axis <= E_AXIS; axis++)
  9020. // current_position[axis] = st_get_position_mm(axis);
  9021. active_extruder = saved_active_extruder; //restore active_extruder
  9022. fanSpeed = saved_fanSpeed;
  9023. if (degTargetHotend(saved_active_extruder) != saved_extruder_temperature)
  9024. {
  9025. setTargetHotendSafe(saved_extruder_temperature, saved_active_extruder);
  9026. heating_status = 1;
  9027. wait_for_heater(_millis(), saved_active_extruder);
  9028. heating_status = 2;
  9029. }
  9030. axis_relative_modes[E_AXIS] = saved_extruder_relative_mode;
  9031. float e = saved_pos[E_AXIS] - e_move;
  9032. plan_set_e_position(e);
  9033. #ifdef FANCHECK
  9034. fans_check_enabled = false;
  9035. #endif
  9036. //first move print head in XY to the saved position:
  9037. 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);
  9038. //then move Z
  9039. 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);
  9040. //and finaly unretract (35mm/s)
  9041. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  9042. st_synchronize();
  9043. #ifdef FANCHECK
  9044. fans_check_enabled = true;
  9045. #endif
  9046. // restore original feedrate/feedmultiply _after_ restoring the extruder position
  9047. feedrate = saved_feedrate2;
  9048. feedmultiply = saved_feedmultiply2;
  9049. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9050. memcpy(destination, current_position, sizeof(destination));
  9051. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  9052. card.setIndex(saved_sdpos);
  9053. sdpos_atomic = saved_sdpos;
  9054. card.sdprinting = true;
  9055. }
  9056. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  9057. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  9058. serial_count = 0;
  9059. FlushSerialRequestResend();
  9060. }
  9061. else {
  9062. //not sd printing nor usb printing
  9063. }
  9064. SERIAL_PROTOCOLLNRPGM(MSG_OK); //dummy response because of octoprint is waiting for this
  9065. lcd_setstatuspgm(_T(WELCOME_MSG));
  9066. saved_printing_type = PRINTING_TYPE_NONE;
  9067. saved_printing = false;
  9068. waiting_inside_plan_buffer_line_print_aborted = true; //unroll the stack
  9069. }
  9070. // Cancel the state related to a currently saved print
  9071. void cancel_saved_printing()
  9072. {
  9073. saved_target[0] = SAVED_TARGET_UNSET;
  9074. saved_printing_type = PRINTING_TYPE_NONE;
  9075. saved_printing = false;
  9076. }
  9077. void print_world_coordinates()
  9078. {
  9079. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  9080. }
  9081. void print_physical_coordinates()
  9082. {
  9083. 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));
  9084. }
  9085. void print_mesh_bed_leveling_table()
  9086. {
  9087. SERIAL_ECHOPGM("mesh bed leveling: ");
  9088. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  9089. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  9090. MYSERIAL.print(mbl.z_values[y][x], 3);
  9091. SERIAL_ECHOPGM(" ");
  9092. }
  9093. SERIAL_ECHOLNPGM("");
  9094. }
  9095. uint16_t print_time_remaining() {
  9096. uint16_t print_t = PRINT_TIME_REMAINING_INIT;
  9097. #ifdef TMC2130
  9098. if (SilentModeMenu == SILENT_MODE_OFF) print_t = print_time_remaining_normal;
  9099. else print_t = print_time_remaining_silent;
  9100. #else
  9101. print_t = print_time_remaining_normal;
  9102. #endif //TMC2130
  9103. if ((print_t != PRINT_TIME_REMAINING_INIT) && (feedmultiply != 0)) print_t = 100ul * print_t / feedmultiply;
  9104. return print_t;
  9105. }
  9106. uint8_t calc_percent_done()
  9107. {
  9108. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  9109. uint8_t percent_done = 0;
  9110. #ifdef TMC2130
  9111. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100) {
  9112. percent_done = print_percent_done_normal;
  9113. }
  9114. else if (print_percent_done_silent <= 100) {
  9115. percent_done = print_percent_done_silent;
  9116. }
  9117. #else
  9118. if (print_percent_done_normal <= 100) {
  9119. percent_done = print_percent_done_normal;
  9120. }
  9121. #endif //TMC2130
  9122. else {
  9123. percent_done = card.percentDone();
  9124. }
  9125. return percent_done;
  9126. }
  9127. static void print_time_remaining_init()
  9128. {
  9129. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  9130. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  9131. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  9132. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  9133. }
  9134. void load_filament_final_feed()
  9135. {
  9136. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  9137. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FINAL, active_extruder);
  9138. }
  9139. //! @brief Wait for user to check the state
  9140. //! @par nozzle_temp nozzle temperature to load filament
  9141. void M600_check_state(float nozzle_temp)
  9142. {
  9143. lcd_change_fil_state = 0;
  9144. while (lcd_change_fil_state != 1)
  9145. {
  9146. lcd_change_fil_state = 0;
  9147. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9148. lcd_alright();
  9149. KEEPALIVE_STATE(IN_HANDLER);
  9150. switch(lcd_change_fil_state)
  9151. {
  9152. // Filament failed to load so load it again
  9153. case 2:
  9154. if (mmu_enabled)
  9155. mmu_M600_load_filament(false, nozzle_temp); //nonautomatic load; change to "wrong filament loaded" option?
  9156. else
  9157. M600_load_filament_movements();
  9158. break;
  9159. // Filament loaded properly but color is not clear
  9160. case 3:
  9161. st_synchronize();
  9162. load_filament_final_feed();
  9163. lcd_loading_color();
  9164. st_synchronize();
  9165. break;
  9166. // Everything good
  9167. default:
  9168. lcd_change_success();
  9169. break;
  9170. }
  9171. }
  9172. }
  9173. //! @brief Wait for user action
  9174. //!
  9175. //! Beep, manage nozzle heater and wait for user to start unload filament
  9176. //! If times out, active extruder temperature is set to 0.
  9177. //!
  9178. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  9179. void M600_wait_for_user(float HotendTempBckp) {
  9180. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9181. int counterBeep = 0;
  9182. unsigned long waiting_start_time = _millis();
  9183. uint8_t wait_for_user_state = 0;
  9184. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9185. bool bFirst=true;
  9186. while (!(wait_for_user_state == 0 && lcd_clicked())){
  9187. manage_heater();
  9188. manage_inactivity(true);
  9189. #if BEEPER > 0
  9190. if (counterBeep == 500) {
  9191. counterBeep = 0;
  9192. }
  9193. SET_OUTPUT(BEEPER);
  9194. if (counterBeep == 0) {
  9195. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  9196. {
  9197. bFirst=false;
  9198. WRITE(BEEPER, HIGH);
  9199. }
  9200. }
  9201. if (counterBeep == 20) {
  9202. WRITE(BEEPER, LOW);
  9203. }
  9204. counterBeep++;
  9205. #endif //BEEPER > 0
  9206. switch (wait_for_user_state) {
  9207. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  9208. delay_keep_alive(4);
  9209. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  9210. lcd_display_message_fullscreen_P(_i("Press knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  9211. wait_for_user_state = 1;
  9212. setAllTargetHotends(0);
  9213. st_synchronize();
  9214. disable_e0();
  9215. disable_e1();
  9216. disable_e2();
  9217. }
  9218. break;
  9219. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  9220. delay_keep_alive(4);
  9221. if (lcd_clicked()) {
  9222. setTargetHotend(HotendTempBckp, active_extruder);
  9223. lcd_wait_for_heater();
  9224. wait_for_user_state = 2;
  9225. }
  9226. break;
  9227. case 2: //waiting for nozzle to reach target temperature
  9228. if (abs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  9229. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9230. waiting_start_time = _millis();
  9231. wait_for_user_state = 0;
  9232. }
  9233. else {
  9234. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  9235. lcd_set_cursor(1, 4);
  9236. lcd_print(ftostr3(degHotend(active_extruder)));
  9237. }
  9238. break;
  9239. }
  9240. }
  9241. WRITE(BEEPER, LOW);
  9242. }
  9243. void M600_load_filament_movements()
  9244. {
  9245. #ifdef SNMM
  9246. display_loading();
  9247. do
  9248. {
  9249. current_position[E_AXIS] += 0.002;
  9250. plan_buffer_line_curposXYZE(500, active_extruder);
  9251. delay_keep_alive(2);
  9252. }
  9253. while (!lcd_clicked());
  9254. st_synchronize();
  9255. current_position[E_AXIS] += bowden_length[mmu_extruder];
  9256. plan_buffer_line_curposXYZE(3000, active_extruder);
  9257. current_position[E_AXIS] += FIL_LOAD_LENGTH - 60;
  9258. plan_buffer_line_curposXYZE(1400, active_extruder);
  9259. current_position[E_AXIS] += 40;
  9260. plan_buffer_line_curposXYZE(400, active_extruder);
  9261. current_position[E_AXIS] += 10;
  9262. plan_buffer_line_curposXYZE(50, active_extruder);
  9263. #else
  9264. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  9265. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST, active_extruder);
  9266. #endif
  9267. load_filament_final_feed();
  9268. lcd_loading_filament();
  9269. st_synchronize();
  9270. }
  9271. void M600_load_filament() {
  9272. //load filament for single material and SNMM
  9273. lcd_wait_interact();
  9274. //load_filament_time = _millis();
  9275. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9276. #ifdef PAT9125
  9277. fsensor_autoload_check_start();
  9278. #endif //PAT9125
  9279. while(!lcd_clicked())
  9280. {
  9281. manage_heater();
  9282. manage_inactivity(true);
  9283. #ifdef FILAMENT_SENSOR
  9284. if (fsensor_check_autoload())
  9285. {
  9286. Sound_MakeCustom(50,1000,false);
  9287. break;
  9288. }
  9289. #endif //FILAMENT_SENSOR
  9290. }
  9291. #ifdef PAT9125
  9292. fsensor_autoload_check_stop();
  9293. #endif //PAT9125
  9294. KEEPALIVE_STATE(IN_HANDLER);
  9295. #ifdef FSENSOR_QUALITY
  9296. fsensor_oq_meassure_start(70);
  9297. #endif //FSENSOR_QUALITY
  9298. M600_load_filament_movements();
  9299. Sound_MakeCustom(50,1000,false);
  9300. #ifdef FSENSOR_QUALITY
  9301. fsensor_oq_meassure_stop();
  9302. if (!fsensor_oq_result())
  9303. {
  9304. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Fil. sensor response is poor, disable it?"), false, true);
  9305. lcd_update_enable(true);
  9306. lcd_update(2);
  9307. if (disable)
  9308. fsensor_disable();
  9309. }
  9310. #endif //FSENSOR_QUALITY
  9311. lcd_update_enable(false);
  9312. }
  9313. //! @brief Wait for click
  9314. //!
  9315. //! Set
  9316. void marlin_wait_for_click()
  9317. {
  9318. int8_t busy_state_backup = busy_state;
  9319. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9320. lcd_consume_click();
  9321. while(!lcd_clicked())
  9322. {
  9323. manage_heater();
  9324. manage_inactivity(true);
  9325. lcd_update(0);
  9326. }
  9327. KEEPALIVE_STATE(busy_state_backup);
  9328. }
  9329. #define FIL_LOAD_LENGTH 60
  9330. #ifdef PSU_Delta
  9331. bool bEnableForce_z;
  9332. void init_force_z()
  9333. {
  9334. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  9335. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  9336. disable_force_z();
  9337. }
  9338. void check_force_z()
  9339. {
  9340. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  9341. init_force_z(); // causes enforced switching into disable-state
  9342. }
  9343. void disable_force_z()
  9344. {
  9345. uint16_t z_microsteps=0;
  9346. if(!bEnableForce_z) return; // motor already disabled (may be ;-p )
  9347. bEnableForce_z=false;
  9348. // switching to silent mode
  9349. #ifdef TMC2130
  9350. tmc2130_mode=TMC2130_MODE_SILENT;
  9351. update_mode_profile();
  9352. tmc2130_init(true);
  9353. #endif // TMC2130
  9354. axis_known_position[Z_AXIS]=false;
  9355. }
  9356. void enable_force_z()
  9357. {
  9358. if(bEnableForce_z)
  9359. return; // motor already enabled (may be ;-p )
  9360. bEnableForce_z=true;
  9361. // mode recovering
  9362. #ifdef TMC2130
  9363. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  9364. update_mode_profile();
  9365. tmc2130_init(true);
  9366. #endif // TMC2130
  9367. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  9368. }
  9369. #endif // PSU_Delta