Marlin_main.cpp 286 KB

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