Marlin_main.cpp 310 KB

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