Marlin_main.cpp 283 KB

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