Marlin_main.cpp 228 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773
  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 "ultralcd.h"
  35. #include "Configuration_prusa.h"
  36. #include "planner.h"
  37. #include "stepper.h"
  38. #include "temperature.h"
  39. #include "motion_control.h"
  40. #include "cardreader.h"
  41. #include "watchdog.h"
  42. #include "ConfigurationStore.h"
  43. #include "language.h"
  44. #include "pins_arduino.h"
  45. #include "math.h"
  46. #include "util.h"
  47. #ifdef HAVE_TMC2130_DRIVERS
  48. #include "tmc2130.h"
  49. #endif //HAVE_TMC2130_DRIVERS
  50. #ifdef BLINKM
  51. #include "BlinkM.h"
  52. #include "Wire.h"
  53. #endif
  54. #ifdef ULTRALCD
  55. #include "ultralcd.h"
  56. #endif
  57. #if NUM_SERVOS > 0
  58. #include "Servo.h"
  59. #endif
  60. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  61. #include <SPI.h>
  62. #endif
  63. #define VERSION_STRING "1.0.2"
  64. #include "ultralcd.h"
  65. // Macros for bit masks
  66. #define BIT(b) (1<<(b))
  67. #define TEST(n,b) (((n)&BIT(b))!=0)
  68. #define SET_BIT(n,b,value) (n) ^= ((-value)^(n)) & (BIT(b))
  69. // look here for descriptions of G-codes: http://linuxcnc.org/handbook/gcode/g-code.html
  70. // http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  71. //Implemented Codes
  72. //-------------------
  73. // PRUSA CODES
  74. // P F - Returns FW versions
  75. // P R - Returns revision of printer
  76. // G0 -> G1
  77. // G1 - Coordinated Movement X Y Z E
  78. // G2 - CW ARC
  79. // G3 - CCW ARC
  80. // G4 - Dwell S<seconds> or P<milliseconds>
  81. // G10 - retract filament according to settings of M207
  82. // G11 - retract recover filament according to settings of M208
  83. // G28 - Home all Axis
  84. // G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  85. // G30 - Single Z Probe, probes bed at current XY location.
  86. // G31 - Dock sled (Z_PROBE_SLED only)
  87. // G32 - Undock sled (Z_PROBE_SLED only)
  88. // G80 - Automatic mesh bed leveling
  89. // G81 - Print bed profile
  90. // G90 - Use Absolute Coordinates
  91. // G91 - Use Relative Coordinates
  92. // G92 - Set current position to coordinates given
  93. // M Codes
  94. // M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  95. // M1 - Same as M0
  96. // M17 - Enable/Power all stepper motors
  97. // M18 - Disable all stepper motors; same as M84
  98. // M20 - List SD card
  99. // M21 - Init SD card
  100. // M22 - Release SD card
  101. // M23 - Select SD file (M23 filename.g)
  102. // M24 - Start/resume SD print
  103. // M25 - Pause SD print
  104. // M26 - Set SD position in bytes (M26 S12345)
  105. // M27 - Report SD print status
  106. // M28 - Start SD write (M28 filename.g)
  107. // M29 - Stop SD write
  108. // M30 - Delete file from SD (M30 filename.g)
  109. // M31 - Output time since last M109 or SD card start to serial
  110. // M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  111. // syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  112. // Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  113. // The '#' is necessary when calling from within sd files, as it stops buffer prereading
  114. // 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.
  115. // M80 - Turn on Power Supply
  116. // M81 - Turn off Power Supply
  117. // M82 - Set E codes absolute (default)
  118. // M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  119. // M84 - Disable steppers until next move,
  120. // or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  121. // M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  122. // M92 - Set axis_steps_per_unit - same syntax as G92
  123. // M104 - Set extruder target temp
  124. // M105 - Read current temp
  125. // M106 - Fan on
  126. // M107 - Fan off
  127. // M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  128. // Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  129. // IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  130. // M112 - Emergency stop
  131. // M114 - Output current position to serial port
  132. // M115 - Capabilities string
  133. // M117 - display message
  134. // M119 - Output Endstop status to serial port
  135. // M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  136. // M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  137. // M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  138. // M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  139. // M140 - Set bed target temp
  140. // 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.
  141. // M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  142. // Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  143. // M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  144. // M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  145. // M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  146. // M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  147. // 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
  148. // 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
  149. // M206 - set additional homing offset
  150. // M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  151. // M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  152. // 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.
  153. // M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  154. // M220 S<factor in percent>- set speed factor override percentage
  155. // M221 S<factor in percent>- set extrude factor override percentage
  156. // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  157. // M240 - Trigger a camera to take a photograph
  158. // M250 - Set LCD contrast C<contrast value> (value 0..63)
  159. // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  160. // M300 - Play beep sound S<frequency Hz> P<duration ms>
  161. // M301 - Set PID parameters P I and D
  162. // M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  163. // M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  164. // M304 - Set bed PID parameters P I and D
  165. // M400 - Finish all moves
  166. // M401 - Lower z-probe if present
  167. // M402 - Raise z-probe if present
  168. // M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  169. // M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  170. // M406 - Turn off Filament Sensor extrusion control
  171. // M407 - Displays measured filament diameter
  172. // M500 - stores parameters in EEPROM
  173. // M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  174. // M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  175. // M503 - print the current settings (from memory not from EEPROM)
  176. // M509 - force language selection on next restart
  177. // M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  178. // M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  179. // M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  180. // M907 - Set digital trimpot motor current using axis codes.
  181. // M908 - Control digital trimpot directly.
  182. // M350 - Set microstepping mode.
  183. // M351 - Toggle MS1 MS2 pins directly.
  184. // M928 - Start SD logging (M928 filename.g) - ended by M29
  185. // M999 - Restart after being stopped by error
  186. //Stepper Movement Variables
  187. //===========================================================================
  188. //=============================imported variables============================
  189. //===========================================================================
  190. //===========================================================================
  191. //=============================public variables=============================
  192. //===========================================================================
  193. #ifdef SDSUPPORT
  194. CardReader card;
  195. #endif
  196. unsigned long TimeSent = millis();
  197. unsigned long TimeNow = millis();
  198. unsigned long PingTime = millis();
  199. union Data
  200. {
  201. byte b[2];
  202. int value;
  203. };
  204. float homing_feedrate[] = HOMING_FEEDRATE;
  205. // Currently only the extruder axis may be switched to a relative mode.
  206. // Other axes are always absolute or relative based on the common relative_mode flag.
  207. bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
  208. int feedmultiply=100; //100->1 200->2
  209. int saved_feedmultiply;
  210. int extrudemultiply=100; //100->1 200->2
  211. int extruder_multiply[EXTRUDERS] = {100
  212. #if EXTRUDERS > 1
  213. , 100
  214. #if EXTRUDERS > 2
  215. , 100
  216. #endif
  217. #endif
  218. };
  219. int bowden_length[4];
  220. bool is_usb_printing = false;
  221. bool homing_flag = false;
  222. bool temp_cal_active = false;
  223. unsigned long kicktime = millis()+100000;
  224. unsigned int usb_printing_counter;
  225. int lcd_change_fil_state = 0;
  226. int feedmultiplyBckp = 100;
  227. float HotendTempBckp = 0;
  228. int fanSpeedBckp = 0;
  229. float pause_lastpos[4];
  230. unsigned long pause_time = 0;
  231. unsigned long start_pause_print = millis();
  232. unsigned long load_filament_time;
  233. bool mesh_bed_leveling_flag = false;
  234. bool mesh_bed_run_from_menu = false;
  235. unsigned char lang_selected = 0;
  236. int8_t FarmMode = 0;
  237. bool prusa_sd_card_upload = false;
  238. unsigned int status_number = 0;
  239. unsigned long total_filament_used;
  240. unsigned int heating_status;
  241. unsigned int heating_status_counter;
  242. bool custom_message;
  243. bool loading_flag = false;
  244. unsigned int custom_message_type;
  245. unsigned int custom_message_state;
  246. char snmm_filaments_used = 0;
  247. float distance_from_min[3];
  248. float angleDiff;
  249. bool fan_state[2];
  250. int fan_edge_counter[2];
  251. int fan_speed[2];
  252. bool volumetric_enabled = false;
  253. float filament_size[EXTRUDERS] = { DEFAULT_NOMINAL_FILAMENT_DIA
  254. #if EXTRUDERS > 1
  255. , DEFAULT_NOMINAL_FILAMENT_DIA
  256. #if EXTRUDERS > 2
  257. , DEFAULT_NOMINAL_FILAMENT_DIA
  258. #endif
  259. #endif
  260. };
  261. float volumetric_multiplier[EXTRUDERS] = {1.0
  262. #if EXTRUDERS > 1
  263. , 1.0
  264. #if EXTRUDERS > 2
  265. , 1.0
  266. #endif
  267. #endif
  268. };
  269. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  270. float add_homing[3]={0,0,0};
  271. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  272. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  273. bool axis_known_position[3] = {false, false, false};
  274. float zprobe_zoffset;
  275. // Extruder offset
  276. #if EXTRUDERS > 1
  277. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  278. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  279. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  280. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  281. #endif
  282. };
  283. #endif
  284. uint8_t active_extruder = 0;
  285. int fanSpeed=0;
  286. #ifdef FWRETRACT
  287. bool autoretract_enabled=false;
  288. bool retracted[EXTRUDERS]={false
  289. #if EXTRUDERS > 1
  290. , false
  291. #if EXTRUDERS > 2
  292. , false
  293. #endif
  294. #endif
  295. };
  296. bool retracted_swap[EXTRUDERS]={false
  297. #if EXTRUDERS > 1
  298. , false
  299. #if EXTRUDERS > 2
  300. , false
  301. #endif
  302. #endif
  303. };
  304. float retract_length = RETRACT_LENGTH;
  305. float retract_length_swap = RETRACT_LENGTH_SWAP;
  306. float retract_feedrate = RETRACT_FEEDRATE;
  307. float retract_zlift = RETRACT_ZLIFT;
  308. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  309. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  310. float retract_recover_feedrate = RETRACT_RECOVER_FEEDRATE;
  311. #endif
  312. #ifdef ULTIPANEL
  313. #ifdef PS_DEFAULT_OFF
  314. bool powersupply = false;
  315. #else
  316. bool powersupply = true;
  317. #endif
  318. #endif
  319. bool cancel_heatup = false ;
  320. #ifdef FILAMENT_SENSOR
  321. //Variables for Filament Sensor input
  322. float filament_width_nominal=DEFAULT_NOMINAL_FILAMENT_DIA; //Set nominal filament width, can be changed with M404
  323. bool filament_sensor=false; //M405 turns on filament_sensor control, M406 turns it off
  324. float filament_width_meas=DEFAULT_MEASURED_FILAMENT_DIA; //Stores the measured filament diameter
  325. signed char measurement_delay[MAX_MEASUREMENT_DELAY+1]; //ring buffer to delay measurement store extruder factor after subtracting 100
  326. int delay_index1=0; //index into ring buffer
  327. int delay_index2=-1; //index into ring buffer - set to -1 on startup to indicate ring buffer needs to be initialized
  328. float delay_dist=0; //delay distance counter
  329. int meas_delay_cm = MEASUREMENT_DELAY_CM; //distance delay setting
  330. #endif
  331. const char errormagic[] PROGMEM = "Error:";
  332. const char echomagic[] PROGMEM = "echo:";
  333. //===========================================================================
  334. //=============================Private Variables=============================
  335. //===========================================================================
  336. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  337. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  338. static float delta[3] = {0.0, 0.0, 0.0};
  339. // For tracing an arc
  340. static float offset[3] = {0.0, 0.0, 0.0};
  341. static bool home_all_axis = true;
  342. static float feedrate = 1500.0, next_feedrate, saved_feedrate;
  343. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  344. // Determines Absolute or Relative Coordinates.
  345. // Also there is bool axis_relative_modes[] per axis flag.
  346. static bool relative_mode = false;
  347. // String circular buffer. Commands may be pushed to the buffer from both sides:
  348. // Chained commands will be pushed to the front, interactive (from LCD menu)
  349. // and printing commands (from serial line or from SD card) are pushed to the tail.
  350. // First character of each entry indicates the type of the entry:
  351. #define CMDBUFFER_CURRENT_TYPE_UNKNOWN 0
  352. // Command in cmdbuffer was sent over USB.
  353. #define CMDBUFFER_CURRENT_TYPE_USB 1
  354. // Command in cmdbuffer was read from SDCARD.
  355. #define CMDBUFFER_CURRENT_TYPE_SDCARD 2
  356. // Command in cmdbuffer was generated by the UI.
  357. #define CMDBUFFER_CURRENT_TYPE_UI 3
  358. // Command in cmdbuffer was generated by another G-code.
  359. #define CMDBUFFER_CURRENT_TYPE_CHAINED 4
  360. // How much space to reserve for the chained commands
  361. // of type CMDBUFFER_CURRENT_TYPE_CHAINED,
  362. // which are pushed to the front of the queue?
  363. // Maximum 5 commands of max length 20 + null terminator.
  364. #define CMDBUFFER_RESERVE_FRONT (5*21)
  365. // Reserve BUFSIZE lines of length MAX_CMD_SIZE plus CMDBUFFER_RESERVE_FRONT.
  366. static char cmdbuffer[BUFSIZE * (MAX_CMD_SIZE + 1) + CMDBUFFER_RESERVE_FRONT];
  367. // Head of the circular buffer, where to read.
  368. static int bufindr = 0;
  369. // Tail of the buffer, where to write.
  370. static int bufindw = 0;
  371. // Number of lines in cmdbuffer.
  372. static int buflen = 0;
  373. // Flag for processing the current command inside the main Arduino loop().
  374. // If a new command was pushed to the front of a command buffer while
  375. // processing another command, this replaces the command on the top.
  376. // Therefore don't remove the command from the queue in the loop() function.
  377. static bool cmdbuffer_front_already_processed = false;
  378. // Type of a command, which is to be executed right now.
  379. #define CMDBUFFER_CURRENT_TYPE (cmdbuffer[bufindr])
  380. // String of a command, which is to be executed right now.
  381. #define CMDBUFFER_CURRENT_STRING (cmdbuffer+bufindr+1)
  382. // Enable debugging of the command buffer.
  383. // Debugging information will be sent to serial line.
  384. // #define CMDBUFFER_DEBUG
  385. static int serial_count = 0; //index of character read from serial line
  386. static boolean comment_mode = false;
  387. static char *strchr_pointer; // just a pointer to find chars in the command string like X, Y, Z, E, etc
  388. const int sensitive_pins[] = SENSITIVE_PINS; // Sensitive pin list for M42
  389. //static float tt = 0;
  390. //static float bt = 0;
  391. //Inactivity shutdown variables
  392. static unsigned long previous_millis_cmd = 0;
  393. unsigned long max_inactive_time = 0;
  394. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  395. unsigned long starttime=0;
  396. unsigned long stoptime=0;
  397. unsigned long _usb_timer = 0;
  398. static uint8_t tmp_extruder;
  399. bool Stopped=false;
  400. #if NUM_SERVOS > 0
  401. Servo servos[NUM_SERVOS];
  402. #endif
  403. bool CooldownNoWait = true;
  404. bool target_direction;
  405. //Insert variables if CHDK is defined
  406. #ifdef CHDK
  407. unsigned long chdkHigh = 0;
  408. boolean chdkActive = false;
  409. #endif
  410. //===========================================================================
  411. //=============================Routines======================================
  412. //===========================================================================
  413. void get_arc_coordinates();
  414. bool setTargetedHotend(int code);
  415. void serial_echopair_P(const char *s_P, float v)
  416. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  417. void serial_echopair_P(const char *s_P, double v)
  418. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  419. void serial_echopair_P(const char *s_P, unsigned long v)
  420. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  421. #ifdef SDSUPPORT
  422. #include "SdFatUtil.h"
  423. int freeMemory() { return SdFatUtil::FreeRam(); }
  424. #else
  425. extern "C" {
  426. extern unsigned int __bss_end;
  427. extern unsigned int __heap_start;
  428. extern void *__brkval;
  429. int freeMemory() {
  430. int free_memory;
  431. if ((int)__brkval == 0)
  432. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  433. else
  434. free_memory = ((int)&free_memory) - ((int)__brkval);
  435. return free_memory;
  436. }
  437. }
  438. #endif //!SDSUPPORT
  439. // Pop the currently processed command from the queue.
  440. // It is expected, that there is at least one command in the queue.
  441. bool cmdqueue_pop_front()
  442. {
  443. if (buflen > 0) {
  444. #ifdef CMDBUFFER_DEBUG
  445. SERIAL_ECHOPGM("Dequeing ");
  446. SERIAL_ECHO(cmdbuffer+bufindr+1);
  447. SERIAL_ECHOLNPGM("");
  448. SERIAL_ECHOPGM("Old indices: buflen ");
  449. SERIAL_ECHO(buflen);
  450. SERIAL_ECHOPGM(", bufindr ");
  451. SERIAL_ECHO(bufindr);
  452. SERIAL_ECHOPGM(", bufindw ");
  453. SERIAL_ECHO(bufindw);
  454. SERIAL_ECHOPGM(", serial_count ");
  455. SERIAL_ECHO(serial_count);
  456. SERIAL_ECHOPGM(", bufsize ");
  457. SERIAL_ECHO(sizeof(cmdbuffer));
  458. SERIAL_ECHOLNPGM("");
  459. #endif /* CMDBUFFER_DEBUG */
  460. if (-- buflen == 0) {
  461. // Empty buffer.
  462. if (serial_count == 0)
  463. // No serial communication is pending. Reset both pointers to zero.
  464. bufindw = 0;
  465. bufindr = bufindw;
  466. } else {
  467. // There is at least one ready line in the buffer.
  468. // First skip the current command ID and iterate up to the end of the string.
  469. for (++ bufindr; cmdbuffer[bufindr] != 0; ++ bufindr) ;
  470. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  471. for (++ bufindr; bufindr < sizeof(cmdbuffer) && cmdbuffer[bufindr] == 0; ++ bufindr) ;
  472. // If the end of the buffer was empty,
  473. if (bufindr == sizeof(cmdbuffer)) {
  474. // skip to the start and find the nonzero command.
  475. for (bufindr = 0; cmdbuffer[bufindr] == 0; ++ bufindr) ;
  476. }
  477. #ifdef CMDBUFFER_DEBUG
  478. SERIAL_ECHOPGM("New indices: buflen ");
  479. SERIAL_ECHO(buflen);
  480. SERIAL_ECHOPGM(", bufindr ");
  481. SERIAL_ECHO(bufindr);
  482. SERIAL_ECHOPGM(", bufindw ");
  483. SERIAL_ECHO(bufindw);
  484. SERIAL_ECHOPGM(", serial_count ");
  485. SERIAL_ECHO(serial_count);
  486. SERIAL_ECHOPGM(" new command on the top: ");
  487. SERIAL_ECHO(cmdbuffer+bufindr+1);
  488. SERIAL_ECHOLNPGM("");
  489. #endif /* CMDBUFFER_DEBUG */
  490. }
  491. return true;
  492. }
  493. return false;
  494. }
  495. void cmdqueue_reset()
  496. {
  497. while (cmdqueue_pop_front()) ;
  498. }
  499. // How long a string could be pushed to the front of the command queue?
  500. // If yes, adjust bufindr to the new position, where the new command could be enqued.
  501. // len_asked does not contain the zero terminator size.
  502. bool cmdqueue_could_enqueue_front(int len_asked)
  503. {
  504. // MAX_CMD_SIZE has to accommodate the zero terminator.
  505. if (len_asked >= MAX_CMD_SIZE)
  506. return false;
  507. // Remove the currently processed command from the queue.
  508. if (! cmdbuffer_front_already_processed) {
  509. cmdqueue_pop_front();
  510. cmdbuffer_front_already_processed = true;
  511. }
  512. if (bufindr == bufindw && buflen > 0)
  513. // Full buffer.
  514. return false;
  515. // Adjust the end of the write buffer based on whether a partial line is in the receive buffer.
  516. int endw = (serial_count > 0) ? (bufindw + MAX_CMD_SIZE + 1) : bufindw;
  517. if (bufindw < bufindr) {
  518. int bufindr_new = bufindr - len_asked - 2;
  519. // Simple case. There is a contiguous space between the write buffer and the read buffer.
  520. if (endw <= bufindr_new) {
  521. bufindr = bufindr_new;
  522. return true;
  523. }
  524. } else {
  525. // Otherwise the free space is split between the start and end.
  526. if (len_asked + 2 <= bufindr) {
  527. // Could fit at the start.
  528. bufindr -= len_asked + 2;
  529. return true;
  530. }
  531. int bufindr_new = sizeof(cmdbuffer) - len_asked - 2;
  532. if (endw <= bufindr_new) {
  533. memset(cmdbuffer, 0, bufindr);
  534. bufindr = bufindr_new;
  535. return true;
  536. }
  537. }
  538. return false;
  539. }
  540. // Could one enqueue a command of lenthg len_asked into the buffer,
  541. // while leaving CMDBUFFER_RESERVE_FRONT at the start?
  542. // If yes, adjust bufindw to the new position, where the new command could be enqued.
  543. // len_asked does not contain the zero terminator size.
  544. bool cmdqueue_could_enqueue_back(int len_asked)
  545. {
  546. // MAX_CMD_SIZE has to accommodate the zero terminator.
  547. if (len_asked >= MAX_CMD_SIZE)
  548. return false;
  549. if (bufindr == bufindw && buflen > 0)
  550. // Full buffer.
  551. return false;
  552. if (serial_count > 0) {
  553. // If there is some data stored starting at bufindw, len_asked is certainly smaller than
  554. // the allocated data buffer. Try to reserve a new buffer and to move the already received
  555. // serial data.
  556. // How much memory to reserve for the commands pushed to the front?
  557. // End of the queue, when pushing to the end.
  558. int endw = bufindw + len_asked + 2;
  559. if (bufindw < bufindr)
  560. // Simple case. There is a contiguous space between the write buffer and the read buffer.
  561. return endw + CMDBUFFER_RESERVE_FRONT <= bufindr;
  562. // Otherwise the free space is split between the start and end.
  563. if (// Could one fit to the end, including the reserve?
  564. endw + CMDBUFFER_RESERVE_FRONT <= sizeof(cmdbuffer) ||
  565. // Could one fit to the end, and the reserve to the start?
  566. (endw <= sizeof(cmdbuffer) && CMDBUFFER_RESERVE_FRONT <= bufindr))
  567. return true;
  568. // Could one fit both to the start?
  569. if (len_asked + 2 + CMDBUFFER_RESERVE_FRONT <= bufindr) {
  570. // Mark the rest of the buffer as used.
  571. memset(cmdbuffer+bufindw, 0, sizeof(cmdbuffer)-bufindw);
  572. // and point to the start.
  573. bufindw = 0;
  574. return true;
  575. }
  576. } else {
  577. // How much memory to reserve for the commands pushed to the front?
  578. // End of the queue, when pushing to the end.
  579. int endw = bufindw + len_asked + 2;
  580. if (bufindw < bufindr)
  581. // Simple case. There is a contiguous space between the write buffer and the read buffer.
  582. return endw + CMDBUFFER_RESERVE_FRONT <= bufindr;
  583. // Otherwise the free space is split between the start and end.
  584. if (// Could one fit to the end, including the reserve?
  585. endw + CMDBUFFER_RESERVE_FRONT <= sizeof(cmdbuffer) ||
  586. // Could one fit to the end, and the reserve to the start?
  587. (endw <= sizeof(cmdbuffer) && CMDBUFFER_RESERVE_FRONT <= bufindr))
  588. return true;
  589. // Could one fit both to the start?
  590. if (len_asked + 2 + CMDBUFFER_RESERVE_FRONT <= bufindr) {
  591. // Mark the rest of the buffer as used.
  592. memset(cmdbuffer+bufindw, 0, sizeof(cmdbuffer)-bufindw);
  593. // and point to the start.
  594. bufindw = 0;
  595. return true;
  596. }
  597. }
  598. return false;
  599. }
  600. #ifdef CMDBUFFER_DEBUG
  601. static void cmdqueue_dump_to_serial_single_line(int nr, const char *p)
  602. {
  603. SERIAL_ECHOPGM("Entry nr: ");
  604. SERIAL_ECHO(nr);
  605. SERIAL_ECHOPGM(", type: ");
  606. SERIAL_ECHO(int(*p));
  607. SERIAL_ECHOPGM(", cmd: ");
  608. SERIAL_ECHO(p+1);
  609. SERIAL_ECHOLNPGM("");
  610. }
  611. static void cmdqueue_dump_to_serial()
  612. {
  613. if (buflen == 0) {
  614. SERIAL_ECHOLNPGM("The command buffer is empty.");
  615. } else {
  616. SERIAL_ECHOPGM("Content of the buffer: entries ");
  617. SERIAL_ECHO(buflen);
  618. SERIAL_ECHOPGM(", indr ");
  619. SERIAL_ECHO(bufindr);
  620. SERIAL_ECHOPGM(", indw ");
  621. SERIAL_ECHO(bufindw);
  622. SERIAL_ECHOLNPGM("");
  623. int nr = 0;
  624. if (bufindr < bufindw) {
  625. for (const char *p = cmdbuffer + bufindr; p < cmdbuffer + bufindw; ++ nr) {
  626. cmdqueue_dump_to_serial_single_line(nr, p);
  627. // Skip the command.
  628. for (++p; *p != 0; ++ p);
  629. // Skip the gaps.
  630. for (++p; p < cmdbuffer + bufindw && *p == 0; ++ p);
  631. }
  632. } else {
  633. for (const char *p = cmdbuffer + bufindr; p < cmdbuffer + sizeof(cmdbuffer); ++ nr) {
  634. cmdqueue_dump_to_serial_single_line(nr, p);
  635. // Skip the command.
  636. for (++p; *p != 0; ++ p);
  637. // Skip the gaps.
  638. for (++p; p < cmdbuffer + sizeof(cmdbuffer) && *p == 0; ++ p);
  639. }
  640. for (const char *p = cmdbuffer; p < cmdbuffer + bufindw; ++ nr) {
  641. cmdqueue_dump_to_serial_single_line(nr, p);
  642. // Skip the command.
  643. for (++p; *p != 0; ++ p);
  644. // Skip the gaps.
  645. for (++p; p < cmdbuffer + bufindw && *p == 0; ++ p);
  646. }
  647. }
  648. SERIAL_ECHOLNPGM("End of the buffer.");
  649. }
  650. }
  651. #endif /* CMDBUFFER_DEBUG */
  652. //adds an command to the main command buffer
  653. //thats really done in a non-safe way.
  654. //needs overworking someday
  655. // Currently the maximum length of a command piped through this function is around 20 characters
  656. void enquecommand(const char *cmd, bool from_progmem)
  657. {
  658. int len = from_progmem ? strlen_P(cmd) : strlen(cmd);
  659. // Does cmd fit the queue while leaving sufficient space at the front for the chained commands?
  660. // If it fits, it may move bufindw, so it points to a contiguous buffer, which fits cmd.
  661. if (cmdqueue_could_enqueue_back(len)) {
  662. // This is dangerous if a mixing of serial and this happens
  663. // This may easily be tested: If serial_count > 0, we have a problem.
  664. cmdbuffer[bufindw] = CMDBUFFER_CURRENT_TYPE_UI;
  665. if (from_progmem)
  666. strcpy_P(cmdbuffer + bufindw + 1, cmd);
  667. else
  668. strcpy(cmdbuffer + bufindw + 1, cmd);
  669. SERIAL_ECHO_START;
  670. SERIAL_ECHORPGM(MSG_Enqueing);
  671. SERIAL_ECHO(cmdbuffer + bufindw + 1);
  672. SERIAL_ECHOLNPGM("\"");
  673. bufindw += len + 2;
  674. if (bufindw == sizeof(cmdbuffer))
  675. bufindw = 0;
  676. ++ buflen;
  677. #ifdef CMDBUFFER_DEBUG
  678. cmdqueue_dump_to_serial();
  679. #endif /* CMDBUFFER_DEBUG */
  680. } else {
  681. SERIAL_ERROR_START;
  682. SERIAL_ECHORPGM(MSG_Enqueing);
  683. if (from_progmem)
  684. SERIAL_PROTOCOLRPGM(cmd);
  685. else
  686. SERIAL_ECHO(cmd);
  687. SERIAL_ECHOLNPGM("\" failed: Buffer full!");
  688. #ifdef CMDBUFFER_DEBUG
  689. cmdqueue_dump_to_serial();
  690. #endif /* CMDBUFFER_DEBUG */
  691. }
  692. }
  693. void enquecommand_front(const char *cmd, bool from_progmem)
  694. {
  695. int len = from_progmem ? strlen_P(cmd) : strlen(cmd);
  696. // Does cmd fit the queue? This call shall move bufindr, so the command may be copied.
  697. if (cmdqueue_could_enqueue_front(len)) {
  698. cmdbuffer[bufindr] = CMDBUFFER_CURRENT_TYPE_UI;
  699. if (from_progmem)
  700. strcpy_P(cmdbuffer + bufindr + 1, cmd);
  701. else
  702. strcpy(cmdbuffer + bufindr + 1, cmd);
  703. ++ buflen;
  704. SERIAL_ECHO_START;
  705. SERIAL_ECHOPGM("Enqueing to the front: \"");
  706. SERIAL_ECHO(cmdbuffer + bufindr + 1);
  707. SERIAL_ECHOLNPGM("\"");
  708. #ifdef CMDBUFFER_DEBUG
  709. cmdqueue_dump_to_serial();
  710. #endif /* CMDBUFFER_DEBUG */
  711. } else {
  712. SERIAL_ERROR_START;
  713. SERIAL_ECHOPGM("Enqueing to the front: \"");
  714. if (from_progmem)
  715. SERIAL_PROTOCOLRPGM(cmd);
  716. else
  717. SERIAL_ECHO(cmd);
  718. SERIAL_ECHOLNPGM("\" failed: Buffer full!");
  719. #ifdef CMDBUFFER_DEBUG
  720. cmdqueue_dump_to_serial();
  721. #endif /* CMDBUFFER_DEBUG */
  722. }
  723. }
  724. // Mark the command at the top of the command queue as new.
  725. // Therefore it will not be removed from the queue.
  726. void repeatcommand_front()
  727. {
  728. cmdbuffer_front_already_processed = true;
  729. }
  730. bool is_buffer_empty()
  731. {
  732. if (buflen == 0) return true;
  733. else return false;
  734. }
  735. void setup_killpin()
  736. {
  737. #if defined(KILL_PIN) && KILL_PIN > -1
  738. SET_INPUT(KILL_PIN);
  739. WRITE(KILL_PIN,HIGH);
  740. #endif
  741. }
  742. // Set home pin
  743. void setup_homepin(void)
  744. {
  745. #if defined(HOME_PIN) && HOME_PIN > -1
  746. SET_INPUT(HOME_PIN);
  747. WRITE(HOME_PIN,HIGH);
  748. #endif
  749. }
  750. void setup_photpin()
  751. {
  752. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  753. SET_OUTPUT(PHOTOGRAPH_PIN);
  754. WRITE(PHOTOGRAPH_PIN, LOW);
  755. #endif
  756. }
  757. void setup_powerhold()
  758. {
  759. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  760. SET_OUTPUT(SUICIDE_PIN);
  761. WRITE(SUICIDE_PIN, HIGH);
  762. #endif
  763. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  764. SET_OUTPUT(PS_ON_PIN);
  765. #if defined(PS_DEFAULT_OFF)
  766. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  767. #else
  768. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  769. #endif
  770. #endif
  771. }
  772. void suicide()
  773. {
  774. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  775. SET_OUTPUT(SUICIDE_PIN);
  776. WRITE(SUICIDE_PIN, LOW);
  777. #endif
  778. }
  779. void servo_init()
  780. {
  781. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  782. servos[0].attach(SERVO0_PIN);
  783. #endif
  784. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  785. servos[1].attach(SERVO1_PIN);
  786. #endif
  787. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  788. servos[2].attach(SERVO2_PIN);
  789. #endif
  790. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  791. servos[3].attach(SERVO3_PIN);
  792. #endif
  793. #if (NUM_SERVOS >= 5)
  794. #error "TODO: enter initalisation code for more servos"
  795. #endif
  796. }
  797. static void lcd_language_menu();
  798. #ifdef MESH_BED_LEVELING
  799. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  800. #endif
  801. // Factory reset function
  802. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  803. // Level input parameter sets depth of reset
  804. // Quiet parameter masks all waitings for user interact.
  805. int er_progress = 0;
  806. void factory_reset(char level, bool quiet)
  807. {
  808. lcd_implementation_clear();
  809. int cursor_pos = 0;
  810. switch (level) {
  811. // Level 0: Language reset
  812. case 0:
  813. WRITE(BEEPER, HIGH);
  814. _delay_ms(100);
  815. WRITE(BEEPER, LOW);
  816. lcd_force_language_selection();
  817. break;
  818. //Level 1: Reset statistics
  819. case 1:
  820. WRITE(BEEPER, HIGH);
  821. _delay_ms(100);
  822. WRITE(BEEPER, LOW);
  823. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  824. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  825. lcd_menu_statistics();
  826. break;
  827. // Level 2: Prepare for shipping
  828. case 2:
  829. //lcd_printPGM(PSTR("Factory RESET"));
  830. //lcd_print_at_PGM(1,2,PSTR("Shipping prep"));
  831. // Force language selection at the next boot up.
  832. lcd_force_language_selection();
  833. // Force the "Follow calibration flow" message at the next boot up.
  834. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  835. farm_no = 0;
  836. farm_mode == false;
  837. eeprom_update_byte((uint8_t*)EEPROM_FARM_MODE, farm_mode);
  838. EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
  839. WRITE(BEEPER, HIGH);
  840. _delay_ms(100);
  841. WRITE(BEEPER, LOW);
  842. //_delay_ms(2000);
  843. break;
  844. // Level 3: erase everything, whole EEPROM will be set to 0xFF
  845. case 3:
  846. lcd_printPGM(PSTR("Factory RESET"));
  847. lcd_print_at_PGM(1, 2, PSTR("ERASING all data"));
  848. WRITE(BEEPER, HIGH);
  849. _delay_ms(100);
  850. WRITE(BEEPER, LOW);
  851. er_progress = 0;
  852. lcd_print_at_PGM(3, 3, PSTR(" "));
  853. lcd_implementation_print_at(3, 3, er_progress);
  854. // Erase EEPROM
  855. for (int i = 0; i < 4096; i++) {
  856. eeprom_write_byte((uint8_t*)i, 0xFF);
  857. if (i % 41 == 0) {
  858. er_progress++;
  859. lcd_print_at_PGM(3, 3, PSTR(" "));
  860. lcd_implementation_print_at(3, 3, er_progress);
  861. lcd_printPGM(PSTR("%"));
  862. }
  863. }
  864. break;
  865. case 4:
  866. bowden_menu();
  867. break;
  868. default:
  869. break;
  870. }
  871. }
  872. // "Setup" function is called by the Arduino framework on startup.
  873. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  874. // are initialized by the main() routine provided by the Arduino framework.
  875. void setup()
  876. {
  877. setup_killpin();
  878. setup_powerhold();
  879. MYSERIAL.begin(BAUDRATE);
  880. SERIAL_PROTOCOLLNPGM("start");
  881. SERIAL_ECHO_START;
  882. #if 0
  883. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  884. for (int i = 0; i < 4096; ++i) {
  885. int b = eeprom_read_byte((unsigned char*)i);
  886. if (b != 255) {
  887. SERIAL_ECHO(i);
  888. SERIAL_ECHO(":");
  889. SERIAL_ECHO(b);
  890. SERIAL_ECHOLN("");
  891. }
  892. }
  893. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  894. #endif
  895. // Check startup - does nothing if bootloader sets MCUSR to 0
  896. byte mcu = MCUSR;
  897. if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  898. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  899. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  900. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  901. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);
  902. MCUSR = 0;
  903. //SERIAL_ECHORPGM(MSG_MARLIN);
  904. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  905. #ifdef STRING_VERSION_CONFIG_H
  906. #ifdef STRING_CONFIG_H_AUTHOR
  907. SERIAL_ECHO_START;
  908. SERIAL_ECHORPGM(MSG_CONFIGURATION_VER);
  909. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  910. SERIAL_ECHORPGM(MSG_AUTHOR);
  911. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  912. SERIAL_ECHOPGM("Compiled: ");
  913. SERIAL_ECHOLNPGM(__DATE__);
  914. #endif
  915. #endif
  916. SERIAL_ECHO_START;
  917. SERIAL_ECHORPGM(MSG_FREE_MEMORY);
  918. SERIAL_ECHO(freeMemory());
  919. SERIAL_ECHORPGM(MSG_PLANNER_BUFFER_BYTES);
  920. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  921. lcd_update_enable(false);
  922. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  923. Config_RetrieveSettings();
  924. SdFatUtil::set_stack_guard(); //writes magic number at the end of static variables to protect against overwriting static memory by stack
  925. tp_init(); // Initialize temperature loop
  926. plan_init(); // Initialize planner;
  927. watchdog_init();
  928. #ifdef HAVE_TMC2130_DRIVERS
  929. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  930. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  931. #endif //HAVE_TMC2130_DRIVERS
  932. st_init(); // Initialize stepper, this enables interrupts!
  933. setup_photpin();
  934. servo_init();
  935. // Reset the machine correction matrix.
  936. // It does not make sense to load the correction matrix until the machine is homed.
  937. world2machine_reset();
  938. lcd_init();
  939. if (!READ(BTN_ENC))
  940. {
  941. _delay_ms(1000);
  942. if (!READ(BTN_ENC))
  943. {
  944. lcd_implementation_clear();
  945. lcd_printPGM(PSTR("Factory RESET"));
  946. SET_OUTPUT(BEEPER);
  947. WRITE(BEEPER, HIGH);
  948. while (!READ(BTN_ENC));
  949. WRITE(BEEPER, LOW);
  950. _delay_ms(2000);
  951. char level = reset_menu();
  952. factory_reset(level, false);
  953. switch (level) {
  954. case 0: _delay_ms(0); break;
  955. case 1: _delay_ms(0); break;
  956. case 2: _delay_ms(0); break;
  957. case 3: _delay_ms(0); break;
  958. }
  959. // _delay_ms(100);
  960. /*
  961. #ifdef MESH_BED_LEVELING
  962. _delay_ms(2000);
  963. if (!READ(BTN_ENC))
  964. {
  965. WRITE(BEEPER, HIGH);
  966. _delay_ms(100);
  967. WRITE(BEEPER, LOW);
  968. _delay_ms(200);
  969. WRITE(BEEPER, HIGH);
  970. _delay_ms(100);
  971. WRITE(BEEPER, LOW);
  972. int _z = 0;
  973. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  974. EEPROM_save_B(EEPROM_BABYSTEP_X, &_z);
  975. EEPROM_save_B(EEPROM_BABYSTEP_Y, &_z);
  976. EEPROM_save_B(EEPROM_BABYSTEP_Z, &_z);
  977. }
  978. else
  979. {
  980. WRITE(BEEPER, HIGH);
  981. _delay_ms(100);
  982. WRITE(BEEPER, LOW);
  983. }
  984. #endif // mesh */
  985. }
  986. }
  987. else
  988. {
  989. _delay_ms(1000); // wait 1sec to display the splash screen
  990. }
  991. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  992. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  993. #endif
  994. #ifdef DIGIPOT_I2C
  995. digipot_i2c_init();
  996. #endif
  997. setup_homepin();
  998. #if defined(Z_AXIS_ALWAYS_ON)
  999. enable_z();
  1000. #endif
  1001. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  1002. EEPROM_read_B(EEPROM_FARM_NUMBER, &farm_no);
  1003. 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
  1004. if (farm_no == 0xFFFF) farm_no = 0;
  1005. if (farm_mode)
  1006. {
  1007. prusa_statistics(8);
  1008. }
  1009. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1010. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1011. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1012. // but this times out if a blocking dialog is shown in setup().
  1013. card.initsd();
  1014. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  1015. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff &&
  1016. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 12)) == 0x0ffffffff) {
  1017. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  1018. // where all the EEPROM entries are set to 0x0ff.
  1019. // Once a firmware boots up, it forces at least a language selection, which changes
  1020. // EEPROM_LANG to number lower than 0x0ff.
  1021. // 1) Set a high power mode.
  1022. eeprom_write_byte((uint8_t*)EEPROM_SILENT, 0);
  1023. }
  1024. #ifdef SNMM
  1025. if (eeprom_read_dword((uint32_t*)EEPROM_BOWDEN_LENGTH) == 0x0ffffffff) { //bowden length used for SNMM
  1026. int _z = BOWDEN_LENGTH;
  1027. for(int i = 0; i<4; i++) EEPROM_save_B(EEPROM_BOWDEN_LENGTH + i * 2, &_z);
  1028. }
  1029. #endif
  1030. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1031. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1032. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1033. lang_selected = eeprom_read_byte((uint8_t*)EEPROM_LANG);
  1034. if (lang_selected >= LANG_NUM){
  1035. lcd_mylang();
  1036. }
  1037. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  1038. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1039. temp_cal_active = false;
  1040. } else temp_cal_active = eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE);
  1041. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1042. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1043. }
  1044. check_babystep(); //checking if Z babystep is in allowed range
  1045. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1046. calibration_status() == CALIBRATION_STATUS_UNKNOWN) {
  1047. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1048. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z, 0);
  1049. // Show the message.
  1050. lcd_show_fullscreen_message_and_wait_P(MSG_FOLLOW_CALIBRATION_FLOW);
  1051. } else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1052. // Show the message.
  1053. lcd_show_fullscreen_message_and_wait_P(MSG_BABYSTEP_Z_NOT_SET);
  1054. lcd_update_enable(true);
  1055. } else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && temp_cal_active == true && calibration_status_pinda() == false) {
  1056. lcd_show_fullscreen_message_and_wait_P(MSG_PINDA_NOT_CALIBRATED);
  1057. lcd_update_enable(true);
  1058. } else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1059. // Show the message.
  1060. lcd_show_fullscreen_message_and_wait_P(MSG_FOLLOW_CALIBRATION_FLOW);
  1061. }
  1062. for (int i = 0; i<4; i++) EEPROM_read_B(EEPROM_BOWDEN_LENGTH + i * 2, &bowden_length[i]);
  1063. lcd_update_enable(true);
  1064. // Store the currently running firmware into an eeprom,
  1065. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1066. update_current_firmware_version_to_eeprom();
  1067. }
  1068. void trace();
  1069. #define CHUNK_SIZE 64 // bytes
  1070. #define SAFETY_MARGIN 1
  1071. char chunk[CHUNK_SIZE+SAFETY_MARGIN];
  1072. int chunkHead = 0;
  1073. int serial_read_stream() {
  1074. setTargetHotend(0, 0);
  1075. setTargetBed(0);
  1076. lcd_implementation_clear();
  1077. lcd_printPGM(PSTR(" Upload in progress"));
  1078. // first wait for how many bytes we will receive
  1079. uint32_t bytesToReceive;
  1080. // receive the four bytes
  1081. char bytesToReceiveBuffer[4];
  1082. for (int i=0; i<4; i++) {
  1083. int data;
  1084. while ((data = MYSERIAL.read()) == -1) {};
  1085. bytesToReceiveBuffer[i] = data;
  1086. }
  1087. // make it a uint32
  1088. memcpy(&bytesToReceive, &bytesToReceiveBuffer, 4);
  1089. // we're ready, notify the sender
  1090. MYSERIAL.write('+');
  1091. // lock in the routine
  1092. uint32_t receivedBytes = 0;
  1093. while (prusa_sd_card_upload) {
  1094. int i;
  1095. for (i=0; i<CHUNK_SIZE; i++) {
  1096. int data;
  1097. // check if we're not done
  1098. if (receivedBytes == bytesToReceive) {
  1099. break;
  1100. }
  1101. // read the next byte
  1102. while ((data = MYSERIAL.read()) == -1) {};
  1103. receivedBytes++;
  1104. // save it to the chunk
  1105. chunk[i] = data;
  1106. }
  1107. // write the chunk to SD
  1108. card.write_command_no_newline(&chunk[0]);
  1109. // notify the sender we're ready for more data
  1110. MYSERIAL.write('+');
  1111. // for safety
  1112. manage_heater();
  1113. // check if we're done
  1114. if(receivedBytes == bytesToReceive) {
  1115. trace(); // beep
  1116. card.closefile();
  1117. prusa_sd_card_upload = false;
  1118. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1119. return 0;
  1120. }
  1121. }
  1122. }
  1123. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1124. // Before loop(), the setup() function is called by the main() routine.
  1125. void loop()
  1126. {
  1127. bool stack_integrity = true;
  1128. if (usb_printing_counter > 0 && millis()-_usb_timer > 1000)
  1129. {
  1130. is_usb_printing = true;
  1131. usb_printing_counter--;
  1132. _usb_timer = millis();
  1133. }
  1134. if (usb_printing_counter == 0)
  1135. {
  1136. is_usb_printing = false;
  1137. }
  1138. if (prusa_sd_card_upload)
  1139. {
  1140. //we read byte-by byte
  1141. serial_read_stream();
  1142. } else
  1143. {
  1144. get_command();
  1145. #ifdef SDSUPPORT
  1146. card.checkautostart(false);
  1147. #endif
  1148. if(buflen)
  1149. {
  1150. #ifdef SDSUPPORT
  1151. if(card.saving)
  1152. {
  1153. // Saving a G-code file onto an SD-card is in progress.
  1154. // Saving starts with M28, saving until M29 is seen.
  1155. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1156. card.write_command(CMDBUFFER_CURRENT_STRING);
  1157. if(card.logging)
  1158. process_commands();
  1159. else
  1160. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1161. } else {
  1162. card.closefile();
  1163. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1164. }
  1165. } else {
  1166. process_commands();
  1167. }
  1168. #else
  1169. process_commands();
  1170. #endif //SDSUPPORT
  1171. if (! cmdbuffer_front_already_processed)
  1172. cmdqueue_pop_front();
  1173. cmdbuffer_front_already_processed = false;
  1174. }
  1175. }
  1176. //check heater every n milliseconds
  1177. manage_heater();
  1178. isPrintPaused ? manage_inactivity(true) : manage_inactivity(false);
  1179. checkHitEndstops();
  1180. lcd_update();
  1181. #ifdef HAVE_TMC2130_DRIVERS
  1182. tmc2130_check_overtemp();
  1183. #endif //HAVE_TMC2130_DRIVERS
  1184. }
  1185. void get_command()
  1186. {
  1187. // Test and reserve space for the new command string.
  1188. if (!cmdqueue_could_enqueue_back(MAX_CMD_SIZE - 1))
  1189. return;
  1190. bool rx_buffer_full = false; //flag that serial rx buffer is full
  1191. while (MYSERIAL.available() > 0) {
  1192. if (MYSERIAL.available() == RX_BUFFER_SIZE - 1) { //compare number of chars buffered in rx buffer with rx buffer size
  1193. SERIAL_ECHOLNPGM("Full RX Buffer"); //if buffer was full, there is danger that reading of last gcode will not be completed
  1194. rx_buffer_full = true; //sets flag that buffer was full
  1195. }
  1196. char serial_char = MYSERIAL.read();
  1197. TimeSent = millis();
  1198. TimeNow = millis();
  1199. if (serial_char < 0)
  1200. // Ignore extended ASCII characters. These characters have no meaning in the G-code apart from the file names
  1201. // and Marlin does not support such file names anyway.
  1202. // Serial characters with a highest bit set to 1 are generated when the USB cable is unplugged, leading
  1203. // to a hang-up of the print process from an SD card.
  1204. continue;
  1205. if(serial_char == '\n' ||
  1206. serial_char == '\r' ||
  1207. (serial_char == ':' && comment_mode == false) ||
  1208. serial_count >= (MAX_CMD_SIZE - 1) )
  1209. {
  1210. if(!serial_count) { //if empty line
  1211. comment_mode = false; //for new command
  1212. return;
  1213. }
  1214. cmdbuffer[bufindw+serial_count+1] = 0; //terminate string
  1215. if(!comment_mode){
  1216. comment_mode = false; //for new command
  1217. if ((strchr_pointer = strstr(cmdbuffer+bufindw+1, "PRUSA")) == NULL && (strchr_pointer = strchr(cmdbuffer+bufindw+1, 'N')) != NULL) {
  1218. if ((strchr_pointer = strchr(cmdbuffer+bufindw+1, 'N')) != NULL)
  1219. {
  1220. // Line number met. When sending a G-code over a serial line, each line may be stamped with its index,
  1221. // and Marlin tests, whether the successive lines are stamped with an increasing line number ID.
  1222. gcode_N = (strtol(strchr_pointer+1, NULL, 10));
  1223. if(gcode_N != gcode_LastN+1 && (strstr_P(cmdbuffer+bufindw+1, PSTR("M110")) == NULL) ) {
  1224. // M110 - set current line number.
  1225. // Line numbers not sent in succession.
  1226. SERIAL_ERROR_START;
  1227. SERIAL_ERRORRPGM(MSG_ERR_LINE_NO);
  1228. SERIAL_ERRORLN(gcode_LastN);
  1229. //Serial.println(gcode_N);
  1230. FlushSerialRequestResend();
  1231. serial_count = 0;
  1232. return;
  1233. }
  1234. if((strchr_pointer = strchr(cmdbuffer+bufindw+1, '*')) != NULL)
  1235. {
  1236. byte checksum = 0;
  1237. char *p = cmdbuffer+bufindw+1;
  1238. while (p != strchr_pointer)
  1239. checksum = checksum^(*p++);
  1240. if (int(strtol(strchr_pointer+1, NULL, 10)) != int(checksum)) {
  1241. SERIAL_ERROR_START;
  1242. SERIAL_ERRORRPGM(MSG_ERR_CHECKSUM_MISMATCH);
  1243. SERIAL_ERRORLN(gcode_LastN);
  1244. FlushSerialRequestResend();
  1245. serial_count = 0;
  1246. return;
  1247. }
  1248. // If no errors, remove the checksum and continue parsing.
  1249. *strchr_pointer = 0;
  1250. }
  1251. else
  1252. {
  1253. SERIAL_ERROR_START;
  1254. SERIAL_ERRORRPGM(MSG_ERR_NO_CHECKSUM);
  1255. SERIAL_ERRORLN(gcode_LastN);
  1256. FlushSerialRequestResend();
  1257. serial_count = 0;
  1258. return;
  1259. }
  1260. gcode_LastN = gcode_N;
  1261. //if no errors, continue parsing
  1262. } // end of 'N' command
  1263. }
  1264. else // if we don't receive 'N' but still see '*'
  1265. {
  1266. if((strchr(cmdbuffer+bufindw+1, '*') != NULL))
  1267. {
  1268. SERIAL_ERROR_START;
  1269. SERIAL_ERRORRPGM(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM);
  1270. SERIAL_ERRORLN(gcode_LastN);
  1271. serial_count = 0;
  1272. return;
  1273. }
  1274. } // end of '*' command
  1275. if ((strchr_pointer = strchr(cmdbuffer+bufindw+1, 'G')) != NULL) {
  1276. if (! IS_SD_PRINTING) {
  1277. usb_printing_counter = 10;
  1278. is_usb_printing = true;
  1279. }
  1280. if (Stopped == true) {
  1281. int gcode = strtol(strchr_pointer+1, NULL, 10);
  1282. if (gcode >= 0 && gcode <= 3) {
  1283. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  1284. LCD_MESSAGERPGM(MSG_STOPPED);
  1285. }
  1286. }
  1287. } // end of 'G' command
  1288. //If command was e-stop process now
  1289. if(strcmp(cmdbuffer+bufindw+1, "M112") == 0)
  1290. kill();
  1291. // Store the current line into buffer, move to the next line.
  1292. cmdbuffer[bufindw] = CMDBUFFER_CURRENT_TYPE_USB;
  1293. #ifdef CMDBUFFER_DEBUG
  1294. SERIAL_ECHO_START;
  1295. SERIAL_ECHOPGM("Storing a command line to buffer: ");
  1296. SERIAL_ECHO(cmdbuffer+bufindw+1);
  1297. SERIAL_ECHOLNPGM("");
  1298. #endif /* CMDBUFFER_DEBUG */
  1299. bufindw += strlen(cmdbuffer+bufindw+1) + 2;
  1300. if (bufindw == sizeof(cmdbuffer))
  1301. bufindw = 0;
  1302. ++ buflen;
  1303. #ifdef CMDBUFFER_DEBUG
  1304. SERIAL_ECHOPGM("Number of commands in the buffer: ");
  1305. SERIAL_ECHO(buflen);
  1306. SERIAL_ECHOLNPGM("");
  1307. #endif /* CMDBUFFER_DEBUG */
  1308. } // end of 'not comment mode'
  1309. serial_count = 0; //clear buffer
  1310. // Don't call cmdqueue_could_enqueue_back if there are no characters waiting
  1311. // in the queue, as this function will reserve the memory.
  1312. if (MYSERIAL.available() == 0 || ! cmdqueue_could_enqueue_back(MAX_CMD_SIZE-1))
  1313. return;
  1314. } // end of "end of line" processing
  1315. else {
  1316. // Not an "end of line" symbol. Store the new character into a buffer.
  1317. if(serial_char == ';') comment_mode = true;
  1318. if(!comment_mode) cmdbuffer[bufindw+1+serial_count++] = serial_char;
  1319. }
  1320. } // end of serial line processing loop
  1321. if(farm_mode){
  1322. TimeNow = millis();
  1323. if ( ((TimeNow - TimeSent) > 800) && (serial_count > 0) ) {
  1324. cmdbuffer[bufindw+serial_count+1] = 0;
  1325. bufindw += strlen(cmdbuffer+bufindw+1) + 2;
  1326. if (bufindw == sizeof(cmdbuffer))
  1327. bufindw = 0;
  1328. ++ buflen;
  1329. serial_count = 0;
  1330. SERIAL_ECHOPGM("TIMEOUT:");
  1331. //memset(cmdbuffer, 0 , sizeof(cmdbuffer));
  1332. return;
  1333. }
  1334. }
  1335. //add comment
  1336. if (rx_buffer_full == true && serial_count > 0) { //if rx buffer was full and string was not properly terminated
  1337. rx_buffer_full = false;
  1338. bufindw = bufindw - serial_count; //adjust tail of the buffer to prepare buffer for writing new command
  1339. serial_count = 0;
  1340. }
  1341. #ifdef SDSUPPORT
  1342. if(!card.sdprinting || serial_count!=0){
  1343. // If there is a half filled buffer from serial line, wait until return before
  1344. // continuing with the serial line.
  1345. return;
  1346. }
  1347. //'#' stops reading from SD to the buffer prematurely, so procedural macro calls are possible
  1348. // if it occurs, stop_buffering is triggered and the buffer is ran dry.
  1349. // this character _can_ occur in serial com, due to checksums. however, no checksums are used in SD printing
  1350. static bool stop_buffering=false;
  1351. if(buflen==0) stop_buffering=false;
  1352. // Reads whole lines from the SD card. Never leaves a half-filled line in the cmdbuffer.
  1353. while( !card.eof() && !stop_buffering) {
  1354. int16_t n=card.get();
  1355. char serial_char = (char)n;
  1356. if(serial_char == '\n' ||
  1357. serial_char == '\r' ||
  1358. (serial_char == '#' && comment_mode == false) ||
  1359. (serial_char == ':' && comment_mode == false) ||
  1360. serial_count >= (MAX_CMD_SIZE - 1)||n==-1)
  1361. {
  1362. if(card.eof()){
  1363. SERIAL_PROTOCOLLNRPGM(MSG_FILE_PRINTED);
  1364. stoptime=millis();
  1365. char time[30];
  1366. unsigned long t=(stoptime-starttime-pause_time)/1000;
  1367. pause_time = 0;
  1368. int hours, minutes;
  1369. minutes=(t/60)%60;
  1370. hours=t/60/60;
  1371. save_statistics(total_filament_used, t);
  1372. sprintf_P(time, PSTR("%i hours %i minutes"),hours, minutes);
  1373. SERIAL_ECHO_START;
  1374. SERIAL_ECHOLN(time);
  1375. lcd_setstatus(time);
  1376. card.printingHasFinished();
  1377. card.checkautostart(true);
  1378. if (farm_mode)
  1379. {
  1380. prusa_statistics(6);
  1381. lcd_commands_type = LCD_COMMAND_FARM_MODE_CONFIRM;
  1382. }
  1383. }
  1384. if(serial_char=='#')
  1385. stop_buffering=true;
  1386. if(!serial_count)
  1387. {
  1388. comment_mode = false; //for new command
  1389. return; //if empty line
  1390. }
  1391. cmdbuffer[bufindw+serial_count+1] = 0; //terminate string
  1392. cmdbuffer[bufindw] = CMDBUFFER_CURRENT_TYPE_SDCARD;
  1393. ++ buflen;
  1394. bufindw += strlen(cmdbuffer+bufindw+1) + 2;
  1395. if (bufindw == sizeof(cmdbuffer))
  1396. bufindw = 0;
  1397. comment_mode = false; //for new command
  1398. serial_count = 0; //clear buffer
  1399. // The following line will reserve buffer space if available.
  1400. if (! cmdqueue_could_enqueue_back(MAX_CMD_SIZE-1))
  1401. return;
  1402. }
  1403. else
  1404. {
  1405. if(serial_char == ';') comment_mode = true;
  1406. if(!comment_mode) cmdbuffer[bufindw+1+serial_count++] = serial_char;
  1407. }
  1408. }
  1409. #endif //SDSUPPORT
  1410. }
  1411. // Return True if a character was found
  1412. static inline bool code_seen(char code) { return (strchr_pointer = strchr(CMDBUFFER_CURRENT_STRING, code)) != NULL; }
  1413. static inline bool code_seen(const char *code) { return (strchr_pointer = strstr(CMDBUFFER_CURRENT_STRING, code)) != NULL; }
  1414. static inline float code_value() { return strtod(strchr_pointer+1, NULL);}
  1415. static inline long code_value_long() { return strtol(strchr_pointer+1, NULL, 10); }
  1416. static inline int16_t code_value_short() { return int16_t(strtol(strchr_pointer+1, NULL, 10)); };
  1417. static inline uint8_t code_value_uint8() { return uint8_t(strtol(strchr_pointer+1, NULL, 10)); };
  1418. #define DEFINE_PGM_READ_ANY(type, reader) \
  1419. static inline type pgm_read_any(const type *p) \
  1420. { return pgm_read_##reader##_near(p); }
  1421. DEFINE_PGM_READ_ANY(float, float);
  1422. DEFINE_PGM_READ_ANY(signed char, byte);
  1423. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1424. static const PROGMEM type array##_P[3] = \
  1425. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1426. static inline type array(int axis) \
  1427. { return pgm_read_any(&array##_P[axis]); } \
  1428. type array##_ext(int axis) \
  1429. { return pgm_read_any(&array##_P[axis]); }
  1430. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1431. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1432. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1433. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1434. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1435. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1436. static void axis_is_at_home(int axis) {
  1437. current_position[axis] = base_home_pos(axis) + add_homing[axis];
  1438. min_pos[axis] = base_min_pos(axis) + add_homing[axis];
  1439. max_pos[axis] = base_max_pos(axis) + add_homing[axis];
  1440. }
  1441. inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); }
  1442. inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); }
  1443. static void setup_for_endstop_move(bool enable_endstops_now = true) {
  1444. saved_feedrate = feedrate;
  1445. saved_feedmultiply = feedmultiply;
  1446. feedmultiply = 100;
  1447. previous_millis_cmd = millis();
  1448. enable_endstops(enable_endstops_now);
  1449. }
  1450. static void clean_up_after_endstop_move() {
  1451. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1452. enable_endstops(false);
  1453. #endif
  1454. feedrate = saved_feedrate;
  1455. feedmultiply = saved_feedmultiply;
  1456. previous_millis_cmd = millis();
  1457. }
  1458. #ifdef ENABLE_AUTO_BED_LEVELING
  1459. #ifdef AUTO_BED_LEVELING_GRID
  1460. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1461. {
  1462. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1463. planeNormal.debug("planeNormal");
  1464. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1465. //bedLevel.debug("bedLevel");
  1466. //plan_bed_level_matrix.debug("bed level before");
  1467. //vector_3 uncorrected_position = plan_get_position_mm();
  1468. //uncorrected_position.debug("position before");
  1469. vector_3 corrected_position = plan_get_position();
  1470. // corrected_position.debug("position after");
  1471. current_position[X_AXIS] = corrected_position.x;
  1472. current_position[Y_AXIS] = corrected_position.y;
  1473. current_position[Z_AXIS] = corrected_position.z;
  1474. // put the bed at 0 so we don't go below it.
  1475. current_position[Z_AXIS] = zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1476. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1477. }
  1478. #else // not AUTO_BED_LEVELING_GRID
  1479. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1480. plan_bed_level_matrix.set_to_identity();
  1481. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1482. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1483. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1484. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1485. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1486. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1487. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1488. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1489. vector_3 corrected_position = plan_get_position();
  1490. current_position[X_AXIS] = corrected_position.x;
  1491. current_position[Y_AXIS] = corrected_position.y;
  1492. current_position[Z_AXIS] = corrected_position.z;
  1493. // put the bed at 0 so we don't go below it.
  1494. current_position[Z_AXIS] = zprobe_zoffset;
  1495. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1496. }
  1497. #endif // AUTO_BED_LEVELING_GRID
  1498. static void run_z_probe() {
  1499. plan_bed_level_matrix.set_to_identity();
  1500. feedrate = homing_feedrate[Z_AXIS];
  1501. // move down until you find the bed
  1502. float zPosition = -10;
  1503. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1504. st_synchronize();
  1505. // we have to let the planner know where we are right now as it is not where we said to go.
  1506. zPosition = st_get_position_mm(Z_AXIS);
  1507. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1508. // move up the retract distance
  1509. zPosition += home_retract_mm(Z_AXIS);
  1510. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1511. st_synchronize();
  1512. // move back down slowly to find bed
  1513. feedrate = homing_feedrate[Z_AXIS]/4;
  1514. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1515. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1516. st_synchronize();
  1517. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1518. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1519. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1520. }
  1521. static void do_blocking_move_to(float x, float y, float z) {
  1522. float oldFeedRate = feedrate;
  1523. feedrate = homing_feedrate[Z_AXIS];
  1524. current_position[Z_AXIS] = z;
  1525. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder);
  1526. st_synchronize();
  1527. feedrate = XY_TRAVEL_SPEED;
  1528. current_position[X_AXIS] = x;
  1529. current_position[Y_AXIS] = y;
  1530. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder);
  1531. st_synchronize();
  1532. feedrate = oldFeedRate;
  1533. }
  1534. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1535. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1536. }
  1537. /// Probe bed height at position (x,y), returns the measured z value
  1538. static float probe_pt(float x, float y, float z_before) {
  1539. // move to right place
  1540. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1541. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1542. run_z_probe();
  1543. float measured_z = current_position[Z_AXIS];
  1544. SERIAL_PROTOCOLRPGM(MSG_BED);
  1545. SERIAL_PROTOCOLPGM(" x: ");
  1546. SERIAL_PROTOCOL(x);
  1547. SERIAL_PROTOCOLPGM(" y: ");
  1548. SERIAL_PROTOCOL(y);
  1549. SERIAL_PROTOCOLPGM(" z: ");
  1550. SERIAL_PROTOCOL(measured_z);
  1551. SERIAL_PROTOCOLPGM("\n");
  1552. return measured_z;
  1553. }
  1554. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1555. /*
  1556. void homeaxis(int axis) {
  1557. #define HOMEAXIS_DO(LETTER) \
  1558. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1559. if (axis==X_AXIS ? HOMEAXIS_DO(X) :
  1560. axis==Y_AXIS ? HOMEAXIS_DO(Y) :
  1561. axis==Z_AXIS ? HOMEAXIS_DO(Z) :
  1562. 0) {
  1563. int axis_home_dir = home_dir(axis);
  1564. #ifdef HAVE_TMC2130_DRIVERS
  1565. if ((axis == X_AXIS) || (axis == Y_AXIS))
  1566. tmc2130_home_enter(axis);
  1567. #endif //HAVE_TMC2130_DRIVERS
  1568. current_position[axis] = 0;
  1569. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1570. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1571. feedrate = homing_feedrate[axis];
  1572. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1573. st_synchronize();
  1574. current_position[axis] = 0;
  1575. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1576. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1577. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1578. st_synchronize();
  1579. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1580. // feedrate = homing_feedrate[axis]/2 ;
  1581. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1582. st_synchronize();
  1583. axis_is_at_home(axis);
  1584. destination[axis] = current_position[axis];
  1585. feedrate = 0.0;
  1586. endstops_hit_on_purpose();
  1587. axis_known_position[axis] = true;
  1588. #ifdef HAVE_TMC2130_DRIVERS
  1589. if ((axis == X_AXIS) || (axis == Y_AXIS))
  1590. tmc2130_home_exit();
  1591. #endif //HAVE_TMC2130_DRIVERS
  1592. }
  1593. }
  1594. /**/
  1595. void homeaxis(int axis) {
  1596. #define HOMEAXIS_DO(LETTER) \
  1597. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1598. if (axis==X_AXIS ? HOMEAXIS_DO(X) :
  1599. axis==Y_AXIS ? HOMEAXIS_DO(Y) :
  1600. 0) {
  1601. int axis_home_dir = home_dir(axis);
  1602. #ifdef HAVE_TMC2130_DRIVERS
  1603. tmc2130_home_enter(axis);
  1604. #endif
  1605. current_position[axis] = 0;
  1606. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1607. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1608. feedrate = homing_feedrate[axis];
  1609. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1610. // sg_homing_delay = 0;
  1611. st_synchronize();
  1612. current_position[axis] = 0;
  1613. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1614. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1615. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1616. // sg_homing_delay = 0;
  1617. st_synchronize();
  1618. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1619. #ifdef HAVE_TMC2130_DRIVERS
  1620. if (tmc2130_didLastHomingStall())
  1621. feedrate = homing_feedrate[axis];
  1622. else
  1623. #endif
  1624. feedrate = homing_feedrate[axis] / 2;
  1625. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1626. // sg_homing_delay = 0;
  1627. st_synchronize();
  1628. axis_is_at_home(axis);
  1629. destination[axis] = current_position[axis];
  1630. feedrate = 0.0;
  1631. endstops_hit_on_purpose();
  1632. axis_known_position[axis] = true;
  1633. #ifdef HAVE_TMC2130_DRIVERS
  1634. tmc2130_home_exit();
  1635. #endif
  1636. }
  1637. else if (axis==Z_AXIS ? HOMEAXIS_DO(Z) :
  1638. 0) {
  1639. int axis_home_dir = home_dir(axis);
  1640. current_position[axis] = 0;
  1641. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1642. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1643. feedrate = homing_feedrate[axis];
  1644. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1645. st_synchronize();
  1646. current_position[axis] = 0;
  1647. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1648. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1649. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1650. st_synchronize();
  1651. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1652. feedrate = homing_feedrate[axis]/2 ;
  1653. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1654. st_synchronize();
  1655. axis_is_at_home(axis);
  1656. destination[axis] = current_position[axis];
  1657. feedrate = 0.0;
  1658. endstops_hit_on_purpose();
  1659. axis_known_position[axis] = true;
  1660. }
  1661. }
  1662. /**/
  1663. void home_xy()
  1664. {
  1665. set_destination_to_current();
  1666. homeaxis(X_AXIS);
  1667. homeaxis(Y_AXIS);
  1668. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1669. endstops_hit_on_purpose();
  1670. }
  1671. void refresh_cmd_timeout(void)
  1672. {
  1673. previous_millis_cmd = millis();
  1674. }
  1675. #ifdef FWRETRACT
  1676. void retract(bool retracting, bool swapretract = false) {
  1677. if(retracting && !retracted[active_extruder]) {
  1678. destination[X_AXIS]=current_position[X_AXIS];
  1679. destination[Y_AXIS]=current_position[Y_AXIS];
  1680. destination[Z_AXIS]=current_position[Z_AXIS];
  1681. destination[E_AXIS]=current_position[E_AXIS];
  1682. if (swapretract) {
  1683. current_position[E_AXIS]+=retract_length_swap/volumetric_multiplier[active_extruder];
  1684. } else {
  1685. current_position[E_AXIS]+=retract_length/volumetric_multiplier[active_extruder];
  1686. }
  1687. plan_set_e_position(current_position[E_AXIS]);
  1688. float oldFeedrate = feedrate;
  1689. feedrate=retract_feedrate*60;
  1690. retracted[active_extruder]=true;
  1691. prepare_move();
  1692. current_position[Z_AXIS]-=retract_zlift;
  1693. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1694. prepare_move();
  1695. feedrate = oldFeedrate;
  1696. } else if(!retracting && retracted[active_extruder]) {
  1697. destination[X_AXIS]=current_position[X_AXIS];
  1698. destination[Y_AXIS]=current_position[Y_AXIS];
  1699. destination[Z_AXIS]=current_position[Z_AXIS];
  1700. destination[E_AXIS]=current_position[E_AXIS];
  1701. current_position[Z_AXIS]+=retract_zlift;
  1702. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1703. //prepare_move();
  1704. if (swapretract) {
  1705. current_position[E_AXIS]-=(retract_length_swap+retract_recover_length_swap)/volumetric_multiplier[active_extruder];
  1706. } else {
  1707. current_position[E_AXIS]-=(retract_length+retract_recover_length)/volumetric_multiplier[active_extruder];
  1708. }
  1709. plan_set_e_position(current_position[E_AXIS]);
  1710. float oldFeedrate = feedrate;
  1711. feedrate=retract_recover_feedrate*60;
  1712. retracted[active_extruder]=false;
  1713. prepare_move();
  1714. feedrate = oldFeedrate;
  1715. }
  1716. } //retract
  1717. #endif //FWRETRACT
  1718. void trace() {
  1719. tone(BEEPER, 440);
  1720. delay(25);
  1721. noTone(BEEPER);
  1722. delay(20);
  1723. }
  1724. /*
  1725. void ramming() {
  1726. // float tmp[4] = DEFAULT_MAX_FEEDRATE;
  1727. if (current_temperature[0] < 230) {
  1728. //PLA
  1729. max_feedrate[E_AXIS] = 50;
  1730. //current_position[E_AXIS] -= 8;
  1731. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  1732. //current_position[E_AXIS] += 8;
  1733. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  1734. current_position[E_AXIS] += 5.4;
  1735. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2800 / 60, active_extruder);
  1736. current_position[E_AXIS] += 3.2;
  1737. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  1738. current_position[E_AXIS] += 3;
  1739. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3400 / 60, active_extruder);
  1740. st_synchronize();
  1741. max_feedrate[E_AXIS] = 80;
  1742. current_position[E_AXIS] -= 82;
  1743. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 9500 / 60, active_extruder);
  1744. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  1745. current_position[E_AXIS] -= 20;
  1746. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 1200 / 60, active_extruder);
  1747. current_position[E_AXIS] += 5;
  1748. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400 / 60, active_extruder);
  1749. current_position[E_AXIS] += 5;
  1750. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1751. current_position[E_AXIS] -= 10;
  1752. st_synchronize();
  1753. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1754. current_position[E_AXIS] += 10;
  1755. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1756. current_position[E_AXIS] -= 10;
  1757. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  1758. current_position[E_AXIS] += 10;
  1759. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  1760. current_position[E_AXIS] -= 10;
  1761. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  1762. st_synchronize();
  1763. }
  1764. else {
  1765. //ABS
  1766. max_feedrate[E_AXIS] = 50;
  1767. //current_position[E_AXIS] -= 8;
  1768. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  1769. //current_position[E_AXIS] += 8;
  1770. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  1771. current_position[E_AXIS] += 3.1;
  1772. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2000 / 60, active_extruder);
  1773. current_position[E_AXIS] += 3.1;
  1774. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2500 / 60, active_extruder);
  1775. current_position[E_AXIS] += 4;
  1776. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  1777. st_synchronize();
  1778. //current_position[X_AXIS] += 23; //delay
  1779. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600/60, active_extruder); //delay
  1780. //current_position[X_AXIS] -= 23; //delay
  1781. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600/60, active_extruder); //delay
  1782. delay(4700);
  1783. max_feedrate[E_AXIS] = 80;
  1784. current_position[E_AXIS] -= 92;
  1785. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 9900 / 60, active_extruder);
  1786. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  1787. current_position[E_AXIS] -= 5;
  1788. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  1789. current_position[E_AXIS] += 5;
  1790. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400 / 60, active_extruder);
  1791. current_position[E_AXIS] -= 5;
  1792. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1793. st_synchronize();
  1794. current_position[E_AXIS] += 5;
  1795. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1796. current_position[E_AXIS] -= 5;
  1797. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1798. current_position[E_AXIS] += 5;
  1799. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1800. current_position[E_AXIS] -= 5;
  1801. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1802. st_synchronize();
  1803. }
  1804. }
  1805. */
  1806. void process_commands()
  1807. {
  1808. #ifdef FILAMENT_RUNOUT_SUPPORT
  1809. SET_INPUT(FR_SENS);
  1810. #endif
  1811. #ifdef CMDBUFFER_DEBUG
  1812. SERIAL_ECHOPGM("Processing a GCODE command: ");
  1813. SERIAL_ECHO(cmdbuffer+bufindr+1);
  1814. SERIAL_ECHOLNPGM("");
  1815. SERIAL_ECHOPGM("In cmdqueue: ");
  1816. SERIAL_ECHO(buflen);
  1817. SERIAL_ECHOLNPGM("");
  1818. #endif /* CMDBUFFER_DEBUG */
  1819. unsigned long codenum; //throw away variable
  1820. char *starpos = NULL;
  1821. #ifdef ENABLE_AUTO_BED_LEVELING
  1822. float x_tmp, y_tmp, z_tmp, real_z;
  1823. #endif
  1824. // PRUSA GCODES
  1825. #ifdef SNMM
  1826. float tmp_motor[3] = DEFAULT_PWM_MOTOR_CURRENT;
  1827. float tmp_motor_loud[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  1828. int8_t SilentMode;
  1829. #endif
  1830. if (code_seen("M117")) { //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  1831. starpos = (strchr(strchr_pointer + 5, '*'));
  1832. if (starpos != NULL)
  1833. *(starpos) = '\0';
  1834. lcd_setstatus(strchr_pointer + 5);
  1835. }
  1836. else if(code_seen("PRUSA")){
  1837. if (code_seen("Ping")) { //PRUSA Ping
  1838. if (farm_mode) {
  1839. PingTime = millis();
  1840. //MYSERIAL.print(farm_no); MYSERIAL.println(": OK");
  1841. }
  1842. }
  1843. else if (code_seen("PRN")) {
  1844. MYSERIAL.println(status_number);
  1845. }else if (code_seen("fn")) {
  1846. if (farm_mode) {
  1847. MYSERIAL.println(farm_no);
  1848. }
  1849. else {
  1850. MYSERIAL.println("Not in farm mode.");
  1851. }
  1852. }else if (code_seen("fv")) {
  1853. // get file version
  1854. #ifdef SDSUPPORT
  1855. card.openFile(strchr_pointer + 3,true);
  1856. while (true) {
  1857. uint16_t readByte = card.get();
  1858. MYSERIAL.write(readByte);
  1859. if (readByte=='\n') {
  1860. break;
  1861. }
  1862. }
  1863. card.closefile();
  1864. #endif // SDSUPPORT
  1865. } else if (code_seen("M28")) {
  1866. trace();
  1867. prusa_sd_card_upload = true;
  1868. card.openFile(strchr_pointer+4,false);
  1869. } else if(code_seen("Fir")){
  1870. SERIAL_PROTOCOLLN(FW_version);
  1871. } else if(code_seen("Rev")){
  1872. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  1873. } else if(code_seen("Lang")) {
  1874. lcd_force_language_selection();
  1875. } else if(code_seen("Lz")) {
  1876. EEPROM_save_B(EEPROM_BABYSTEP_Z,0);
  1877. } else if (code_seen("SERIAL LOW")) {
  1878. MYSERIAL.println("SERIAL LOW");
  1879. MYSERIAL.begin(BAUDRATE);
  1880. return;
  1881. } else if (code_seen("SERIAL HIGH")) {
  1882. MYSERIAL.println("SERIAL HIGH");
  1883. MYSERIAL.begin(1152000);
  1884. return;
  1885. } else if(code_seen("Beat")) {
  1886. // Kick farm link timer
  1887. kicktime = millis();
  1888. } else if(code_seen("FR")) {
  1889. // Factory full reset
  1890. factory_reset(0,true);
  1891. }
  1892. //else if (code_seen('Cal')) {
  1893. // lcd_calibration();
  1894. // }
  1895. }
  1896. else if (code_seen('^')) {
  1897. // nothing, this is a version line
  1898. } else if(code_seen('G'))
  1899. {
  1900. switch((int)code_value())
  1901. {
  1902. case 0: // G0 -> G1
  1903. case 1: // G1
  1904. if(Stopped == false) {
  1905. #ifdef FILAMENT_RUNOUT_SUPPORT
  1906. if(READ(FR_SENS)){
  1907. feedmultiplyBckp=feedmultiply;
  1908. float target[4];
  1909. float lastpos[4];
  1910. target[X_AXIS]=current_position[X_AXIS];
  1911. target[Y_AXIS]=current_position[Y_AXIS];
  1912. target[Z_AXIS]=current_position[Z_AXIS];
  1913. target[E_AXIS]=current_position[E_AXIS];
  1914. lastpos[X_AXIS]=current_position[X_AXIS];
  1915. lastpos[Y_AXIS]=current_position[Y_AXIS];
  1916. lastpos[Z_AXIS]=current_position[Z_AXIS];
  1917. lastpos[E_AXIS]=current_position[E_AXIS];
  1918. //retract by E
  1919. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT ;
  1920. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  1921. target[Z_AXIS]+= FILAMENTCHANGE_ZADD ;
  1922. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 300, active_extruder);
  1923. target[X_AXIS]= FILAMENTCHANGE_XPOS ;
  1924. target[Y_AXIS]= FILAMENTCHANGE_YPOS ;
  1925. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder);
  1926. target[E_AXIS]+= FILAMENTCHANGE_FINALRETRACT ;
  1927. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  1928. //finish moves
  1929. st_synchronize();
  1930. //disable extruder steppers so filament can be removed
  1931. disable_e0();
  1932. disable_e1();
  1933. disable_e2();
  1934. delay(100);
  1935. //LCD_ALERTMESSAGEPGM(MSG_FILAMENTCHANGE);
  1936. uint8_t cnt=0;
  1937. int counterBeep = 0;
  1938. lcd_wait_interact();
  1939. while(!lcd_clicked()){
  1940. cnt++;
  1941. manage_heater();
  1942. manage_inactivity(true);
  1943. //lcd_update();
  1944. if(cnt==0)
  1945. {
  1946. #if BEEPER > 0
  1947. if (counterBeep== 500){
  1948. counterBeep = 0;
  1949. }
  1950. SET_OUTPUT(BEEPER);
  1951. if (counterBeep== 0){
  1952. WRITE(BEEPER,HIGH);
  1953. }
  1954. if (counterBeep== 20){
  1955. WRITE(BEEPER,LOW);
  1956. }
  1957. counterBeep++;
  1958. #else
  1959. #if !defined(LCD_FEEDBACK_FREQUENCY_HZ) || !defined(LCD_FEEDBACK_FREQUENCY_DURATION_MS)
  1960. lcd_buzz(1000/6,100);
  1961. #else
  1962. lcd_buzz(LCD_FEEDBACK_FREQUENCY_DURATION_MS,LCD_FEEDBACK_FREQUENCY_HZ);
  1963. #endif
  1964. #endif
  1965. }
  1966. }
  1967. WRITE(BEEPER,LOW);
  1968. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  1969. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  1970. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  1971. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1972. lcd_change_fil_state = 0;
  1973. lcd_loading_filament();
  1974. while ((lcd_change_fil_state == 0)||(lcd_change_fil_state != 1)){
  1975. lcd_change_fil_state = 0;
  1976. lcd_alright();
  1977. switch(lcd_change_fil_state){
  1978. case 2:
  1979. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  1980. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  1981. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  1982. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1983. lcd_loading_filament();
  1984. break;
  1985. case 3:
  1986. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  1987. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1988. lcd_loading_color();
  1989. break;
  1990. default:
  1991. lcd_change_success();
  1992. break;
  1993. }
  1994. }
  1995. target[E_AXIS]+= 5;
  1996. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1997. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT;
  1998. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  1999. //current_position[E_AXIS]=target[E_AXIS]; //the long retract of L is compensated by manual filament feeding
  2000. //plan_set_e_position(current_position[E_AXIS]);
  2001. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //should do nothing
  2002. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //move xy back
  2003. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 200, active_extruder); //move z back
  2004. target[E_AXIS]= target[E_AXIS] - FILAMENTCHANGE_FIRSTRETRACT;
  2005. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 5, active_extruder); //final untretract
  2006. plan_set_e_position(lastpos[E_AXIS]);
  2007. feedmultiply=feedmultiplyBckp;
  2008. char cmd[9];
  2009. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  2010. enquecommand(cmd);
  2011. }
  2012. #endif
  2013. get_coordinates(); // For X Y Z E F
  2014. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  2015. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  2016. }
  2017. #ifdef FWRETRACT
  2018. if(autoretract_enabled)
  2019. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  2020. float echange=destination[E_AXIS]-current_position[E_AXIS];
  2021. if((echange<-MIN_RETRACT && !retracted) || (echange>MIN_RETRACT && retracted)) { //move appears to be an attempt to retract or recover
  2022. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  2023. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  2024. retract(!retracted);
  2025. return;
  2026. }
  2027. }
  2028. #endif //FWRETRACT
  2029. prepare_move();
  2030. //ClearToSend();
  2031. }
  2032. break;
  2033. case 2: // G2 - CW ARC
  2034. if(Stopped == false) {
  2035. get_arc_coordinates();
  2036. prepare_arc_move(true);
  2037. }
  2038. break;
  2039. case 3: // G3 - CCW ARC
  2040. if(Stopped == false) {
  2041. get_arc_coordinates();
  2042. prepare_arc_move(false);
  2043. }
  2044. break;
  2045. case 4: // G4 dwell
  2046. codenum = 0;
  2047. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  2048. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  2049. if(codenum != 0) LCD_MESSAGERPGM(MSG_DWELL);
  2050. st_synchronize();
  2051. codenum += millis(); // keep track of when we started waiting
  2052. previous_millis_cmd = millis();
  2053. while(millis() < codenum) {
  2054. manage_heater();
  2055. manage_inactivity();
  2056. lcd_update();
  2057. }
  2058. break;
  2059. #ifdef FWRETRACT
  2060. case 10: // G10 retract
  2061. #if EXTRUDERS > 1
  2062. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  2063. retract(true,retracted_swap[active_extruder]);
  2064. #else
  2065. retract(true);
  2066. #endif
  2067. break;
  2068. case 11: // G11 retract_recover
  2069. #if EXTRUDERS > 1
  2070. retract(false,retracted_swap[active_extruder]);
  2071. #else
  2072. retract(false);
  2073. #endif
  2074. break;
  2075. #endif //FWRETRACT
  2076. case 28: //G28 Home all Axis one at a time
  2077. homing_flag = true;
  2078. #ifdef ENABLE_AUTO_BED_LEVELING
  2079. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2080. #endif //ENABLE_AUTO_BED_LEVELING
  2081. // For mesh bed leveling deactivate the matrix temporarily
  2082. #ifdef MESH_BED_LEVELING
  2083. mbl.active = 0;
  2084. #endif
  2085. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2086. // the planner will not perform any adjustments in the XY plane.
  2087. // Wait for the motors to stop and update the current position with the absolute values.
  2088. world2machine_revert_to_uncorrected();
  2089. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  2090. // consumed during the first movements following this statement.
  2091. babystep_undo();
  2092. saved_feedrate = feedrate;
  2093. saved_feedmultiply = feedmultiply;
  2094. feedmultiply = 100;
  2095. previous_millis_cmd = millis();
  2096. enable_endstops(true);
  2097. for(int8_t i=0; i < NUM_AXIS; i++)
  2098. destination[i] = current_position[i];
  2099. feedrate = 0.0;
  2100. home_all_axis = !((code_seen(axis_codes[X_AXIS])) || (code_seen(axis_codes[Y_AXIS])) || (code_seen(axis_codes[Z_AXIS])));
  2101. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2102. if((home_all_axis) || (code_seen(axis_codes[Z_AXIS]))) {
  2103. homeaxis(Z_AXIS);
  2104. }
  2105. #endif
  2106. #ifdef QUICK_HOME
  2107. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2108. if((home_all_axis)||( code_seen(axis_codes[X_AXIS]) && code_seen(axis_codes[Y_AXIS])) ) //first diagonal move
  2109. {
  2110. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2111. int x_axis_home_dir = home_dir(X_AXIS);
  2112. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2113. 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);
  2114. feedrate = homing_feedrate[X_AXIS];
  2115. if(homing_feedrate[Y_AXIS]<feedrate)
  2116. feedrate = homing_feedrate[Y_AXIS];
  2117. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2118. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2119. } else {
  2120. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2121. }
  2122. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  2123. st_synchronize();
  2124. axis_is_at_home(X_AXIS);
  2125. axis_is_at_home(Y_AXIS);
  2126. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2127. destination[X_AXIS] = current_position[X_AXIS];
  2128. destination[Y_AXIS] = current_position[Y_AXIS];
  2129. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  2130. feedrate = 0.0;
  2131. st_synchronize();
  2132. endstops_hit_on_purpose();
  2133. current_position[X_AXIS] = destination[X_AXIS];
  2134. current_position[Y_AXIS] = destination[Y_AXIS];
  2135. current_position[Z_AXIS] = destination[Z_AXIS];
  2136. }
  2137. #endif /* QUICK_HOME */
  2138. if((home_all_axis) || (code_seen(axis_codes[X_AXIS])))
  2139. homeaxis(X_AXIS);
  2140. if((home_all_axis) || (code_seen(axis_codes[Y_AXIS])))
  2141. homeaxis(Y_AXIS);
  2142. if(code_seen(axis_codes[X_AXIS]) && code_value_long() != 0)
  2143. current_position[X_AXIS]=code_value()+add_homing[X_AXIS];
  2144. if(code_seen(axis_codes[Y_AXIS]) && code_value_long() != 0)
  2145. current_position[Y_AXIS]=code_value()+add_homing[Y_AXIS];
  2146. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2147. #ifndef Z_SAFE_HOMING
  2148. if((home_all_axis) || (code_seen(axis_codes[Z_AXIS]))) {
  2149. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2150. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2151. feedrate = max_feedrate[Z_AXIS];
  2152. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2153. st_synchronize();
  2154. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2155. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP)) // If Mesh bed leveling, moxve X&Y to safe position for home
  2156. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] ))
  2157. {
  2158. homeaxis(X_AXIS);
  2159. homeaxis(Y_AXIS);
  2160. }
  2161. // 1st mesh bed leveling measurement point, corrected.
  2162. world2machine_initialize();
  2163. world2machine(pgm_read_float(bed_ref_points), pgm_read_float(bed_ref_points+1), destination[X_AXIS], destination[Y_AXIS]);
  2164. world2machine_reset();
  2165. if (destination[Y_AXIS] < Y_MIN_POS)
  2166. destination[Y_AXIS] = Y_MIN_POS;
  2167. destination[Z_AXIS] = MESH_HOME_Z_SEARCH; // Set destination away from bed
  2168. feedrate = homing_feedrate[Z_AXIS]/10;
  2169. current_position[Z_AXIS] = 0;
  2170. enable_endstops(false);
  2171. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2172. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2173. st_synchronize();
  2174. current_position[X_AXIS] = destination[X_AXIS];
  2175. current_position[Y_AXIS] = destination[Y_AXIS];
  2176. enable_endstops(true);
  2177. endstops_hit_on_purpose();
  2178. homeaxis(Z_AXIS);
  2179. #else // MESH_BED_LEVELING
  2180. homeaxis(Z_AXIS);
  2181. #endif // MESH_BED_LEVELING
  2182. }
  2183. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2184. if(home_all_axis) {
  2185. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2186. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2187. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2188. feedrate = XY_TRAVEL_SPEED/60;
  2189. current_position[Z_AXIS] = 0;
  2190. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2191. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2192. st_synchronize();
  2193. current_position[X_AXIS] = destination[X_AXIS];
  2194. current_position[Y_AXIS] = destination[Y_AXIS];
  2195. homeaxis(Z_AXIS);
  2196. }
  2197. // Let's see if X and Y are homed and probe is inside bed area.
  2198. if(code_seen(axis_codes[Z_AXIS])) {
  2199. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2200. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2201. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2202. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2203. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2204. current_position[Z_AXIS] = 0;
  2205. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2206. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2207. feedrate = max_feedrate[Z_AXIS];
  2208. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2209. st_synchronize();
  2210. homeaxis(Z_AXIS);
  2211. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2212. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2213. SERIAL_ECHO_START;
  2214. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2215. } else {
  2216. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2217. SERIAL_ECHO_START;
  2218. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2219. }
  2220. }
  2221. #endif // Z_SAFE_HOMING
  2222. #endif // Z_HOME_DIR < 0
  2223. if(code_seen(axis_codes[Z_AXIS])) {
  2224. if(code_value_long() != 0) {
  2225. current_position[Z_AXIS]=code_value()+add_homing[Z_AXIS];
  2226. }
  2227. }
  2228. #ifdef ENABLE_AUTO_BED_LEVELING
  2229. if((home_all_axis) || (code_seen(axis_codes[Z_AXIS]))) {
  2230. current_position[Z_AXIS] += zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2231. }
  2232. #endif
  2233. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2234. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  2235. enable_endstops(false);
  2236. #endif
  2237. feedrate = saved_feedrate;
  2238. feedmultiply = saved_feedmultiply;
  2239. previous_millis_cmd = millis();
  2240. endstops_hit_on_purpose();
  2241. #ifndef MESH_BED_LEVELING
  2242. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  2243. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  2244. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  2245. lcd_adjust_z();
  2246. #endif
  2247. // Load the machine correction matrix
  2248. world2machine_initialize();
  2249. // and correct the current_position to match the transformed coordinate system.
  2250. world2machine_update_current();
  2251. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP))
  2252. if (code_seen(axis_codes[X_AXIS]) || code_seen(axis_codes[Y_AXIS]) || code_seen('W') || code_seen(axis_codes[Z_AXIS]))
  2253. {
  2254. }
  2255. else
  2256. {
  2257. st_synchronize();
  2258. homing_flag = false;
  2259. // Push the commands to the front of the message queue in the reverse order!
  2260. // There shall be always enough space reserved for these commands.
  2261. // enquecommand_front_P((PSTR("G80")));
  2262. goto case_G80;
  2263. }
  2264. #endif
  2265. if (farm_mode) { prusa_statistics(20); };
  2266. homing_flag = false;
  2267. break;
  2268. #ifdef ENABLE_AUTO_BED_LEVELING
  2269. case 29: // G29 Detailed Z-Probe, probes the bed at 3 or more points.
  2270. {
  2271. #if Z_MIN_PIN == -1
  2272. #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."
  2273. #endif
  2274. // Prevent user from running a G29 without first homing in X and Y
  2275. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  2276. {
  2277. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2278. SERIAL_ECHO_START;
  2279. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2280. break; // abort G29, since we don't know where we are
  2281. }
  2282. st_synchronize();
  2283. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  2284. //vector_3 corrected_position = plan_get_position_mm();
  2285. //corrected_position.debug("position before G29");
  2286. plan_bed_level_matrix.set_to_identity();
  2287. vector_3 uncorrected_position = plan_get_position();
  2288. //uncorrected_position.debug("position durring G29");
  2289. current_position[X_AXIS] = uncorrected_position.x;
  2290. current_position[Y_AXIS] = uncorrected_position.y;
  2291. current_position[Z_AXIS] = uncorrected_position.z;
  2292. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2293. setup_for_endstop_move();
  2294. feedrate = homing_feedrate[Z_AXIS];
  2295. #ifdef AUTO_BED_LEVELING_GRID
  2296. // probe at the points of a lattice grid
  2297. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  2298. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  2299. // solve the plane equation ax + by + d = z
  2300. // A is the matrix with rows [x y 1] for all the probed points
  2301. // B is the vector of the Z positions
  2302. // 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
  2303. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  2304. // "A" matrix of the linear system of equations
  2305. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  2306. // "B" vector of Z points
  2307. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  2308. int probePointCounter = 0;
  2309. bool zig = true;
  2310. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  2311. {
  2312. int xProbe, xInc;
  2313. if (zig)
  2314. {
  2315. xProbe = LEFT_PROBE_BED_POSITION;
  2316. //xEnd = RIGHT_PROBE_BED_POSITION;
  2317. xInc = xGridSpacing;
  2318. zig = false;
  2319. } else // zag
  2320. {
  2321. xProbe = RIGHT_PROBE_BED_POSITION;
  2322. //xEnd = LEFT_PROBE_BED_POSITION;
  2323. xInc = -xGridSpacing;
  2324. zig = true;
  2325. }
  2326. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  2327. {
  2328. float z_before;
  2329. if (probePointCounter == 0)
  2330. {
  2331. // raise before probing
  2332. z_before = Z_RAISE_BEFORE_PROBING;
  2333. } else
  2334. {
  2335. // raise extruder
  2336. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  2337. }
  2338. float measured_z = probe_pt(xProbe, yProbe, z_before);
  2339. eqnBVector[probePointCounter] = measured_z;
  2340. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  2341. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  2342. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  2343. probePointCounter++;
  2344. xProbe += xInc;
  2345. }
  2346. }
  2347. clean_up_after_endstop_move();
  2348. // solve lsq problem
  2349. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  2350. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  2351. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  2352. SERIAL_PROTOCOLPGM(" b: ");
  2353. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  2354. SERIAL_PROTOCOLPGM(" d: ");
  2355. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  2356. set_bed_level_equation_lsq(plane_equation_coefficients);
  2357. free(plane_equation_coefficients);
  2358. #else // AUTO_BED_LEVELING_GRID not defined
  2359. // Probe at 3 arbitrary points
  2360. // probe 1
  2361. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  2362. // probe 2
  2363. 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);
  2364. // probe 3
  2365. 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);
  2366. clean_up_after_endstop_move();
  2367. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  2368. #endif // AUTO_BED_LEVELING_GRID
  2369. st_synchronize();
  2370. // The following code correct the Z height difference from z-probe position and hotend tip position.
  2371. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  2372. // When the bed is uneven, this height must be corrected.
  2373. 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)
  2374. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  2375. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  2376. z_tmp = current_position[Z_AXIS];
  2377. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  2378. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  2379. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2380. }
  2381. break;
  2382. #ifndef Z_PROBE_SLED
  2383. case 30: // G30 Single Z Probe
  2384. {
  2385. st_synchronize();
  2386. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  2387. setup_for_endstop_move();
  2388. feedrate = homing_feedrate[Z_AXIS];
  2389. run_z_probe();
  2390. SERIAL_PROTOCOLPGM(MSG_BED);
  2391. SERIAL_PROTOCOLPGM(" X: ");
  2392. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2393. SERIAL_PROTOCOLPGM(" Y: ");
  2394. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2395. SERIAL_PROTOCOLPGM(" Z: ");
  2396. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2397. SERIAL_PROTOCOLPGM("\n");
  2398. clean_up_after_endstop_move();
  2399. }
  2400. break;
  2401. #else
  2402. case 31: // dock the sled
  2403. dock_sled(true);
  2404. break;
  2405. case 32: // undock the sled
  2406. dock_sled(false);
  2407. break;
  2408. #endif // Z_PROBE_SLED
  2409. #endif // ENABLE_AUTO_BED_LEVELING
  2410. #ifdef MESH_BED_LEVELING
  2411. case 30: // G30 Single Z Probe
  2412. {
  2413. st_synchronize();
  2414. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  2415. setup_for_endstop_move();
  2416. feedrate = homing_feedrate[Z_AXIS];
  2417. find_bed_induction_sensor_point_z(-10.f, 3);
  2418. SERIAL_PROTOCOLRPGM(MSG_BED);
  2419. SERIAL_PROTOCOLPGM(" X: ");
  2420. MYSERIAL.print(current_position[X_AXIS], 5);
  2421. SERIAL_PROTOCOLPGM(" Y: ");
  2422. MYSERIAL.print(current_position[Y_AXIS], 5);
  2423. SERIAL_PROTOCOLPGM(" Z: ");
  2424. MYSERIAL.print(current_position[Z_AXIS], 5);
  2425. SERIAL_PROTOCOLPGM("\n");
  2426. clean_up_after_endstop_move();
  2427. }
  2428. break;
  2429. case 75:
  2430. {
  2431. for (int i = 40; i <= 110; i++) {
  2432. MYSERIAL.print(i);
  2433. MYSERIAL.print(" ");
  2434. MYSERIAL.println(temp_comp_interpolation(i));// / axis_steps_per_unit[Z_AXIS]);
  2435. }
  2436. }
  2437. break;
  2438. case 76: //PINDA probe temperature calibration
  2439. {
  2440. setTargetBed(PINDA_MIN_T);
  2441. float zero_z;
  2442. int z_shift = 0; //unit: steps
  2443. int t_c; // temperature
  2444. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2445. // We don't know where we are! HOME!
  2446. // Push the commands to the front of the message queue in the reverse order!
  2447. // There shall be always enough space reserved for these commands.
  2448. repeatcommand_front(); // repeat G76 with all its parameters
  2449. enquecommand_front_P((PSTR("G28 W0")));
  2450. break;
  2451. }
  2452. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  2453. custom_message = true;
  2454. custom_message_type = 4;
  2455. custom_message_state = 1;
  2456. custom_message = MSG_TEMP_CALIBRATION;
  2457. current_position[X_AXIS] = PINDA_PREHEAT_X;
  2458. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  2459. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  2460. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2461. st_synchronize();
  2462. while (abs(degBed() - PINDA_MIN_T) > 1) {
  2463. delay_keep_alive(1000);
  2464. serialecho_temperatures();
  2465. }
  2466. //enquecommand_P(PSTR("M190 S50"));
  2467. for (int i = 0; i < PINDA_HEAT_T; i++) {
  2468. delay_keep_alive(1000);
  2469. serialecho_temperatures();
  2470. }
  2471. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  2472. current_position[Z_AXIS] = 5;
  2473. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2474. current_position[X_AXIS] = pgm_read_float(bed_ref_points);
  2475. current_position[Y_AXIS] = pgm_read_float(bed_ref_points + 1);
  2476. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2477. st_synchronize();
  2478. find_bed_induction_sensor_point_z(-1.f);
  2479. zero_z = current_position[Z_AXIS];
  2480. //current_position[Z_AXIS]
  2481. SERIAL_ECHOLNPGM("");
  2482. SERIAL_ECHOPGM("ZERO: ");
  2483. MYSERIAL.print(current_position[Z_AXIS]);
  2484. SERIAL_ECHOLNPGM("");
  2485. for (int i = 0; i<5; i++) {
  2486. SERIAL_ECHOPGM("Step: ");
  2487. MYSERIAL.print(i+2);
  2488. SERIAL_ECHOLNPGM("/6");
  2489. custom_message_state = i + 2;
  2490. t_c = 60 + i * 10;
  2491. setTargetBed(t_c);
  2492. current_position[X_AXIS] = PINDA_PREHEAT_X;
  2493. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  2494. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  2495. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2496. st_synchronize();
  2497. while (degBed() < t_c) {
  2498. delay_keep_alive(1000);
  2499. serialecho_temperatures();
  2500. }
  2501. for (int i = 0; i < PINDA_HEAT_T; i++) {
  2502. delay_keep_alive(1000);
  2503. serialecho_temperatures();
  2504. }
  2505. current_position[Z_AXIS] = 5;
  2506. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2507. current_position[X_AXIS] = pgm_read_float(bed_ref_points);
  2508. current_position[Y_AXIS] = pgm_read_float(bed_ref_points + 1);
  2509. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2510. st_synchronize();
  2511. find_bed_induction_sensor_point_z(-1.f);
  2512. z_shift = (int)((current_position[Z_AXIS] - zero_z)*axis_steps_per_unit[Z_AXIS]);
  2513. SERIAL_ECHOLNPGM("");
  2514. SERIAL_ECHOPGM("Temperature: ");
  2515. MYSERIAL.print(t_c);
  2516. SERIAL_ECHOPGM(" Z shift (mm):");
  2517. MYSERIAL.print(current_position[Z_AXIS] - zero_z);
  2518. SERIAL_ECHOLNPGM("");
  2519. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i*2, &z_shift);
  2520. }
  2521. custom_message_type = 0;
  2522. custom_message = false;
  2523. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  2524. SERIAL_ECHOLNPGM("Temperature calibration done. Continue with pressing the knob.");
  2525. disable_x();
  2526. disable_y();
  2527. disable_z();
  2528. disable_e0();
  2529. disable_e1();
  2530. disable_e2();
  2531. setTargetBed(0); //set bed target temperature back to 0
  2532. lcd_show_fullscreen_message_and_wait_P(MSG_TEMP_CALIBRATION_DONE);
  2533. lcd_update_enable(true);
  2534. lcd_update(2);
  2535. }
  2536. break;
  2537. #ifdef DIS
  2538. case 77:
  2539. {
  2540. //G77 X200 Y150 XP100 YP15 XO10 Y015
  2541. //for 9 point mesh bed leveling G77 X203 Y196 XP3 YP3 XO0 YO0
  2542. //G77 X232 Y218 XP116 YP109 XO-11 YO0
  2543. float dimension_x = 40;
  2544. float dimension_y = 40;
  2545. int points_x = 40;
  2546. int points_y = 40;
  2547. float offset_x = 74;
  2548. float offset_y = 33;
  2549. if (code_seen('X')) dimension_x = code_value();
  2550. if (code_seen('Y')) dimension_y = code_value();
  2551. if (code_seen('XP')) points_x = code_value();
  2552. if (code_seen('YP')) points_y = code_value();
  2553. if (code_seen('XO')) offset_x = code_value();
  2554. if (code_seen('YO')) offset_y = code_value();
  2555. bed_analysis(dimension_x,dimension_y,points_x,points_y,offset_x,offset_y);
  2556. } break;
  2557. #endif
  2558. /**
  2559. * G80: Mesh-based Z probe, probes a grid and produces a
  2560. * mesh to compensate for variable bed height
  2561. *
  2562. * The S0 report the points as below
  2563. *
  2564. * +----> X-axis
  2565. * |
  2566. * |
  2567. * v Y-axis
  2568. *
  2569. */
  2570. case 80:
  2571. #ifdef MK1BP
  2572. break;
  2573. #endif //MK1BP
  2574. case_G80:
  2575. {
  2576. mesh_bed_leveling_flag = true;
  2577. int8_t verbosity_level = 0;
  2578. static bool run = false;
  2579. if (code_seen('V')) {
  2580. // Just 'V' without a number counts as V1.
  2581. char c = strchr_pointer[1];
  2582. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  2583. }
  2584. // Firstly check if we know where we are
  2585. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2586. // We don't know where we are! HOME!
  2587. // Push the commands to the front of the message queue in the reverse order!
  2588. // There shall be always enough space reserved for these commands.
  2589. if (lcd_commands_type != LCD_COMMAND_STOP_PRINT) {
  2590. repeatcommand_front(); // repeat G80 with all its parameters
  2591. enquecommand_front_P((PSTR("G28 W0")));
  2592. }
  2593. else {
  2594. mesh_bed_leveling_flag = false;
  2595. }
  2596. break;
  2597. }
  2598. if (run == false && temp_cal_active == true && calibration_status_pinda() == true && target_temperature_bed >= 50) {
  2599. if (lcd_commands_type != LCD_COMMAND_STOP_PRINT) {
  2600. temp_compensation_start();
  2601. run = true;
  2602. repeatcommand_front(); // repeat G80 with all its parameters
  2603. enquecommand_front_P((PSTR("G28 W0")));
  2604. }
  2605. else {
  2606. mesh_bed_leveling_flag = false;
  2607. }
  2608. break;
  2609. }
  2610. run = false;
  2611. if (lcd_commands_type == LCD_COMMAND_STOP_PRINT) {
  2612. mesh_bed_leveling_flag = false;
  2613. break;
  2614. }
  2615. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  2616. bool custom_message_old = custom_message;
  2617. unsigned int custom_message_type_old = custom_message_type;
  2618. unsigned int custom_message_state_old = custom_message_state;
  2619. custom_message = true;
  2620. custom_message_type = 1;
  2621. custom_message_state = (MESH_MEAS_NUM_X_POINTS * MESH_MEAS_NUM_Y_POINTS) + 10;
  2622. lcd_update(1);
  2623. mbl.reset(); //reset mesh bed leveling
  2624. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  2625. // consumed during the first movements following this statement.
  2626. babystep_undo();
  2627. // Cycle through all points and probe them
  2628. // First move up. During this first movement, the babystepping will be reverted.
  2629. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2630. 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);
  2631. // The move to the first calibration point.
  2632. current_position[X_AXIS] = pgm_read_float(bed_ref_points);
  2633. current_position[Y_AXIS] = pgm_read_float(bed_ref_points + 1);
  2634. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2635. if (verbosity_level >= 1) {
  2636. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  2637. }
  2638. // mbl.get_meas_xy(0, 0, current_position[X_AXIS], current_position[Y_AXIS], false);
  2639. 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);
  2640. // Wait until the move is finished.
  2641. st_synchronize();
  2642. int mesh_point = 0; //index number of calibration point
  2643. int ix = 0;
  2644. int iy = 0;
  2645. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  2646. int Z_PROBE_FEEDRATE = homing_feedrate[Z_AXIS] / 60;
  2647. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  2648. 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)
  2649. if (verbosity_level >= 1) {
  2650. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  2651. }
  2652. setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  2653. const char *kill_message = NULL;
  2654. while (mesh_point != MESH_MEAS_NUM_X_POINTS * MESH_MEAS_NUM_Y_POINTS) {
  2655. if (verbosity_level >= 1) SERIAL_ECHOLNPGM("");
  2656. // Get coords of a measuring point.
  2657. ix = mesh_point % MESH_MEAS_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  2658. iy = mesh_point / MESH_MEAS_NUM_X_POINTS;
  2659. if (iy & 1) ix = (MESH_MEAS_NUM_X_POINTS - 1) - ix; // Zig zag
  2660. float z0 = 0.f;
  2661. if (has_z && mesh_point > 0) {
  2662. uint16_t z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  2663. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  2664. //#if 0
  2665. if (verbosity_level >= 1) {
  2666. SERIAL_ECHOPGM("Bed leveling, point: ");
  2667. MYSERIAL.print(mesh_point);
  2668. SERIAL_ECHOPGM(", calibration z: ");
  2669. MYSERIAL.print(z0, 5);
  2670. SERIAL_ECHOLNPGM("");
  2671. }
  2672. //#endif
  2673. }
  2674. // Move Z up to MESH_HOME_Z_SEARCH.
  2675. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2676. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  2677. st_synchronize();
  2678. // Move to XY position of the sensor point.
  2679. current_position[X_AXIS] = pgm_read_float(bed_ref_points + 2 * mesh_point);
  2680. current_position[Y_AXIS] = pgm_read_float(bed_ref_points + 2 * mesh_point + 1);
  2681. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2682. if (verbosity_level >= 1) {
  2683. SERIAL_PROTOCOL(mesh_point);
  2684. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  2685. }
  2686. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], XY_AXIS_FEEDRATE, active_extruder);
  2687. st_synchronize();
  2688. // Go down until endstop is hit
  2689. const float Z_CALIBRATION_THRESHOLD = 1.f;
  2690. 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
  2691. kill_message = MSG_BED_LEVELING_FAILED_POINT_LOW;
  2692. break;
  2693. }
  2694. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  2695. kill_message = MSG_BED_LEVELING_FAILED_PROBE_DISCONNECTED;
  2696. break;
  2697. }
  2698. 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
  2699. kill_message = MSG_BED_LEVELING_FAILED_POINT_HIGH;
  2700. break;
  2701. }
  2702. if (verbosity_level >= 10) {
  2703. SERIAL_ECHOPGM("X: ");
  2704. MYSERIAL.print(current_position[X_AXIS], 5);
  2705. SERIAL_ECHOLNPGM("");
  2706. SERIAL_ECHOPGM("Y: ");
  2707. MYSERIAL.print(current_position[Y_AXIS], 5);
  2708. SERIAL_PROTOCOLPGM("\n");
  2709. }
  2710. if (verbosity_level >= 1) {
  2711. SERIAL_ECHOPGM("mesh bed leveling: ");
  2712. MYSERIAL.print(current_position[Z_AXIS], 5);
  2713. SERIAL_ECHOLNPGM("");
  2714. }
  2715. mbl.set_z(ix, iy, current_position[Z_AXIS]); //store measured z values z_values[iy][ix] = z;
  2716. custom_message_state--;
  2717. mesh_point++;
  2718. lcd_update(1);
  2719. }
  2720. if (verbosity_level >= 20) SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  2721. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2722. if (verbosity_level >= 20) {
  2723. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  2724. MYSERIAL.print(current_position[Z_AXIS], 5);
  2725. }
  2726. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  2727. st_synchronize();
  2728. if (mesh_point != MESH_MEAS_NUM_X_POINTS * MESH_MEAS_NUM_Y_POINTS) {
  2729. kill(kill_message);
  2730. SERIAL_ECHOLNPGM("killed");
  2731. }
  2732. clean_up_after_endstop_move();
  2733. SERIAL_ECHOLNPGM("clean up finished ");
  2734. if(temp_cal_active == true && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  2735. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  2736. SERIAL_ECHOLNPGM("babystep applied");
  2737. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  2738. if (verbosity_level >= 1) {
  2739. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  2740. }
  2741. for (uint8_t i = 0; i < 4; ++i) {
  2742. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  2743. long correction = 0;
  2744. if (code_seen(codes[i]))
  2745. correction = code_value_long();
  2746. else if (eeprom_bed_correction_valid) {
  2747. unsigned char *addr = (i < 2) ?
  2748. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  2749. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  2750. correction = eeprom_read_int8(addr);
  2751. }
  2752. if (correction == 0)
  2753. continue;
  2754. float offset = float(correction) * 0.001f;
  2755. if (fabs(offset) > 0.101f) {
  2756. SERIAL_ERROR_START;
  2757. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  2758. SERIAL_ECHO(offset);
  2759. SERIAL_ECHOLNPGM(" microns");
  2760. }
  2761. else {
  2762. switch (i) {
  2763. case 0:
  2764. for (uint8_t row = 0; row < 3; ++row) {
  2765. mbl.z_values[row][1] += 0.5f * offset;
  2766. mbl.z_values[row][0] += offset;
  2767. }
  2768. break;
  2769. case 1:
  2770. for (uint8_t row = 0; row < 3; ++row) {
  2771. mbl.z_values[row][1] += 0.5f * offset;
  2772. mbl.z_values[row][2] += offset;
  2773. }
  2774. break;
  2775. case 2:
  2776. for (uint8_t col = 0; col < 3; ++col) {
  2777. mbl.z_values[1][col] += 0.5f * offset;
  2778. mbl.z_values[0][col] += offset;
  2779. }
  2780. break;
  2781. case 3:
  2782. for (uint8_t col = 0; col < 3; ++col) {
  2783. mbl.z_values[1][col] += 0.5f * offset;
  2784. mbl.z_values[2][col] += offset;
  2785. }
  2786. break;
  2787. }
  2788. }
  2789. }
  2790. SERIAL_ECHOLNPGM("Bed leveling correction finished");
  2791. 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)
  2792. SERIAL_ECHOLNPGM("Upsample finished");
  2793. mbl.active = 1; //activate mesh bed leveling
  2794. SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  2795. go_home_with_z_lift();
  2796. SERIAL_ECHOLNPGM("Go home finished");
  2797. //unretract (after PINDA preheat retraction)
  2798. if (degHotend(active_extruder) > EXTRUDE_MINTEMP && temp_cal_active == true && calibration_status_pinda() == true && target_temperature_bed >= 50) {
  2799. current_position[E_AXIS] += DEFAULT_RETRACTION;
  2800. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  2801. }
  2802. // Restore custom message state
  2803. custom_message = custom_message_old;
  2804. custom_message_type = custom_message_type_old;
  2805. custom_message_state = custom_message_state_old;
  2806. mesh_bed_leveling_flag = false;
  2807. mesh_bed_run_from_menu = false;
  2808. lcd_update(2);
  2809. }
  2810. break;
  2811. /**
  2812. * G81: Print mesh bed leveling status and bed profile if activated
  2813. */
  2814. case 81:
  2815. if (mbl.active) {
  2816. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2817. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2818. SERIAL_PROTOCOLPGM(",");
  2819. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2820. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2821. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2822. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2823. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2824. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2825. SERIAL_PROTOCOLPGM(" ");
  2826. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2827. }
  2828. SERIAL_PROTOCOLPGM("\n");
  2829. }
  2830. }
  2831. else
  2832. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  2833. break;
  2834. #if 0
  2835. /**
  2836. * G82: Single Z probe at current location
  2837. *
  2838. * WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  2839. *
  2840. */
  2841. case 82:
  2842. SERIAL_PROTOCOLLNPGM("Finding bed ");
  2843. setup_for_endstop_move();
  2844. find_bed_induction_sensor_point_z();
  2845. clean_up_after_endstop_move();
  2846. SERIAL_PROTOCOLPGM("Bed found at: ");
  2847. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  2848. SERIAL_PROTOCOLPGM("\n");
  2849. break;
  2850. /**
  2851. * G83: Prusa3D specific: Babystep in Z and store to EEPROM
  2852. */
  2853. case 83:
  2854. {
  2855. int babystepz = code_seen('S') ? code_value() : 0;
  2856. int BabyPosition = code_seen('P') ? code_value() : 0;
  2857. if (babystepz != 0) {
  2858. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  2859. // Is the axis indexed starting with zero or one?
  2860. if (BabyPosition > 4) {
  2861. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  2862. }else{
  2863. // Save it to the eeprom
  2864. babystepLoadZ = babystepz;
  2865. EEPROM_save_B(EEPROM_BABYSTEP_Z0+(BabyPosition*2),&babystepLoadZ);
  2866. // adjust the Z
  2867. babystepsTodoZadd(babystepLoadZ);
  2868. }
  2869. }
  2870. }
  2871. break;
  2872. /**
  2873. * G84: Prusa3D specific: UNDO Babystep Z (move Z axis back)
  2874. */
  2875. case 84:
  2876. babystepsTodoZsubtract(babystepLoadZ);
  2877. // babystepLoadZ = 0;
  2878. break;
  2879. /**
  2880. * G85: Prusa3D specific: Pick best babystep
  2881. */
  2882. case 85:
  2883. lcd_pick_babystep();
  2884. break;
  2885. #endif
  2886. /**
  2887. * G86: Prusa3D specific: Disable babystep correction after home.
  2888. * This G-code will be performed at the start of a calibration script.
  2889. */
  2890. case 86:
  2891. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2892. break;
  2893. /**
  2894. * G87: Prusa3D specific: Enable babystep correction after home
  2895. * This G-code will be performed at the end of a calibration script.
  2896. */
  2897. case 87:
  2898. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2899. break;
  2900. /**
  2901. * G88: Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  2902. */
  2903. case 88:
  2904. break;
  2905. #endif // ENABLE_MESH_BED_LEVELING
  2906. case 90: // G90
  2907. relative_mode = false;
  2908. break;
  2909. case 91: // G91
  2910. relative_mode = true;
  2911. break;
  2912. case 92: // G92
  2913. if(!code_seen(axis_codes[E_AXIS]))
  2914. st_synchronize();
  2915. for(int8_t i=0; i < NUM_AXIS; i++) {
  2916. if(code_seen(axis_codes[i])) {
  2917. if(i == E_AXIS) {
  2918. current_position[i] = code_value();
  2919. plan_set_e_position(current_position[E_AXIS]);
  2920. }
  2921. else {
  2922. current_position[i] = code_value()+add_homing[i];
  2923. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2924. }
  2925. }
  2926. }
  2927. break;
  2928. case 98: //activate farm mode
  2929. farm_mode = 1;
  2930. PingTime = millis();
  2931. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  2932. break;
  2933. case 99: //deactivate farm mode
  2934. farm_mode = 0;
  2935. lcd_printer_connected();
  2936. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  2937. lcd_update(2);
  2938. break;
  2939. }
  2940. } // end if(code_seen('G'))
  2941. else if(code_seen('M'))
  2942. {
  2943. int index;
  2944. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  2945. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  2946. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  2947. SERIAL_ECHOLNPGM("Invalid M code");
  2948. } else
  2949. switch((int)code_value())
  2950. {
  2951. #ifdef ULTIPANEL
  2952. case 0: // M0 - Unconditional stop - Wait for user button press on LCD
  2953. case 1: // M1 - Conditional stop - Wait for user button press on LCD
  2954. {
  2955. char *src = strchr_pointer + 2;
  2956. codenum = 0;
  2957. bool hasP = false, hasS = false;
  2958. if (code_seen('P')) {
  2959. codenum = code_value(); // milliseconds to wait
  2960. hasP = codenum > 0;
  2961. }
  2962. if (code_seen('S')) {
  2963. codenum = code_value() * 1000; // seconds to wait
  2964. hasS = codenum > 0;
  2965. }
  2966. starpos = strchr(src, '*');
  2967. if (starpos != NULL) *(starpos) = '\0';
  2968. while (*src == ' ') ++src;
  2969. if (!hasP && !hasS && *src != '\0') {
  2970. lcd_setstatus(src);
  2971. } else {
  2972. LCD_MESSAGERPGM(MSG_USERWAIT);
  2973. }
  2974. lcd_ignore_click(); //call lcd_ignore_click aslo for else ???
  2975. st_synchronize();
  2976. previous_millis_cmd = millis();
  2977. if (codenum > 0){
  2978. codenum += millis(); // keep track of when we started waiting
  2979. while(millis() < codenum && !lcd_clicked()){
  2980. manage_heater();
  2981. manage_inactivity(true);
  2982. lcd_update();
  2983. }
  2984. lcd_ignore_click(false);
  2985. }else{
  2986. if (!lcd_detected())
  2987. break;
  2988. while(!lcd_clicked()){
  2989. manage_heater();
  2990. manage_inactivity(true);
  2991. lcd_update();
  2992. }
  2993. }
  2994. if (IS_SD_PRINTING)
  2995. LCD_MESSAGERPGM(MSG_RESUMING);
  2996. else
  2997. LCD_MESSAGERPGM(WELCOME_MSG);
  2998. }
  2999. break;
  3000. #endif
  3001. case 17:
  3002. LCD_MESSAGERPGM(MSG_NO_MOVE);
  3003. enable_x();
  3004. enable_y();
  3005. enable_z();
  3006. enable_e0();
  3007. enable_e1();
  3008. enable_e2();
  3009. break;
  3010. #ifdef SDSUPPORT
  3011. case 20: // M20 - list SD card
  3012. SERIAL_PROTOCOLLNRPGM(MSG_BEGIN_FILE_LIST);
  3013. card.ls();
  3014. SERIAL_PROTOCOLLNRPGM(MSG_END_FILE_LIST);
  3015. break;
  3016. case 21: // M21 - init SD card
  3017. card.initsd();
  3018. break;
  3019. case 22: //M22 - release SD card
  3020. card.release();
  3021. break;
  3022. case 23: //M23 - Select file
  3023. starpos = (strchr(strchr_pointer + 4,'*'));
  3024. if(starpos!=NULL)
  3025. *(starpos)='\0';
  3026. card.openFile(strchr_pointer + 4,true);
  3027. break;
  3028. case 24: //M24 - Start SD print
  3029. card.startFileprint();
  3030. starttime=millis();
  3031. break;
  3032. case 25: //M25 - Pause SD print
  3033. card.pauseSDPrint();
  3034. break;
  3035. case 26: //M26 - Set SD index
  3036. if(card.cardOK && code_seen('S')) {
  3037. card.setIndex(code_value_long());
  3038. }
  3039. break;
  3040. case 27: //M27 - Get SD status
  3041. card.getStatus();
  3042. break;
  3043. case 28: //M28 - Start SD write
  3044. starpos = (strchr(strchr_pointer + 4,'*'));
  3045. if(starpos != NULL){
  3046. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  3047. strchr_pointer = strchr(npos,' ') + 1;
  3048. *(starpos) = '\0';
  3049. }
  3050. card.openFile(strchr_pointer+4,false);
  3051. break;
  3052. case 29: //M29 - Stop SD write
  3053. //processed in write to file routine above
  3054. //card,saving = false;
  3055. break;
  3056. case 30: //M30 <filename> Delete File
  3057. if (card.cardOK){
  3058. card.closefile();
  3059. starpos = (strchr(strchr_pointer + 4,'*'));
  3060. if(starpos != NULL){
  3061. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  3062. strchr_pointer = strchr(npos,' ') + 1;
  3063. *(starpos) = '\0';
  3064. }
  3065. card.removeFile(strchr_pointer + 4);
  3066. }
  3067. break;
  3068. case 32: //M32 - Select file and start SD print
  3069. {
  3070. if(card.sdprinting) {
  3071. st_synchronize();
  3072. }
  3073. starpos = (strchr(strchr_pointer + 4,'*'));
  3074. char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  3075. if(namestartpos==NULL)
  3076. {
  3077. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  3078. }
  3079. else
  3080. namestartpos++; //to skip the '!'
  3081. if(starpos!=NULL)
  3082. *(starpos)='\0';
  3083. bool call_procedure=(code_seen('P'));
  3084. if(strchr_pointer>namestartpos)
  3085. call_procedure=false; //false alert, 'P' found within filename
  3086. if( card.cardOK )
  3087. {
  3088. card.openFile(namestartpos,true,!call_procedure);
  3089. if(code_seen('S'))
  3090. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  3091. card.setIndex(code_value_long());
  3092. card.startFileprint();
  3093. if(!call_procedure)
  3094. starttime=millis(); //procedure calls count as normal print time.
  3095. }
  3096. } break;
  3097. case 928: //M928 - Start SD write
  3098. starpos = (strchr(strchr_pointer + 5,'*'));
  3099. if(starpos != NULL){
  3100. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  3101. strchr_pointer = strchr(npos,' ') + 1;
  3102. *(starpos) = '\0';
  3103. }
  3104. card.openLogFile(strchr_pointer+5);
  3105. break;
  3106. #endif //SDSUPPORT
  3107. case 31: //M31 take time since the start of the SD print or an M109 command
  3108. {
  3109. stoptime=millis();
  3110. char time[30];
  3111. unsigned long t=(stoptime-starttime)/1000;
  3112. int sec,min;
  3113. min=t/60;
  3114. sec=t%60;
  3115. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  3116. SERIAL_ECHO_START;
  3117. SERIAL_ECHOLN(time);
  3118. lcd_setstatus(time);
  3119. autotempShutdown();
  3120. }
  3121. break;
  3122. case 42: //M42 -Change pin status via gcode
  3123. if (code_seen('S'))
  3124. {
  3125. int pin_status = code_value();
  3126. int pin_number = LED_PIN;
  3127. if (code_seen('P') && pin_status >= 0 && pin_status <= 255)
  3128. pin_number = code_value();
  3129. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  3130. {
  3131. if (sensitive_pins[i] == pin_number)
  3132. {
  3133. pin_number = -1;
  3134. break;
  3135. }
  3136. }
  3137. #if defined(FAN_PIN) && FAN_PIN > -1
  3138. if (pin_number == FAN_PIN)
  3139. fanSpeed = pin_status;
  3140. #endif
  3141. if (pin_number > -1)
  3142. {
  3143. pinMode(pin_number, OUTPUT);
  3144. digitalWrite(pin_number, pin_status);
  3145. analogWrite(pin_number, pin_status);
  3146. }
  3147. }
  3148. break;
  3149. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  3150. // Reset the baby step value and the baby step applied flag.
  3151. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  3152. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z, 0);
  3153. // Reset the skew and offset in both RAM and EEPROM.
  3154. reset_bed_offset_and_skew();
  3155. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  3156. // the planner will not perform any adjustments in the XY plane.
  3157. // Wait for the motors to stop and update the current position with the absolute values.
  3158. world2machine_revert_to_uncorrected();
  3159. break;
  3160. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  3161. {
  3162. // Only Z calibration?
  3163. bool onlyZ = code_seen('Z');
  3164. if (!onlyZ) {
  3165. setTargetBed(0);
  3166. setTargetHotend(0, 0);
  3167. setTargetHotend(0, 1);
  3168. setTargetHotend(0, 2);
  3169. adjust_bed_reset(); //reset bed level correction
  3170. }
  3171. // Disable the default update procedure of the display. We will do a modal dialog.
  3172. lcd_update_enable(false);
  3173. // Let the planner use the uncorrected coordinates.
  3174. mbl.reset();
  3175. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  3176. // the planner will not perform any adjustments in the XY plane.
  3177. // Wait for the motors to stop and update the current position with the absolute values.
  3178. world2machine_revert_to_uncorrected();
  3179. // Reset the baby step value applied without moving the axes.
  3180. babystep_reset();
  3181. // Mark all axes as in a need for homing.
  3182. memset(axis_known_position, 0, sizeof(axis_known_position));
  3183. // Let the user move the Z axes up to the end stoppers.
  3184. if (lcd_calibrate_z_end_stop_manual( onlyZ )) {
  3185. refresh_cmd_timeout();
  3186. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ)) {
  3187. lcd_wait_for_cool_down();
  3188. lcd_show_fullscreen_message_and_wait_P(MSG_PAPER);
  3189. lcd_display_message_fullscreen_P(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1);
  3190. lcd_implementation_print_at(0, 2, 1);
  3191. lcd_printPGM(MSG_FIND_BED_OFFSET_AND_SKEW_LINE2);
  3192. }
  3193. // Move the print head close to the bed.
  3194. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3195. 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);
  3196. st_synchronize();
  3197. // Home in the XY plane.
  3198. set_destination_to_current();
  3199. setup_for_endstop_move();
  3200. home_xy();
  3201. int8_t verbosity_level = 0;
  3202. if (code_seen('V')) {
  3203. // Just 'V' without a number counts as V1.
  3204. char c = strchr_pointer[1];
  3205. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  3206. }
  3207. if (onlyZ) {
  3208. clean_up_after_endstop_move();
  3209. // Z only calibration.
  3210. // Load the machine correction matrix
  3211. world2machine_initialize();
  3212. // and correct the current_position to match the transformed coordinate system.
  3213. world2machine_update_current();
  3214. //FIXME
  3215. bool result = sample_mesh_and_store_reference();
  3216. if (result) {
  3217. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  3218. // Shipped, the nozzle height has been set already. The user can start printing now.
  3219. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  3220. // babystep_apply();
  3221. }
  3222. } else {
  3223. // Reset the baby step value and the baby step applied flag.
  3224. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  3225. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z, 0);
  3226. // Complete XYZ calibration.
  3227. uint8_t point_too_far_mask = 0;
  3228. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  3229. clean_up_after_endstop_move();
  3230. // Print head up.
  3231. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3232. 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);
  3233. st_synchronize();
  3234. if (result >= 0) {
  3235. point_too_far_mask = 0;
  3236. // Second half: The fine adjustment.
  3237. // Let the planner use the uncorrected coordinates.
  3238. mbl.reset();
  3239. world2machine_reset();
  3240. // Home in the XY plane.
  3241. setup_for_endstop_move();
  3242. home_xy();
  3243. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  3244. clean_up_after_endstop_move();
  3245. // Print head up.
  3246. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3247. 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);
  3248. st_synchronize();
  3249. // if (result >= 0) babystep_apply();
  3250. }
  3251. lcd_bed_calibration_show_result(result, point_too_far_mask);
  3252. if (result >= 0) {
  3253. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  3254. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  3255. lcd_show_fullscreen_message_and_wait_P(MSG_BABYSTEP_Z_NOT_SET);
  3256. }
  3257. }
  3258. } else {
  3259. // Timeouted.
  3260. }
  3261. lcd_update_enable(true);
  3262. break;
  3263. }
  3264. /*
  3265. case 46:
  3266. {
  3267. // M46: Prusa3D: Show the assigned IP address.
  3268. uint8_t ip[4];
  3269. bool hasIP = card.ToshibaFlashAir_GetIP(ip);
  3270. if (hasIP) {
  3271. SERIAL_ECHOPGM("Toshiba FlashAir current IP: ");
  3272. SERIAL_ECHO(int(ip[0]));
  3273. SERIAL_ECHOPGM(".");
  3274. SERIAL_ECHO(int(ip[1]));
  3275. SERIAL_ECHOPGM(".");
  3276. SERIAL_ECHO(int(ip[2]));
  3277. SERIAL_ECHOPGM(".");
  3278. SERIAL_ECHO(int(ip[3]));
  3279. SERIAL_ECHOLNPGM("");
  3280. } else {
  3281. SERIAL_ECHOLNPGM("Toshiba FlashAir GetIP failed");
  3282. }
  3283. break;
  3284. }
  3285. */
  3286. case 47:
  3287. // M47: Prusa3D: Show end stops dialog on the display.
  3288. lcd_diag_show_end_stops();
  3289. break;
  3290. #if 0
  3291. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  3292. {
  3293. // Disable the default update procedure of the display. We will do a modal dialog.
  3294. lcd_update_enable(false);
  3295. // Let the planner use the uncorrected coordinates.
  3296. mbl.reset();
  3297. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  3298. // the planner will not perform any adjustments in the XY plane.
  3299. // Wait for the motors to stop and update the current position with the absolute values.
  3300. world2machine_revert_to_uncorrected();
  3301. // Move the print head close to the bed.
  3302. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3303. 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);
  3304. st_synchronize();
  3305. // Home in the XY plane.
  3306. set_destination_to_current();
  3307. setup_for_endstop_move();
  3308. home_xy();
  3309. int8_t verbosity_level = 0;
  3310. if (code_seen('V')) {
  3311. // Just 'V' without a number counts as V1.
  3312. char c = strchr_pointer[1];
  3313. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  3314. }
  3315. bool success = scan_bed_induction_points(verbosity_level);
  3316. clean_up_after_endstop_move();
  3317. // Print head up.
  3318. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3319. 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);
  3320. st_synchronize();
  3321. lcd_update_enable(true);
  3322. break;
  3323. }
  3324. #endif
  3325. // M48 Z-Probe repeatability measurement function.
  3326. //
  3327. // 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>
  3328. //
  3329. // This function assumes the bed has been homed. Specificaly, that a G28 command
  3330. // as been issued prior to invoking the M48 Z-Probe repeatability measurement function.
  3331. // Any information generated by a prior G29 Bed leveling command will be lost and need to be
  3332. // regenerated.
  3333. //
  3334. // The number of samples will default to 10 if not specified. You can use upper or lower case
  3335. // letters for any of the options EXCEPT n. n must be in lower case because Marlin uses a capital
  3336. // N for its communication protocol and will get horribly confused if you send it a capital N.
  3337. //
  3338. #ifdef ENABLE_AUTO_BED_LEVELING
  3339. #ifdef Z_PROBE_REPEATABILITY_TEST
  3340. case 48: // M48 Z-Probe repeatability
  3341. {
  3342. #if Z_MIN_PIN == -1
  3343. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  3344. #endif
  3345. double sum=0.0;
  3346. double mean=0.0;
  3347. double sigma=0.0;
  3348. double sample_set[50];
  3349. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  3350. double X_current, Y_current, Z_current;
  3351. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  3352. if (code_seen('V') || code_seen('v')) {
  3353. verbose_level = code_value();
  3354. if (verbose_level<0 || verbose_level>4 ) {
  3355. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  3356. goto Sigma_Exit;
  3357. }
  3358. }
  3359. if (verbose_level > 0) {
  3360. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  3361. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  3362. }
  3363. if (code_seen('n')) {
  3364. n_samples = code_value();
  3365. if (n_samples<4 || n_samples>50 ) {
  3366. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  3367. goto Sigma_Exit;
  3368. }
  3369. }
  3370. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  3371. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  3372. Z_current = st_get_position_mm(Z_AXIS);
  3373. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  3374. ext_position = st_get_position_mm(E_AXIS);
  3375. if (code_seen('X') || code_seen('x') ) {
  3376. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  3377. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  3378. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  3379. goto Sigma_Exit;
  3380. }
  3381. }
  3382. if (code_seen('Y') || code_seen('y') ) {
  3383. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  3384. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  3385. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  3386. goto Sigma_Exit;
  3387. }
  3388. }
  3389. if (code_seen('L') || code_seen('l') ) {
  3390. n_legs = code_value();
  3391. if ( n_legs==1 )
  3392. n_legs = 2;
  3393. if ( n_legs<0 || n_legs>15 ) {
  3394. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  3395. goto Sigma_Exit;
  3396. }
  3397. }
  3398. //
  3399. // Do all the preliminary setup work. First raise the probe.
  3400. //
  3401. st_synchronize();
  3402. plan_bed_level_matrix.set_to_identity();
  3403. plan_buffer_line( X_current, Y_current, Z_start_location,
  3404. ext_position,
  3405. homing_feedrate[Z_AXIS]/60,
  3406. active_extruder);
  3407. st_synchronize();
  3408. //
  3409. // Now get everything to the specified probe point So we can safely do a probe to
  3410. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  3411. // use that as a starting point for each probe.
  3412. //
  3413. if (verbose_level > 2)
  3414. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  3415. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  3416. ext_position,
  3417. homing_feedrate[X_AXIS]/60,
  3418. active_extruder);
  3419. st_synchronize();
  3420. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  3421. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  3422. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  3423. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  3424. //
  3425. // OK, do the inital probe to get us close to the bed.
  3426. // Then retrace the right amount and use that in subsequent probes
  3427. //
  3428. setup_for_endstop_move();
  3429. run_z_probe();
  3430. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  3431. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  3432. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  3433. ext_position,
  3434. homing_feedrate[X_AXIS]/60,
  3435. active_extruder);
  3436. st_synchronize();
  3437. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  3438. for( n=0; n<n_samples; n++) {
  3439. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  3440. if ( n_legs) {
  3441. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  3442. int rotational_direction, l;
  3443. rotational_direction = (unsigned long) millis() & 0x0001; // clockwise or counter clockwise
  3444. radius = (unsigned long) millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  3445. theta = (float) ((unsigned long) millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  3446. //SERIAL_ECHOPAIR("starting radius: ",radius);
  3447. //SERIAL_ECHOPAIR(" theta: ",theta);
  3448. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  3449. //SERIAL_PROTOCOLLNPGM("");
  3450. for( l=0; l<n_legs-1; l++) {
  3451. if (rotational_direction==1)
  3452. theta += (float) ((unsigned long) millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  3453. else
  3454. theta -= (float) ((unsigned long) millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  3455. radius += (float) ( ((long) ((unsigned long) millis() % (long) 10)) - 5);
  3456. if ( radius<0.0 )
  3457. radius = -radius;
  3458. X_current = X_probe_location + cos(theta) * radius;
  3459. Y_current = Y_probe_location + sin(theta) * radius;
  3460. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  3461. X_current = X_MIN_POS;
  3462. if ( X_current>X_MAX_POS)
  3463. X_current = X_MAX_POS;
  3464. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  3465. Y_current = Y_MIN_POS;
  3466. if ( Y_current>Y_MAX_POS)
  3467. Y_current = Y_MAX_POS;
  3468. if (verbose_level>3 ) {
  3469. SERIAL_ECHOPAIR("x: ", X_current);
  3470. SERIAL_ECHOPAIR("y: ", Y_current);
  3471. SERIAL_PROTOCOLLNPGM("");
  3472. }
  3473. do_blocking_move_to( X_current, Y_current, Z_current );
  3474. }
  3475. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  3476. }
  3477. setup_for_endstop_move();
  3478. run_z_probe();
  3479. sample_set[n] = current_position[Z_AXIS];
  3480. //
  3481. // Get the current mean for the data points we have so far
  3482. //
  3483. sum=0.0;
  3484. for( j=0; j<=n; j++) {
  3485. sum = sum + sample_set[j];
  3486. }
  3487. mean = sum / (double (n+1));
  3488. //
  3489. // Now, use that mean to calculate the standard deviation for the
  3490. // data points we have so far
  3491. //
  3492. sum=0.0;
  3493. for( j=0; j<=n; j++) {
  3494. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  3495. }
  3496. sigma = sqrt( sum / (double (n+1)) );
  3497. if (verbose_level > 1) {
  3498. SERIAL_PROTOCOL(n+1);
  3499. SERIAL_PROTOCOL(" of ");
  3500. SERIAL_PROTOCOL(n_samples);
  3501. SERIAL_PROTOCOLPGM(" z: ");
  3502. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  3503. }
  3504. if (verbose_level > 2) {
  3505. SERIAL_PROTOCOL(" mean: ");
  3506. SERIAL_PROTOCOL_F(mean,6);
  3507. SERIAL_PROTOCOL(" sigma: ");
  3508. SERIAL_PROTOCOL_F(sigma,6);
  3509. }
  3510. if (verbose_level > 0)
  3511. SERIAL_PROTOCOLPGM("\n");
  3512. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  3513. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  3514. st_synchronize();
  3515. }
  3516. delay(1000);
  3517. clean_up_after_endstop_move();
  3518. // enable_endstops(true);
  3519. if (verbose_level > 0) {
  3520. SERIAL_PROTOCOLPGM("Mean: ");
  3521. SERIAL_PROTOCOL_F(mean, 6);
  3522. SERIAL_PROTOCOLPGM("\n");
  3523. }
  3524. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  3525. SERIAL_PROTOCOL_F(sigma, 6);
  3526. SERIAL_PROTOCOLPGM("\n\n");
  3527. Sigma_Exit:
  3528. break;
  3529. }
  3530. #endif // Z_PROBE_REPEATABILITY_TEST
  3531. #endif // ENABLE_AUTO_BED_LEVELING
  3532. case 104: // M104
  3533. if(setTargetedHotend(104)){
  3534. break;
  3535. }
  3536. if (code_seen('S')) setTargetHotend(code_value(), tmp_extruder);
  3537. setWatch();
  3538. break;
  3539. case 112: // M112 -Emergency Stop
  3540. kill();
  3541. break;
  3542. case 140: // M140 set bed temp
  3543. if (code_seen('S')) setTargetBed(code_value());
  3544. break;
  3545. case 105 : // M105
  3546. if(setTargetedHotend(105)){
  3547. break;
  3548. }
  3549. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  3550. SERIAL_PROTOCOLPGM("ok T:");
  3551. SERIAL_PROTOCOL_F(degHotend(tmp_extruder),1);
  3552. SERIAL_PROTOCOLPGM(" /");
  3553. SERIAL_PROTOCOL_F(degTargetHotend(tmp_extruder),1);
  3554. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  3555. SERIAL_PROTOCOLPGM(" B:");
  3556. SERIAL_PROTOCOL_F(degBed(),1);
  3557. SERIAL_PROTOCOLPGM(" /");
  3558. SERIAL_PROTOCOL_F(degTargetBed(),1);
  3559. #endif //TEMP_BED_PIN
  3560. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  3561. SERIAL_PROTOCOLPGM(" T");
  3562. SERIAL_PROTOCOL(cur_extruder);
  3563. SERIAL_PROTOCOLPGM(":");
  3564. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  3565. SERIAL_PROTOCOLPGM(" /");
  3566. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  3567. }
  3568. #else
  3569. SERIAL_ERROR_START;
  3570. SERIAL_ERRORLNRPGM(MSG_ERR_NO_THERMISTORS);
  3571. #endif
  3572. SERIAL_PROTOCOLPGM(" @:");
  3573. #ifdef EXTRUDER_WATTS
  3574. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  3575. SERIAL_PROTOCOLPGM("W");
  3576. #else
  3577. SERIAL_PROTOCOL(getHeaterPower(tmp_extruder));
  3578. #endif
  3579. SERIAL_PROTOCOLPGM(" B@:");
  3580. #ifdef BED_WATTS
  3581. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  3582. SERIAL_PROTOCOLPGM("W");
  3583. #else
  3584. SERIAL_PROTOCOL(getHeaterPower(-1));
  3585. #endif
  3586. #ifdef SHOW_TEMP_ADC_VALUES
  3587. {float raw = 0.0;
  3588. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  3589. SERIAL_PROTOCOLPGM(" ADC B:");
  3590. SERIAL_PROTOCOL_F(degBed(),1);
  3591. SERIAL_PROTOCOLPGM("C->");
  3592. raw = rawBedTemp();
  3593. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  3594. SERIAL_PROTOCOLPGM(" Rb->");
  3595. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  3596. SERIAL_PROTOCOLPGM(" Rxb->");
  3597. SERIAL_PROTOCOL_F(raw, 5);
  3598. #endif
  3599. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  3600. SERIAL_PROTOCOLPGM(" T");
  3601. SERIAL_PROTOCOL(cur_extruder);
  3602. SERIAL_PROTOCOLPGM(":");
  3603. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  3604. SERIAL_PROTOCOLPGM("C->");
  3605. raw = rawHotendTemp(cur_extruder);
  3606. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  3607. SERIAL_PROTOCOLPGM(" Rt");
  3608. SERIAL_PROTOCOL(cur_extruder);
  3609. SERIAL_PROTOCOLPGM("->");
  3610. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  3611. SERIAL_PROTOCOLPGM(" Rx");
  3612. SERIAL_PROTOCOL(cur_extruder);
  3613. SERIAL_PROTOCOLPGM("->");
  3614. SERIAL_PROTOCOL_F(raw, 5);
  3615. }}
  3616. #endif
  3617. SERIAL_PROTOCOLLN("");
  3618. return;
  3619. break;
  3620. case 109:
  3621. {// M109 - Wait for extruder heater to reach target.
  3622. if(setTargetedHotend(109)){
  3623. break;
  3624. }
  3625. LCD_MESSAGERPGM(MSG_HEATING);
  3626. heating_status = 1;
  3627. if (farm_mode) { prusa_statistics(1); };
  3628. #ifdef AUTOTEMP
  3629. autotemp_enabled=false;
  3630. #endif
  3631. if (code_seen('S')) {
  3632. setTargetHotend(code_value(), tmp_extruder);
  3633. CooldownNoWait = true;
  3634. } else if (code_seen('R')) {
  3635. setTargetHotend(code_value(), tmp_extruder);
  3636. CooldownNoWait = false;
  3637. }
  3638. #ifdef AUTOTEMP
  3639. if (code_seen('S')) autotemp_min=code_value();
  3640. if (code_seen('B')) autotemp_max=code_value();
  3641. if (code_seen('F'))
  3642. {
  3643. autotemp_factor=code_value();
  3644. autotemp_enabled=true;
  3645. }
  3646. #endif
  3647. setWatch();
  3648. codenum = millis();
  3649. /* See if we are heating up or cooling down */
  3650. target_direction = isHeatingHotend(tmp_extruder); // true if heating, false if cooling
  3651. cancel_heatup = false;
  3652. wait_for_heater(codenum); //loops until target temperature is reached
  3653. LCD_MESSAGERPGM(MSG_HEATING_COMPLETE);
  3654. heating_status = 2;
  3655. if (farm_mode) { prusa_statistics(2); };
  3656. //starttime=millis();
  3657. previous_millis_cmd = millis();
  3658. }
  3659. break;
  3660. case 190: // M190 - Wait for bed heater to reach target.
  3661. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  3662. LCD_MESSAGERPGM(MSG_BED_HEATING);
  3663. heating_status = 3;
  3664. if (farm_mode) { prusa_statistics(1); };
  3665. if (code_seen('S'))
  3666. {
  3667. setTargetBed(code_value());
  3668. CooldownNoWait = true;
  3669. }
  3670. else if (code_seen('R'))
  3671. {
  3672. setTargetBed(code_value());
  3673. CooldownNoWait = false;
  3674. }
  3675. codenum = millis();
  3676. cancel_heatup = false;
  3677. target_direction = isHeatingBed(); // true if heating, false if cooling
  3678. while ( (target_direction)&&(!cancel_heatup) ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false)) )
  3679. {
  3680. if(( millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  3681. {
  3682. if (!farm_mode) {
  3683. float tt = degHotend(active_extruder);
  3684. SERIAL_PROTOCOLPGM("T:");
  3685. SERIAL_PROTOCOL(tt);
  3686. SERIAL_PROTOCOLPGM(" E:");
  3687. SERIAL_PROTOCOL((int)active_extruder);
  3688. SERIAL_PROTOCOLPGM(" B:");
  3689. SERIAL_PROTOCOL_F(degBed(), 1);
  3690. SERIAL_PROTOCOLLN("");
  3691. }
  3692. codenum = millis();
  3693. }
  3694. manage_heater();
  3695. manage_inactivity();
  3696. lcd_update();
  3697. }
  3698. LCD_MESSAGERPGM(MSG_BED_DONE);
  3699. heating_status = 4;
  3700. previous_millis_cmd = millis();
  3701. #endif
  3702. break;
  3703. #if defined(FAN_PIN) && FAN_PIN > -1
  3704. case 106: //M106 Fan On
  3705. if (code_seen('S')){
  3706. fanSpeed=constrain(code_value(),0,255);
  3707. }
  3708. else {
  3709. fanSpeed=255;
  3710. }
  3711. break;
  3712. case 107: //M107 Fan Off
  3713. fanSpeed = 0;
  3714. break;
  3715. #endif //FAN_PIN
  3716. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  3717. case 80: // M80 - Turn on Power Supply
  3718. SET_OUTPUT(PS_ON_PIN); //GND
  3719. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  3720. // If you have a switch on suicide pin, this is useful
  3721. // if you want to start another print with suicide feature after
  3722. // a print without suicide...
  3723. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  3724. SET_OUTPUT(SUICIDE_PIN);
  3725. WRITE(SUICIDE_PIN, HIGH);
  3726. #endif
  3727. #ifdef ULTIPANEL
  3728. powersupply = true;
  3729. LCD_MESSAGERPGM(WELCOME_MSG);
  3730. lcd_update();
  3731. #endif
  3732. break;
  3733. #endif
  3734. case 81: // M81 - Turn off Power Supply
  3735. disable_heater();
  3736. st_synchronize();
  3737. disable_e0();
  3738. disable_e1();
  3739. disable_e2();
  3740. finishAndDisableSteppers();
  3741. fanSpeed = 0;
  3742. delay(1000); // Wait a little before to switch off
  3743. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  3744. st_synchronize();
  3745. suicide();
  3746. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  3747. SET_OUTPUT(PS_ON_PIN);
  3748. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  3749. #endif
  3750. #ifdef ULTIPANEL
  3751. powersupply = false;
  3752. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR("."))); //!!
  3753. /*
  3754. MACHNAME = "Prusa i3"
  3755. MSGOFF = "Vypnuto"
  3756. "Prusai3"" ""vypnuto""."
  3757. "Prusa i3"" "MSG_ALL[lang_selected][50]"."
  3758. */
  3759. lcd_update();
  3760. #endif
  3761. break;
  3762. case 82:
  3763. axis_relative_modes[3] = false;
  3764. break;
  3765. case 83:
  3766. axis_relative_modes[3] = true;
  3767. break;
  3768. case 18: //compatibility
  3769. case 84: // M84
  3770. if(code_seen('S')){
  3771. stepper_inactive_time = code_value() * 1000;
  3772. }
  3773. else
  3774. {
  3775. 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])));
  3776. if(all_axis)
  3777. {
  3778. st_synchronize();
  3779. disable_e0();
  3780. disable_e1();
  3781. disable_e2();
  3782. finishAndDisableSteppers();
  3783. }
  3784. else
  3785. {
  3786. st_synchronize();
  3787. if (code_seen('X')) disable_x();
  3788. if (code_seen('Y')) disable_y();
  3789. if (code_seen('Z')) disable_z();
  3790. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  3791. if (code_seen('E')) {
  3792. disable_e0();
  3793. disable_e1();
  3794. disable_e2();
  3795. }
  3796. #endif
  3797. }
  3798. }
  3799. snmm_filaments_used = 0;
  3800. break;
  3801. case 85: // M85
  3802. if(code_seen('S')) {
  3803. max_inactive_time = code_value() * 1000;
  3804. }
  3805. break;
  3806. case 92: // M92
  3807. for(int8_t i=0; i < NUM_AXIS; i++)
  3808. {
  3809. if(code_seen(axis_codes[i]))
  3810. {
  3811. if(i == 3) { // E
  3812. float value = code_value();
  3813. if(value < 20.0) {
  3814. float factor = axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  3815. max_jerk[E_AXIS] *= factor;
  3816. max_feedrate[i] *= factor;
  3817. axis_steps_per_sqr_second[i] *= factor;
  3818. }
  3819. axis_steps_per_unit[i] = value;
  3820. }
  3821. else {
  3822. axis_steps_per_unit[i] = code_value();
  3823. }
  3824. }
  3825. }
  3826. break;
  3827. case 115: // M115
  3828. if (code_seen('V')) {
  3829. // Report the Prusa version number.
  3830. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  3831. } else if (code_seen('U')) {
  3832. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  3833. // pause the print and ask the user to upgrade the firmware.
  3834. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  3835. } else {
  3836. SERIAL_PROTOCOLRPGM(MSG_M115_REPORT);
  3837. }
  3838. break;
  3839. /* case 117: // M117 display message
  3840. starpos = (strchr(strchr_pointer + 5,'*'));
  3841. if(starpos!=NULL)
  3842. *(starpos)='\0';
  3843. lcd_setstatus(strchr_pointer + 5);
  3844. break;*/
  3845. case 114: // M114
  3846. SERIAL_PROTOCOLPGM("X:");
  3847. SERIAL_PROTOCOL(current_position[X_AXIS]);
  3848. SERIAL_PROTOCOLPGM(" Y:");
  3849. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3850. SERIAL_PROTOCOLPGM(" Z:");
  3851. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3852. SERIAL_PROTOCOLPGM(" E:");
  3853. SERIAL_PROTOCOL(current_position[E_AXIS]);
  3854. SERIAL_PROTOCOLRPGM(MSG_COUNT_X);
  3855. SERIAL_PROTOCOL(float(st_get_position(X_AXIS))/axis_steps_per_unit[X_AXIS]);
  3856. SERIAL_PROTOCOLPGM(" Y:");
  3857. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS))/axis_steps_per_unit[Y_AXIS]);
  3858. SERIAL_PROTOCOLPGM(" Z:");
  3859. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS))/axis_steps_per_unit[Z_AXIS]);
  3860. SERIAL_PROTOCOLLN("");
  3861. break;
  3862. case 120: // M120
  3863. enable_endstops(false) ;
  3864. break;
  3865. case 121: // M121
  3866. enable_endstops(true) ;
  3867. break;
  3868. case 119: // M119
  3869. SERIAL_PROTOCOLRPGM(MSG_M119_REPORT);
  3870. SERIAL_PROTOCOLLN("");
  3871. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  3872. SERIAL_PROTOCOLRPGM(MSG_X_MIN);
  3873. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  3874. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3875. }else{
  3876. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3877. }
  3878. SERIAL_PROTOCOLLN("");
  3879. #endif
  3880. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  3881. SERIAL_PROTOCOLRPGM(MSG_X_MAX);
  3882. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  3883. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3884. }else{
  3885. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3886. }
  3887. SERIAL_PROTOCOLLN("");
  3888. #endif
  3889. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  3890. SERIAL_PROTOCOLRPGM(MSG_Y_MIN);
  3891. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  3892. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3893. }else{
  3894. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3895. }
  3896. SERIAL_PROTOCOLLN("");
  3897. #endif
  3898. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  3899. SERIAL_PROTOCOLRPGM(MSG_Y_MAX);
  3900. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  3901. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3902. }else{
  3903. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3904. }
  3905. SERIAL_PROTOCOLLN("");
  3906. #endif
  3907. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  3908. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  3909. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  3910. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3911. }else{
  3912. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3913. }
  3914. SERIAL_PROTOCOLLN("");
  3915. #endif
  3916. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  3917. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  3918. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  3919. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3920. }else{
  3921. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3922. }
  3923. SERIAL_PROTOCOLLN("");
  3924. #endif
  3925. break;
  3926. //TODO: update for all axis, use for loop
  3927. #ifdef BLINKM
  3928. case 150: // M150
  3929. {
  3930. byte red;
  3931. byte grn;
  3932. byte blu;
  3933. if(code_seen('R')) red = code_value();
  3934. if(code_seen('U')) grn = code_value();
  3935. if(code_seen('B')) blu = code_value();
  3936. SendColors(red,grn,blu);
  3937. }
  3938. break;
  3939. #endif //BLINKM
  3940. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3941. {
  3942. tmp_extruder = active_extruder;
  3943. if(code_seen('T')) {
  3944. tmp_extruder = code_value();
  3945. if(tmp_extruder >= EXTRUDERS) {
  3946. SERIAL_ECHO_START;
  3947. SERIAL_ECHO(MSG_M200_INVALID_EXTRUDER);
  3948. break;
  3949. }
  3950. }
  3951. float area = .0;
  3952. if(code_seen('D')) {
  3953. float diameter = (float)code_value();
  3954. if (diameter == 0.0) {
  3955. // setting any extruder filament size disables volumetric on the assumption that
  3956. // slicers either generate in extruder values as cubic mm or as as filament feeds
  3957. // for all extruders
  3958. volumetric_enabled = false;
  3959. } else {
  3960. filament_size[tmp_extruder] = (float)code_value();
  3961. // make sure all extruders have some sane value for the filament size
  3962. filament_size[0] = (filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : filament_size[0]);
  3963. #if EXTRUDERS > 1
  3964. filament_size[1] = (filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : filament_size[1]);
  3965. #if EXTRUDERS > 2
  3966. filament_size[2] = (filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : filament_size[2]);
  3967. #endif
  3968. #endif
  3969. volumetric_enabled = true;
  3970. }
  3971. } else {
  3972. //reserved for setting filament diameter via UFID or filament measuring device
  3973. break;
  3974. }
  3975. calculate_volumetric_multipliers();
  3976. }
  3977. break;
  3978. case 201: // M201
  3979. for(int8_t i=0; i < NUM_AXIS; i++)
  3980. {
  3981. if(code_seen(axis_codes[i]))
  3982. {
  3983. max_acceleration_units_per_sq_second[i] = code_value();
  3984. }
  3985. }
  3986. // 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)
  3987. reset_acceleration_rates();
  3988. break;
  3989. #if 0 // Not used for Sprinter/grbl gen6
  3990. case 202: // M202
  3991. for(int8_t i=0; i < NUM_AXIS; i++) {
  3992. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * axis_steps_per_unit[i];
  3993. }
  3994. break;
  3995. #endif
  3996. case 203: // M203 max feedrate mm/sec
  3997. for(int8_t i=0; i < NUM_AXIS; i++) {
  3998. if(code_seen(axis_codes[i])) max_feedrate[i] = code_value();
  3999. }
  4000. break;
  4001. case 204: // M204 acclereration S normal moves T filmanent only moves
  4002. {
  4003. if(code_seen('S')) acceleration = code_value() ;
  4004. if(code_seen('T')) retract_acceleration = code_value() ;
  4005. }
  4006. break;
  4007. 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
  4008. {
  4009. if(code_seen('S')) minimumfeedrate = code_value();
  4010. if(code_seen('T')) mintravelfeedrate = code_value();
  4011. if(code_seen('B')) minsegmenttime = code_value() ;
  4012. if(code_seen('X')) max_jerk[X_AXIS] = max_jerk[Y_AXIS] = code_value();
  4013. if(code_seen('Y')) max_jerk[Y_AXIS] = code_value();
  4014. if(code_seen('Z')) max_jerk[Z_AXIS] = code_value();
  4015. if(code_seen('E')) max_jerk[E_AXIS] = code_value();
  4016. }
  4017. break;
  4018. case 206: // M206 additional homing offset
  4019. for(int8_t i=0; i < 3; i++)
  4020. {
  4021. if(code_seen(axis_codes[i])) add_homing[i] = code_value();
  4022. }
  4023. break;
  4024. #ifdef FWRETRACT
  4025. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  4026. {
  4027. if(code_seen('S'))
  4028. {
  4029. retract_length = code_value() ;
  4030. }
  4031. if(code_seen('F'))
  4032. {
  4033. retract_feedrate = code_value()/60 ;
  4034. }
  4035. if(code_seen('Z'))
  4036. {
  4037. retract_zlift = code_value() ;
  4038. }
  4039. }break;
  4040. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  4041. {
  4042. if(code_seen('S'))
  4043. {
  4044. retract_recover_length = code_value() ;
  4045. }
  4046. if(code_seen('F'))
  4047. {
  4048. retract_recover_feedrate = code_value()/60 ;
  4049. }
  4050. }break;
  4051. 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.
  4052. {
  4053. if(code_seen('S'))
  4054. {
  4055. int t= code_value() ;
  4056. switch(t)
  4057. {
  4058. case 0:
  4059. {
  4060. autoretract_enabled=false;
  4061. retracted[0]=false;
  4062. #if EXTRUDERS > 1
  4063. retracted[1]=false;
  4064. #endif
  4065. #if EXTRUDERS > 2
  4066. retracted[2]=false;
  4067. #endif
  4068. }break;
  4069. case 1:
  4070. {
  4071. autoretract_enabled=true;
  4072. retracted[0]=false;
  4073. #if EXTRUDERS > 1
  4074. retracted[1]=false;
  4075. #endif
  4076. #if EXTRUDERS > 2
  4077. retracted[2]=false;
  4078. #endif
  4079. }break;
  4080. default:
  4081. SERIAL_ECHO_START;
  4082. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  4083. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  4084. SERIAL_ECHOLNPGM("\"");
  4085. }
  4086. }
  4087. }break;
  4088. #endif // FWRETRACT
  4089. #if EXTRUDERS > 1
  4090. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  4091. {
  4092. if(setTargetedHotend(218)){
  4093. break;
  4094. }
  4095. if(code_seen('X'))
  4096. {
  4097. extruder_offset[X_AXIS][tmp_extruder] = code_value();
  4098. }
  4099. if(code_seen('Y'))
  4100. {
  4101. extruder_offset[Y_AXIS][tmp_extruder] = code_value();
  4102. }
  4103. SERIAL_ECHO_START;
  4104. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  4105. for(tmp_extruder = 0; tmp_extruder < EXTRUDERS; tmp_extruder++)
  4106. {
  4107. SERIAL_ECHO(" ");
  4108. SERIAL_ECHO(extruder_offset[X_AXIS][tmp_extruder]);
  4109. SERIAL_ECHO(",");
  4110. SERIAL_ECHO(extruder_offset[Y_AXIS][tmp_extruder]);
  4111. }
  4112. SERIAL_ECHOLN("");
  4113. }break;
  4114. #endif
  4115. case 220: // M220 S<factor in percent>- set speed factor override percentage
  4116. {
  4117. if(code_seen('S'))
  4118. {
  4119. feedmultiply = code_value() ;
  4120. }
  4121. }
  4122. break;
  4123. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  4124. {
  4125. if(code_seen('S'))
  4126. {
  4127. int tmp_code = code_value();
  4128. if (code_seen('T'))
  4129. {
  4130. if(setTargetedHotend(221)){
  4131. break;
  4132. }
  4133. extruder_multiply[tmp_extruder] = tmp_code;
  4134. }
  4135. else
  4136. {
  4137. extrudemultiply = tmp_code ;
  4138. }
  4139. }
  4140. }
  4141. break;
  4142. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  4143. {
  4144. if(code_seen('P')){
  4145. int pin_number = code_value(); // pin number
  4146. int pin_state = -1; // required pin state - default is inverted
  4147. if(code_seen('S')) pin_state = code_value(); // required pin state
  4148. if(pin_state >= -1 && pin_state <= 1){
  4149. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  4150. {
  4151. if (sensitive_pins[i] == pin_number)
  4152. {
  4153. pin_number = -1;
  4154. break;
  4155. }
  4156. }
  4157. if (pin_number > -1)
  4158. {
  4159. int target = LOW;
  4160. st_synchronize();
  4161. pinMode(pin_number, INPUT);
  4162. switch(pin_state){
  4163. case 1:
  4164. target = HIGH;
  4165. break;
  4166. case 0:
  4167. target = LOW;
  4168. break;
  4169. case -1:
  4170. target = !digitalRead(pin_number);
  4171. break;
  4172. }
  4173. while(digitalRead(pin_number) != target){
  4174. manage_heater();
  4175. manage_inactivity();
  4176. lcd_update();
  4177. }
  4178. }
  4179. }
  4180. }
  4181. }
  4182. break;
  4183. #if NUM_SERVOS > 0
  4184. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  4185. {
  4186. int servo_index = -1;
  4187. int servo_position = 0;
  4188. if (code_seen('P'))
  4189. servo_index = code_value();
  4190. if (code_seen('S')) {
  4191. servo_position = code_value();
  4192. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  4193. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  4194. servos[servo_index].attach(0);
  4195. #endif
  4196. servos[servo_index].write(servo_position);
  4197. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  4198. delay(PROBE_SERVO_DEACTIVATION_DELAY);
  4199. servos[servo_index].detach();
  4200. #endif
  4201. }
  4202. else {
  4203. SERIAL_ECHO_START;
  4204. SERIAL_ECHO("Servo ");
  4205. SERIAL_ECHO(servo_index);
  4206. SERIAL_ECHOLN(" out of range");
  4207. }
  4208. }
  4209. else if (servo_index >= 0) {
  4210. SERIAL_PROTOCOL(MSG_OK);
  4211. SERIAL_PROTOCOL(" Servo ");
  4212. SERIAL_PROTOCOL(servo_index);
  4213. SERIAL_PROTOCOL(": ");
  4214. SERIAL_PROTOCOL(servos[servo_index].read());
  4215. SERIAL_PROTOCOLLN("");
  4216. }
  4217. }
  4218. break;
  4219. #endif // NUM_SERVOS > 0
  4220. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  4221. case 300: // M300
  4222. {
  4223. int beepS = code_seen('S') ? code_value() : 110;
  4224. int beepP = code_seen('P') ? code_value() : 1000;
  4225. if (beepS > 0)
  4226. {
  4227. #if BEEPER > 0
  4228. tone(BEEPER, beepS);
  4229. delay(beepP);
  4230. noTone(BEEPER);
  4231. #elif defined(ULTRALCD)
  4232. lcd_buzz(beepS, beepP);
  4233. #elif defined(LCD_USE_I2C_BUZZER)
  4234. lcd_buzz(beepP, beepS);
  4235. #endif
  4236. }
  4237. else
  4238. {
  4239. delay(beepP);
  4240. }
  4241. }
  4242. break;
  4243. #endif // M300
  4244. #ifdef PIDTEMP
  4245. case 301: // M301
  4246. {
  4247. if(code_seen('P')) Kp = code_value();
  4248. if(code_seen('I')) Ki = scalePID_i(code_value());
  4249. if(code_seen('D')) Kd = scalePID_d(code_value());
  4250. #ifdef PID_ADD_EXTRUSION_RATE
  4251. if(code_seen('C')) Kc = code_value();
  4252. #endif
  4253. updatePID();
  4254. SERIAL_PROTOCOLRPGM(MSG_OK);
  4255. SERIAL_PROTOCOL(" p:");
  4256. SERIAL_PROTOCOL(Kp);
  4257. SERIAL_PROTOCOL(" i:");
  4258. SERIAL_PROTOCOL(unscalePID_i(Ki));
  4259. SERIAL_PROTOCOL(" d:");
  4260. SERIAL_PROTOCOL(unscalePID_d(Kd));
  4261. #ifdef PID_ADD_EXTRUSION_RATE
  4262. SERIAL_PROTOCOL(" c:");
  4263. //Kc does not have scaling applied above, or in resetting defaults
  4264. SERIAL_PROTOCOL(Kc);
  4265. #endif
  4266. SERIAL_PROTOCOLLN("");
  4267. }
  4268. break;
  4269. #endif //PIDTEMP
  4270. #ifdef PIDTEMPBED
  4271. case 304: // M304
  4272. {
  4273. if(code_seen('P')) bedKp = code_value();
  4274. if(code_seen('I')) bedKi = scalePID_i(code_value());
  4275. if(code_seen('D')) bedKd = scalePID_d(code_value());
  4276. updatePID();
  4277. SERIAL_PROTOCOLRPGM(MSG_OK);
  4278. SERIAL_PROTOCOL(" p:");
  4279. SERIAL_PROTOCOL(bedKp);
  4280. SERIAL_PROTOCOL(" i:");
  4281. SERIAL_PROTOCOL(unscalePID_i(bedKi));
  4282. SERIAL_PROTOCOL(" d:");
  4283. SERIAL_PROTOCOL(unscalePID_d(bedKd));
  4284. SERIAL_PROTOCOLLN("");
  4285. }
  4286. break;
  4287. #endif //PIDTEMP
  4288. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  4289. {
  4290. #ifdef CHDK
  4291. SET_OUTPUT(CHDK);
  4292. WRITE(CHDK, HIGH);
  4293. chdkHigh = millis();
  4294. chdkActive = true;
  4295. #else
  4296. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  4297. const uint8_t NUM_PULSES=16;
  4298. const float PULSE_LENGTH=0.01524;
  4299. for(int i=0; i < NUM_PULSES; i++) {
  4300. WRITE(PHOTOGRAPH_PIN, HIGH);
  4301. _delay_ms(PULSE_LENGTH);
  4302. WRITE(PHOTOGRAPH_PIN, LOW);
  4303. _delay_ms(PULSE_LENGTH);
  4304. }
  4305. delay(7.33);
  4306. for(int i=0; i < NUM_PULSES; i++) {
  4307. WRITE(PHOTOGRAPH_PIN, HIGH);
  4308. _delay_ms(PULSE_LENGTH);
  4309. WRITE(PHOTOGRAPH_PIN, LOW);
  4310. _delay_ms(PULSE_LENGTH);
  4311. }
  4312. #endif
  4313. #endif //chdk end if
  4314. }
  4315. break;
  4316. #ifdef DOGLCD
  4317. case 250: // M250 Set LCD contrast value: C<value> (value 0..63)
  4318. {
  4319. if (code_seen('C')) {
  4320. lcd_setcontrast( ((int)code_value())&63 );
  4321. }
  4322. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  4323. SERIAL_PROTOCOL(lcd_contrast);
  4324. SERIAL_PROTOCOLLN("");
  4325. }
  4326. break;
  4327. #endif
  4328. #ifdef PREVENT_DANGEROUS_EXTRUDE
  4329. case 302: // allow cold extrudes, or set the minimum extrude temperature
  4330. {
  4331. float temp = .0;
  4332. if (code_seen('S')) temp=code_value();
  4333. set_extrude_min_temp(temp);
  4334. }
  4335. break;
  4336. #endif
  4337. case 303: // M303 PID autotune
  4338. {
  4339. float temp = 150.0;
  4340. int e=0;
  4341. int c=5;
  4342. if (code_seen('E')) e=code_value();
  4343. if (e<0)
  4344. temp=70;
  4345. if (code_seen('S')) temp=code_value();
  4346. if (code_seen('C')) c=code_value();
  4347. PID_autotune(temp, e, c);
  4348. }
  4349. break;
  4350. case 400: // M400 finish all moves
  4351. {
  4352. st_synchronize();
  4353. }
  4354. break;
  4355. #ifdef FILAMENT_SENSOR
  4356. case 404: //M404 Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  4357. {
  4358. #if (FILWIDTH_PIN > -1)
  4359. if(code_seen('N')) filament_width_nominal=code_value();
  4360. else{
  4361. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  4362. SERIAL_PROTOCOLLN(filament_width_nominal);
  4363. }
  4364. #endif
  4365. }
  4366. break;
  4367. case 405: //M405 Turn on filament sensor for control
  4368. {
  4369. if(code_seen('D')) meas_delay_cm=code_value();
  4370. if(meas_delay_cm> MAX_MEASUREMENT_DELAY)
  4371. meas_delay_cm = MAX_MEASUREMENT_DELAY;
  4372. if(delay_index2 == -1) //initialize the ring buffer if it has not been done since startup
  4373. {
  4374. int temp_ratio = widthFil_to_size_ratio();
  4375. for (delay_index1=0; delay_index1<(MAX_MEASUREMENT_DELAY+1); ++delay_index1 ){
  4376. measurement_delay[delay_index1]=temp_ratio-100; //subtract 100 to scale within a signed byte
  4377. }
  4378. delay_index1=0;
  4379. delay_index2=0;
  4380. }
  4381. filament_sensor = true ;
  4382. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  4383. //SERIAL_PROTOCOL(filament_width_meas);
  4384. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  4385. //SERIAL_PROTOCOL(extrudemultiply);
  4386. }
  4387. break;
  4388. case 406: //M406 Turn off filament sensor for control
  4389. {
  4390. filament_sensor = false ;
  4391. }
  4392. break;
  4393. case 407: //M407 Display measured filament diameter
  4394. {
  4395. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  4396. SERIAL_PROTOCOLLN(filament_width_meas);
  4397. }
  4398. break;
  4399. #endif
  4400. case 500: // M500 Store settings in EEPROM
  4401. {
  4402. Config_StoreSettings();
  4403. }
  4404. break;
  4405. case 501: // M501 Read settings from EEPROM
  4406. {
  4407. Config_RetrieveSettings();
  4408. }
  4409. break;
  4410. case 502: // M502 Revert to default settings
  4411. {
  4412. Config_ResetDefault();
  4413. }
  4414. break;
  4415. case 503: // M503 print settings currently in memory
  4416. {
  4417. Config_PrintSettings();
  4418. }
  4419. break;
  4420. case 509: //M509 Force language selection
  4421. {
  4422. lcd_force_language_selection();
  4423. SERIAL_ECHO_START;
  4424. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  4425. }
  4426. break;
  4427. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  4428. case 540:
  4429. {
  4430. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  4431. }
  4432. break;
  4433. #endif
  4434. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  4435. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  4436. {
  4437. float value;
  4438. if (code_seen('Z'))
  4439. {
  4440. value = code_value();
  4441. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  4442. {
  4443. zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  4444. SERIAL_ECHO_START;
  4445. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  4446. SERIAL_PROTOCOLLN("");
  4447. }
  4448. else
  4449. {
  4450. SERIAL_ECHO_START;
  4451. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  4452. SERIAL_ECHORPGM(MSG_Z_MIN);
  4453. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  4454. SERIAL_ECHORPGM(MSG_Z_MAX);
  4455. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  4456. SERIAL_PROTOCOLLN("");
  4457. }
  4458. }
  4459. else
  4460. {
  4461. SERIAL_ECHO_START;
  4462. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  4463. SERIAL_ECHO(-zprobe_zoffset);
  4464. SERIAL_PROTOCOLLN("");
  4465. }
  4466. break;
  4467. }
  4468. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  4469. #ifdef FILAMENTCHANGEENABLE
  4470. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  4471. {
  4472. st_synchronize();
  4473. float target[4];
  4474. float lastpos[4];
  4475. if (farm_mode)
  4476. {
  4477. prusa_statistics(22);
  4478. }
  4479. feedmultiplyBckp=feedmultiply;
  4480. int8_t TooLowZ = 0;
  4481. target[X_AXIS]=current_position[X_AXIS];
  4482. target[Y_AXIS]=current_position[Y_AXIS];
  4483. target[Z_AXIS]=current_position[Z_AXIS];
  4484. target[E_AXIS]=current_position[E_AXIS];
  4485. lastpos[X_AXIS]=current_position[X_AXIS];
  4486. lastpos[Y_AXIS]=current_position[Y_AXIS];
  4487. lastpos[Z_AXIS]=current_position[Z_AXIS];
  4488. lastpos[E_AXIS]=current_position[E_AXIS];
  4489. //Restract extruder
  4490. if(code_seen('E'))
  4491. {
  4492. target[E_AXIS]+= code_value();
  4493. }
  4494. else
  4495. {
  4496. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  4497. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT ;
  4498. #endif
  4499. }
  4500. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  4501. //Lift Z
  4502. if(code_seen('Z'))
  4503. {
  4504. target[Z_AXIS]+= code_value();
  4505. }
  4506. else
  4507. {
  4508. #ifdef FILAMENTCHANGE_ZADD
  4509. target[Z_AXIS]+= FILAMENTCHANGE_ZADD ;
  4510. if(target[Z_AXIS] < 10){
  4511. target[Z_AXIS]+= 10 ;
  4512. TooLowZ = 1;
  4513. }else{
  4514. TooLowZ = 0;
  4515. }
  4516. #endif
  4517. }
  4518. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  4519. //Move XY to side
  4520. if(code_seen('X'))
  4521. {
  4522. target[X_AXIS]+= code_value();
  4523. }
  4524. else
  4525. {
  4526. #ifdef FILAMENTCHANGE_XPOS
  4527. target[X_AXIS]= FILAMENTCHANGE_XPOS ;
  4528. #endif
  4529. }
  4530. if(code_seen('Y'))
  4531. {
  4532. target[Y_AXIS]= code_value();
  4533. }
  4534. else
  4535. {
  4536. #ifdef FILAMENTCHANGE_YPOS
  4537. target[Y_AXIS]= FILAMENTCHANGE_YPOS ;
  4538. #endif
  4539. }
  4540. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  4541. st_synchronize();
  4542. custom_message = true;
  4543. lcd_setstatuspgm(MSG_UNLOADING_FILAMENT);
  4544. // Unload filament
  4545. if(code_seen('L'))
  4546. {
  4547. target[E_AXIS]+= code_value();
  4548. }
  4549. else
  4550. {
  4551. #ifdef SNMM
  4552. #else
  4553. #ifdef FILAMENTCHANGE_FINALRETRACT
  4554. target[E_AXIS] += FILAMENTCHANGE_FINALRETRACT;
  4555. #endif
  4556. #endif // SNMM
  4557. }
  4558. #ifdef SNMM
  4559. target[E_AXIS] += 12;
  4560. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 3500, active_extruder);
  4561. target[E_AXIS] += 6;
  4562. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 5000, active_extruder);
  4563. target[E_AXIS] += (FIL_LOAD_LENGTH * -1);
  4564. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 5000, active_extruder);
  4565. st_synchronize();
  4566. target[E_AXIS] += (FIL_COOLING);
  4567. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 50, active_extruder);
  4568. target[E_AXIS] += (FIL_COOLING*-1);
  4569. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 50, active_extruder);
  4570. target[E_AXIS] += (bowden_length[snmm_extruder] *-1);
  4571. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 3000, active_extruder);
  4572. st_synchronize();
  4573. #else
  4574. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  4575. #endif // SNMM
  4576. //finish moves
  4577. st_synchronize();
  4578. //disable extruder steppers so filament can be removed
  4579. disable_e0();
  4580. disable_e1();
  4581. disable_e2();
  4582. delay(100);
  4583. //Wait for user to insert filament
  4584. uint8_t cnt=0;
  4585. int counterBeep = 0;
  4586. lcd_wait_interact();
  4587. load_filament_time = millis();
  4588. while(!lcd_clicked()){
  4589. cnt++;
  4590. manage_heater();
  4591. manage_inactivity(true);
  4592. /*#ifdef SNMM
  4593. target[E_AXIS] += 0.002;
  4594. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 500, active_extruder);
  4595. #endif // SNMM*/
  4596. if(cnt==0)
  4597. {
  4598. #if BEEPER > 0
  4599. if (counterBeep== 500){
  4600. counterBeep = 0;
  4601. }
  4602. SET_OUTPUT(BEEPER);
  4603. if (counterBeep== 0){
  4604. WRITE(BEEPER,HIGH);
  4605. }
  4606. if (counterBeep== 20){
  4607. WRITE(BEEPER,LOW);
  4608. }
  4609. counterBeep++;
  4610. #else
  4611. #if !defined(LCD_FEEDBACK_FREQUENCY_HZ) || !defined(LCD_FEEDBACK_FREQUENCY_DURATION_MS)
  4612. lcd_buzz(1000/6,100);
  4613. #else
  4614. lcd_buzz(LCD_FEEDBACK_FREQUENCY_DURATION_MS,LCD_FEEDBACK_FREQUENCY_HZ);
  4615. #endif
  4616. #endif
  4617. }
  4618. }
  4619. #ifdef SNMM
  4620. display_loading();
  4621. do {
  4622. target[E_AXIS] += 0.002;
  4623. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 500, active_extruder);
  4624. delay_keep_alive(2);
  4625. } while (!lcd_clicked());
  4626. /*if (millis() - load_filament_time > 2) {
  4627. load_filament_time = millis();
  4628. target[E_AXIS] += 0.001;
  4629. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 1000, active_extruder);
  4630. }*/
  4631. #endif
  4632. //Filament inserted
  4633. WRITE(BEEPER,LOW);
  4634. //Feed the filament to the end of nozzle quickly
  4635. #ifdef SNMM
  4636. st_synchronize();
  4637. target[E_AXIS] += bowden_length[snmm_extruder];
  4638. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 3000, active_extruder);
  4639. target[E_AXIS] += FIL_LOAD_LENGTH - 60;
  4640. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 1400, active_extruder);
  4641. target[E_AXIS] += 40;
  4642. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  4643. target[E_AXIS] += 10;
  4644. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 50, active_extruder);
  4645. #else
  4646. target[E_AXIS] += FILAMENTCHANGE_FIRSTFEED;
  4647. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EFEED, active_extruder);
  4648. #endif // SNMM
  4649. //Extrude some filament
  4650. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  4651. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EXFEED, active_extruder);
  4652. //Wait for user to check the state
  4653. lcd_change_fil_state = 0;
  4654. lcd_loading_filament();
  4655. while ((lcd_change_fil_state == 0)||(lcd_change_fil_state != 1)){
  4656. lcd_change_fil_state = 0;
  4657. lcd_alright();
  4658. switch(lcd_change_fil_state){
  4659. // Filament failed to load so load it again
  4660. case 2:
  4661. #ifdef SNMM
  4662. display_loading();
  4663. do {
  4664. target[E_AXIS] += 0.002;
  4665. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 500, active_extruder);
  4666. delay_keep_alive(2);
  4667. } while (!lcd_clicked());
  4668. st_synchronize();
  4669. target[E_AXIS] += bowden_length[snmm_extruder];
  4670. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 3000, active_extruder);
  4671. target[E_AXIS] += FIL_LOAD_LENGTH - 60;
  4672. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 1400, active_extruder);
  4673. target[E_AXIS] += 40;
  4674. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  4675. target[E_AXIS] += 10;
  4676. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 50, active_extruder);
  4677. #else
  4678. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  4679. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EFEED, active_extruder);
  4680. #endif
  4681. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  4682. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EXFEED, active_extruder);
  4683. lcd_loading_filament();
  4684. break;
  4685. // Filament loaded properly but color is not clear
  4686. case 3:
  4687. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  4688. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  4689. lcd_loading_color();
  4690. break;
  4691. // Everything good
  4692. default:
  4693. lcd_change_success();
  4694. lcd_update_enable(true);
  4695. break;
  4696. }
  4697. }
  4698. //Not let's go back to print
  4699. //Feed a little of filament to stabilize pressure
  4700. target[E_AXIS]+= FILAMENTCHANGE_RECFEED;
  4701. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EXFEED, active_extruder);
  4702. //Retract
  4703. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT;
  4704. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  4705. //plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //should do nothing
  4706. //Move XY back
  4707. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  4708. //Move Z back
  4709. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  4710. target[E_AXIS]= target[E_AXIS] - FILAMENTCHANGE_FIRSTRETRACT;
  4711. //Unretract
  4712. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  4713. //Set E position to original
  4714. plan_set_e_position(lastpos[E_AXIS]);
  4715. //Recover feed rate
  4716. feedmultiply=feedmultiplyBckp;
  4717. char cmd[9];
  4718. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  4719. enquecommand(cmd);
  4720. lcd_setstatuspgm(WELCOME_MSG);
  4721. custom_message = false;
  4722. custom_message_type = 0;
  4723. }
  4724. break;
  4725. #endif //FILAMENTCHANGEENABLE
  4726. case 601: {
  4727. if(lcd_commands_type == 0) lcd_commands_type = LCD_COMMAND_LONG_PAUSE;
  4728. }
  4729. break;
  4730. case 602: {
  4731. if(lcd_commands_type == 0) lcd_commands_type = LCD_COMMAND_LONG_PAUSE_RESUME;
  4732. }
  4733. break;
  4734. case 907: // M907 Set digital trimpot motor current using axis codes.
  4735. {
  4736. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  4737. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) digipot_current(i,code_value());
  4738. if(code_seen('B')) digipot_current(4,code_value());
  4739. if(code_seen('S')) for(int i=0;i<=4;i++) digipot_current(i,code_value());
  4740. #endif
  4741. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  4742. if(code_seen('X')) digipot_current(0, code_value());
  4743. #endif
  4744. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  4745. if(code_seen('Z')) digipot_current(1, code_value());
  4746. #endif
  4747. #ifdef MOTOR_CURRENT_PWM_E_PIN
  4748. if(code_seen('E')) digipot_current(2, code_value());
  4749. #endif
  4750. #ifdef DIGIPOT_I2C
  4751. // this one uses actual amps in floating point
  4752. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) digipot_i2c_set_current(i, code_value());
  4753. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  4754. for(int i=NUM_AXIS;i<DIGIPOT_I2C_NUM_CHANNELS;i++) if(code_seen('B'+i-NUM_AXIS)) digipot_i2c_set_current(i, code_value());
  4755. #endif
  4756. }
  4757. break;
  4758. case 908: // M908 Control digital trimpot directly.
  4759. {
  4760. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  4761. uint8_t channel,current;
  4762. if(code_seen('P')) channel=code_value();
  4763. if(code_seen('S')) current=code_value();
  4764. digitalPotWrite(channel, current);
  4765. #endif
  4766. }
  4767. break;
  4768. case 910: // M910 TMC2130 init
  4769. {
  4770. tmc2130_init();
  4771. }
  4772. break;
  4773. case 911: // M911 Set TMC2130 holding currents
  4774. {
  4775. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  4776. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  4777. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  4778. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  4779. }
  4780. break;
  4781. case 912: // M912 Set TMC2130 running currents
  4782. {
  4783. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  4784. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  4785. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  4786. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  4787. }
  4788. break;
  4789. case 913: // M913 Print TMC2130 currents
  4790. {
  4791. tmc2130_print_currents();
  4792. }
  4793. break;
  4794. case 914: // M914 Set normal mode
  4795. {
  4796. tmc2130_mode = TMC2130_MODE_NORMAL;
  4797. tmc2130_init();
  4798. }
  4799. break;
  4800. case 915: // M915 Set silent mode
  4801. {
  4802. tmc2130_mode = TMC2130_MODE_SILENT;
  4803. tmc2130_init();
  4804. }
  4805. break;
  4806. case 916: // M916 Set sg_thrs
  4807. {
  4808. if (code_seen('X')) sg_thrs_x = code_value();
  4809. if (code_seen('Y')) sg_thrs_y = code_value();
  4810. MYSERIAL.print("sg_thrs_x=");
  4811. MYSERIAL.print(sg_thrs_x, DEC);
  4812. MYSERIAL.print(" sg_thrs_y=");
  4813. MYSERIAL.println(sg_thrs_y, DEC);
  4814. }
  4815. break;
  4816. case 350: // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  4817. {
  4818. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  4819. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  4820. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  4821. if(code_seen('B')) microstep_mode(4,code_value());
  4822. microstep_readings();
  4823. #endif
  4824. }
  4825. break;
  4826. case 351: // M351 Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  4827. {
  4828. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  4829. if(code_seen('S')) switch((int)code_value())
  4830. {
  4831. case 1:
  4832. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  4833. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  4834. break;
  4835. case 2:
  4836. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  4837. if(code_seen('B')) microstep_ms(4,-1,code_value());
  4838. break;
  4839. }
  4840. microstep_readings();
  4841. #endif
  4842. }
  4843. break;
  4844. case 701: //M701: load filament
  4845. {
  4846. enable_z();
  4847. custom_message = true;
  4848. custom_message_type = 2;
  4849. lcd_setstatuspgm(MSG_LOADING_FILAMENT);
  4850. current_position[E_AXIS] += 70;
  4851. 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
  4852. current_position[E_AXIS] += 25;
  4853. 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
  4854. st_synchronize();
  4855. if (!farm_mode && loading_flag) {
  4856. bool clean = lcd_show_fullscreen_message_yes_no_and_wait_P(MSG_FILAMENT_CLEAN, false, true);
  4857. while (!clean) {
  4858. lcd_update_enable(true);
  4859. lcd_update(2);
  4860. current_position[E_AXIS] += 25;
  4861. 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
  4862. st_synchronize();
  4863. clean = lcd_show_fullscreen_message_yes_no_and_wait_P(MSG_FILAMENT_CLEAN, false, true);
  4864. }
  4865. }
  4866. lcd_update_enable(true);
  4867. lcd_update(2);
  4868. lcd_setstatuspgm(WELCOME_MSG);
  4869. disable_z();
  4870. loading_flag = false;
  4871. custom_message = false;
  4872. custom_message_type = 0;
  4873. }
  4874. break;
  4875. case 702:
  4876. {
  4877. #ifdef SNMM
  4878. if (code_seen('U')) {
  4879. extr_unload_used(); //unload all filaments which were used in current print
  4880. }
  4881. else if (code_seen('C')) {
  4882. extr_unload(); //unload just current filament
  4883. }
  4884. else {
  4885. extr_unload_all(); //unload all filaments
  4886. }
  4887. #else
  4888. custom_message = true;
  4889. custom_message_type = 2;
  4890. lcd_setstatuspgm(MSG_UNLOADING_FILAMENT);
  4891. current_position[E_AXIS] -= 80;
  4892. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 7000 / 60, active_extruder);
  4893. st_synchronize();
  4894. lcd_setstatuspgm(WELCOME_MSG);
  4895. custom_message = false;
  4896. custom_message_type = 0;
  4897. #endif
  4898. }
  4899. break;
  4900. case 999: // M999: Restart after being stopped
  4901. Stopped = false;
  4902. lcd_reset_alert_level();
  4903. gcode_LastN = Stopped_gcode_LastN;
  4904. FlushSerialRequestResend();
  4905. break;
  4906. default: SERIAL_ECHOLNPGM("Invalid M code.");
  4907. }
  4908. } // end if(code_seen('M')) (end of M codes)
  4909. else if(code_seen('T'))
  4910. {
  4911. int index;
  4912. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4913. if ((*(strchr_pointer + index) < '0' || *(strchr_pointer + index) > '9') && *(strchr_pointer + index) != '?') {
  4914. SERIAL_ECHOLNPGM("Invalid T code.");
  4915. }
  4916. else {
  4917. if (*(strchr_pointer + index) == '?') {
  4918. tmp_extruder = choose_extruder_menu();
  4919. }
  4920. else {
  4921. tmp_extruder = code_value();
  4922. }
  4923. snmm_filaments_used |= (1 << tmp_extruder); //for stop print
  4924. #ifdef SNMM
  4925. snmm_extruder = tmp_extruder;
  4926. st_synchronize();
  4927. delay(100);
  4928. disable_e0();
  4929. disable_e1();
  4930. disable_e2();
  4931. pinMode(E_MUX0_PIN, OUTPUT);
  4932. pinMode(E_MUX1_PIN, OUTPUT);
  4933. pinMode(E_MUX2_PIN, OUTPUT);
  4934. delay(100);
  4935. SERIAL_ECHO_START;
  4936. SERIAL_ECHO("T:");
  4937. SERIAL_ECHOLN((int)tmp_extruder);
  4938. switch (tmp_extruder) {
  4939. case 1:
  4940. WRITE(E_MUX0_PIN, HIGH);
  4941. WRITE(E_MUX1_PIN, LOW);
  4942. WRITE(E_MUX2_PIN, LOW);
  4943. break;
  4944. case 2:
  4945. WRITE(E_MUX0_PIN, LOW);
  4946. WRITE(E_MUX1_PIN, HIGH);
  4947. WRITE(E_MUX2_PIN, LOW);
  4948. break;
  4949. case 3:
  4950. WRITE(E_MUX0_PIN, HIGH);
  4951. WRITE(E_MUX1_PIN, HIGH);
  4952. WRITE(E_MUX2_PIN, LOW);
  4953. break;
  4954. default:
  4955. WRITE(E_MUX0_PIN, LOW);
  4956. WRITE(E_MUX1_PIN, LOW);
  4957. WRITE(E_MUX2_PIN, LOW);
  4958. break;
  4959. }
  4960. delay(100);
  4961. #else
  4962. if (tmp_extruder >= EXTRUDERS) {
  4963. SERIAL_ECHO_START;
  4964. SERIAL_ECHOPGM("T");
  4965. SERIAL_PROTOCOLLN((int)tmp_extruder);
  4966. SERIAL_ECHOLNRPGM(MSG_INVALID_EXTRUDER);
  4967. }
  4968. else {
  4969. boolean make_move = false;
  4970. if (code_seen('F')) {
  4971. make_move = true;
  4972. next_feedrate = code_value();
  4973. if (next_feedrate > 0.0) {
  4974. feedrate = next_feedrate;
  4975. }
  4976. }
  4977. #if EXTRUDERS > 1
  4978. if (tmp_extruder != active_extruder) {
  4979. // Save current position to return to after applying extruder offset
  4980. memcpy(destination, current_position, sizeof(destination));
  4981. // Offset extruder (only by XY)
  4982. int i;
  4983. for (i = 0; i < 2; i++) {
  4984. current_position[i] = current_position[i] -
  4985. extruder_offset[i][active_extruder] +
  4986. extruder_offset[i][tmp_extruder];
  4987. }
  4988. // Set the new active extruder and position
  4989. active_extruder = tmp_extruder;
  4990. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  4991. // Move to the old position if 'F' was in the parameters
  4992. if (make_move && Stopped == false) {
  4993. prepare_move();
  4994. }
  4995. }
  4996. #endif
  4997. SERIAL_ECHO_START;
  4998. SERIAL_ECHORPGM(MSG_ACTIVE_EXTRUDER);
  4999. SERIAL_PROTOCOLLN((int)active_extruder);
  5000. }
  5001. #endif
  5002. }
  5003. } // end if(code_seen('T')) (end of T codes)
  5004. else
  5005. {
  5006. SERIAL_ECHO_START;
  5007. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  5008. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  5009. SERIAL_ECHOLNPGM("\"");
  5010. }
  5011. ClearToSend();
  5012. }
  5013. void FlushSerialRequestResend()
  5014. {
  5015. //char cmdbuffer[bufindr][100]="Resend:";
  5016. MYSERIAL.flush();
  5017. SERIAL_PROTOCOLRPGM(MSG_RESEND);
  5018. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  5019. ClearToSend();
  5020. }
  5021. // Confirm the execution of a command, if sent from a serial line.
  5022. // Execution of a command from a SD card will not be confirmed.
  5023. void ClearToSend()
  5024. {
  5025. previous_millis_cmd = millis();
  5026. if (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB)
  5027. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  5028. }
  5029. void get_coordinates()
  5030. {
  5031. bool seen[4]={false,false,false,false};
  5032. for(int8_t i=0; i < NUM_AXIS; i++) {
  5033. if(code_seen(axis_codes[i]))
  5034. {
  5035. destination[i] = (float)code_value() + (axis_relative_modes[i] || relative_mode)*current_position[i];
  5036. seen[i]=true;
  5037. }
  5038. else destination[i] = current_position[i]; //Are these else lines really needed?
  5039. }
  5040. if(code_seen('F')) {
  5041. next_feedrate = code_value();
  5042. #ifdef MAX_SILENT_FEEDRATE
  5043. if (tmc2130_mode == TMC2130_MODE_SILENT)
  5044. if (next_feedrate > MAX_SILENT_FEEDRATE) next_feedrate = MAX_SILENT_FEEDRATE;
  5045. #endif //MAX_SILENT_FEEDRATE
  5046. if(next_feedrate > 0.0) feedrate = next_feedrate;
  5047. }
  5048. }
  5049. void get_arc_coordinates()
  5050. {
  5051. #ifdef SF_ARC_FIX
  5052. bool relative_mode_backup = relative_mode;
  5053. relative_mode = true;
  5054. #endif
  5055. get_coordinates();
  5056. #ifdef SF_ARC_FIX
  5057. relative_mode=relative_mode_backup;
  5058. #endif
  5059. if(code_seen('I')) {
  5060. offset[0] = code_value();
  5061. }
  5062. else {
  5063. offset[0] = 0.0;
  5064. }
  5065. if(code_seen('J')) {
  5066. offset[1] = code_value();
  5067. }
  5068. else {
  5069. offset[1] = 0.0;
  5070. }
  5071. }
  5072. void clamp_to_software_endstops(float target[3])
  5073. {
  5074. world2machine_clamp(target[0], target[1]);
  5075. // Clamp the Z coordinate.
  5076. if (min_software_endstops) {
  5077. float negative_z_offset = 0;
  5078. #ifdef ENABLE_AUTO_BED_LEVELING
  5079. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  5080. if (add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + add_homing[Z_AXIS];
  5081. #endif
  5082. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  5083. }
  5084. if (max_software_endstops) {
  5085. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  5086. }
  5087. }
  5088. #ifdef MESH_BED_LEVELING
  5089. 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) {
  5090. float dx = x - current_position[X_AXIS];
  5091. float dy = y - current_position[Y_AXIS];
  5092. float dz = z - current_position[Z_AXIS];
  5093. int n_segments = 0;
  5094. if (mbl.active) {
  5095. float len = abs(dx) + abs(dy);
  5096. if (len > 0)
  5097. // Split to 3cm segments or shorter.
  5098. n_segments = int(ceil(len / 30.f));
  5099. }
  5100. if (n_segments > 1) {
  5101. float de = e - current_position[E_AXIS];
  5102. for (int i = 1; i < n_segments; ++ i) {
  5103. float t = float(i) / float(n_segments);
  5104. plan_buffer_line(
  5105. current_position[X_AXIS] + t * dx,
  5106. current_position[Y_AXIS] + t * dy,
  5107. current_position[Z_AXIS] + t * dz,
  5108. current_position[E_AXIS] + t * de,
  5109. feed_rate, extruder);
  5110. }
  5111. }
  5112. // The rest of the path.
  5113. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  5114. current_position[X_AXIS] = x;
  5115. current_position[Y_AXIS] = y;
  5116. current_position[Z_AXIS] = z;
  5117. current_position[E_AXIS] = e;
  5118. }
  5119. #endif // MESH_BED_LEVELING
  5120. void prepare_move()
  5121. {
  5122. clamp_to_software_endstops(destination);
  5123. previous_millis_cmd = millis();
  5124. // Do not use feedmultiply for E or Z only moves
  5125. if( (current_position[X_AXIS] == destination [X_AXIS]) && (current_position[Y_AXIS] == destination [Y_AXIS])) {
  5126. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  5127. }
  5128. else {
  5129. #ifdef MESH_BED_LEVELING
  5130. 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);
  5131. #else
  5132. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate*feedmultiply*(1./(60.f*100.f)), active_extruder);
  5133. #endif
  5134. }
  5135. for(int8_t i=0; i < NUM_AXIS; i++) {
  5136. current_position[i] = destination[i];
  5137. }
  5138. }
  5139. void prepare_arc_move(char isclockwise) {
  5140. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  5141. // Trace the arc
  5142. mc_arc(current_position, destination, offset, X_AXIS, Y_AXIS, Z_AXIS, feedrate*feedmultiply/60/100.0, r, isclockwise, active_extruder);
  5143. // As far as the parser is concerned, the position is now == target. In reality the
  5144. // motion control system might still be processing the action and the real tool position
  5145. // in any intermediate location.
  5146. for(int8_t i=0; i < NUM_AXIS; i++) {
  5147. current_position[i] = destination[i];
  5148. }
  5149. previous_millis_cmd = millis();
  5150. }
  5151. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  5152. #if defined(FAN_PIN)
  5153. #if CONTROLLERFAN_PIN == FAN_PIN
  5154. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  5155. #endif
  5156. #endif
  5157. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  5158. unsigned long lastMotorCheck = 0;
  5159. void controllerFan()
  5160. {
  5161. if ((millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  5162. {
  5163. lastMotorCheck = millis();
  5164. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  5165. #if EXTRUDERS > 2
  5166. || !READ(E2_ENABLE_PIN)
  5167. #endif
  5168. #if EXTRUDER > 1
  5169. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  5170. || !READ(X2_ENABLE_PIN)
  5171. #endif
  5172. || !READ(E1_ENABLE_PIN)
  5173. #endif
  5174. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  5175. {
  5176. lastMotor = millis(); //... set time to NOW so the fan will turn on
  5177. }
  5178. if ((millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  5179. {
  5180. digitalWrite(CONTROLLERFAN_PIN, 0);
  5181. analogWrite(CONTROLLERFAN_PIN, 0);
  5182. }
  5183. else
  5184. {
  5185. // allows digital or PWM fan output to be used (see M42 handling)
  5186. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  5187. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  5188. }
  5189. }
  5190. }
  5191. #endif
  5192. #ifdef TEMP_STAT_LEDS
  5193. static bool blue_led = false;
  5194. static bool red_led = false;
  5195. static uint32_t stat_update = 0;
  5196. void handle_status_leds(void) {
  5197. float max_temp = 0.0;
  5198. if(millis() > stat_update) {
  5199. stat_update += 500; // Update every 0.5s
  5200. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  5201. max_temp = max(max_temp, degHotend(cur_extruder));
  5202. max_temp = max(max_temp, degTargetHotend(cur_extruder));
  5203. }
  5204. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5205. max_temp = max(max_temp, degTargetBed());
  5206. max_temp = max(max_temp, degBed());
  5207. #endif
  5208. if((max_temp > 55.0) && (red_led == false)) {
  5209. digitalWrite(STAT_LED_RED, 1);
  5210. digitalWrite(STAT_LED_BLUE, 0);
  5211. red_led = true;
  5212. blue_led = false;
  5213. }
  5214. if((max_temp < 54.0) && (blue_led == false)) {
  5215. digitalWrite(STAT_LED_RED, 0);
  5216. digitalWrite(STAT_LED_BLUE, 1);
  5217. red_led = false;
  5218. blue_led = true;
  5219. }
  5220. }
  5221. }
  5222. #endif
  5223. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  5224. {
  5225. #if defined(KILL_PIN) && KILL_PIN > -1
  5226. static int killCount = 0; // make the inactivity button a bit less responsive
  5227. const int KILL_DELAY = 10000;
  5228. #endif
  5229. if(buflen < (BUFSIZE-1)){
  5230. get_command();
  5231. }
  5232. if( (millis() - previous_millis_cmd) > max_inactive_time )
  5233. if(max_inactive_time)
  5234. kill();
  5235. if(stepper_inactive_time) {
  5236. if( (millis() - previous_millis_cmd) > stepper_inactive_time )
  5237. {
  5238. if(blocks_queued() == false && ignore_stepper_queue == false) {
  5239. disable_x();
  5240. // SERIAL_ECHOLNPGM("manage_inactivity - disable Y");
  5241. disable_y();
  5242. disable_z();
  5243. disable_e0();
  5244. disable_e1();
  5245. disable_e2();
  5246. }
  5247. }
  5248. }
  5249. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  5250. if (chdkActive && (millis() - chdkHigh > CHDK_DELAY))
  5251. {
  5252. chdkActive = false;
  5253. WRITE(CHDK, LOW);
  5254. }
  5255. #endif
  5256. #if defined(KILL_PIN) && KILL_PIN > -1
  5257. // Check if the kill button was pressed and wait just in case it was an accidental
  5258. // key kill key press
  5259. // -------------------------------------------------------------------------------
  5260. if( 0 == READ(KILL_PIN) )
  5261. {
  5262. killCount++;
  5263. }
  5264. else if (killCount > 0)
  5265. {
  5266. killCount--;
  5267. }
  5268. // Exceeded threshold and we can confirm that it was not accidental
  5269. // KILL the machine
  5270. // ----------------------------------------------------------------
  5271. if ( killCount >= KILL_DELAY)
  5272. {
  5273. kill();
  5274. }
  5275. #endif
  5276. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  5277. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  5278. #endif
  5279. #ifdef EXTRUDER_RUNOUT_PREVENT
  5280. if( (millis() - previous_millis_cmd) > EXTRUDER_RUNOUT_SECONDS*1000 )
  5281. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  5282. {
  5283. bool oldstatus=READ(E0_ENABLE_PIN);
  5284. enable_e0();
  5285. float oldepos=current_position[E_AXIS];
  5286. float oldedes=destination[E_AXIS];
  5287. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  5288. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/axis_steps_per_unit[E_AXIS],
  5289. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/axis_steps_per_unit[E_AXIS], active_extruder);
  5290. current_position[E_AXIS]=oldepos;
  5291. destination[E_AXIS]=oldedes;
  5292. plan_set_e_position(oldepos);
  5293. previous_millis_cmd=millis();
  5294. st_synchronize();
  5295. WRITE(E0_ENABLE_PIN,oldstatus);
  5296. }
  5297. #endif
  5298. #ifdef TEMP_STAT_LEDS
  5299. handle_status_leds();
  5300. #endif
  5301. check_axes_activity();
  5302. }
  5303. void kill(const char *full_screen_message)
  5304. {
  5305. cli(); // Stop interrupts
  5306. disable_heater();
  5307. disable_x();
  5308. // SERIAL_ECHOLNPGM("kill - disable Y");
  5309. disable_y();
  5310. disable_z();
  5311. disable_e0();
  5312. disable_e1();
  5313. disable_e2();
  5314. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5315. pinMode(PS_ON_PIN,INPUT);
  5316. #endif
  5317. SERIAL_ERROR_START;
  5318. SERIAL_ERRORLNRPGM(MSG_ERR_KILLED);
  5319. if (full_screen_message != NULL) {
  5320. SERIAL_ERRORLNRPGM(full_screen_message);
  5321. lcd_display_message_fullscreen_P(full_screen_message);
  5322. } else {
  5323. LCD_ALERTMESSAGERPGM(MSG_KILLED);
  5324. }
  5325. // FMC small patch to update the LCD before ending
  5326. sei(); // enable interrupts
  5327. for ( int i=5; i--; lcd_update())
  5328. {
  5329. delay(200);
  5330. }
  5331. cli(); // disable interrupts
  5332. suicide();
  5333. while(1) { /* Intentionally left empty */ } // Wait for reset
  5334. }
  5335. void Stop()
  5336. {
  5337. disable_heater();
  5338. if(Stopped == false) {
  5339. Stopped = true;
  5340. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  5341. SERIAL_ERROR_START;
  5342. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  5343. LCD_MESSAGERPGM(MSG_STOPPED);
  5344. }
  5345. }
  5346. bool IsStopped() { return Stopped; };
  5347. #ifdef FAST_PWM_FAN
  5348. void setPwmFrequency(uint8_t pin, int val)
  5349. {
  5350. val &= 0x07;
  5351. switch(digitalPinToTimer(pin))
  5352. {
  5353. #if defined(TCCR0A)
  5354. case TIMER0A:
  5355. case TIMER0B:
  5356. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  5357. // TCCR0B |= val;
  5358. break;
  5359. #endif
  5360. #if defined(TCCR1A)
  5361. case TIMER1A:
  5362. case TIMER1B:
  5363. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  5364. // TCCR1B |= val;
  5365. break;
  5366. #endif
  5367. #if defined(TCCR2)
  5368. case TIMER2:
  5369. case TIMER2:
  5370. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  5371. TCCR2 |= val;
  5372. break;
  5373. #endif
  5374. #if defined(TCCR2A)
  5375. case TIMER2A:
  5376. case TIMER2B:
  5377. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  5378. TCCR2B |= val;
  5379. break;
  5380. #endif
  5381. #if defined(TCCR3A)
  5382. case TIMER3A:
  5383. case TIMER3B:
  5384. case TIMER3C:
  5385. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  5386. TCCR3B |= val;
  5387. break;
  5388. #endif
  5389. #if defined(TCCR4A)
  5390. case TIMER4A:
  5391. case TIMER4B:
  5392. case TIMER4C:
  5393. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  5394. TCCR4B |= val;
  5395. break;
  5396. #endif
  5397. #if defined(TCCR5A)
  5398. case TIMER5A:
  5399. case TIMER5B:
  5400. case TIMER5C:
  5401. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  5402. TCCR5B |= val;
  5403. break;
  5404. #endif
  5405. }
  5406. }
  5407. #endif //FAST_PWM_FAN
  5408. bool setTargetedHotend(int code){
  5409. tmp_extruder = active_extruder;
  5410. if(code_seen('T')) {
  5411. tmp_extruder = code_value();
  5412. if(tmp_extruder >= EXTRUDERS) {
  5413. SERIAL_ECHO_START;
  5414. switch(code){
  5415. case 104:
  5416. SERIAL_ECHORPGM(MSG_M104_INVALID_EXTRUDER);
  5417. break;
  5418. case 105:
  5419. SERIAL_ECHO(MSG_M105_INVALID_EXTRUDER);
  5420. break;
  5421. case 109:
  5422. SERIAL_ECHO(MSG_M109_INVALID_EXTRUDER);
  5423. break;
  5424. case 218:
  5425. SERIAL_ECHO(MSG_M218_INVALID_EXTRUDER);
  5426. break;
  5427. case 221:
  5428. SERIAL_ECHO(MSG_M221_INVALID_EXTRUDER);
  5429. break;
  5430. }
  5431. SERIAL_PROTOCOLLN((int)tmp_extruder);
  5432. return true;
  5433. }
  5434. }
  5435. return false;
  5436. }
  5437. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  5438. {
  5439. 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)
  5440. {
  5441. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  5442. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  5443. }
  5444. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  5445. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  5446. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  5447. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  5448. total_filament_used = 0;
  5449. }
  5450. float calculate_volumetric_multiplier(float diameter) {
  5451. float area = .0;
  5452. float radius = .0;
  5453. radius = diameter * .5;
  5454. if (! volumetric_enabled || radius == 0) {
  5455. area = 1;
  5456. }
  5457. else {
  5458. area = M_PI * pow(radius, 2);
  5459. }
  5460. return 1.0 / area;
  5461. }
  5462. void calculate_volumetric_multipliers() {
  5463. volumetric_multiplier[0] = calculate_volumetric_multiplier(filament_size[0]);
  5464. #if EXTRUDERS > 1
  5465. volumetric_multiplier[1] = calculate_volumetric_multiplier(filament_size[1]);
  5466. #if EXTRUDERS > 2
  5467. volumetric_multiplier[2] = calculate_volumetric_multiplier(filament_size[2]);
  5468. #endif
  5469. #endif
  5470. }
  5471. void delay_keep_alive(unsigned int ms)
  5472. {
  5473. for (;;) {
  5474. manage_heater();
  5475. // Manage inactivity, but don't disable steppers on timeout.
  5476. manage_inactivity(true);
  5477. lcd_update();
  5478. if (ms == 0)
  5479. break;
  5480. else if (ms >= 50) {
  5481. delay(50);
  5482. ms -= 50;
  5483. } else {
  5484. delay(ms);
  5485. ms = 0;
  5486. }
  5487. }
  5488. }
  5489. void wait_for_heater(long codenum) {
  5490. #ifdef TEMP_RESIDENCY_TIME
  5491. long residencyStart;
  5492. residencyStart = -1;
  5493. /* continue to loop until we have reached the target temp
  5494. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  5495. while ((!cancel_heatup) && ((residencyStart == -1) ||
  5496. (residencyStart >= 0 && (((unsigned int)(millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  5497. #else
  5498. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  5499. #endif //TEMP_RESIDENCY_TIME
  5500. if ((millis() - codenum) > 1000UL)
  5501. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  5502. if (!farm_mode) {
  5503. SERIAL_PROTOCOLPGM("T:");
  5504. SERIAL_PROTOCOL_F(degHotend(tmp_extruder), 1);
  5505. SERIAL_PROTOCOLPGM(" E:");
  5506. SERIAL_PROTOCOL((int)tmp_extruder);
  5507. #ifdef TEMP_RESIDENCY_TIME
  5508. SERIAL_PROTOCOLPGM(" W:");
  5509. if (residencyStart > -1)
  5510. {
  5511. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (millis() - residencyStart)) / 1000UL;
  5512. SERIAL_PROTOCOLLN(codenum);
  5513. }
  5514. else
  5515. {
  5516. SERIAL_PROTOCOLLN("?");
  5517. }
  5518. }
  5519. #else
  5520. SERIAL_PROTOCOLLN("");
  5521. #endif
  5522. codenum = millis();
  5523. }
  5524. manage_heater();
  5525. manage_inactivity();
  5526. lcd_update();
  5527. #ifdef TEMP_RESIDENCY_TIME
  5528. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  5529. or when current temp falls outside the hysteresis after target temp was reached */
  5530. if ((residencyStart == -1 && target_direction && (degHotend(tmp_extruder) >= (degTargetHotend(tmp_extruder) - TEMP_WINDOW))) ||
  5531. (residencyStart == -1 && !target_direction && (degHotend(tmp_extruder) <= (degTargetHotend(tmp_extruder) + TEMP_WINDOW))) ||
  5532. (residencyStart > -1 && labs(degHotend(tmp_extruder) - degTargetHotend(tmp_extruder)) > TEMP_HYSTERESIS))
  5533. {
  5534. residencyStart = millis();
  5535. }
  5536. #endif //TEMP_RESIDENCY_TIME
  5537. }
  5538. }
  5539. void check_babystep() {
  5540. int babystep_z;
  5541. EEPROM_read_B(EEPROM_BABYSTEP_Z, &babystep_z);
  5542. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  5543. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  5544. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  5545. EEPROM_save_B(EEPROM_BABYSTEP_Z, &babystep_z);
  5546. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  5547. lcd_update_enable(true);
  5548. }
  5549. }
  5550. #ifdef DIS
  5551. void d_setup()
  5552. {
  5553. pinMode(D_DATACLOCK, INPUT_PULLUP);
  5554. pinMode(D_DATA, INPUT_PULLUP);
  5555. pinMode(D_REQUIRE, OUTPUT);
  5556. digitalWrite(D_REQUIRE, HIGH);
  5557. }
  5558. float d_ReadData()
  5559. {
  5560. int digit[13];
  5561. String mergeOutput;
  5562. float output;
  5563. digitalWrite(D_REQUIRE, HIGH);
  5564. for (int i = 0; i<13; i++)
  5565. {
  5566. for (int j = 0; j < 4; j++)
  5567. {
  5568. while (digitalRead(D_DATACLOCK) == LOW) {}
  5569. while (digitalRead(D_DATACLOCK) == HIGH) {}
  5570. bitWrite(digit[i], j, digitalRead(D_DATA));
  5571. }
  5572. }
  5573. digitalWrite(D_REQUIRE, LOW);
  5574. mergeOutput = "";
  5575. output = 0;
  5576. for (int r = 5; r <= 10; r++) //Merge digits
  5577. {
  5578. mergeOutput += digit[r];
  5579. }
  5580. output = mergeOutput.toFloat();
  5581. if (digit[4] == 8) //Handle sign
  5582. {
  5583. output *= -1;
  5584. }
  5585. for (int i = digit[11]; i > 0; i--) //Handle floating point
  5586. {
  5587. output /= 10;
  5588. }
  5589. return output;
  5590. }
  5591. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  5592. int t1 = 0;
  5593. int t_delay = 0;
  5594. int digit[13];
  5595. int m;
  5596. char str[3];
  5597. //String mergeOutput;
  5598. char mergeOutput[15];
  5599. float output;
  5600. int mesh_point = 0; //index number of calibration point
  5601. 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
  5602. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  5603. float mesh_home_z_search = 4;
  5604. float row[x_points_num];
  5605. int ix = 0;
  5606. int iy = 0;
  5607. char* filename_wldsd = "wldsd.txt";
  5608. char data_wldsd[70];
  5609. char numb_wldsd[10];
  5610. d_setup();
  5611. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  5612. // We don't know where we are! HOME!
  5613. // Push the commands to the front of the message queue in the reverse order!
  5614. // There shall be always enough space reserved for these commands.
  5615. repeatcommand_front(); // repeat G80 with all its parameters
  5616. enquecommand_front_P((PSTR("G28 W0")));
  5617. enquecommand_front_P((PSTR("G1 Z5")));
  5618. return;
  5619. }
  5620. bool custom_message_old = custom_message;
  5621. unsigned int custom_message_type_old = custom_message_type;
  5622. unsigned int custom_message_state_old = custom_message_state;
  5623. custom_message = true;
  5624. custom_message_type = 1;
  5625. custom_message_state = (x_points_num * y_points_num) + 10;
  5626. lcd_update(1);
  5627. mbl.reset();
  5628. babystep_undo();
  5629. card.openFile(filename_wldsd, false);
  5630. current_position[Z_AXIS] = mesh_home_z_search;
  5631. 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);
  5632. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  5633. int Z_PROBE_FEEDRATE = homing_feedrate[Z_AXIS] / 60;
  5634. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  5635. setup_for_endstop_move(false);
  5636. SERIAL_PROTOCOLPGM("Num X,Y: ");
  5637. SERIAL_PROTOCOL(x_points_num);
  5638. SERIAL_PROTOCOLPGM(",");
  5639. SERIAL_PROTOCOL(y_points_num);
  5640. SERIAL_PROTOCOLPGM("\nZ search height: ");
  5641. SERIAL_PROTOCOL(mesh_home_z_search);
  5642. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  5643. SERIAL_PROTOCOL(x_dimension);
  5644. SERIAL_PROTOCOLPGM(",");
  5645. SERIAL_PROTOCOL(y_dimension);
  5646. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  5647. while (mesh_point != x_points_num * y_points_num) {
  5648. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  5649. iy = mesh_point / x_points_num;
  5650. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  5651. float z0 = 0.f;
  5652. current_position[Z_AXIS] = mesh_home_z_search;
  5653. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  5654. st_synchronize();
  5655. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  5656. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  5657. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], XY_AXIS_FEEDRATE, active_extruder);
  5658. st_synchronize();
  5659. 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
  5660. break;
  5661. card.closefile();
  5662. }
  5663. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  5664. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  5665. //strcat(data_wldsd, numb_wldsd);
  5666. //MYSERIAL.println(data_wldsd);
  5667. //delay(1000);
  5668. //delay(3000);
  5669. //t1 = millis();
  5670. //while (digitalRead(D_DATACLOCK) == LOW) {}
  5671. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  5672. memset(digit, 0, sizeof(digit));
  5673. //cli();
  5674. digitalWrite(D_REQUIRE, LOW);
  5675. for (int i = 0; i<13; i++)
  5676. {
  5677. //t1 = millis();
  5678. for (int j = 0; j < 4; j++)
  5679. {
  5680. while (digitalRead(D_DATACLOCK) == LOW) {}
  5681. while (digitalRead(D_DATACLOCK) == HIGH) {}
  5682. bitWrite(digit[i], j, digitalRead(D_DATA));
  5683. }
  5684. //t_delay = (millis() - t1);
  5685. //SERIAL_PROTOCOLPGM(" ");
  5686. //SERIAL_PROTOCOL_F(t_delay, 5);
  5687. //SERIAL_PROTOCOLPGM(" ");
  5688. }
  5689. //sei();
  5690. digitalWrite(D_REQUIRE, HIGH);
  5691. mergeOutput[0] = '\0';
  5692. output = 0;
  5693. for (int r = 5; r <= 10; r++) //Merge digits
  5694. {
  5695. sprintf(str, "%d", digit[r]);
  5696. strcat(mergeOutput, str);
  5697. }
  5698. output = atof(mergeOutput);
  5699. if (digit[4] == 8) //Handle sign
  5700. {
  5701. output *= -1;
  5702. }
  5703. for (int i = digit[11]; i > 0; i--) //Handle floating point
  5704. {
  5705. output *= 0.1;
  5706. }
  5707. //output = d_ReadData();
  5708. //row[ix] = current_position[Z_AXIS];
  5709. memset(data_wldsd, 0, sizeof(data_wldsd));
  5710. for (int i = 0; i <3; i++) {
  5711. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  5712. dtostrf(current_position[i], 8, 5, numb_wldsd);
  5713. strcat(data_wldsd, numb_wldsd);
  5714. strcat(data_wldsd, ";");
  5715. }
  5716. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  5717. dtostrf(output, 8, 5, numb_wldsd);
  5718. strcat(data_wldsd, numb_wldsd);
  5719. //strcat(data_wldsd, ";");
  5720. card.write_command(data_wldsd);
  5721. //row[ix] = d_ReadData();
  5722. row[ix] = output; // current_position[Z_AXIS];
  5723. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  5724. for (int i = 0; i < x_points_num; i++) {
  5725. SERIAL_PROTOCOLPGM(" ");
  5726. SERIAL_PROTOCOL_F(row[i], 5);
  5727. }
  5728. SERIAL_PROTOCOLPGM("\n");
  5729. }
  5730. custom_message_state--;
  5731. mesh_point++;
  5732. lcd_update(1);
  5733. }
  5734. card.closefile();
  5735. }
  5736. #endif
  5737. void temp_compensation_start() {
  5738. custom_message = true;
  5739. custom_message_type = 5;
  5740. custom_message_state = PINDA_HEAT_T + 1;
  5741. lcd_update(2);
  5742. if (degHotend(active_extruder) > EXTRUDE_MINTEMP) {
  5743. current_position[E_AXIS] -= DEFAULT_RETRACTION;
  5744. }
  5745. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  5746. current_position[X_AXIS] = PINDA_PREHEAT_X;
  5747. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  5748. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  5749. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  5750. st_synchronize();
  5751. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  5752. for (int i = 0; i < PINDA_HEAT_T; i++) {
  5753. delay_keep_alive(1000);
  5754. custom_message_state = PINDA_HEAT_T - i;
  5755. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  5756. else lcd_update(1);
  5757. }
  5758. custom_message_type = 0;
  5759. custom_message_state = 0;
  5760. custom_message = false;
  5761. }
  5762. void temp_compensation_apply() {
  5763. int i_add;
  5764. int compensation_value;
  5765. int z_shift = 0;
  5766. float z_shift_mm;
  5767. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  5768. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  5769. i_add = (target_temperature_bed - 60) / 10;
  5770. EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + i_add * 2, &z_shift);
  5771. z_shift_mm = z_shift / axis_steps_per_unit[Z_AXIS];
  5772. }else {
  5773. //interpolation
  5774. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / axis_steps_per_unit[Z_AXIS];
  5775. }
  5776. SERIAL_PROTOCOLPGM("\n");
  5777. SERIAL_PROTOCOLPGM("Z shift applied:");
  5778. MYSERIAL.print(z_shift_mm);
  5779. 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);
  5780. st_synchronize();
  5781. plan_set_z_position(current_position[Z_AXIS]);
  5782. }
  5783. else {
  5784. //we have no temp compensation data
  5785. }
  5786. }
  5787. float temp_comp_interpolation(float inp_temperature) {
  5788. //cubic spline interpolation
  5789. int n, i, j, k;
  5790. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  5791. int shift[10];
  5792. int temp_C[10];
  5793. n = 6; //number of measured points
  5794. shift[0] = 0;
  5795. for (i = 0; i < n; i++) {
  5796. if (i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i-1) * 2, &shift[i]); //read shift in steps from EEPROM
  5797. temp_C[i] = 50 + i * 10; //temperature in C
  5798. x[i] = (float)temp_C[i];
  5799. f[i] = (float)shift[i];
  5800. }
  5801. if (inp_temperature < x[0]) return 0;
  5802. for (i = n - 1; i>0; i--) {
  5803. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  5804. h[i - 1] = x[i] - x[i - 1];
  5805. }
  5806. //*********** formation of h, s , f matrix **************
  5807. for (i = 1; i<n - 1; i++) {
  5808. m[i][i] = 2 * (h[i - 1] + h[i]);
  5809. if (i != 1) {
  5810. m[i][i - 1] = h[i - 1];
  5811. m[i - 1][i] = h[i - 1];
  5812. }
  5813. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  5814. }
  5815. //*********** forward elimination **************
  5816. for (i = 1; i<n - 2; i++) {
  5817. temp = (m[i + 1][i] / m[i][i]);
  5818. for (j = 1; j <= n - 1; j++)
  5819. m[i + 1][j] -= temp*m[i][j];
  5820. }
  5821. //*********** backward substitution *********
  5822. for (i = n - 2; i>0; i--) {
  5823. sum = 0;
  5824. for (j = i; j <= n - 2; j++)
  5825. sum += m[i][j] * s[j];
  5826. s[i] = (m[i][n - 1] - sum) / m[i][i];
  5827. }
  5828. for (i = 0; i<n - 1; i++)
  5829. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  5830. a = (s[i + 1] - s[i]) / (6 * h[i]);
  5831. b = s[i] / 2;
  5832. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  5833. d = f[i];
  5834. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  5835. }
  5836. return sum;
  5837. }
  5838. void long_pause() //long pause print
  5839. {
  5840. st_synchronize();
  5841. //save currently set parameters to global variables
  5842. saved_feedmultiply = feedmultiply;
  5843. HotendTempBckp = degTargetHotend(active_extruder);
  5844. fanSpeedBckp = fanSpeed;
  5845. start_pause_print = millis();
  5846. //save position
  5847. pause_lastpos[X_AXIS] = current_position[X_AXIS];
  5848. pause_lastpos[Y_AXIS] = current_position[Y_AXIS];
  5849. pause_lastpos[Z_AXIS] = current_position[Z_AXIS];
  5850. pause_lastpos[E_AXIS] = current_position[E_AXIS];
  5851. //retract
  5852. current_position[E_AXIS] -= DEFAULT_RETRACTION;
  5853. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  5854. //lift z
  5855. current_position[Z_AXIS] += Z_PAUSE_LIFT;
  5856. if (current_position[Z_AXIS] > Z_MAX_POS) current_position[Z_AXIS] = Z_MAX_POS;
  5857. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 15, active_extruder);
  5858. //set nozzle target temperature to 0
  5859. setTargetHotend(0, 0);
  5860. setTargetHotend(0, 1);
  5861. setTargetHotend(0, 2);
  5862. //Move XY to side
  5863. current_position[X_AXIS] = X_PAUSE_POS;
  5864. current_position[Y_AXIS] = Y_PAUSE_POS;
  5865. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 50, active_extruder);
  5866. // Turn off the print fan
  5867. fanSpeed = 0;
  5868. st_synchronize();
  5869. }
  5870. void serialecho_temperatures() {
  5871. float tt = degHotend(active_extruder);
  5872. SERIAL_PROTOCOLPGM("T:");
  5873. SERIAL_PROTOCOL(tt);
  5874. SERIAL_PROTOCOLPGM(" E:");
  5875. SERIAL_PROTOCOL((int)active_extruder);
  5876. SERIAL_PROTOCOLPGM(" B:");
  5877. SERIAL_PROTOCOL_F(degBed(), 1);
  5878. SERIAL_PROTOCOLLN("");
  5879. }