fsl_flexcan.c 172 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641
  1. /*
  2. * Copyright (c) 2015, Freescale Semiconductor, Inc.
  3. * Copyright 2016-2021 NXP
  4. * All rights reserved.
  5. *
  6. * SPDX-License-Identifier: BSD-3-Clause
  7. */
  8. #include "fsl_flexcan.h"
  9. /*******************************************************************************
  10. * Definitions
  11. ******************************************************************************/
  12. /* Component ID definition, used by tools. */
  13. #ifndef FSL_COMPONENT_ID
  14. #define FSL_COMPONENT_ID "platform.drivers.flexcan"
  15. #endif
  16. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_6032) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_6032)
  17. #define RXINTERMISSION (CAN_DBG1_CFSM(0x2f))
  18. #define TXINTERMISSION (CAN_DBG1_CFSM(0x14))
  19. #define BUSIDLE (CAN_DBG1_CFSM(0x02))
  20. #define CBN_VALUE3 (CAN_DBG1_CBN(0x03))
  21. #define DELAY_BUSIDLE (200)
  22. #endif
  23. /* According to CiA doc 1301 v1.0.0, specified data/nominal phase sample point postion for CAN FD at 80 MHz. */
  24. #define IDEAL_DATA_SP_1 (800U)
  25. #define IDEAL_DATA_SP_2 (750U)
  26. #define IDEAL_DATA_SP_3 (700U)
  27. #define IDEAL_DATA_SP_4 (625U)
  28. #define IDEAL_NOMINAL_SP (800U)
  29. /* According to CiA doc 301 v4.2.0 and previous version. */
  30. #define IDEAL_SP_LOW (750U)
  31. #define IDEAL_SP_MID (800U)
  32. #define IDEAL_SP_HIGH (875U)
  33. #define IDEAL_SP_FACTOR (1000U)
  34. /* Define the max value of bit timing segments when use different timing register. */
  35. #define MAX_PROPSEG (CAN_CTRL1_PROPSEG_MASK >> CAN_CTRL1_PROPSEG_SHIFT)
  36. #define MAX_PSEG1 (CAN_CTRL1_PSEG1_MASK >> CAN_CTRL1_PSEG1_SHIFT)
  37. #define MAX_PSEG2 (CAN_CTRL1_PSEG2_MASK >> CAN_CTRL1_PSEG2_SHIFT)
  38. #define MAX_RJW (CAN_CTRL1_RJW_MASK >> CAN_CTRL1_RJW_SHIFT)
  39. #define MAX_PRESDIV (CAN_CTRL1_PRESDIV_MASK >> CAN_CTRL1_PRESDIV_SHIFT)
  40. #define CTRL1_MAX_TIME_QUANTA (1U + MAX_PROPSEG + 1U + MAX_PSEG1 + 1U + MAX_PSEG2 + 1U)
  41. #define CTRL1_MIN_TIME_QUANTA (8U)
  42. #define MAX_EPROPSEG (CAN_CBT_EPROPSEG_MASK >> CAN_CBT_EPROPSEG_SHIFT)
  43. #define MAX_EPSEG1 (CAN_CBT_EPSEG1_MASK >> CAN_CBT_EPSEG1_SHIFT)
  44. #define MAX_EPSEG2 (CAN_CBT_EPSEG2_MASK >> CAN_CBT_EPSEG2_SHIFT)
  45. #define MAX_ERJW (CAN_CBT_ERJW_MASK >> CAN_CBT_ERJW_SHIFT)
  46. #define MAX_EPRESDIV (CAN_CBT_EPRESDIV_MASK >> CAN_CBT_EPRESDIV_SHIFT)
  47. #define CBT_MAX_TIME_QUANTA (1U + MAX_EPROPSEG + 1U + MAX_EPSEG1 + 1U + MAX_EPSEG2 + 1U)
  48. #define CBT_MIN_TIME_QUANTA (8U)
  49. #define MAX_FPROPSEG (CAN_FDCBT_FPROPSEG_MASK >> CAN_FDCBT_FPROPSEG_SHIFT)
  50. #define MAX_FPSEG1 (CAN_FDCBT_FPSEG1_MASK >> CAN_FDCBT_FPSEG1_SHIFT)
  51. #define MAX_FPSEG2 (CAN_FDCBT_FPSEG2_MASK >> CAN_FDCBT_FPSEG2_SHIFT)
  52. #define MAX_FRJW (CAN_FDCBT_FRJW_MASK >> CAN_FDCBT_FRJW_SHIFT)
  53. #define MAX_FPRESDIV (CAN_FDCBT_FPRESDIV_MASK >> CAN_FDCBT_FPRESDIV_SHIFT)
  54. #define FDCBT_MAX_TIME_QUANTA (1U + MAX_FPROPSEG + 0U + MAX_FPSEG1 + 1U + MAX_FPSEG2 + 1U)
  55. #define FDCBT_MIN_TIME_QUANTA (5U)
  56. #define MAX_TDCOFF ((uint32_t)CAN_FDCTRL_TDCOFF_MASK >> CAN_FDCTRL_TDCOFF_SHIFT)
  57. #define MAX_NTSEG1 (CAN_ENCBT_NTSEG1_MASK >> CAN_ENCBT_NTSEG1_SHIFT)
  58. #define MAX_NTSEG2 (CAN_ENCBT_NTSEG2_MASK >> CAN_ENCBT_NTSEG2_SHIFT)
  59. #define MAX_NRJW (CAN_ENCBT_NRJW_MASK >> CAN_ENCBT_NRJW_SHIFT)
  60. #define MAX_ENPRESDIV (CAN_EPRS_ENPRESDIV_MASK >> CAN_EPRS_ENPRESDIV_SHIFT)
  61. #define ENCBT_MAX_TIME_QUANTA (1U + MAX_NTSEG1 + 1U + MAX_NTSEG2 + 1U)
  62. #define ENCBT_MIN_TIME_QUANTA (8U)
  63. #define MAX_DTSEG1 (CAN_EDCBT_DTSEG1_MASK >> CAN_EDCBT_DTSEG1_SHIFT)
  64. #define MAX_DTSEG2 (CAN_EDCBT_DTSEG2_MASK >> CAN_EDCBT_DTSEG2_SHIFT)
  65. #define MAX_DRJW (CAN_EDCBT_DRJW_MASK >> CAN_EDCBT_DRJW_SHIFT)
  66. #define MAX_EDPRESDIV (CAN_EPRS_EDPRESDIV_MASK >> CAN_EPRS_EDPRESDIV_SHIFT)
  67. #define EDCBT_MAX_TIME_QUANTA (1U + MAX_DTSEG1 + 1U + MAX_DTSEG2 + 1U)
  68. #define EDCBT_MIN_TIME_QUANTA (5U)
  69. #define MAX_ETDCOFF ((uint32_t)CAN_ETDC_ETDCOFF_MASK >> CAN_ETDC_ETDCOFF_SHIFT)
  70. /* TSEG1 corresponds to the sum of xPROPSEG and xPSEG1, TSEG2 corresponds to the xPSEG2 value. */
  71. #define MIN_TIME_SEGMENT1 (2U)
  72. #define MIN_TIME_SEGMENT2 (2U)
  73. /* Define maximum CAN and CAN FD bit rate supported by FLEXCAN. */
  74. #define MAX_CANFD_BITRATE (8000000U)
  75. #define MAX_CAN_BITRATE (1000000U)
  76. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_9595) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_9595)
  77. #define CAN_ESR1_FLTCONF_BUSOFF CAN_ESR1_FLTCONF(2U)
  78. #endif
  79. /* Define the range of memory that needs to be initialized when the device has memory error detection feature. */
  80. #if (defined(FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL) && FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL)
  81. #define CAN_INIT_RXFIR ((uint32_t)base + 0x4Cu)
  82. #define CAN_INIT_MEMORY_BASE_1 (uint32_t *)((uint32_t)base + (uint32_t)FSL_FEATURE_FLEXCAN_INIT_MEMORY_BASE_1)
  83. #define CAN_INIT_MEMORY_SIZE_1 FSL_FEATURE_FLEXCAN_INIT_MEMORY_SIZE_1
  84. #define CAN_INIT_MEMORY_BASE_2 (uint32_t *)((uint32_t)base + (uint32_t)FSL_FEATURE_FLEXCAN_INIT_MEMORY_BASE_2)
  85. #define CAN_INIT_MEMORY_SIZE_2 FSL_FEATURE_FLEXCAN_INIT_MEMORY_SIZE_2
  86. #endif
  87. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  88. #ifndef CAN_CLOCK_CHECK_NO_AFFECTS
  89. /* If no define such MACRO, it mean that the CAN in current device have no clock affect issue. */
  90. #define CAN_CLOCK_CHECK_NO_AFFECTS (true)
  91. #endif /* CAN_CLOCK_CHECK_NO_AFFECTS */
  92. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  93. /*! @brief FlexCAN Internal State. */
  94. enum _flexcan_state
  95. {
  96. kFLEXCAN_StateIdle = 0x0, /*!< MB/RxFIFO idle.*/
  97. kFLEXCAN_StateRxData = 0x1, /*!< MB receiving.*/
  98. kFLEXCAN_StateRxRemote = 0x2, /*!< MB receiving remote reply.*/
  99. kFLEXCAN_StateTxData = 0x3, /*!< MB transmitting.*/
  100. kFLEXCAN_StateTxRemote = 0x4, /*!< MB transmitting remote request.*/
  101. kFLEXCAN_StateRxFifo = 0x5, /*!< RxFIFO receiving.*/
  102. };
  103. /*! @brief FlexCAN message buffer CODE for Rx buffers. */
  104. enum _flexcan_mb_code_rx
  105. {
  106. kFLEXCAN_RxMbInactive = 0x0, /*!< MB is not active.*/
  107. kFLEXCAN_RxMbFull = 0x2, /*!< MB is full.*/
  108. kFLEXCAN_RxMbEmpty = 0x4, /*!< MB is active and empty.*/
  109. kFLEXCAN_RxMbOverrun = 0x6, /*!< MB is overwritten into a full buffer.*/
  110. kFLEXCAN_RxMbBusy = 0x8, /*!< FlexCAN is updating the contents of the MB, The CPU must not access the MB.*/
  111. kFLEXCAN_RxMbRanswer = 0xA, /*!< A frame was configured to recognize a Remote Request Frame and transmit a
  112. Response Frame in return.*/
  113. kFLEXCAN_RxMbNotUsed = 0xF, /*!< Not used.*/
  114. };
  115. /*! @brief FlexCAN message buffer CODE FOR Tx buffers. */
  116. enum _flexcan_mb_code_tx
  117. {
  118. kFLEXCAN_TxMbInactive = 0x8, /*!< MB is not active.*/
  119. kFLEXCAN_TxMbAbort = 0x9, /*!< MB is aborted.*/
  120. kFLEXCAN_TxMbDataOrRemote = 0xC, /*!< MB is a TX Data Frame(when MB RTR = 0) or MB is a TX Remote Request
  121. Frame (when MB RTR = 1).*/
  122. kFLEXCAN_TxMbTanswer = 0xE, /*!< MB is a TX Response Request Frame from an incoming Remote Request Frame.*/
  123. kFLEXCAN_TxMbNotUsed = 0xF, /*!< Not used.*/
  124. };
  125. /* Typedef for interrupt handler. */
  126. typedef void (*flexcan_isr_t)(CAN_Type *base, flexcan_handle_t *handle);
  127. /*******************************************************************************
  128. * Prototypes
  129. ******************************************************************************/
  130. #if !defined(NDEBUG)
  131. /*!
  132. * @brief Check if Message Buffer is occupied by Rx FIFO.
  133. *
  134. * This function check if Message Buffer is occupied by Rx FIFO.
  135. *
  136. * @param base FlexCAN peripheral base address.
  137. * @param mbIdx The FlexCAN Message Buffer index.
  138. * @return TRUE if the index MB is occupied by Rx FIFO, FALSE if the index MB not occupied by Rx FIFO.
  139. */
  140. static bool FLEXCAN_IsMbOccupied(CAN_Type *base, uint8_t mbIdx);
  141. #endif
  142. #if ((defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) || \
  143. (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829))
  144. /*!
  145. * @brief Get the first valid Message buffer ID of give FlexCAN instance.
  146. *
  147. * This function is a helper function for Errata 5641 workaround.
  148. *
  149. * @param base FlexCAN peripheral base address.
  150. * @return The first valid Message Buffer Number.
  151. */
  152. static uint8_t FLEXCAN_GetFirstValidMb(CAN_Type *base);
  153. #endif
  154. /*!
  155. * @brief Check if Message Buffer interrupt is enabled.
  156. *
  157. * This function check if Message Buffer interrupt is enabled.
  158. *
  159. * @param base FlexCAN peripheral base address.
  160. * @param mbIdx The FlexCAN Message Buffer index.
  161. *
  162. * @return TRUE if the index MB interrupt mask enabled, FALSE if the index MB interrupt mask disabled.
  163. */
  164. static bool FLEXCAN_IsMbIntEnabled(CAN_Type *base, uint8_t mbIdx);
  165. /*!
  166. * @brief Reset the FlexCAN Instance.
  167. *
  168. * Restores the FlexCAN module to reset state, notice that this function
  169. * will set all the registers to reset state so the FlexCAN module can not work
  170. * after calling this API.
  171. *
  172. * @param base FlexCAN peripheral base address.
  173. */
  174. static void FLEXCAN_Reset(CAN_Type *base);
  175. /*!
  176. * @brief Set bit rate of FlexCAN classical CAN frame or CAN FD frame nominal phase.
  177. *
  178. * This function set the bit rate of classical CAN frame or CAN FD frame nominal phase base on the value of the
  179. * parameter passed in. Users need to ensure that the timing segment values (phaseSeg1, phaseSeg2 and propSeg) match the
  180. * clock and bit rate, if not match, the final output bit rate may not equal the bitRate_Bps value. Suggest use
  181. * FLEXCAN_CalculateImprovedTimingValues() to get timing configuration.
  182. *
  183. * @param base FlexCAN peripheral base address.
  184. * @param sourceClock_Hz Source Clock in Hz.
  185. * @param bitRate_Bps Bit rate in Bps.
  186. * @param timingConfig FlexCAN timingConfig.
  187. */
  188. static void FLEXCAN_SetBitRate(CAN_Type *base,
  189. uint32_t sourceClock_Hz,
  190. uint32_t bitRate_Bps,
  191. flexcan_timing_config_t timingConfig);
  192. /*!
  193. * @brief Calculates the segment values for a single bit time for classical CAN.
  194. *
  195. * This function use to calculates the Classical CAN segment values which will be set in CTRL1/CBT/ENCBT register.
  196. *
  197. * @param base FlexCAN peripheral base address.
  198. * @param tqNum Number of time quantas per bit, range in 8 ~ 25 when use CTRL1, range in 8 ~ 129 when use CBT, range in
  199. * 8 ~ 385 when use ENCBT. param pTimingConfig Pointer to the FlexCAN timing configuration structure.
  200. */
  201. static void FLEXCAN_GetSegments(CAN_Type *base,
  202. uint32_t bitRate,
  203. uint32_t tqNum,
  204. flexcan_timing_config_t *pTimingConfig);
  205. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  206. /*!
  207. * @brief Set data phase bit rate of FlexCAN FD frame.
  208. *
  209. * This function set the data phase bit rate of CAN FD frame base on the value of the parameter
  210. * passed in. Users need to ensure that the timing segment values (fphaseSeg1, fphaseSeg2 and fpropSeg) match the clock
  211. * and bit rate, if not match, the final output bit rate may not equal the bitRateFD value. Suggest use
  212. * FLEXCAN_FDCalculateImprovedTimingValues() to get timing configuration.
  213. *
  214. *
  215. * @param base FlexCAN peripheral base address.
  216. * @param sourceClock_Hz Source Clock in Hz.
  217. * @param bitRateFD_Bps FD frame data phase bit rate in Bps.
  218. * @param timingConfig FlexCAN timingConfig.
  219. */
  220. static void FLEXCAN_SetFDBitRate(CAN_Type *base,
  221. uint32_t sourceClock_Hz,
  222. uint32_t bitRateFD_Bps,
  223. flexcan_timing_config_t timingConfig);
  224. /*!
  225. * @brief Get Mailbox offset number by dword.
  226. *
  227. * This function gets the offset number of the specified mailbox.
  228. * Mailbox is not consecutive between memory regions when payload is not 8 bytes
  229. * so need to calculate the specified mailbox address.
  230. * For example, in the first memory region, MB[0].CS address is 0x4002_4080. For 32 bytes
  231. * payload frame, the second mailbox is ((1/12)*512 + 1%12*40)/4 = 10, meaning 10 dword
  232. * after the 0x4002_4080, which is actually the address of mailbox MB[1].CS.
  233. *
  234. * @param base FlexCAN peripheral base address.
  235. * @param mbIdx Mailbox index.
  236. */
  237. static uint32_t FLEXCAN_GetFDMailboxOffset(CAN_Type *base, uint8_t mbIdx);
  238. /*!
  239. * @brief Calculates the segment values for a single bit time for CAN FD data phase.
  240. *
  241. * This function use to calculates the CAN FD data phase segment values which will be set in CFDCBT/EDCBT
  242. * register.
  243. *
  244. * @param bitRateFD Data phase bit rate
  245. * @param tqNum Number of time quanta per bit
  246. * @param pTimingConfig Pointer to the FlexCAN timing configuration structure.
  247. */
  248. static void FLEXCAN_FDGetSegments(uint32_t bitRateFD, uint32_t tqNum, flexcan_timing_config_t *pTimingConfig);
  249. /*!
  250. * @brief Calculates the improved timing values by specific bit rate for CAN FD nominal phase.
  251. *
  252. * This function use to calculates the CAN FD nominal phase timing values according to the given nominal phase bit rate.
  253. * The Calculated timing values will be set in CBT/ENCBT registers. The calculation is based on the recommendation of
  254. * the CiA 1301 v1.0.0 document.
  255. *
  256. * @param bitRate The CAN FD nominal phase speed in bps defined by user, should be less than or equal to 1Mbps.
  257. * @param sourceClock_Hz The Source clock frequency in Hz.
  258. * @param pTimingConfig Pointer to the FlexCAN timing configuration structure.
  259. *
  260. * @return TRUE if timing configuration found, FALSE if failed to find configuration.
  261. */
  262. static bool FLEXCAN_CalculateImprovedNominalTimingValues(uint32_t bitRate,
  263. uint32_t sourceClock_Hz,
  264. flexcan_timing_config_t *pTimingConfig);
  265. #endif
  266. /*!
  267. * @brief Check unhandle interrupt events
  268. *
  269. * @param base FlexCAN peripheral base address.
  270. * @return TRUE if unhandled interrupt action exist, FALSE if no unhandlered interrupt action exist.
  271. */
  272. static bool FLEXCAN_CheckUnhandleInterruptEvents(CAN_Type *base);
  273. /*!
  274. * @brief Sub Handler Data Trasfered Events
  275. *
  276. * @param base FlexCAN peripheral base address.
  277. * @param handle FlexCAN handle pointer.
  278. * @param pResult Pointer to the Handle result.
  279. *
  280. * @return the status after handle each data transfered event.
  281. */
  282. static status_t FLEXCAN_SubHandlerForDataTransfered(CAN_Type *base, flexcan_handle_t *handle, uint32_t *pResult);
  283. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO)
  284. /*!
  285. * @brief Sub Handler Ehanced Rx FIFO event
  286. *
  287. * @param base FlexCAN peripheral base address.
  288. * @param handle FlexCAN handle pointer.
  289. * @param flags FlexCAN interrupt flags.
  290. *
  291. * @return the status after handle Ehanced Rx FIFO event.
  292. */
  293. static status_t FLEXCAN_SubHandlerForEhancedRxFifo(CAN_Type *base, flexcan_handle_t *handle, uint64_t flags);
  294. #endif
  295. /*******************************************************************************
  296. * Variables
  297. ******************************************************************************/
  298. /* Array of FlexCAN peripheral base address. */
  299. static CAN_Type *const s_flexcanBases[] = CAN_BASE_PTRS;
  300. /* Array of FlexCAN IRQ number. */
  301. static const IRQn_Type s_flexcanRxWarningIRQ[] = CAN_Rx_Warning_IRQS;
  302. static const IRQn_Type s_flexcanTxWarningIRQ[] = CAN_Tx_Warning_IRQS;
  303. static const IRQn_Type s_flexcanWakeUpIRQ[] = CAN_Wake_Up_IRQS;
  304. static const IRQn_Type s_flexcanErrorIRQ[] = CAN_Error_IRQS;
  305. static const IRQn_Type s_flexcanBusOffIRQ[] = CAN_Bus_Off_IRQS;
  306. static const IRQn_Type s_flexcanMbIRQ[] = CAN_ORed_Message_buffer_IRQS;
  307. /* Array of FlexCAN handle. */
  308. static flexcan_handle_t *s_flexcanHandle[ARRAY_SIZE(s_flexcanBases)];
  309. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  310. /* Array of FlexCAN clock name. */
  311. static const clock_ip_name_t s_flexcanClock[] = FLEXCAN_CLOCKS;
  312. #if defined(FLEXCAN_PERIPH_CLOCKS)
  313. /* Array of FlexCAN serial clock name. */
  314. static const clock_ip_name_t s_flexcanPeriphClock[] = FLEXCAN_PERIPH_CLOCKS;
  315. #endif /* FLEXCAN_PERIPH_CLOCKS */
  316. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  317. /* FlexCAN ISR for transactional APIs. */
  318. #if defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
  319. static flexcan_isr_t s_flexcanIsr = (flexcan_isr_t)DefaultISR;
  320. #else
  321. static flexcan_isr_t s_flexcanIsr;
  322. #endif
  323. /*******************************************************************************
  324. * Code
  325. ******************************************************************************/
  326. /*!
  327. * brief Get the FlexCAN instance from peripheral base address.
  328. *
  329. * param base FlexCAN peripheral base address.
  330. * return FlexCAN instance.
  331. */
  332. uint32_t FLEXCAN_GetInstance(CAN_Type *base)
  333. {
  334. uint32_t instance;
  335. /* Find the instance index from base address mappings. */
  336. for (instance = 0; instance < ARRAY_SIZE(s_flexcanBases); instance++)
  337. {
  338. if (s_flexcanBases[instance] == base)
  339. {
  340. break;
  341. }
  342. }
  343. assert(instance < ARRAY_SIZE(s_flexcanBases));
  344. return instance;
  345. }
  346. /*!
  347. * brief Enter FlexCAN Freeze Mode.
  348. *
  349. * This function makes the FlexCAN work under Freeze Mode.
  350. *
  351. * param base FlexCAN peripheral base address.
  352. */
  353. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_9595) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_9595)
  354. void FLEXCAN_EnterFreezeMode(CAN_Type *base)
  355. {
  356. uint32_t u32TimeoutCount = 0U;
  357. uint32_t u32TempMCR = 0U;
  358. uint32_t u32TempIMASK1 = 0U;
  359. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  360. uint32_t u32TempIMASK2 = 0U;
  361. #endif
  362. /* Step1: set FRZ enable in MCR. */
  363. base->MCR |= CAN_MCR_FRZ_MASK;
  364. /* Step2: to check if MDIS bit set in MCR. if yes, clear it. */
  365. if (0U != (base->MCR & CAN_MCR_MDIS_MASK))
  366. {
  367. base->MCR &= ~CAN_MCR_MDIS_MASK;
  368. }
  369. /* Step3: polling LPMACK. */
  370. u32TimeoutCount = (uint32_t)FLEXCAN_WAIT_TIMEOUT;
  371. while ((0U == (base->MCR & CAN_MCR_LPMACK_MASK)) && (u32TimeoutCount > 0U))
  372. {
  373. u32TimeoutCount--;
  374. }
  375. /* Step4: to check FLTCONF in ESR1 register */
  376. if (0U == (base->ESR1 & CAN_ESR1_FLTCONF_BUSOFF))
  377. {
  378. /* Step5B: Set Halt bits. */
  379. base->MCR |= CAN_MCR_HALT_MASK;
  380. /* Step6B: Poll the MCR register until the Freeze Acknowledge (FRZACK) bit is set, timeout need more than 178
  381. * CAN bit length, so 20 multiply timeout is enough. */
  382. u32TimeoutCount = (uint32_t)FLEXCAN_WAIT_TIMEOUT * 20U;
  383. while ((0U == (base->MCR & CAN_MCR_FRZACK_MASK)) && (u32TimeoutCount > 0U))
  384. {
  385. u32TimeoutCount--;
  386. }
  387. }
  388. else
  389. {
  390. /* backup MCR and IMASK register. Errata document not descript it, but we need backup for step 8A and 9A. */
  391. u32TempMCR = base->MCR;
  392. u32TempIMASK1 = base->IMASK1;
  393. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  394. u32TempIMASK2 = base->IMASK2;
  395. #endif
  396. /* Step5A: Set the Soft Reset bit ((SOFTRST) in the MCR.*/
  397. base->MCR |= CAN_MCR_SOFTRST_MASK;
  398. /* Step6A: Poll the MCR register until the Soft Reset (SOFTRST) bit is cleared. */
  399. u32TimeoutCount = (uint32_t)FLEXCAN_WAIT_TIMEOUT;
  400. while ((CAN_MCR_SOFTRST_MASK == (base->MCR & CAN_MCR_SOFTRST_MASK)) && (u32TimeoutCount > 0U))
  401. {
  402. u32TimeoutCount--;
  403. }
  404. /* Step7A: Poll the MCR register until the Freeze Acknowledge (FRZACK) bit is set. */
  405. u32TimeoutCount = (uint32_t)FLEXCAN_WAIT_TIMEOUT;
  406. while ((0U == (base->MCR & CAN_MCR_FRZACK_MASK)) && (u32TimeoutCount > 0U))
  407. {
  408. u32TimeoutCount--;
  409. }
  410. /* Step8A: reconfig MCR. */
  411. base->MCR = u32TempMCR;
  412. /* Step9A: reconfig IMASK. */
  413. base->IMASK1 = u32TempIMASK1;
  414. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  415. base->IMASK2 = u32TempIMASK2;
  416. #endif
  417. }
  418. }
  419. #elif (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_8341) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_8341)
  420. void FLEXCAN_EnterFreezeMode(CAN_Type *base)
  421. {
  422. uint32_t u32TimeoutCount = 0U;
  423. uint32_t u32TempMCR = 0U;
  424. uint32_t u32TempIMASK1 = 0U;
  425. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  426. uint32_t u32TempIMASK2 = 0U;
  427. #endif
  428. /* Step1: set FRZ and HALT bit enable in MCR. */
  429. base->MCR |= CAN_MCR_FRZ_MASK;
  430. base->MCR |= CAN_MCR_HALT_MASK;
  431. /* Step2: to check if MDIS bit set in MCR. if yes, clear it. */
  432. if (0U != (base->MCR & CAN_MCR_MDIS_MASK))
  433. {
  434. base->MCR &= ~CAN_MCR_MDIS_MASK;
  435. }
  436. /* Step3: Poll the MCR register until the Freeze Acknowledge (FRZACK) bit is set. */
  437. u32TimeoutCount = (uint32_t)FLEXCAN_WAIT_TIMEOUT * 100U;
  438. while ((0U == (base->MCR & CAN_MCR_FRZACK_MASK)) && (u32TimeoutCount > 0U))
  439. {
  440. u32TimeoutCount--;
  441. }
  442. /* Step4: check whether the timeout reached. if no skip step5 to step8. */
  443. if (0U == u32TimeoutCount)
  444. {
  445. /* backup MCR and IMASK register. Errata document not descript it, but we need backup for step 8A and 9A. */
  446. u32TempMCR = base->MCR;
  447. u32TempIMASK1 = base->IMASK1;
  448. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  449. u32TempIMASK2 = base->IMASK2;
  450. #endif
  451. /* Step5: Set the Soft Reset bit ((SOFTRST) in the MCR.*/
  452. base->MCR |= CAN_MCR_SOFTRST_MASK;
  453. /* Step6: Poll the MCR register until the Soft Reset (SOFTRST) bit is cleared. */
  454. while (CAN_MCR_SOFTRST_MASK == (base->MCR & CAN_MCR_SOFTRST_MASK))
  455. {
  456. }
  457. /* Step7: reconfig MCR. */
  458. base->MCR = u32TempMCR;
  459. /* Step8: reconfig IMASK. */
  460. base->IMASK1 = u32TempIMASK1;
  461. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  462. base->IMASK2 = u32TempIMASK2;
  463. #endif
  464. }
  465. }
  466. #else
  467. void FLEXCAN_EnterFreezeMode(CAN_Type *base)
  468. {
  469. /* Set Freeze, Halt bits. */
  470. base->MCR |= CAN_MCR_FRZ_MASK;
  471. base->MCR |= CAN_MCR_HALT_MASK;
  472. while (0U == (base->MCR & CAN_MCR_FRZACK_MASK))
  473. {
  474. }
  475. }
  476. #endif
  477. /*!
  478. * brief Exit FlexCAN Freeze Mode.
  479. *
  480. * This function makes the FlexCAN leave Freeze Mode.
  481. *
  482. * param base FlexCAN peripheral base address.
  483. */
  484. void FLEXCAN_ExitFreezeMode(CAN_Type *base)
  485. {
  486. #if (defined(FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL) && FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL)
  487. /* Clean FlexCAN Access With Non-Correctable Error Interrupt Flag to avoid be put in freeze mode. */
  488. FLEXCAN_ClearStatusFlags(base, (uint64_t)kFLEXCAN_FlexCanAccessNonCorrectableErrorIntFlag |
  489. (uint64_t)kFLEXCAN_FlexCanAccessNonCorrectableErrorOverrunFlag);
  490. #endif
  491. /* Clear Freeze, Halt bits. */
  492. base->MCR &= ~CAN_MCR_HALT_MASK;
  493. base->MCR &= ~CAN_MCR_FRZ_MASK;
  494. /* Wait until the FlexCAN Module exit freeze mode. */
  495. while (0U != (base->MCR & CAN_MCR_FRZACK_MASK))
  496. {
  497. }
  498. }
  499. #if !defined(NDEBUG)
  500. /*!
  501. * brief Check if Message Buffer is occupied by Rx FIFO.
  502. *
  503. * This function check if Message Buffer is occupied by Rx FIFO.
  504. *
  505. * param base FlexCAN peripheral base address.
  506. * param mbIdx The FlexCAN Message Buffer index.
  507. * return TRUE if the index MB is occupied by Rx FIFO, FALSE if the index MB not occupied by Rx FIFO.
  508. */
  509. static bool FLEXCAN_IsMbOccupied(CAN_Type *base, uint8_t mbIdx)
  510. {
  511. uint8_t lastOccupiedMb;
  512. bool fgRet;
  513. /* Is Rx FIFO enabled? */
  514. if (0U != (base->MCR & CAN_MCR_RFEN_MASK))
  515. {
  516. /* Get RFFN value. */
  517. lastOccupiedMb = (uint8_t)((base->CTRL2 & CAN_CTRL2_RFFN_MASK) >> CAN_CTRL2_RFFN_SHIFT);
  518. /* Calculate the number of last Message Buffer occupied by Rx FIFO. */
  519. lastOccupiedMb = ((lastOccupiedMb + 1U) * 2U) + 5U;
  520. #if ((defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) || \
  521. (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829))
  522. /* the first valid MB should be occupied by ERRATA 5461 or 5829. */
  523. lastOccupiedMb += 1U;
  524. #endif
  525. fgRet = (mbIdx <= lastOccupiedMb);
  526. }
  527. else
  528. {
  529. #if ((defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) || \
  530. (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829))
  531. if (0U == mbIdx)
  532. {
  533. fgRet = true;
  534. }
  535. else
  536. #endif
  537. {
  538. fgRet = false;
  539. }
  540. }
  541. return fgRet;
  542. }
  543. #endif
  544. #if ((defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) || \
  545. (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829))
  546. /*!
  547. * brief Get the first valid Message buffer ID of give FlexCAN instance.
  548. *
  549. * This function is a helper function for Errata 5641 workaround.
  550. *
  551. * param base FlexCAN peripheral base address.
  552. * return The first valid Message Buffer Number.
  553. */
  554. static uint8_t FLEXCAN_GetFirstValidMb(CAN_Type *base)
  555. {
  556. uint8_t firstValidMbNum;
  557. if (0U != (base->MCR & CAN_MCR_RFEN_MASK))
  558. {
  559. firstValidMbNum = (uint8_t)((base->CTRL2 & CAN_CTRL2_RFFN_MASK) >> CAN_CTRL2_RFFN_SHIFT);
  560. firstValidMbNum = ((firstValidMbNum + 1U) * 2U) + 6U;
  561. }
  562. else
  563. {
  564. firstValidMbNum = 0U;
  565. }
  566. return firstValidMbNum;
  567. }
  568. #endif
  569. /*!
  570. * brief Check if Message Buffer interrupt is enabled.
  571. *
  572. * This function check if Message Buffer interrupt is enabled.
  573. *
  574. * param base FlexCAN peripheral base address.
  575. * param mbIdx The FlexCAN Message Buffer index.
  576. *
  577. * return TRUE if the index MB interrupt mask enabled, FALSE if the index MB interrupt mask disabled.
  578. */
  579. static bool FLEXCAN_IsMbIntEnabled(CAN_Type *base, uint8_t mbIdx)
  580. {
  581. /* Assertion. */
  582. assert(mbIdx < (uint8_t)FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base));
  583. uint32_t flag = 1U;
  584. bool fgRet = false;
  585. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  586. if (mbIdx >= 32U)
  587. {
  588. fgRet = (0U != (base->IMASK2 & (flag << (mbIdx - 32U))));
  589. }
  590. else
  591. #endif
  592. {
  593. fgRet = (0U != (base->IMASK1 & (flag << mbIdx)));
  594. }
  595. return fgRet;
  596. }
  597. /*!
  598. * brief Reset the FlexCAN Instance.
  599. *
  600. * Restores the FlexCAN module to reset state, notice that this function
  601. * will set all the registers to reset state so the FlexCAN module can not work
  602. * after calling this API.
  603. *
  604. * param base FlexCAN peripheral base address.
  605. */
  606. static void FLEXCAN_Reset(CAN_Type *base)
  607. {
  608. /* The module must should be first exit from low power
  609. * mode, and then soft reset can be applied.
  610. */
  611. assert(0U == (base->MCR & CAN_MCR_MDIS_MASK));
  612. uint8_t i;
  613. #if (defined(FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT) && FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT)
  614. if (0 != (FSL_FEATURE_FLEXCAN_INSTANCE_HAS_DOZE_MODE_SUPPORTn(base)))
  615. {
  616. /* De-assert DOZE Enable Bit. */
  617. base->MCR &= ~CAN_MCR_DOZE_MASK;
  618. }
  619. #endif
  620. /* Wait until FlexCAN exit from any Low Power Mode. */
  621. while (0U != (base->MCR & CAN_MCR_LPMACK_MASK))
  622. {
  623. }
  624. /* Assert Soft Reset Signal. */
  625. base->MCR |= CAN_MCR_SOFTRST_MASK;
  626. /* Wait until FlexCAN reset completes. */
  627. while (0U != (base->MCR & CAN_MCR_SOFTRST_MASK))
  628. {
  629. }
  630. /* Reset MCR register. */
  631. #if (defined(FSL_FEATURE_FLEXCAN_HAS_GLITCH_FILTER) && FSL_FEATURE_FLEXCAN_HAS_GLITCH_FILTER)
  632. base->MCR |= CAN_MCR_WRNEN_MASK | CAN_MCR_WAKSRC_MASK |
  633. CAN_MCR_MAXMB((uint32_t)FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base) - 1U);
  634. #else
  635. base->MCR |=
  636. CAN_MCR_WRNEN_MASK | CAN_MCR_MAXMB((uint32_t)FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base) - 1U);
  637. #endif
  638. /* Reset CTRL1 and CTRL2 register, default to eanble SMP feature which enable three sample point to determine the
  639. * received bit's value of the. */
  640. base->CTRL1 = CAN_CTRL1_SMP_MASK;
  641. base->CTRL2 = CAN_CTRL2_TASD(0x16) | CAN_CTRL2_RRS_MASK | CAN_CTRL2_EACEN_MASK;
  642. #if (defined(FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL) && FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL)
  643. /* Enable unrestricted write access to FlexCAN memory. */
  644. base->CTRL2 |= CAN_CTRL2_WRMFRZ_MASK;
  645. /* Do memory initialization for all FlexCAN RAM in order to have the parity bits in memory properly
  646. updated. */
  647. *(volatile uint32_t *)CAN_INIT_RXFIR = 0x0U;
  648. (void)memset((void *)CAN_INIT_MEMORY_BASE_1, 0, CAN_INIT_MEMORY_SIZE_1);
  649. (void)memset((void *)CAN_INIT_MEMORY_BASE_2, 0, CAN_INIT_MEMORY_SIZE_2);
  650. /* Disable unrestricted write access to FlexCAN memory. */
  651. base->CTRL2 &= ~CAN_CTRL2_WRMFRZ_MASK;
  652. /* Clean all memory error flags. */
  653. FLEXCAN_ClearStatusFlags(base, (uint64_t)kFLEXCAN_AllMemoryErrorFlag);
  654. #else
  655. /* Only need clean all Message Buffer memory. */
  656. (void)memset((void *)&base->MB[0], 0, sizeof(base->MB));
  657. #endif
  658. /* Clean all individual Rx Mask of Message Buffers. */
  659. for (i = 0; i < (uint32_t)FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base); i++)
  660. {
  661. base->RXIMR[i] = 0x3FFFFFFF;
  662. }
  663. /* Clean Global Mask of Message Buffers. */
  664. base->RXMGMASK = 0x3FFFFFFF;
  665. /* Clean Global Mask of Message Buffer 14. */
  666. base->RX14MASK = 0x3FFFFFFF;
  667. /* Clean Global Mask of Message Buffer 15. */
  668. base->RX15MASK = 0x3FFFFFFF;
  669. /* Clean Global Mask of Rx FIFO. */
  670. base->RXFGMASK = 0x3FFFFFFF;
  671. }
  672. /*!
  673. * brief Set bit rate of FlexCAN classical CAN frame or CAN FD frame nominal phase.
  674. *
  675. * This function set the bit rate of classical CAN frame or CAN FD frame nominal phase base on the value of the
  676. * parameter passed in. Users need to ensure that the timing segment values (phaseSeg1, phaseSeg2 and propSeg) match the
  677. * clock and bit rate, if not match, the final output bit rate may not equal the bitRate_Bps value. Suggest use
  678. * FLEXCAN_CalculateImprovedTimingValues() to get timing configuration.
  679. *
  680. * param base FlexCAN peripheral base address.
  681. * param sourceClock_Hz Source Clock in Hz.
  682. * param bitRate_Bps Bit rate in Bps.
  683. * param timingConfig FlexCAN timingConfig.
  684. */
  685. static void FLEXCAN_SetBitRate(CAN_Type *base,
  686. uint32_t sourceClock_Hz,
  687. uint32_t bitRate_Bps,
  688. flexcan_timing_config_t timingConfig)
  689. {
  690. /* FlexCAN classical CAN frame or CAN FD frame nominal phase timing setting formula:
  691. * quantum = 1 + (phaseSeg1 + 1) + (phaseSeg2 + 1) + (propSeg + 1);
  692. */
  693. uint32_t quantum = (1U + ((uint32_t)timingConfig.phaseSeg1 + 1U) + ((uint32_t)timingConfig.phaseSeg2 + 1U) +
  694. ((uint32_t)timingConfig.propSeg + 1U));
  695. /* Assertion: Desired bit rate is too high. */
  696. assert(bitRate_Bps <= 1000000U);
  697. /* Assertion: Source clock should greater than or equal to bit rate * quantum. */
  698. assert((bitRate_Bps * quantum) <= sourceClock_Hz);
  699. /* Assertion: Desired bit rate is too low, the bit rate * quantum * max prescaler divider value should greater than
  700. or equal to source clock. */
  701. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  702. if (0 != FSL_FEATURE_FLEXCAN_INSTANCE_HAS_FLEXIBLE_DATA_RATEn(base))
  703. {
  704. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG)
  705. assert((bitRate_Bps * quantum * MAX_ENPRESDIV) >= sourceClock_Hz);
  706. #else
  707. assert((bitRate_Bps * quantum * MAX_EPRESDIV) >= sourceClock_Hz);
  708. #endif
  709. }
  710. else
  711. {
  712. assert((bitRate_Bps * quantum * MAX_PRESDIV) >= sourceClock_Hz);
  713. }
  714. #else
  715. assert((bitRate_Bps * quantum * MAX_PRESDIV) >= sourceClock_Hz);
  716. #endif
  717. if (quantum < (MIN_TIME_SEGMENT1 + MIN_TIME_SEGMENT2 + 1U))
  718. {
  719. /* No valid timing configuration. */
  720. timingConfig.preDivider = 0U;
  721. }
  722. else
  723. {
  724. timingConfig.preDivider = (uint16_t)((sourceClock_Hz / (bitRate_Bps * quantum)) - 1U);
  725. }
  726. /* Update actual timing characteristic. */
  727. FLEXCAN_SetTimingConfig(base, (const flexcan_timing_config_t *)(uint32_t)&timingConfig);
  728. }
  729. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  730. /*!
  731. * brief Set data phase bit rate of FlexCAN FD frame.
  732. *
  733. * This function set the data phase bit rate of CAN FD frame base on the value of the parameter
  734. * passed in. Users need to ensure that the timing segment values (fphaseSeg1, fphaseSeg2 and fpropSeg) match the clock
  735. * and bit rate, if not match, the final output bit rate may not equal the bitRateFD value. Suggest use
  736. * FLEXCAN_FDCalculateImprovedTimingValues() to get timing configuration.
  737. *
  738. *
  739. * param base FlexCAN peripheral base address.
  740. * param sourceClock_Hz Source Clock in Hz.
  741. * param bitRateFD_Bps FD frame data phase bit rate in Bps.
  742. * param timingConfig FlexCAN timingConfig.
  743. */
  744. static void FLEXCAN_SetFDBitRate(CAN_Type *base,
  745. uint32_t sourceClock_Hz,
  746. uint32_t bitRateFD_Bps,
  747. flexcan_timing_config_t timingConfig)
  748. {
  749. /* FlexCAN FD frame data phase timing setting formula:
  750. * quantum = 1 + (fphaseSeg1 + 1) + (fphaseSeg2 + 1) + fpropSeg;
  751. */
  752. uint32_t quantum = (1U + ((uint32_t)timingConfig.fphaseSeg1 + 1U) + ((uint32_t)timingConfig.fphaseSeg2 + 1U) +
  753. (uint32_t)timingConfig.fpropSeg);
  754. /* Assertion: Desired bit rate is too high. */
  755. assert(bitRateFD_Bps <= 8000000U);
  756. /* Assertion: Source clock should greater than or equal to bit rate * quantum. */
  757. assert((bitRateFD_Bps * quantum) <= sourceClock_Hz);
  758. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG)
  759. /* Assertion: Desired bit rate is too low, the bit rate * quantum * max prescaler divider value should greater than
  760. or equal to source clock. */
  761. assert((bitRateFD_Bps * quantum * MAX_EDPRESDIV) >= sourceClock_Hz);
  762. #else
  763. assert((bitRateFD_Bps * quantum * MAX_FPRESDIV) >= sourceClock_Hz);
  764. #endif
  765. if (quantum < (MIN_TIME_SEGMENT1 + MIN_TIME_SEGMENT2 + 1U))
  766. {
  767. /* No valid data phase timing configuration. */
  768. timingConfig.fpreDivider = 0U;
  769. }
  770. else
  771. {
  772. timingConfig.fpreDivider = (uint16_t)((sourceClock_Hz / (bitRateFD_Bps * quantum)) - 1U);
  773. }
  774. /* Update actual timing characteristic. */
  775. FLEXCAN_SetFDTimingConfig(base, (const flexcan_timing_config_t *)(uint32_t)&timingConfig);
  776. }
  777. #endif
  778. /*!
  779. * brief Initializes a FlexCAN instance.
  780. *
  781. * This function initializes the FlexCAN module with user-defined settings.
  782. * This example shows how to set up the flexcan_config_t parameters and how
  783. * to call the FLEXCAN_Init function by passing in these parameters.
  784. * code
  785. * flexcan_config_t flexcanConfig;
  786. * flexcanConfig.clkSrc = kFLEXCAN_ClkSrc0;
  787. * flexcanConfig.bitRate = 1000000U;
  788. * flexcanConfig.maxMbNum = 16;
  789. * flexcanConfig.enableLoopBack = false;
  790. * flexcanConfig.enableSelfWakeup = false;
  791. * flexcanConfig.enableIndividMask = false;
  792. * flexcanConfig.disableSelfReception = false;
  793. * flexcanConfig.enableListenOnlyMode = false;
  794. * flexcanConfig.enableDoze = false;
  795. * flexcanConfig.timingConfig = timingConfig;
  796. * FLEXCAN_Init(CAN0, &flexcanConfig, 40000000UL);
  797. * endcode
  798. *
  799. * param base FlexCAN peripheral base address.
  800. * param pConfig Pointer to the user-defined configuration structure.
  801. * param sourceClock_Hz FlexCAN Protocol Engine clock source frequency in Hz.
  802. */
  803. void FLEXCAN_Init(CAN_Type *base, const flexcan_config_t *pConfig, uint32_t sourceClock_Hz)
  804. {
  805. /* Assertion. */
  806. assert(NULL != pConfig);
  807. assert((pConfig->maxMbNum > 0U) &&
  808. (pConfig->maxMbNum <= (uint8_t)FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base)));
  809. assert(pConfig->bitRate > 0U);
  810. uint32_t mcrTemp;
  811. uint32_t ctrl1Temp;
  812. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  813. uint32_t instance;
  814. #endif
  815. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  816. instance = FLEXCAN_GetInstance(base);
  817. /* Enable FlexCAN clock. */
  818. (void)CLOCK_EnableClock(s_flexcanClock[instance]);
  819. /*
  820. * Check the CAN clock in this device whether affected by Other clock gate
  821. * If it affected, we'd better to change other clock source,
  822. * If user insist on using that clock source, user need open these gate at same time,
  823. * In this scene, User need to care the power consumption.
  824. */
  825. assert(CAN_CLOCK_CHECK_NO_AFFECTS);
  826. #if defined(FLEXCAN_PERIPH_CLOCKS)
  827. /* Enable FlexCAN serial clock. */
  828. (void)CLOCK_EnableClock(s_flexcanPeriphClock[instance]);
  829. #endif /* FLEXCAN_PERIPH_CLOCKS */
  830. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  831. #if defined(CAN_CTRL1_CLKSRC_MASK)
  832. #if (defined(FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE) && FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE)
  833. if (0 == FSL_FEATURE_FLEXCAN_INSTANCE_SUPPORT_ENGINE_CLK_SEL_REMOVEn(base))
  834. #endif /* FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE */
  835. {
  836. /* Disable FlexCAN Module. */
  837. FLEXCAN_Enable(base, false);
  838. /* Protocol-Engine clock source selection, This bit must be set
  839. * when FlexCAN Module in Disable Mode.
  840. */
  841. base->CTRL1 = (kFLEXCAN_ClkSrc0 == pConfig->clkSrc) ? (base->CTRL1 & ~CAN_CTRL1_CLKSRC_MASK) :
  842. (base->CTRL1 | CAN_CTRL1_CLKSRC_MASK);
  843. }
  844. #endif /* CAN_CTRL1_CLKSRC_MASK */
  845. /* Enable FlexCAN Module for configuration. */
  846. FLEXCAN_Enable(base, true);
  847. /* Reset to known status. */
  848. FLEXCAN_Reset(base);
  849. #if (defined(FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL) && FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL)
  850. /* Enable to update in MCER. */
  851. base->CTRL2 |= CAN_CTRL2_ECRWRE_MASK;
  852. base->MECR &= ~CAN_MECR_ECRWRDIS_MASK;
  853. /* Enable/Disable Memory Error Detection and Correction.*/
  854. base->MECR = (pConfig->enableMemoryErrorControl) ? (base->MECR & ~CAN_MECR_ECCDIS_MASK) :
  855. (base->MECR | CAN_MECR_ECCDIS_MASK);
  856. /* Enable/Disable Non-Correctable Errors In FlexCAN Access Put Device In Freeze Mode. */
  857. base->MECR = (pConfig->enableNonCorrectableErrorEnterFreeze) ? (base->MECR | CAN_MECR_NCEFAFRZ_MASK) :
  858. (base->MECR & ~CAN_MECR_NCEFAFRZ_MASK);
  859. /* Lock MCER register. */
  860. base->CTRL2 &= ~CAN_CTRL2_ECRWRE_MASK;
  861. #endif
  862. /* Save current CTRL1 value and enable to enter Freeze mode(enabled by default). */
  863. ctrl1Temp = base->CTRL1;
  864. /* Save current MCR value and enable to enter Freeze mode(enabled by default). */
  865. mcrTemp = base->MCR;
  866. /* Enable Loop Back Mode? */
  867. ctrl1Temp = (pConfig->enableLoopBack) ? (ctrl1Temp | CAN_CTRL1_LPB_MASK) : (ctrl1Temp & ~CAN_CTRL1_LPB_MASK);
  868. /* Enable Timer Sync? */
  869. ctrl1Temp = (pConfig->enableTimerSync) ? (ctrl1Temp | CAN_CTRL1_TSYN_MASK) : (ctrl1Temp & ~CAN_CTRL1_TSYN_MASK);
  870. /* Enable Listen Only Mode? */
  871. ctrl1Temp = (pConfig->enableListenOnlyMode) ? ctrl1Temp | CAN_CTRL1_LOM_MASK : ctrl1Temp & ~CAN_CTRL1_LOM_MASK;
  872. #if !(defined(FSL_FEATURE_FLEXCAN_HAS_NO_SUPV_SUPPORT) && FSL_FEATURE_FLEXCAN_HAS_NO_SUPV_SUPPORT)
  873. /* Enable Supervisor Mode? */
  874. mcrTemp = (pConfig->enableSupervisorMode) ? mcrTemp | CAN_MCR_SUPV_MASK : mcrTemp & ~CAN_MCR_SUPV_MASK;
  875. #endif
  876. /* Set the maximum number of Message Buffers */
  877. mcrTemp = (mcrTemp & ~CAN_MCR_MAXMB_MASK) | CAN_MCR_MAXMB((uint32_t)pConfig->maxMbNum - 1U);
  878. /* Enable Self Wake Up Mode and configure the wake up source. */
  879. mcrTemp = (pConfig->enableSelfWakeup) ? (mcrTemp | CAN_MCR_SLFWAK_MASK) : (mcrTemp & ~CAN_MCR_SLFWAK_MASK);
  880. mcrTemp = (kFLEXCAN_WakeupSrcFiltered == pConfig->wakeupSrc) ? (mcrTemp | CAN_MCR_WAKSRC_MASK) :
  881. (mcrTemp & ~CAN_MCR_WAKSRC_MASK);
  882. #if (defined(FSL_FEATURE_FLEXCAN_HAS_PN_MODE) && FSL_FEATURE_FLEXCAN_HAS_PN_MODE)
  883. /* Enable Pretended Networking Mode? When Pretended Networking mode is set, Self Wake Up feature must be disabled.*/
  884. mcrTemp = (pConfig->enablePretendedeNetworking) ? ((mcrTemp & ~CAN_MCR_SLFWAK_MASK) | CAN_MCR_PNET_EN_MASK) :
  885. (mcrTemp & ~CAN_MCR_PNET_EN_MASK);
  886. #endif
  887. /* Enable Individual Rx Masking and Queue feature? */
  888. mcrTemp = (pConfig->enableIndividMask) ? (mcrTemp | CAN_MCR_IRMQ_MASK) : (mcrTemp & ~CAN_MCR_IRMQ_MASK);
  889. /* Disable Self Reception? */
  890. mcrTemp = (pConfig->disableSelfReception) ? mcrTemp | CAN_MCR_SRXDIS_MASK : mcrTemp & ~CAN_MCR_SRXDIS_MASK;
  891. #if (defined(FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT) && FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT)
  892. if (0 != FSL_FEATURE_FLEXCAN_INSTANCE_HAS_DOZE_MODE_SUPPORTn(base))
  893. {
  894. /* Enable Doze Mode? */
  895. mcrTemp = (pConfig->enableDoze) ? (mcrTemp | CAN_MCR_DOZE_MASK) : (mcrTemp & ~CAN_MCR_DOZE_MASK);
  896. }
  897. #endif
  898. /* Write back CTRL1 Configuration to register. */
  899. base->CTRL1 = ctrl1Temp;
  900. /* Write back MCR Configuration to register. */
  901. base->MCR = mcrTemp;
  902. /* Bit Rate Configuration.*/
  903. FLEXCAN_SetBitRate(base, sourceClock_Hz, pConfig->bitRate, pConfig->timingConfig);
  904. }
  905. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  906. /*!
  907. * brief Initializes a FlexCAN instance.
  908. *
  909. * This function initializes the FlexCAN module with user-defined settings.
  910. * This example shows how to set up the flexcan_config_t parameters and how
  911. * to call the FLEXCAN_FDInit function by passing in these parameters.
  912. * code
  913. * flexcan_config_t flexcanConfig;
  914. * flexcanConfig.clkSrc = kFLEXCAN_ClkSrc0;
  915. * flexcanConfig.bitRate = 1000000U;
  916. * flexcanConfig.bitRateFD = 2000000U;
  917. * flexcanConfig.maxMbNum = 16;
  918. * flexcanConfig.enableLoopBack = false;
  919. * flexcanConfig.enableSelfWakeup = false;
  920. * flexcanConfig.enableIndividMask = false;
  921. * flexcanConfig.disableSelfReception = false;
  922. * flexcanConfig.enableListenOnlyMode = false;
  923. * flexcanConfig.enableDoze = false;
  924. * flexcanConfig.timingConfig = timingConfig;
  925. * FLEXCAN_FDInit(CAN0, &flexcanConfig, 80000000UL, kFLEXCAN_16BperMB, true);
  926. * endcode
  927. *
  928. * param base FlexCAN peripheral base address.
  929. * param pConfig Pointer to the user-defined configuration structure.
  930. * param sourceClock_Hz FlexCAN Protocol Engine clock source frequency in Hz.
  931. * param dataSize FlexCAN Message Buffer payload size. The actual transmitted or received CAN FD frame data size needs
  932. * to be less than or equal to this value.
  933. * param brs True if bit rate switch is enabled in FD mode.
  934. */
  935. void FLEXCAN_FDInit(
  936. CAN_Type *base, const flexcan_config_t *pConfig, uint32_t sourceClock_Hz, flexcan_mb_size_t dataSize, bool brs)
  937. {
  938. assert((uint32_t)dataSize <= 3U);
  939. assert(((pConfig->bitRate < pConfig->bitRateFD) && brs) || ((pConfig->bitRate == pConfig->bitRateFD) && (!brs)));
  940. uint32_t fdctrl = 0U;
  941. /* Initialization of classical CAN. */
  942. FLEXCAN_Init(base, pConfig, sourceClock_Hz);
  943. /* Extra bit rate setting for CAN FD data phase. */
  944. FLEXCAN_SetFDBitRate(base, sourceClock_Hz, pConfig->bitRateFD, pConfig->timingConfig);
  945. /* read FDCTRL register. */
  946. fdctrl = base->FDCTRL;
  947. /* Enable FD operation and set bit rate switch. */
  948. if (brs)
  949. {
  950. fdctrl |= CAN_FDCTRL_FDRATE_MASK;
  951. }
  952. else
  953. {
  954. fdctrl &= ~CAN_FDCTRL_FDRATE_MASK;
  955. }
  956. /* Before use "|=" operation for multi-bits field, CPU should clean previous Setting. */
  957. fdctrl = (fdctrl & ~CAN_FDCTRL_MBDSR0_MASK) | CAN_FDCTRL_MBDSR0(dataSize);
  958. #if defined(CAN_FDCTRL_MBDSR1_MASK)
  959. fdctrl = (fdctrl & ~CAN_FDCTRL_MBDSR1_MASK) | CAN_FDCTRL_MBDSR1(dataSize);
  960. #endif
  961. #if defined(CAN_FDCTRL_MBDSR2_MASK)
  962. fdctrl = (fdctrl & ~CAN_FDCTRL_MBDSR2_MASK) | CAN_FDCTRL_MBDSR2(dataSize);
  963. #endif
  964. #if defined(CAN_FDCTRL_MBDSR3_MASK)
  965. fdctrl = (fdctrl & ~CAN_FDCTRL_MBDSR3_MASK) | CAN_FDCTRL_MBDSR3(dataSize);
  966. #endif
  967. /* Enter Freeze Mode. */
  968. FLEXCAN_EnterFreezeMode(base);
  969. /* Enable CAN FD operation. */
  970. base->MCR |= CAN_MCR_FDEN_MASK;
  971. /* Clear SMP bit when CAN FD is enabled (CAN FD only can use one regular sample point plus one optional secondary
  972. * sampling point). */
  973. base->CTRL1 &= ~CAN_CTRL1_SMP_MASK;
  974. if (brs && !(pConfig->enableLoopBack))
  975. {
  976. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG)
  977. /* The TDC offset should be configured as shown in this equation : offset = DTSEG1 + 2 */
  978. if (((uint32_t)pConfig->timingConfig.fphaseSeg1 + pConfig->timingConfig.fpropSeg + 2U) *
  979. (pConfig->timingConfig.fpreDivider + 1U) <
  980. MAX_ETDCOFF)
  981. {
  982. base->ETDC =
  983. CAN_ETDC_ETDCEN_MASK | CAN_ETDC_TDMDIS(!pConfig->enableTransceiverDelayMeasure) |
  984. CAN_ETDC_ETDCOFF(((uint32_t)pConfig->timingConfig.fphaseSeg1 + pConfig->timingConfig.fpropSeg + 2U) *
  985. (pConfig->timingConfig.fpreDivider + 1U));
  986. }
  987. else
  988. {
  989. /* Enable the Transceiver Delay Compensation */
  990. base->ETDC = CAN_ETDC_ETDCEN_MASK | CAN_ETDC_TDMDIS(!pConfig->enableTransceiverDelayMeasure) |
  991. CAN_ETDC_ETDCOFF(MAX_ETDCOFF);
  992. }
  993. #else
  994. /* The TDC offset should be configured as shown in this equation : offset = PSEG1 + PROPSEG + 2 */
  995. if (((uint32_t)pConfig->timingConfig.fphaseSeg1 + pConfig->timingConfig.fpropSeg + 2U) *
  996. (pConfig->timingConfig.fpreDivider + 1U) <
  997. MAX_TDCOFF)
  998. {
  999. fdctrl =
  1000. (fdctrl & ~CAN_FDCTRL_TDCOFF_MASK) |
  1001. CAN_FDCTRL_TDCOFF(((uint32_t)pConfig->timingConfig.fphaseSeg1 + pConfig->timingConfig.fpropSeg + 2U) *
  1002. (pConfig->timingConfig.fpreDivider + 1U));
  1003. }
  1004. else
  1005. {
  1006. fdctrl = (fdctrl & ~CAN_FDCTRL_TDCOFF_MASK) | CAN_FDCTRL_TDCOFF(MAX_TDCOFF);
  1007. }
  1008. /* Enable the Transceiver Delay Compensation */
  1009. fdctrl = (fdctrl & ~CAN_FDCTRL_TDCEN_MASK) | CAN_FDCTRL_TDCEN_MASK;
  1010. #endif
  1011. }
  1012. /* update the FDCTL register. */
  1013. base->FDCTRL = fdctrl;
  1014. /* Enable CAN FD ISO mode by default. */
  1015. base->CTRL2 |= CAN_CTRL2_ISOCANFDEN_MASK;
  1016. /* Exit Freeze Mode. */
  1017. FLEXCAN_ExitFreezeMode(base);
  1018. }
  1019. #endif
  1020. /*!
  1021. * brief De-initializes a FlexCAN instance.
  1022. *
  1023. * This function disables the FlexCAN module clock and sets all register values
  1024. * to the reset value.
  1025. *
  1026. * param base FlexCAN peripheral base address.
  1027. */
  1028. void FLEXCAN_Deinit(CAN_Type *base)
  1029. {
  1030. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  1031. uint32_t instance;
  1032. #endif
  1033. /* Reset all Register Contents. */
  1034. FLEXCAN_Reset(base);
  1035. /* Disable FlexCAN module. */
  1036. FLEXCAN_Enable(base, false);
  1037. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  1038. instance = FLEXCAN_GetInstance(base);
  1039. #if defined(FLEXCAN_PERIPH_CLOCKS)
  1040. /* Disable FlexCAN serial clock. */
  1041. (void)CLOCK_DisableClock(s_flexcanPeriphClock[instance]);
  1042. #endif /* FLEXCAN_PERIPH_CLOCKS */
  1043. /* Disable FlexCAN clock. */
  1044. (void)CLOCK_DisableClock(s_flexcanClock[instance]);
  1045. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  1046. }
  1047. /*!
  1048. * brief Gets the default configuration structure.
  1049. *
  1050. * This function initializes the FlexCAN configuration structure to default values. The default
  1051. * values are as follows.
  1052. * flexcanConfig->clkSrc = kFLEXCAN_ClkSrc0;
  1053. * flexcanConfig->bitRate = 1000000U;
  1054. * flexcanConfig->bitRateFD = 2000000U;
  1055. * flexcanConfig->maxMbNum = 16;
  1056. * flexcanConfig->enableLoopBack = false;
  1057. * flexcanConfig->enableSelfWakeup = false;
  1058. * flexcanConfig->enableIndividMask = false;
  1059. * flexcanConfig->disableSelfReception = false;
  1060. * flexcanConfig->enableListenOnlyMode = false;
  1061. * flexcanConfig->enableDoze = false;
  1062. * flexcanConfig->enablePretendedeNetworking = false;
  1063. * flexcanConfig->enableMemoryErrorControl = true;
  1064. * flexcanConfig->enableNonCorrectableErrorEnterFreeze = true;
  1065. * flexcanConfig->enableTransceiverDelayMeasure = true;
  1066. * flexcanConfig.timingConfig = timingConfig;
  1067. *
  1068. * param pConfig Pointer to the FlexCAN configuration structure.
  1069. */
  1070. void FLEXCAN_GetDefaultConfig(flexcan_config_t *pConfig)
  1071. {
  1072. /* Assertion. */
  1073. assert(NULL != pConfig);
  1074. /* Initializes the configure structure to zero. */
  1075. (void)memset(pConfig, 0, sizeof(*pConfig));
  1076. /* Initialize FlexCAN Module config struct with default value. */
  1077. pConfig->clkSrc = kFLEXCAN_ClkSrc0;
  1078. pConfig->bitRate = 1000000U;
  1079. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  1080. pConfig->bitRateFD = 2000000U;
  1081. #endif
  1082. pConfig->maxMbNum = 16;
  1083. pConfig->enableLoopBack = false;
  1084. pConfig->enableTimerSync = true;
  1085. pConfig->enableSelfWakeup = false;
  1086. pConfig->wakeupSrc = kFLEXCAN_WakeupSrcUnfiltered;
  1087. pConfig->enableIndividMask = false;
  1088. pConfig->disableSelfReception = false;
  1089. pConfig->enableListenOnlyMode = false;
  1090. #if !(defined(FSL_FEATURE_FLEXCAN_HAS_NO_SUPV_SUPPORT) && FSL_FEATURE_FLEXCAN_HAS_NO_SUPV_SUPPORT)
  1091. pConfig->enableSupervisorMode = true;
  1092. #endif
  1093. #if (defined(FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT) && FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT)
  1094. pConfig->enableDoze = false;
  1095. #endif
  1096. #if (defined(FSL_FEATURE_FLEXCAN_HAS_PN_MODE) && FSL_FEATURE_FLEXCAN_HAS_PN_MODE)
  1097. pConfig->enablePretendedeNetworking = false;
  1098. #endif
  1099. #if (defined(FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL) && FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL)
  1100. pConfig->enableMemoryErrorControl = true;
  1101. pConfig->enableNonCorrectableErrorEnterFreeze = true;
  1102. #endif
  1103. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG)
  1104. pConfig->enableTransceiverDelayMeasure = true;
  1105. #endif
  1106. /* Default protocol timing configuration, nominal bit time quantum is 10 (80% SP), data bit time quantum is 5
  1107. * (60%). Suggest use FLEXCAN_CalculateImprovedTimingValues/FLEXCAN_FDCalculateImprovedTimingValues to get the
  1108. * improved timing configuration.*/
  1109. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  1110. pConfig->timingConfig.phaseSeg1 = 1;
  1111. pConfig->timingConfig.phaseSeg2 = 1;
  1112. pConfig->timingConfig.propSeg = 4;
  1113. pConfig->timingConfig.rJumpwidth = 1;
  1114. pConfig->timingConfig.fphaseSeg1 = 1;
  1115. pConfig->timingConfig.fphaseSeg2 = 1;
  1116. pConfig->timingConfig.fpropSeg = 0;
  1117. pConfig->timingConfig.frJumpwidth = 1;
  1118. #else
  1119. pConfig->timingConfig.phaseSeg1 = 1;
  1120. pConfig->timingConfig.phaseSeg2 = 1;
  1121. pConfig->timingConfig.propSeg = 4;
  1122. pConfig->timingConfig.rJumpwidth = 1;
  1123. #endif
  1124. }
  1125. #if (defined(FSL_FEATURE_FLEXCAN_HAS_PN_MODE) && FSL_FEATURE_FLEXCAN_HAS_PN_MODE)
  1126. /*!
  1127. * brief Configures the FlexCAN Pretended Networking mode.
  1128. *
  1129. * This function configures the FlexCAN Pretended Networking mode with given configuration.
  1130. *
  1131. * param base FlexCAN peripheral base address.
  1132. * param pConfig Pointer to the FlexCAN Rx FIFO configuration structure.
  1133. */
  1134. void FLEXCAN_SetPNConfig(CAN_Type *base, const flexcan_pn_config_t *pConfig)
  1135. {
  1136. /* Assertion. */
  1137. assert(NULL != pConfig);
  1138. assert(0U != pConfig->matchNum);
  1139. uint32_t pnctrl;
  1140. /* Enter Freeze Mode. */
  1141. FLEXCAN_EnterFreezeMode(base);
  1142. pnctrl = (pConfig->matchNum > 1U) ? CAN_CTRL1_PN_FCS(0x2U | (uint32_t)pConfig->matchSrc) :
  1143. CAN_CTRL1_PN_FCS(pConfig->matchSrc);
  1144. pnctrl |= (pConfig->enableMatch) ? (CAN_CTRL1_PN_WUMF_MSK_MASK) : 0U;
  1145. pnctrl |= (pConfig->enableTimeout) ? (CAN_CTRL1_PN_WTOF_MSK_MASK) : 0U;
  1146. pnctrl |= CAN_CTRL1_PN_NMATCH(pConfig->matchNum) | CAN_CTRL1_PN_IDFS(pConfig->idMatchMode) |
  1147. CAN_CTRL1_PN_PLFS(pConfig->dataMatchMode);
  1148. base->CTRL1_PN = pnctrl;
  1149. base->CTRL2_PN = CAN_CTRL2_PN_MATCHTO(pConfig->timeoutValue);
  1150. base->FLT_ID1 = pConfig->idLower;
  1151. base->FLT_ID2_IDMASK = pConfig->idUpper;
  1152. base->FLT_DLC = CAN_FLT_DLC_FLT_DLC_LO(pConfig->lengthLower) | CAN_FLT_DLC_FLT_DLC_HI(pConfig->lengthUpper);
  1153. base->PL1_LO = pConfig->lowerWord0;
  1154. base->PL1_HI = pConfig->lowerWord1;
  1155. base->PL2_PLMASK_LO = pConfig->upperWord0;
  1156. base->PL2_PLMASK_HI = pConfig->upperWord1;
  1157. FLEXCAN_ClearStatusFlags(base, (uint64_t)kFLEXCAN_PNMatchIntFlag | (uint64_t)kFLEXCAN_PNTimeoutIntFlag);
  1158. /* Exit Freeze Mode. */
  1159. FLEXCAN_ExitFreezeMode(base);
  1160. }
  1161. /*!
  1162. * brief Reads a FlexCAN Message from Wake Up MB.
  1163. *
  1164. * This function reads a CAN message from the FlexCAN Wake up Message Buffers. There are four Wake up Message Buffers
  1165. * (WMBs) used to store incoming messages in Pretended Networking mode. The WMB index indicates the arrival order. The
  1166. * last message is stored in WMB3.
  1167. *
  1168. * param base FlexCAN peripheral base address.
  1169. * param pRxFrame Pointer to CAN message frame structure for reception.
  1170. * param mbIdx The FlexCAN Wake up Message Buffer index. Range in 0x0 ~ 0x3.
  1171. * retval kStatus_Success - Read Message from Wake up Message Buffer successfully.
  1172. * retval kStatus_Fail - Wake up Message Buffer has no valid content.
  1173. */
  1174. status_t FLEXCAN_ReadPNWakeUpMB(CAN_Type *base, uint8_t mbIdx, flexcan_frame_t *pRxFrame)
  1175. {
  1176. /* Assertion. */
  1177. assert(NULL != pRxFrame);
  1178. assert(mbIdx <= 0x3U);
  1179. uint32_t cs_temp;
  1180. status_t status;
  1181. /* Check if Wake Up MB has valid content. */
  1182. if (CAN_WU_MTC_MCOUNTER(mbIdx) <= (base->WU_MTC & CAN_WU_MTC_MCOUNTER_MASK))
  1183. {
  1184. /* Read CS field of wake up Message Buffer. */
  1185. cs_temp = base->WMB[mbIdx].CS;
  1186. /* Store Message ID. */
  1187. pRxFrame->id = base->WMB[mbIdx].ID & (CAN_ID_EXT_MASK | CAN_ID_STD_MASK);
  1188. /* Get the message ID and format. */
  1189. pRxFrame->format = (cs_temp & CAN_CS_IDE_MASK) != 0U ? (uint8_t)kFLEXCAN_FrameFormatExtend :
  1190. (uint8_t)kFLEXCAN_FrameFormatStandard;
  1191. /* Get the message type. */
  1192. pRxFrame->type =
  1193. (cs_temp & CAN_CS_RTR_MASK) != 0U ? (uint8_t)kFLEXCAN_FrameTypeRemote : (uint8_t)kFLEXCAN_FrameTypeData;
  1194. /* Get the message length. */
  1195. pRxFrame->length = (uint8_t)((cs_temp & CAN_CS_DLC_MASK) >> CAN_CS_DLC_SHIFT);
  1196. /* Messages received during Pretended Networking mode don't have time stamps, and the respective field in the
  1197. WMB structure must be ignored. */
  1198. pRxFrame->timestamp = 0x0;
  1199. /* Store Message Payload. */
  1200. pRxFrame->dataWord0 = base->WMB[mbIdx].D03;
  1201. pRxFrame->dataWord1 = base->WMB[mbIdx].D47;
  1202. status = kStatus_Success;
  1203. }
  1204. else
  1205. {
  1206. status = kStatus_Fail;
  1207. }
  1208. return status;
  1209. }
  1210. #endif
  1211. /*!
  1212. * brief Sets the FlexCAN classical protocol timing characteristic.
  1213. *
  1214. * This function gives user settings to classical CAN or CAN FD nominal phase timing characteristic.
  1215. * The function is for an experienced user. For less experienced users, call the FLEXCAN_GetDefaultConfig()
  1216. * and get the default timing characteristicsthe, then call FLEXCAN_Init() and fill the
  1217. * bit rate field.
  1218. *
  1219. * note Calling FLEXCAN_SetTimingConfig() overrides the bit rate set
  1220. * in FLEXCAN_Init().
  1221. *
  1222. * param base FlexCAN peripheral base address.
  1223. * param pConfig Pointer to the timing configuration structure.
  1224. */
  1225. void FLEXCAN_SetTimingConfig(CAN_Type *base, const flexcan_timing_config_t *pConfig)
  1226. {
  1227. /* Assertion. */
  1228. assert(NULL != pConfig);
  1229. /* Enter Freeze Mode. */
  1230. FLEXCAN_EnterFreezeMode(base);
  1231. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  1232. if (0 != FSL_FEATURE_FLEXCAN_INSTANCE_HAS_FLEXIBLE_DATA_RATEn(base))
  1233. {
  1234. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG)
  1235. /* Enable extended Bit Timing register ENCBT. */
  1236. base->CTRL2 |= CAN_CTRL2_BTE_MASK;
  1237. /* Updating Timing Setting according to configuration structure. */
  1238. base->EPRS = (base->EPRS & (~CAN_EPRS_ENPRESDIV_MASK)) | CAN_EPRS_ENPRESDIV(pConfig->preDivider);
  1239. base->ENCBT = CAN_ENCBT_NRJW(pConfig->rJumpwidth) |
  1240. CAN_ENCBT_NTSEG1((uint32_t)pConfig->phaseSeg1 + pConfig->propSeg + 1U) |
  1241. CAN_ENCBT_NTSEG2(pConfig->phaseSeg2);
  1242. #else
  1243. /* On RT106x devices, a single write may be ignored, so it is necessary to read back the register value to
  1244. * determine whether the value is written successfully. */
  1245. do
  1246. {
  1247. /* Enable Bit Timing register CBT, updating Timing Setting according to configuration structure. */
  1248. base->CBT = CAN_CBT_BTF_MASK | CAN_CBT_EPRESDIV(pConfig->preDivider) | CAN_CBT_ERJW(pConfig->rJumpwidth) |
  1249. CAN_CBT_EPSEG1(pConfig->phaseSeg1) | CAN_CBT_EPSEG2(pConfig->phaseSeg2) |
  1250. CAN_CBT_EPROPSEG(pConfig->propSeg);
  1251. } while ((CAN_CBT_EPRESDIV(pConfig->preDivider) | CAN_CBT_ERJW(pConfig->rJumpwidth) |
  1252. CAN_CBT_EPSEG1(pConfig->phaseSeg1) | CAN_CBT_EPSEG2(pConfig->phaseSeg2) |
  1253. CAN_CBT_EPROPSEG(pConfig->propSeg)) !=
  1254. (base->CBT & (CAN_CBT_EPRESDIV_MASK | CAN_CBT_ERJW_MASK | CAN_CBT_EPSEG1_MASK | CAN_CBT_EPSEG2_MASK |
  1255. CAN_CBT_EPROPSEG_MASK)));
  1256. #endif
  1257. }
  1258. else
  1259. {
  1260. /* Cleaning previous Timing Setting. */
  1261. base->CTRL1 &= ~(CAN_CTRL1_PRESDIV_MASK | CAN_CTRL1_RJW_MASK | CAN_CTRL1_PSEG1_MASK | CAN_CTRL1_PSEG2_MASK |
  1262. CAN_CTRL1_PROPSEG_MASK);
  1263. /* Updating Timing Setting according to configuration structure. */
  1264. base->CTRL1 |= (CAN_CTRL1_PRESDIV(pConfig->preDivider) | CAN_CTRL1_RJW(pConfig->rJumpwidth) |
  1265. CAN_CTRL1_PSEG1(pConfig->phaseSeg1) | CAN_CTRL1_PSEG2(pConfig->phaseSeg2) |
  1266. CAN_CTRL1_PROPSEG(pConfig->propSeg));
  1267. }
  1268. #else
  1269. /* Cleaning previous Timing Setting. */
  1270. base->CTRL1 &= ~(CAN_CTRL1_PRESDIV_MASK | CAN_CTRL1_RJW_MASK | CAN_CTRL1_PSEG1_MASK | CAN_CTRL1_PSEG2_MASK |
  1271. CAN_CTRL1_PROPSEG_MASK);
  1272. /* Updating Timing Setting according to configuration structure. */
  1273. base->CTRL1 |= (CAN_CTRL1_PRESDIV(pConfig->preDivider) | CAN_CTRL1_RJW(pConfig->rJumpwidth) |
  1274. CAN_CTRL1_PSEG1(pConfig->phaseSeg1) | CAN_CTRL1_PSEG2(pConfig->phaseSeg2) |
  1275. CAN_CTRL1_PROPSEG(pConfig->propSeg));
  1276. #endif
  1277. /* Exit Freeze Mode. */
  1278. FLEXCAN_ExitFreezeMode(base);
  1279. }
  1280. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  1281. /*!
  1282. * brief Sets the FlexCAN FD data phase timing characteristic.
  1283. *
  1284. * This function gives user settings to CAN FD data phase timing characteristic.
  1285. * The function is for an experienced user. For less experienced users, call the FLEXCAN_GetDefaultConfig()
  1286. * and get the default timing characteristicsthe, then call FLEXCAN_FDInit() and fill the
  1287. * data phase bit rate field.
  1288. *
  1289. * note Calling FLEXCAN_SetFDTimingConfig() overrides the bit rate set
  1290. * in FLEXCAN_FDInit().
  1291. *
  1292. * param base FlexCAN peripheral base address.
  1293. * param pConfig Pointer to the timing configuration structure.
  1294. */
  1295. void FLEXCAN_SetFDTimingConfig(CAN_Type *base, const flexcan_timing_config_t *pConfig)
  1296. {
  1297. /* Assertion. */
  1298. assert(NULL != pConfig);
  1299. /* Enter Freeze Mode. */
  1300. FLEXCAN_EnterFreezeMode(base);
  1301. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG)
  1302. /* Enable extended Bit Timing register EDCBT. */
  1303. base->CTRL2 |= CAN_CTRL2_BTE_MASK;
  1304. base->EPRS = (base->EPRS & (~CAN_EPRS_EDPRESDIV_MASK)) | CAN_EPRS_EDPRESDIV(pConfig->fpreDivider);
  1305. base->EDCBT = CAN_EDCBT_DRJW(pConfig->frJumpwidth) | CAN_EDCBT_DTSEG2(pConfig->fphaseSeg2) |
  1306. CAN_EDCBT_DTSEG1((uint32_t)pConfig->fphaseSeg1 + pConfig->fpropSeg);
  1307. #else
  1308. /* Enable Bit Timing register FDCBT,*/
  1309. base->CBT |= CAN_CBT_BTF_MASK;
  1310. /* On RT106x devices, a single write may be ignored, so it is necessary to read back the register value to determine
  1311. * whether the value is written successfully. */
  1312. do
  1313. {
  1314. /* Updating Timing Setting according to configuration structure. */
  1315. base->FDCBT = (CAN_FDCBT_FPRESDIV(pConfig->fpreDivider) | CAN_FDCBT_FRJW(pConfig->frJumpwidth) |
  1316. CAN_FDCBT_FPSEG1(pConfig->fphaseSeg1) | CAN_FDCBT_FPSEG2(pConfig->fphaseSeg2) |
  1317. CAN_FDCBT_FPROPSEG(pConfig->fpropSeg));
  1318. } while ((CAN_FDCBT_FPRESDIV(pConfig->fpreDivider) | CAN_FDCBT_FRJW(pConfig->frJumpwidth) |
  1319. CAN_FDCBT_FPSEG1(pConfig->fphaseSeg1) | CAN_FDCBT_FPSEG2(pConfig->fphaseSeg2) |
  1320. CAN_FDCBT_FPROPSEG(pConfig->fpropSeg)) !=
  1321. (base->FDCBT & (CAN_FDCBT_FPRESDIV_MASK | CAN_FDCBT_FRJW_MASK | CAN_FDCBT_FPSEG1_MASK |
  1322. CAN_FDCBT_FPSEG2_MASK | CAN_FDCBT_FPROPSEG_MASK)));
  1323. #endif
  1324. /* Exit Freeze Mode. */
  1325. FLEXCAN_ExitFreezeMode(base);
  1326. }
  1327. #endif
  1328. /*!
  1329. * brief Sets the FlexCAN receive message buffer global mask.
  1330. *
  1331. * This function sets the global mask for the FlexCAN message buffer in a matching process.
  1332. * The configuration is only effective when the Rx individual mask is disabled in the FLEXCAN_Init().
  1333. *
  1334. * param base FlexCAN peripheral base address.
  1335. * param mask Rx Message Buffer Global Mask value.
  1336. */
  1337. void FLEXCAN_SetRxMbGlobalMask(CAN_Type *base, uint32_t mask)
  1338. {
  1339. /* Enter Freeze Mode. */
  1340. FLEXCAN_EnterFreezeMode(base);
  1341. /* Setting Rx Message Buffer Global Mask value. */
  1342. base->RXMGMASK = mask;
  1343. base->RX14MASK = mask;
  1344. base->RX15MASK = mask;
  1345. /* Exit Freeze Mode. */
  1346. FLEXCAN_ExitFreezeMode(base);
  1347. }
  1348. /*!
  1349. * brief Sets the FlexCAN receive FIFO global mask.
  1350. *
  1351. * This function sets the global mask for FlexCAN FIFO in a matching process.
  1352. *
  1353. * param base FlexCAN peripheral base address.
  1354. * param mask Rx Fifo Global Mask value.
  1355. */
  1356. void FLEXCAN_SetRxFifoGlobalMask(CAN_Type *base, uint32_t mask)
  1357. {
  1358. /* Enter Freeze Mode. */
  1359. FLEXCAN_EnterFreezeMode(base);
  1360. /* Setting Rx FIFO Global Mask value. */
  1361. base->RXFGMASK = mask;
  1362. /* Exit Freeze Mode. */
  1363. FLEXCAN_ExitFreezeMode(base);
  1364. }
  1365. /*!
  1366. * brief Sets the FlexCAN receive individual mask.
  1367. *
  1368. * This function sets the individual mask for the FlexCAN matching process.
  1369. * The configuration is only effective when the Rx individual mask is enabled in the FLEXCAN_Init().
  1370. * If the Rx FIFO is disabled, the individual mask is applied to the corresponding Message Buffer.
  1371. * If the Rx FIFO is enabled, the individual mask for Rx FIFO occupied Message Buffer is applied to
  1372. * the Rx Filter with the same index. Note that only the first 32
  1373. * individual masks can be used as the Rx FIFO filter mask.
  1374. *
  1375. * param base FlexCAN peripheral base address.
  1376. * param maskIdx The Index of individual Mask.
  1377. * param mask Rx Individual Mask value.
  1378. */
  1379. void FLEXCAN_SetRxIndividualMask(CAN_Type *base, uint8_t maskIdx, uint32_t mask)
  1380. {
  1381. assert(maskIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  1382. /* Enter Freeze Mode. */
  1383. FLEXCAN_EnterFreezeMode(base);
  1384. /* Setting Rx Individual Mask value. */
  1385. base->RXIMR[maskIdx] = mask;
  1386. /* Exit Freeze Mode. */
  1387. FLEXCAN_ExitFreezeMode(base);
  1388. }
  1389. /*!
  1390. * brief Configures a FlexCAN transmit message buffer.
  1391. *
  1392. * This function aborts the previous transmission, cleans the Message Buffer, and
  1393. * configures it as a Transmit Message Buffer.
  1394. *
  1395. * param base FlexCAN peripheral base address.
  1396. * param mbIdx The Message Buffer index.
  1397. * param enable Enable/disable Tx Message Buffer.
  1398. * - true: Enable Tx Message Buffer.
  1399. * - false: Disable Tx Message Buffer.
  1400. */
  1401. void FLEXCAN_SetTxMbConfig(CAN_Type *base, uint8_t mbIdx, bool enable)
  1402. {
  1403. /* Assertion. */
  1404. assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  1405. #if !defined(NDEBUG)
  1406. assert(!FLEXCAN_IsMbOccupied(base, mbIdx));
  1407. #endif
  1408. /* Inactivate Message Buffer. */
  1409. if (enable)
  1410. {
  1411. base->MB[mbIdx].CS = CAN_CS_CODE(kFLEXCAN_TxMbInactive);
  1412. }
  1413. else
  1414. {
  1415. base->MB[mbIdx].CS = 0;
  1416. }
  1417. /* Clean Message Buffer content. */
  1418. base->MB[mbIdx].ID = 0x0;
  1419. base->MB[mbIdx].WORD0 = 0x0;
  1420. base->MB[mbIdx].WORD1 = 0x0;
  1421. }
  1422. /*!
  1423. * brief Calculates the segment values for a single bit time for classical CAN.
  1424. *
  1425. * This function use to calculates the Classical CAN segment values which will be set in CTRL1/CBT/ENCBT register.
  1426. *
  1427. * param bitRate The classical CAN bit rate in bps.
  1428. * param base FlexCAN peripheral base address.
  1429. * param tqNum Number of time quantas per bit, range in 8 ~ 25 when use CTRL1, range in 8 ~ 129 when use CBT, range in
  1430. * 8 ~ 385 when use ENCBT. param pTimingConfig Pointer to the FlexCAN timing configuration structure.
  1431. */
  1432. static void FLEXCAN_GetSegments(CAN_Type *base,
  1433. uint32_t bitRate,
  1434. uint32_t tqNum,
  1435. flexcan_timing_config_t *pTimingConfig)
  1436. {
  1437. uint32_t ideal_sp;
  1438. uint32_t seg1Max, seg2Max, proSegMax, sjwMAX;
  1439. uint32_t seg1Temp;
  1440. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  1441. if (0 != FSL_FEATURE_FLEXCAN_INSTANCE_HAS_FLEXIBLE_DATA_RATEn(base))
  1442. {
  1443. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG)
  1444. /* Maximum value allowed in ENCBT register. */
  1445. seg1Max = MAX_NTSEG2 + 1U;
  1446. proSegMax = MAX_NTSEG1 - MAX_NTSEG2;
  1447. seg2Max = MAX_NTSEG2 + 1U;
  1448. sjwMAX = MAX_NRJW + 1U;
  1449. #else
  1450. /* Maximum value allowed in CBT register. */
  1451. seg1Max = MAX_EPSEG1 + 1U;
  1452. proSegMax = MAX_EPROPSEG + 1U;
  1453. seg2Max = MAX_EPSEG2 + 1U;
  1454. sjwMAX = MAX_ERJW + 1U;
  1455. #endif
  1456. }
  1457. else
  1458. {
  1459. /* Maximum value allowed in CTRL1 register. */
  1460. seg1Max = MAX_PSEG1 + 1U;
  1461. proSegMax = MAX_PROPSEG + 1U;
  1462. seg2Max = MAX_PSEG2 + 1U;
  1463. sjwMAX = MAX_RJW + 1U;
  1464. }
  1465. #else
  1466. /* Maximum value allowed in CTRL1 register. */
  1467. seg1Max = MAX_PSEG1 + 1U;
  1468. proSegMax = MAX_PROPSEG + 1U;
  1469. seg2Max = MAX_PSEG2 + 1U;
  1470. sjwMAX = MAX_RJW + 1U;
  1471. #endif
  1472. /* Try to find the ideal sample point, according to CiA 301 doc.*/
  1473. if (bitRate == 1000000U)
  1474. {
  1475. ideal_sp = IDEAL_SP_LOW;
  1476. }
  1477. else if (bitRate >= 800000U)
  1478. {
  1479. ideal_sp = IDEAL_SP_MID;
  1480. }
  1481. else
  1482. {
  1483. ideal_sp = IDEAL_SP_HIGH;
  1484. }
  1485. /* Calculates phaseSeg2. */
  1486. pTimingConfig->phaseSeg2 = (uint8_t)(tqNum - (tqNum * ideal_sp) / (uint32_t)IDEAL_SP_FACTOR);
  1487. if (pTimingConfig->phaseSeg2 < MIN_TIME_SEGMENT2)
  1488. {
  1489. pTimingConfig->phaseSeg2 = MIN_TIME_SEGMENT2;
  1490. }
  1491. else if (pTimingConfig->phaseSeg2 > seg2Max)
  1492. {
  1493. pTimingConfig->phaseSeg2 = (uint8_t)seg2Max;
  1494. }
  1495. else
  1496. {
  1497. ; /* Intentional empty */
  1498. }
  1499. /* Calculates phaseSeg1 and propSeg and try to make phaseSeg1 equal to phaseSeg2. */
  1500. if ((tqNum - pTimingConfig->phaseSeg2 - 1U) > (seg1Max + proSegMax))
  1501. {
  1502. seg1Temp = seg1Max + proSegMax;
  1503. pTimingConfig->phaseSeg2 = (uint8_t)(tqNum - 1U - seg1Temp);
  1504. }
  1505. else
  1506. {
  1507. seg1Temp = tqNum - pTimingConfig->phaseSeg2 - 1U;
  1508. }
  1509. if (seg1Temp > (pTimingConfig->phaseSeg2 + proSegMax))
  1510. {
  1511. pTimingConfig->propSeg = (uint8_t)proSegMax;
  1512. pTimingConfig->phaseSeg1 = (uint8_t)(seg1Temp - proSegMax);
  1513. }
  1514. else if (seg1Temp > pTimingConfig->phaseSeg2)
  1515. {
  1516. pTimingConfig->propSeg = (uint8_t)(seg1Temp - pTimingConfig->phaseSeg2);
  1517. pTimingConfig->phaseSeg1 = pTimingConfig->phaseSeg2;
  1518. }
  1519. else
  1520. {
  1521. pTimingConfig->propSeg = 1U;
  1522. pTimingConfig->phaseSeg1 = pTimingConfig->phaseSeg2 - 1U;
  1523. }
  1524. /* rJumpwidth (sjw) is the minimum value of phaseSeg1 and phaseSeg2. */
  1525. pTimingConfig->rJumpwidth =
  1526. (pTimingConfig->phaseSeg1 > pTimingConfig->phaseSeg2) ? pTimingConfig->phaseSeg2 : pTimingConfig->phaseSeg1;
  1527. if (pTimingConfig->rJumpwidth > sjwMAX)
  1528. {
  1529. pTimingConfig->rJumpwidth = (uint8_t)sjwMAX;
  1530. }
  1531. pTimingConfig->phaseSeg1 -= 1U;
  1532. pTimingConfig->phaseSeg2 -= 1U;
  1533. pTimingConfig->propSeg -= 1U;
  1534. pTimingConfig->rJumpwidth -= 1U;
  1535. }
  1536. /*!
  1537. * brief Calculates the improved timing values by specific bit Rates for classical CAN.
  1538. *
  1539. * This function use to calculates the Classical CAN timing values according to the given bit rate. The Calculated
  1540. * timing values will be set in CTRL1/CBT/ENCBT register. The calculation is based on the recommendation of the CiA 301
  1541. * v4.2.0 and previous version document.
  1542. *
  1543. * param base FlexCAN peripheral base address.
  1544. * param bitRate The classical CAN speed in bps defined by user, should be less than or equal to 1Mbps.
  1545. * param sourceClock_Hz The Source clock frequency in Hz.
  1546. * param pTimingConfig Pointer to the FlexCAN timing configuration structure.
  1547. *
  1548. * return TRUE if timing configuration found, FALSE if failed to find configuration.
  1549. */
  1550. bool FLEXCAN_CalculateImprovedTimingValues(CAN_Type *base,
  1551. uint32_t bitRate,
  1552. uint32_t sourceClock_Hz,
  1553. flexcan_timing_config_t *pTimingConfig)
  1554. {
  1555. /* Observe bit rate maximums. */
  1556. assert(bitRate <= MAX_CAN_BITRATE);
  1557. uint32_t clk;
  1558. uint32_t tqNum, tqMin, pdivMAX;
  1559. uint32_t spTemp = 1000U;
  1560. flexcan_timing_config_t configTemp = {0};
  1561. bool fgRet = false;
  1562. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  1563. if (0 != FSL_FEATURE_FLEXCAN_INSTANCE_HAS_FLEXIBLE_DATA_RATEn(base))
  1564. {
  1565. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG)
  1566. /* Auto Improved Protocal timing for ENCBT. */
  1567. tqNum = ENCBT_MAX_TIME_QUANTA;
  1568. tqMin = ENCBT_MIN_TIME_QUANTA;
  1569. pdivMAX = MAX_ENPRESDIV;
  1570. #else
  1571. /* Auto Improved Protocal timing for CBT. */
  1572. tqNum = CBT_MAX_TIME_QUANTA;
  1573. tqMin = CBT_MIN_TIME_QUANTA;
  1574. pdivMAX = MAX_PRESDIV;
  1575. #endif
  1576. }
  1577. else
  1578. {
  1579. /* Auto Improved Protocal timing for CTRL1. */
  1580. tqNum = CTRL1_MAX_TIME_QUANTA;
  1581. tqMin = CTRL1_MIN_TIME_QUANTA;
  1582. pdivMAX = MAX_PRESDIV;
  1583. }
  1584. #else
  1585. /* Auto Improved Protocal timing for CTRL1. */
  1586. tqNum = CTRL1_MAX_TIME_QUANTA;
  1587. tqMin = CTRL1_MIN_TIME_QUANTA;
  1588. pdivMAX = MAX_PRESDIV;
  1589. #endif
  1590. do
  1591. {
  1592. clk = bitRate * tqNum;
  1593. if (clk > sourceClock_Hz)
  1594. {
  1595. continue; /* tqNum too large, clk has been exceed sourceClock_Hz. */
  1596. }
  1597. if ((sourceClock_Hz / clk * clk) != sourceClock_Hz)
  1598. {
  1599. continue; /* Non-supporting: the frequency of clock source is not divisible by target bit rate, the user
  1600. should change a divisible bit rate. */
  1601. }
  1602. configTemp.preDivider = (uint16_t)(sourceClock_Hz / clk) - 1U;
  1603. if (configTemp.preDivider > pdivMAX)
  1604. {
  1605. break; /* The frequency of source clock is too large or the bit rate is too small, the pre-divider could
  1606. not handle it. */
  1607. }
  1608. /* Calculates the best timing configuration under current tqNum. */
  1609. FLEXCAN_GetSegments(base, bitRate, tqNum, &configTemp);
  1610. /* Determine whether the calculated timing configuration can get the optimal sampling point. */
  1611. if (((((uint32_t)configTemp.phaseSeg2 + 1U) * 1000U) / tqNum) < spTemp)
  1612. {
  1613. spTemp = (((uint32_t)configTemp.phaseSeg2 + 1U) * 1000U) / tqNum;
  1614. pTimingConfig->preDivider = configTemp.preDivider;
  1615. pTimingConfig->rJumpwidth = configTemp.rJumpwidth;
  1616. pTimingConfig->phaseSeg1 = configTemp.phaseSeg1;
  1617. pTimingConfig->phaseSeg2 = configTemp.phaseSeg2;
  1618. pTimingConfig->propSeg = configTemp.propSeg;
  1619. }
  1620. fgRet = true;
  1621. } while (--tqNum >= tqMin);
  1622. return fgRet;
  1623. }
  1624. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  1625. /*!
  1626. * brief Get Mailbox offset number by dword.
  1627. *
  1628. * This function gets the offset number of the specified mailbox.
  1629. * Mailbox is not consecutive between memory regions when payload is not 8 bytes
  1630. * so need to calculate the specified mailbox address.
  1631. * For example, in the first memory region, MB[0].CS address is 0x4002_4080. For 32 bytes
  1632. * payload frame, the second mailbox is ((1/12)*512 + 1%12*40)/4 = 10, meaning 10 dword
  1633. * after the 0x4002_4080, which is actually the address of mailbox MB[1].CS.
  1634. *
  1635. * param base FlexCAN peripheral base address.
  1636. * param mbIdx Mailbox index.
  1637. */
  1638. static uint32_t FLEXCAN_GetFDMailboxOffset(CAN_Type *base, uint8_t mbIdx)
  1639. {
  1640. uint32_t offset = 0;
  1641. uint32_t dataSize = (base->FDCTRL & CAN_FDCTRL_MBDSR0_MASK) >> CAN_FDCTRL_MBDSR0_SHIFT;
  1642. switch (dataSize)
  1643. {
  1644. case (uint32_t)kFLEXCAN_8BperMB:
  1645. offset = (((uint32_t)mbIdx / 32U) * 512U + ((uint32_t)mbIdx % 32U) * 16U);
  1646. break;
  1647. case (uint32_t)kFLEXCAN_16BperMB:
  1648. offset = (((uint32_t)mbIdx / 21U) * 512U + ((uint32_t)mbIdx % 21U) * 24U);
  1649. break;
  1650. case (uint32_t)kFLEXCAN_32BperMB:
  1651. offset = (((uint32_t)mbIdx / 12U) * 512U + ((uint32_t)mbIdx % 12U) * 40U);
  1652. break;
  1653. case (uint32_t)kFLEXCAN_64BperMB:
  1654. offset = (((uint32_t)mbIdx / 7U) * 512U + ((uint32_t)mbIdx % 7U) * 72U);
  1655. break;
  1656. default:
  1657. /* All the cases have been listed above, the default clause should not be reached. */
  1658. assert(false);
  1659. break;
  1660. }
  1661. /* To get the dword aligned offset, need to divide by 4. */
  1662. offset = offset / 4U;
  1663. return offset;
  1664. }
  1665. /*!
  1666. * brief Calculates the segment values for a single bit time for CAN FD data phase.
  1667. *
  1668. * This function use to calculates the CAN FD data phase segment values which will be set in CFDCBT/EDCBT
  1669. * register.
  1670. *
  1671. * param bitRateFD CAN FD data phase bit rate.
  1672. * param tqNum Number of time quanta per bit
  1673. * param pTimingConfig Pointer to the FlexCAN timing configuration structure.
  1674. */
  1675. static void FLEXCAN_FDGetSegments(uint32_t bitRateFD, uint32_t tqNum, flexcan_timing_config_t *pTimingConfig)
  1676. {
  1677. uint32_t ideal_sp;
  1678. uint32_t seg1Max, proSegMax, seg2Max, sjwMAX;
  1679. uint32_t seg1Temp;
  1680. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG)
  1681. /* Maximum value allowed in EDCBT register. */
  1682. seg1Max = MAX_DTSEG2 + 1U;
  1683. proSegMax = MAX_DTSEG1 - MAX_DTSEG2;
  1684. seg2Max = MAX_DTSEG2 + 1U;
  1685. sjwMAX = MAX_DRJW + 1U;
  1686. #else
  1687. /* Maximum value allowed in FDCBT register. */
  1688. seg1Max = MAX_FPSEG1 + 1U;
  1689. proSegMax = MAX_FPROPSEG;
  1690. seg2Max = MAX_FPSEG2 + 1U;
  1691. sjwMAX = MAX_FRJW + 1U;
  1692. #endif
  1693. /* According to CiA doc 1301 v1.0.0, which specified data phase sample point postion for CAN FD at 80 MHz. */
  1694. if (bitRateFD <= 1000000U)
  1695. {
  1696. ideal_sp = IDEAL_DATA_SP_1;
  1697. }
  1698. else if (bitRateFD <= 2000000U)
  1699. {
  1700. ideal_sp = IDEAL_DATA_SP_2;
  1701. }
  1702. else if (bitRateFD <= 4000000U)
  1703. {
  1704. ideal_sp = IDEAL_DATA_SP_3;
  1705. }
  1706. else
  1707. {
  1708. ideal_sp = IDEAL_DATA_SP_4;
  1709. }
  1710. /* Calculates fphaseSeg2. */
  1711. pTimingConfig->fphaseSeg2 = (uint8_t)(tqNum - (tqNum * ideal_sp) / (uint32_t)IDEAL_SP_FACTOR);
  1712. if (pTimingConfig->fphaseSeg2 < MIN_TIME_SEGMENT2)
  1713. {
  1714. pTimingConfig->fphaseSeg2 = MIN_TIME_SEGMENT2;
  1715. }
  1716. else if (pTimingConfig->fphaseSeg2 > seg2Max)
  1717. {
  1718. pTimingConfig->fphaseSeg2 = (uint8_t)seg2Max;
  1719. }
  1720. else
  1721. {
  1722. ; /* Intentional empty */
  1723. }
  1724. /* Calculates fphaseSeg1 and fpropSeg and try to make phaseSeg1 equal to phaseSeg2 */
  1725. if ((tqNum - pTimingConfig->fphaseSeg2 - 1U) > (seg1Max + proSegMax))
  1726. {
  1727. seg1Temp = seg1Max + proSegMax;
  1728. pTimingConfig->fphaseSeg2 = (uint8_t)(tqNum - 1U - seg1Temp);
  1729. }
  1730. else
  1731. {
  1732. seg1Temp = tqNum - pTimingConfig->fphaseSeg2 - 1U;
  1733. }
  1734. if (seg1Temp > (pTimingConfig->fphaseSeg2 + proSegMax))
  1735. {
  1736. pTimingConfig->fpropSeg = (uint8_t)proSegMax;
  1737. pTimingConfig->fphaseSeg1 = (uint8_t)(seg1Temp - proSegMax);
  1738. }
  1739. else if (seg1Temp > pTimingConfig->fphaseSeg2)
  1740. {
  1741. pTimingConfig->fpropSeg = (uint8_t)(seg1Temp - pTimingConfig->fphaseSeg2);
  1742. pTimingConfig->fphaseSeg1 = pTimingConfig->fphaseSeg2;
  1743. }
  1744. else
  1745. {
  1746. pTimingConfig->fpropSeg = 0U;
  1747. pTimingConfig->fphaseSeg1 = (uint8_t)seg1Temp;
  1748. }
  1749. /* rJumpwidth (sjw) is the minimum value of phaseSeg1 and phaseSeg2. */
  1750. pTimingConfig->frJumpwidth =
  1751. (pTimingConfig->fphaseSeg1 > pTimingConfig->fphaseSeg2) ? pTimingConfig->fphaseSeg2 : pTimingConfig->fphaseSeg1;
  1752. if (pTimingConfig->frJumpwidth > sjwMAX)
  1753. {
  1754. pTimingConfig->frJumpwidth = (uint8_t)sjwMAX;
  1755. }
  1756. pTimingConfig->fphaseSeg1 -= 1U;
  1757. pTimingConfig->fphaseSeg2 -= 1U;
  1758. pTimingConfig->frJumpwidth -= 1U;
  1759. }
  1760. /*!
  1761. * brief Calculates the improved timing values by specific bit rate for CAN FD nominal phase.
  1762. *
  1763. * This function use to calculates the CAN FD nominal phase timing values according to the given nominal phase bit rate.
  1764. * The Calculated timing values will be set in CBT/ENCBT registers. The calculation is based on the recommendation of
  1765. * the CiA 1301 v1.0.0 document.
  1766. *
  1767. * param bitRate The CAN FD nominal phase speed in bps defined by user, should be less than or equal to 1Mbps.
  1768. * param sourceClock_Hz The Source clock frequency in Hz.
  1769. * param pTimingConfig Pointer to the FlexCAN timing configuration structure.
  1770. *
  1771. * return TRUE if timing configuration found, FALSE if failed to find configuration.
  1772. */
  1773. static bool FLEXCAN_CalculateImprovedNominalTimingValues(uint32_t bitRate,
  1774. uint32_t sourceClock_Hz,
  1775. flexcan_timing_config_t *pTimingConfig)
  1776. {
  1777. /* Observe bit rate maximums. */
  1778. assert(bitRate <= MAX_CAN_BITRATE);
  1779. uint32_t clk;
  1780. uint32_t tqNum, tqMin, pdivMAX, seg1Max, proSegMax, seg2Max, sjwMAX, seg1Temp;
  1781. uint32_t spTemp = 1000U;
  1782. flexcan_timing_config_t configTemp = {0};
  1783. bool fgRet = false;
  1784. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG)
  1785. /* Auto Improved Protocal timing for ENCBT. */
  1786. tqNum = ENCBT_MAX_TIME_QUANTA;
  1787. tqMin = ENCBT_MIN_TIME_QUANTA;
  1788. pdivMAX = MAX_ENPRESDIV;
  1789. seg1Max = MAX_NTSEG2 + 1U;
  1790. proSegMax = MAX_NTSEG1 - MAX_NTSEG2;
  1791. seg2Max = MAX_NTSEG2 + 1U;
  1792. sjwMAX = MAX_NRJW + 1U;
  1793. #else
  1794. /* Auto Improved Protocal timing for CBT. */
  1795. tqNum = CBT_MAX_TIME_QUANTA;
  1796. tqMin = CBT_MIN_TIME_QUANTA;
  1797. pdivMAX = MAX_PRESDIV;
  1798. seg1Max = MAX_EPSEG1 + 1U;
  1799. proSegMax = MAX_EPROPSEG + 1U;
  1800. seg2Max = MAX_EPSEG2 + 1U;
  1801. sjwMAX = MAX_ERJW + 1U;
  1802. #endif
  1803. do
  1804. {
  1805. clk = bitRate * tqNum;
  1806. if (clk > sourceClock_Hz)
  1807. {
  1808. continue; /* tqNum too large, clk has been exceed sourceClock_Hz. */
  1809. }
  1810. if ((sourceClock_Hz / clk * clk) != sourceClock_Hz)
  1811. {
  1812. continue; /* Non-supporting: the frequency of clock source is not divisible by target bit rate, the user
  1813. should change a divisible bit rate. */
  1814. }
  1815. configTemp.preDivider = (uint16_t)(sourceClock_Hz / clk) - 1U;
  1816. if (configTemp.preDivider > pdivMAX)
  1817. {
  1818. break; /* The frequency of source clock is too large or the bit rate is too small, the pre-divider could
  1819. not handle it. */
  1820. }
  1821. /* Calculates the best timing configuration under current tqNum. */
  1822. configTemp.phaseSeg2 = (uint8_t)(tqNum - (tqNum * IDEAL_NOMINAL_SP) / (uint32_t)IDEAL_SP_FACTOR);
  1823. if (configTemp.phaseSeg2 < MIN_TIME_SEGMENT2)
  1824. {
  1825. configTemp.phaseSeg2 = MIN_TIME_SEGMENT2;
  1826. }
  1827. else if (configTemp.phaseSeg2 > seg2Max)
  1828. {
  1829. configTemp.phaseSeg2 = (uint8_t)seg2Max;
  1830. }
  1831. else
  1832. {
  1833. ; /* Intentional empty */
  1834. }
  1835. /* Calculates phaseSeg1 and propSeg and try to make phaseSeg1 equal to phaseSeg2. */
  1836. if ((tqNum - configTemp.phaseSeg2 - 1U) > (seg1Max + proSegMax))
  1837. {
  1838. seg1Temp = seg1Max + proSegMax;
  1839. configTemp.phaseSeg2 = (uint8_t)(tqNum - 1U - seg1Temp);
  1840. }
  1841. else
  1842. {
  1843. seg1Temp = tqNum - configTemp.phaseSeg2 - 1U;
  1844. }
  1845. if (seg1Temp > (configTemp.phaseSeg2 + proSegMax))
  1846. {
  1847. configTemp.propSeg = (uint8_t)proSegMax;
  1848. configTemp.phaseSeg1 = (uint8_t)(seg1Temp - proSegMax);
  1849. }
  1850. else
  1851. {
  1852. configTemp.propSeg = (uint8_t)(seg1Temp - configTemp.phaseSeg2);
  1853. configTemp.phaseSeg1 = configTemp.phaseSeg2;
  1854. }
  1855. /* rJumpwidth (sjw) is the minimum value of phaseSeg1 and phaseSeg2. */
  1856. configTemp.rJumpwidth =
  1857. (configTemp.phaseSeg1 > configTemp.phaseSeg2) ? configTemp.phaseSeg2 : configTemp.phaseSeg1;
  1858. if (configTemp.rJumpwidth > sjwMAX)
  1859. {
  1860. configTemp.rJumpwidth = (uint8_t)sjwMAX;
  1861. }
  1862. configTemp.phaseSeg1 -= 1U;
  1863. configTemp.phaseSeg2 -= 1U;
  1864. configTemp.propSeg -= 1U;
  1865. configTemp.rJumpwidth -= 1U;
  1866. if (((((uint32_t)configTemp.phaseSeg2 + 1U) * 1000U) / tqNum) < spTemp)
  1867. {
  1868. spTemp = (((uint32_t)configTemp.phaseSeg2 + 1U) * 1000U) / tqNum;
  1869. pTimingConfig->preDivider = configTemp.preDivider;
  1870. pTimingConfig->rJumpwidth = configTemp.rJumpwidth;
  1871. pTimingConfig->phaseSeg1 = configTemp.phaseSeg1;
  1872. pTimingConfig->phaseSeg2 = configTemp.phaseSeg2;
  1873. pTimingConfig->propSeg = configTemp.propSeg;
  1874. }
  1875. fgRet = true;
  1876. } while (--tqNum >= tqMin);
  1877. return fgRet;
  1878. }
  1879. /*!
  1880. * brief Calculates the improved timing values by specific bit rates for CAN FD.
  1881. *
  1882. * This function use to calculates the CAN FD timing values according to the given nominal phase bit rate and data phase
  1883. * bit rate. The Calculated timing values will be set in CBT/ENCBT and FDCBT/EDCBT registers. The calculation is based
  1884. * on the recommendation of the CiA 1301 v1.0.0 document.
  1885. *
  1886. * param bitRate The CAN FD nominal phase speed in bps defined by user.
  1887. * param bitRateFD The CAN FD data phase speed in bps defined by user. Equal to bitRate means disable bit rate
  1888. * switching. param sourceClock_Hz The Source clock frequency in Hz. param pTimingConfig Pointer to the FlexCAN timing
  1889. * configuration structure.
  1890. *
  1891. * return TRUE if timing configuration found, FALSE if failed to find configuration
  1892. */
  1893. bool FLEXCAN_FDCalculateImprovedTimingValues(CAN_Type *base,
  1894. uint32_t bitRate,
  1895. uint32_t bitRateFD,
  1896. uint32_t sourceClock_Hz,
  1897. flexcan_timing_config_t *pTimingConfig)
  1898. {
  1899. /* Observe bit rate maximums */
  1900. assert(bitRate <= MAX_CANFD_BITRATE);
  1901. assert(bitRateFD <= MAX_CANFD_BITRATE);
  1902. /* Data phase bit rate need greater or equal to nominal phase bit rate. */
  1903. assert(bitRate <= bitRateFD);
  1904. uint32_t clk;
  1905. uint32_t tqMin, pdivMAX, tqTemp;
  1906. bool fgRet = false;
  1907. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_BIT_TIMING_REG)
  1908. /* Auto Improved Protocal timing for EDCBT. */
  1909. tqTemp = EDCBT_MAX_TIME_QUANTA;
  1910. tqMin = EDCBT_MIN_TIME_QUANTA;
  1911. pdivMAX = MAX_EDPRESDIV;
  1912. #else
  1913. /* Auto Improved Protocal timing for FDCBT. */
  1914. tqTemp = FDCBT_MAX_TIME_QUANTA;
  1915. tqMin = FDCBT_MIN_TIME_QUANTA;
  1916. pdivMAX = MAX_FPRESDIV;
  1917. #endif
  1918. if (bitRate != bitRateFD)
  1919. {
  1920. /* To minimize errors when processing FD frames, try to get the same bit rate prescaler value for nominal phase
  1921. and data phase. */
  1922. do
  1923. {
  1924. clk = bitRateFD * tqTemp;
  1925. if (clk > sourceClock_Hz)
  1926. {
  1927. continue; /* tqTemp too large, clk x tqTemp has been exceed sourceClock_Hz. */
  1928. }
  1929. if ((sourceClock_Hz / clk * clk) != sourceClock_Hz)
  1930. {
  1931. continue; /* the frequency of clock source is not divisible by target bit rate. */
  1932. }
  1933. pTimingConfig->fpreDivider = (uint16_t)(sourceClock_Hz / clk) - 1U;
  1934. if (pTimingConfig->fpreDivider > pdivMAX)
  1935. {
  1936. break; /* The frequency of source clock is too large or the bit rate is too small, the pre-divider
  1937. could not handle it. */
  1938. }
  1939. /* Calculates the best data phase timing configuration. */
  1940. FLEXCAN_FDGetSegments(bitRateFD, tqTemp, pTimingConfig);
  1941. if (FLEXCAN_CalculateImprovedNominalTimingValues(
  1942. bitRate, sourceClock_Hz / ((uint32_t)pTimingConfig->fpreDivider + 1U), pTimingConfig))
  1943. {
  1944. fgRet = true;
  1945. if (pTimingConfig->preDivider == 0U)
  1946. {
  1947. pTimingConfig->preDivider = pTimingConfig->fpreDivider;
  1948. break;
  1949. }
  1950. else
  1951. {
  1952. pTimingConfig->preDivider =
  1953. (pTimingConfig->preDivider + 1U) * (pTimingConfig->fpreDivider + 1U) - 1U;
  1954. continue;
  1955. }
  1956. }
  1957. } while (--tqTemp >= tqMin);
  1958. }
  1959. else
  1960. {
  1961. if (FLEXCAN_CalculateImprovedNominalTimingValues(bitRate, sourceClock_Hz, pTimingConfig))
  1962. {
  1963. /* No need data phase timing configuration, data phase rate equal to nominal phase rate, user don't use Brs
  1964. feature. */
  1965. pTimingConfig->fpreDivider = 0U;
  1966. pTimingConfig->frJumpwidth = 0U;
  1967. pTimingConfig->fphaseSeg1 = 0U;
  1968. pTimingConfig->fphaseSeg2 = 0U;
  1969. pTimingConfig->fpropSeg = 0U;
  1970. fgRet = true;
  1971. }
  1972. }
  1973. return fgRet;
  1974. }
  1975. /*!
  1976. * brief Configures a FlexCAN transmit message buffer.
  1977. *
  1978. * This function aborts the previous transmission, cleans the Message Buffer, and
  1979. * configures it as a Transmit Message Buffer.
  1980. *
  1981. * param base FlexCAN peripheral base address.
  1982. * param mbIdx The Message Buffer index.
  1983. * param enable Enable/disable Tx Message Buffer.
  1984. * - true: Enable Tx Message Buffer.
  1985. * - false: Disable Tx Message Buffer.
  1986. */
  1987. void FLEXCAN_SetFDTxMbConfig(CAN_Type *base, uint8_t mbIdx, bool enable)
  1988. {
  1989. /* Assertion. */
  1990. assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  1991. #if !defined(NDEBUG)
  1992. assert(!FLEXCAN_IsMbOccupied(base, mbIdx));
  1993. #endif
  1994. uint8_t cnt = 0;
  1995. uint8_t payload_dword = 1;
  1996. uint32_t dataSize;
  1997. dataSize = (base->FDCTRL & CAN_FDCTRL_MBDSR0_MASK) >> CAN_FDCTRL_MBDSR0_SHIFT;
  1998. volatile uint32_t *mbAddr = &(base->MB[0].CS);
  1999. uint32_t offset = FLEXCAN_GetFDMailboxOffset(base, mbIdx);
  2000. #if ((defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) || \
  2001. (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829))
  2002. uint32_t availoffset = FLEXCAN_GetFDMailboxOffset(base, FLEXCAN_GetFirstValidMb(base));
  2003. #endif
  2004. /* Inactivate Message Buffer. */
  2005. if (enable)
  2006. {
  2007. /* Inactivate by writing CS. */
  2008. mbAddr[offset] = CAN_CS_CODE(kFLEXCAN_TxMbInactive);
  2009. }
  2010. else
  2011. {
  2012. mbAddr[offset] = 0x0;
  2013. }
  2014. /* Calculate the DWORD number, dataSize 0/1/2/3 corresponds to 8/16/32/64
  2015. Bytes payload. */
  2016. for (cnt = 0; cnt < (dataSize + 1U); cnt++)
  2017. {
  2018. payload_dword *= 2U;
  2019. }
  2020. /* Clean ID. */
  2021. mbAddr[offset + 1U] = 0x0U;
  2022. /* Clean Message Buffer content, DWORD by DWORD. */
  2023. for (cnt = 0; cnt < payload_dword; cnt++)
  2024. {
  2025. mbAddr[offset + 2U + cnt] = 0x0U;
  2026. }
  2027. #if ((defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) || \
  2028. (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829))
  2029. mbAddr[availoffset] = CAN_CS_CODE(kFLEXCAN_TxMbInactive);
  2030. #endif
  2031. }
  2032. #endif /* FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE */
  2033. /*!
  2034. * brief Configures a FlexCAN Receive Message Buffer.
  2035. *
  2036. * This function cleans a FlexCAN build-in Message Buffer and configures it
  2037. * as a Receive Message Buffer.
  2038. *
  2039. * param base FlexCAN peripheral base address.
  2040. * param mbIdx The Message Buffer index.
  2041. * param pRxMbConfig Pointer to the FlexCAN Message Buffer configuration structure.
  2042. * param enable Enable/disable Rx Message Buffer.
  2043. * - true: Enable Rx Message Buffer.
  2044. * - false: Disable Rx Message Buffer.
  2045. */
  2046. void FLEXCAN_SetRxMbConfig(CAN_Type *base, uint8_t mbIdx, const flexcan_rx_mb_config_t *pRxMbConfig, bool enable)
  2047. {
  2048. /* Assertion. */
  2049. assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  2050. assert(((NULL != pRxMbConfig) || (false == enable)));
  2051. #if !defined(NDEBUG)
  2052. assert(!FLEXCAN_IsMbOccupied(base, mbIdx));
  2053. #endif
  2054. uint32_t cs_temp = 0;
  2055. /* Inactivate Message Buffer. */
  2056. base->MB[mbIdx].CS = 0;
  2057. /* Clean Message Buffer content. */
  2058. base->MB[mbIdx].ID = 0x0;
  2059. base->MB[mbIdx].WORD0 = 0x0;
  2060. base->MB[mbIdx].WORD1 = 0x0;
  2061. if (enable)
  2062. {
  2063. /* Setup Message Buffer ID. */
  2064. base->MB[mbIdx].ID = pRxMbConfig->id;
  2065. /* Setup Message Buffer format. */
  2066. if (kFLEXCAN_FrameFormatExtend == pRxMbConfig->format)
  2067. {
  2068. cs_temp |= CAN_CS_IDE_MASK;
  2069. }
  2070. /* Setup Message Buffer type. */
  2071. if (kFLEXCAN_FrameTypeRemote == pRxMbConfig->type)
  2072. {
  2073. cs_temp |= CAN_CS_RTR_MASK;
  2074. }
  2075. /* Activate Rx Message Buffer. */
  2076. cs_temp |= CAN_CS_CODE(kFLEXCAN_RxMbEmpty);
  2077. base->MB[mbIdx].CS = cs_temp;
  2078. }
  2079. }
  2080. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  2081. /*!
  2082. * brief Configures a FlexCAN Receive Message Buffer.
  2083. *
  2084. * This function cleans a FlexCAN build-in Message Buffer and configures it
  2085. * as a Receive Message Buffer.
  2086. *
  2087. * param base FlexCAN peripheral base address.
  2088. * param mbIdx The Message Buffer index.
  2089. * param pRxMbConfig Pointer to the FlexCAN Message Buffer configuration structure.
  2090. * param enable Enable/disable Rx Message Buffer.
  2091. * - true: Enable Rx Message Buffer.
  2092. * - false: Disable Rx Message Buffer.
  2093. */
  2094. void FLEXCAN_SetFDRxMbConfig(CAN_Type *base, uint8_t mbIdx, const flexcan_rx_mb_config_t *pRxMbConfig, bool enable)
  2095. {
  2096. /* Assertion. */
  2097. assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  2098. assert(((NULL != pRxMbConfig) || (false == enable)));
  2099. #if !defined(NDEBUG)
  2100. assert(!FLEXCAN_IsMbOccupied(base, mbIdx));
  2101. #endif
  2102. uint32_t cs_temp = 0;
  2103. uint8_t cnt = 0;
  2104. volatile uint32_t *mbAddr = &(base->MB[0].CS);
  2105. uint32_t offset = FLEXCAN_GetFDMailboxOffset(base, mbIdx);
  2106. uint8_t payload_dword;
  2107. uint32_t dataSize = (base->FDCTRL & CAN_FDCTRL_MBDSR0_MASK) >> CAN_FDCTRL_MBDSR0_SHIFT;
  2108. /* Inactivate Message Buffer. */
  2109. mbAddr[offset] = 0U;
  2110. /* Clean Message Buffer content. */
  2111. mbAddr[offset + 1U] = 0U;
  2112. /* Calculate the DWORD number, dataSize 0/1/2/3 corresponds to 8/16/32/64
  2113. Bytes payload. */
  2114. payload_dword = (2U << dataSize);
  2115. for (cnt = 0; cnt < payload_dword; cnt++)
  2116. {
  2117. mbAddr[offset + 2U + cnt] = 0x0;
  2118. }
  2119. if (enable)
  2120. {
  2121. /* Setup Message Buffer ID. */
  2122. mbAddr[offset + 1U] = pRxMbConfig->id;
  2123. /* Setup Message Buffer format. */
  2124. if (kFLEXCAN_FrameFormatExtend == pRxMbConfig->format)
  2125. {
  2126. cs_temp |= CAN_CS_IDE_MASK;
  2127. }
  2128. /* Setup Message Buffer type. */
  2129. if (kFLEXCAN_FrameTypeRemote == pRxMbConfig->type)
  2130. {
  2131. cs_temp |= CAN_CS_RTR_MASK;
  2132. }
  2133. /* Activate Rx Message Buffer. */
  2134. cs_temp |= CAN_CS_CODE(kFLEXCAN_RxMbEmpty);
  2135. mbAddr[offset] = cs_temp;
  2136. }
  2137. }
  2138. #endif
  2139. /*!
  2140. * brief Configures the FlexCAN Legacy Rx FIFO.
  2141. *
  2142. * This function configures the FlexCAN Rx FIFO with given configuration.
  2143. * note Legacy Rx FIFO only can receive classic CAN message.
  2144. *
  2145. * param base FlexCAN peripheral base address.
  2146. * param pRxFifoConfig Pointer to the FlexCAN Legacy Rx FIFO configuration structure. Can be NULL when enable parameter
  2147. * is false.
  2148. * param enable Enable/disable Legacy Rx FIFO.
  2149. * - true: Enable Legacy Rx FIFO.
  2150. * - false: Disable Legacy Rx FIFO.
  2151. */
  2152. void FLEXCAN_SetRxFifoConfig(CAN_Type *base, const flexcan_rx_fifo_config_t *pRxFifoConfig, bool enable)
  2153. {
  2154. /* Assertion. */
  2155. assert((NULL != pRxFifoConfig) || (false == enable));
  2156. volatile uint32_t *mbAddr;
  2157. uint8_t i, j, k, rffn = 0, numMbOccupy;
  2158. uint32_t setup_mb = 0;
  2159. /* Enter Freeze Mode. */
  2160. FLEXCAN_EnterFreezeMode(base);
  2161. if (enable)
  2162. {
  2163. assert(pRxFifoConfig->idFilterNum <= 128U);
  2164. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO)
  2165. /* Legacy Rx FIFO and Enhanced Rx FIFO cannot be enabled at the same time. */
  2166. assert((base->ERFCR & CAN_ERFCR_ERFEN_MASK) == 0U);
  2167. #endif
  2168. /* Get the setup_mb value. */
  2169. setup_mb = (uint8_t)((base->MCR & CAN_MCR_MAXMB_MASK) >> CAN_MCR_MAXMB_SHIFT);
  2170. setup_mb = (setup_mb < (uint32_t)FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base)) ?
  2171. setup_mb :
  2172. (uint32_t)FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base);
  2173. /* Determine RFFN value. */
  2174. for (i = 0; i <= 0xFU; i++)
  2175. {
  2176. if ((8U * (i + 1U)) >= pRxFifoConfig->idFilterNum)
  2177. {
  2178. rffn = i;
  2179. assert(((setup_mb - 8U) - (2U * rffn)) > 0U);
  2180. base->CTRL2 = (base->CTRL2 & ~CAN_CTRL2_RFFN_MASK) | CAN_CTRL2_RFFN(rffn);
  2181. break;
  2182. }
  2183. }
  2184. /* caculate the Number of Mailboxes occupied by RX Legacy FIFO and the filter. */
  2185. numMbOccupy = 6U + (rffn + 1U) * 2U;
  2186. /* Copy ID filter table to Message Buffer Region (Fix MISRA_C-2012 Rule 18.1). */
  2187. j = 0U;
  2188. for (i = 6U; i < numMbOccupy; i++)
  2189. {
  2190. /* Get address for current mail box. */
  2191. mbAddr = &(base->MB[i].CS);
  2192. /* One Mail box contain 4U DWORD registers. */
  2193. for (k = 0; k < 4U; k++)
  2194. {
  2195. /* Fill all valid filter in the mail box occupied by filter.
  2196. * Disable unused Rx FIFO Filter, the other rest of register in the last Mail box occupied by fiter set
  2197. * as 0xffffffff.
  2198. */
  2199. mbAddr[k] = (j < pRxFifoConfig->idFilterNum) ? (pRxFifoConfig->idFilterTable[j]) : 0xFFFFFFFFU;
  2200. /* Try to fill next filter in current Mail Box. */
  2201. j++;
  2202. }
  2203. }
  2204. /* Setup ID Fitlter Type. */
  2205. switch (pRxFifoConfig->idFilterType)
  2206. {
  2207. case kFLEXCAN_RxFifoFilterTypeA:
  2208. base->MCR = (base->MCR & ~CAN_MCR_IDAM_MASK) | CAN_MCR_IDAM(0x0);
  2209. break;
  2210. case kFLEXCAN_RxFifoFilterTypeB:
  2211. base->MCR = (base->MCR & ~CAN_MCR_IDAM_MASK) | CAN_MCR_IDAM(0x1);
  2212. break;
  2213. case kFLEXCAN_RxFifoFilterTypeC:
  2214. base->MCR = (base->MCR & ~CAN_MCR_IDAM_MASK) | CAN_MCR_IDAM(0x2);
  2215. break;
  2216. case kFLEXCAN_RxFifoFilterTypeD:
  2217. /* All frames rejected. */
  2218. base->MCR = (base->MCR & ~CAN_MCR_IDAM_MASK) | CAN_MCR_IDAM(0x3);
  2219. break;
  2220. default:
  2221. /* All the cases have been listed above, the default clause should not be reached. */
  2222. assert(false);
  2223. break;
  2224. }
  2225. /* Setting Message Reception Priority. */
  2226. base->CTRL2 = (pRxFifoConfig->priority == kFLEXCAN_RxFifoPrioHigh) ? (base->CTRL2 & ~CAN_CTRL2_MRP_MASK) :
  2227. (base->CTRL2 | CAN_CTRL2_MRP_MASK);
  2228. /* Enable Rx Message FIFO. */
  2229. base->MCR |= CAN_MCR_RFEN_MASK;
  2230. }
  2231. else
  2232. {
  2233. rffn = (uint8_t)((base->CTRL2 & CAN_CTRL2_RFFN_MASK) >> CAN_CTRL2_RFFN_SHIFT);
  2234. /* caculate the Number of Mailboxes occupied by RX Legacy FIFO and the filter. */
  2235. numMbOccupy = 6U + (rffn + 1U) * 2U;
  2236. /* Disable Rx Message FIFO. */
  2237. base->MCR &= ~CAN_MCR_RFEN_MASK;
  2238. /* Clean MB0 ~ MB5 and all MB occupied by ID filters (Fix MISRA_C-2012 Rule 18.1). */
  2239. for (i = 0; i < numMbOccupy; i++)
  2240. {
  2241. FLEXCAN_SetRxMbConfig(base, i, NULL, false);
  2242. }
  2243. }
  2244. /* Exit Freeze Mode. */
  2245. FLEXCAN_ExitFreezeMode(base);
  2246. }
  2247. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO)
  2248. /*!
  2249. * brief Configures the FlexCAN Enhanced Rx FIFO.
  2250. *
  2251. * This function configures the Enhanced Rx FIFO with given configuration.
  2252. * note Enhanced Rx FIFO support receive classic CAN or CAN FD messages, Legacy Rx FIFO and Enhanced Rx FIFO
  2253. * cannot be enabled at the same time.
  2254. *
  2255. * param base FlexCAN peripheral base address.
  2256. * param pConfig Pointer to the FlexCAN Enhanced Rx FIFO configuration structure. Can be NULL when enable parameter
  2257. * is false.
  2258. * param enable Enable/disable Enhanced Rx FIFO.
  2259. * - true: Enable Enhanced Rx FIFO.
  2260. * - false: Disable Enhanced Rx FIFO.
  2261. */
  2262. void FLEXCAN_SetEnhancedRxFifoConfig(CAN_Type *base, const flexcan_enhanced_rx_fifo_config_t *pConfig, bool enable)
  2263. {
  2264. /* Assertion. */
  2265. assert((NULL != pConfig) || (false == enable));
  2266. uint32_t i;
  2267. /* Enter Freeze Mode. */
  2268. FLEXCAN_EnterFreezeMode(base);
  2269. if (enable)
  2270. {
  2271. /* Each pair of filter elements occupies 2 words and can consist of one extended ID filter element or two
  2272. * standard ID filter elements. */
  2273. assert((pConfig->idFilterPairNum < (uint32_t)FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO_FILTER_MAX_NUMBER) &&
  2274. (pConfig->extendIdFilterNum <= (pConfig->idFilterPairNum + 1U)));
  2275. /* The Enhanced Rx FIFO Watermark cannot be greater than the enhanced Rx FIFO size. */
  2276. assert(pConfig->fifoWatermark < (uint32_t)FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO_SIZE);
  2277. /* Legacy Rx FIFO and Enhanced Rx FIFO cannot be enabled at the same time. */
  2278. assert((base->MCR & CAN_MCR_RFEN_MASK) == 0U);
  2279. /* Enable Enhanced Rx FIFO. */
  2280. base->ERFCR = CAN_ERFCR_ERFEN_MASK;
  2281. /* Reset Enhanced Rx FIFO engine and clear flags. */
  2282. base->ERFSR |= CAN_ERFSR_ERFCLR_MASK | CAN_ERFSR_ERFUFW_MASK | CAN_ERFSR_ERFOVF_MASK | CAN_ERFSR_ERFWMI_MASK |
  2283. CAN_ERFSR_ERFDA_MASK;
  2284. /* Setting Enhanced Rx FIFO. */
  2285. base->ERFCR |= CAN_ERFCR_DMALW(pConfig->dmaPerReadLength) | CAN_ERFCR_NEXIF(pConfig->extendIdFilterNum) |
  2286. CAN_ERFCR_NFE(pConfig->idFilterPairNum) | CAN_ERFCR_ERFWM(pConfig->fifoWatermark);
  2287. /* Copy ID filter table to Enhanced Rx FIFO Filter Element registers. */
  2288. for (i = 0; i < (uint32_t)FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO_FILTER_MAX_NUMBER; i++)
  2289. {
  2290. base->ERFFEL[i] = (i < ((uint32_t)pConfig->idFilterPairNum * 2U)) ? pConfig->idFilterTable[i] : 0xFFFFFFFFU;
  2291. }
  2292. /* Setting Message Reception Priority. */
  2293. base->CTRL2 = (pConfig->priority == kFLEXCAN_RxFifoPrioHigh) ? (base->CTRL2 & ~CAN_CTRL2_MRP_MASK) :
  2294. (base->CTRL2 | CAN_CTRL2_MRP_MASK);
  2295. }
  2296. else
  2297. {
  2298. /* Disable Enhanced Rx FIFO. */
  2299. base->ERFCR &= ~CAN_ERFCR_ERFEN_MASK;
  2300. /* Clean all Enhanced Rx FIFO Filter Element registers. */
  2301. for (i = 0; i < (uint32_t)FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO_FILTER_MAX_NUMBER; i++)
  2302. {
  2303. base->ERFFEL[i] = 0xFFFFFFFFU;
  2304. }
  2305. }
  2306. /* Exit Freeze Mode. */
  2307. FLEXCAN_ExitFreezeMode(base);
  2308. }
  2309. #endif
  2310. #if (defined(FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA) && FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA)
  2311. /*!
  2312. * brief Enables or disables the FlexCAN Legacy/Enhanced Rx FIFO DMA request.
  2313. *
  2314. * This function enables or disables the DMA feature of FlexCAN build-in Rx FIFO.
  2315. *
  2316. * param base FlexCAN peripheral base address.
  2317. * param enable true to enable, false to disable.
  2318. */
  2319. void FLEXCAN_EnableRxFifoDMA(CAN_Type *base, bool enable)
  2320. {
  2321. if (enable)
  2322. {
  2323. /* Enter Freeze Mode. */
  2324. FLEXCAN_EnterFreezeMode(base);
  2325. /* Enable FlexCAN DMA. */
  2326. base->MCR |= CAN_MCR_DMA_MASK;
  2327. /* Exit Freeze Mode. */
  2328. FLEXCAN_ExitFreezeMode(base);
  2329. }
  2330. else
  2331. {
  2332. /* Enter Freeze Mode. */
  2333. FLEXCAN_EnterFreezeMode(base);
  2334. /* Disable FlexCAN DMA. */
  2335. base->MCR &= ~CAN_MCR_DMA_MASK;
  2336. /* Exit Freeze Mode. */
  2337. FLEXCAN_ExitFreezeMode(base);
  2338. }
  2339. }
  2340. #endif /* FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA */
  2341. #if (defined(FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL) && FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL)
  2342. /*!
  2343. * brief Gets the FlexCAN Memory Error Report registers status.
  2344. *
  2345. * This function gets the FlexCAN Memory Error Report registers status.
  2346. *
  2347. * param base FlexCAN peripheral base address.
  2348. * param errorStatus Pointer to FlexCAN Memory Error Report registers status structure.
  2349. */
  2350. void FLEXCAN_GetMemoryErrorReportStatus(CAN_Type *base, flexcan_memory_error_report_status_t *errorStatus)
  2351. {
  2352. uint32_t temp;
  2353. /* Disable updates of the error report registers. */
  2354. base->MECR |= CAN_MECR_RERRDIS_MASK;
  2355. errorStatus->accessAddress = (uint16_t)(base->RERRAR & CAN_RERRAR_ERRADDR_MASK);
  2356. errorStatus->errorData = base->RERRDR;
  2357. errorStatus->errorType =
  2358. (base->RERRAR & CAN_RERRAR_NCE_MASK) == 0U ? kFLEXCAN_CorrectableError : kFLEXCAN_NonCorrectableError;
  2359. temp = (base->RERRAR & CAN_RERRAR_SAID_MASK) >> CAN_RERRAR_SAID_SHIFT;
  2360. switch (temp)
  2361. {
  2362. case (uint32_t)kFLEXCAN_MoveOutFlexCanAccess:
  2363. case (uint32_t)kFLEXCAN_MoveInAccess:
  2364. case (uint32_t)kFLEXCAN_TxArbitrationAccess:
  2365. case (uint32_t)kFLEXCAN_RxMatchingAccess:
  2366. case (uint32_t)kFLEXCAN_MoveOutHostAccess:
  2367. errorStatus->accessType = (flexcan_memory_access_type_t)temp;
  2368. break;
  2369. default:
  2370. assert(false);
  2371. break;
  2372. }
  2373. for (uint32_t i = 0; i < 4U; i++)
  2374. {
  2375. temp = (base->RERRSYNR & ((uint32_t)CAN_RERRSYNR_SYND0_MASK << (i * 8U))) >> (i * 8U);
  2376. errorStatus->byteStatus[i].byteIsRead = (base->RERRSYNR & ((uint32_t)CAN_RERRSYNR_BE0_MASK << (i * 8U))) != 0U;
  2377. switch (temp)
  2378. {
  2379. case CAN_RERRSYNR_SYND0(kFLEXCAN_NoError):
  2380. case CAN_RERRSYNR_SYND0(kFLEXCAN_ParityBits0Error):
  2381. case CAN_RERRSYNR_SYND0(kFLEXCAN_ParityBits1Error):
  2382. case CAN_RERRSYNR_SYND0(kFLEXCAN_ParityBits2Error):
  2383. case CAN_RERRSYNR_SYND0(kFLEXCAN_ParityBits3Error):
  2384. case CAN_RERRSYNR_SYND0(kFLEXCAN_ParityBits4Error):
  2385. case CAN_RERRSYNR_SYND0(kFLEXCAN_DataBits0Error):
  2386. case CAN_RERRSYNR_SYND0(kFLEXCAN_DataBits1Error):
  2387. case CAN_RERRSYNR_SYND0(kFLEXCAN_DataBits2Error):
  2388. case CAN_RERRSYNR_SYND0(kFLEXCAN_DataBits3Error):
  2389. case CAN_RERRSYNR_SYND0(kFLEXCAN_DataBits4Error):
  2390. case CAN_RERRSYNR_SYND0(kFLEXCAN_DataBits5Error):
  2391. case CAN_RERRSYNR_SYND0(kFLEXCAN_DataBits6Error):
  2392. case CAN_RERRSYNR_SYND0(kFLEXCAN_DataBits7Error):
  2393. case CAN_RERRSYNR_SYND0(kFLEXCAN_AllZeroError):
  2394. case CAN_RERRSYNR_SYND0(kFLEXCAN_AllOneError):
  2395. errorStatus->byteStatus[i].bitAffected = (flexcan_byte_error_syndrome_t)temp;
  2396. break;
  2397. default:
  2398. errorStatus->byteStatus[i].bitAffected = kFLEXCAN_NonCorrectableErrors;
  2399. break;
  2400. }
  2401. }
  2402. /* Re-enable updates of the error report registers. */
  2403. base->MECR &= CAN_MECR_RERRDIS_MASK;
  2404. }
  2405. #endif
  2406. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_6032) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_6032)
  2407. /*!
  2408. * FlexCAN: A frame with wrong ID or payload is transmitted into
  2409. * the CAN bus when the Message Buffer under transmission is
  2410. * either aborted or deactivated while the CAN bus is in the Bus Idle state
  2411. *
  2412. * This function to do workaround for ERR006032
  2413. *
  2414. * param base FlexCAN peripheral base address.
  2415. * param mbIdx The FlexCAN Message Buffer index.
  2416. */
  2417. static void FLEXCAN_ERRATA_6032(CAN_Type *base, volatile uint32_t *mbCSAddr)
  2418. {
  2419. uint32_t dbg_temp = 0U;
  2420. uint32_t u32TempCS = 0U;
  2421. uint32_t u32Timeout = DELAY_BUSIDLE;
  2422. uint32_t u32TempIMASK1 = base->IMASK1;
  2423. /*after backup all interruption, disable ALL interruption*/
  2424. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  2425. uint32_t u32TempIMASK2 = base->IMASK2;
  2426. base->IMASK2 = 0;
  2427. #endif
  2428. base->IMASK1 = 0;
  2429. dbg_temp = (uint32_t)(base->DBG1);
  2430. switch (dbg_temp & CAN_DBG1_CFSM_MASK)
  2431. {
  2432. case RXINTERMISSION:
  2433. if (CBN_VALUE3 == (dbg_temp & CAN_DBG1_CBN_MASK))
  2434. {
  2435. /*wait until CFSM is different from RXINTERMISSION */
  2436. while (RXINTERMISSION == (base->DBG1 & CAN_DBG1_CFSM_MASK))
  2437. {
  2438. __NOP();
  2439. }
  2440. }
  2441. break;
  2442. case TXINTERMISSION:
  2443. if (CBN_VALUE3 == (dbg_temp & CAN_DBG1_CBN_MASK))
  2444. {
  2445. /*wait until CFSM is different from TXINTERMISSION*/
  2446. while (TXINTERMISSION == (base->DBG1 & CAN_DBG1_CFSM_MASK))
  2447. {
  2448. __NOP();
  2449. }
  2450. }
  2451. break;
  2452. default:
  2453. /* To avoid MISRA-C 2012 rule 16.4 issue. */
  2454. break;
  2455. }
  2456. /*Anyway, BUSIDLE need to delay*/
  2457. if (BUSIDLE == (base->DBG1 & CAN_DBG1_CFSM_MASK))
  2458. {
  2459. while (u32Timeout-- > 0U)
  2460. {
  2461. __NOP();
  2462. }
  2463. /*Write 0x0 into Code field of CS word.*/
  2464. u32TempCS = (uint32_t)(*mbCSAddr);
  2465. u32TempCS &= ~CAN_CS_CODE_MASK;
  2466. *mbCSAddr = u32TempCS;
  2467. }
  2468. /*restore interruption*/
  2469. base->IMASK1 = u32TempIMASK1;
  2470. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  2471. base->IMASK2 = u32TempIMASK2;
  2472. #endif
  2473. }
  2474. #endif
  2475. /*!
  2476. * brief Writes a FlexCAN Message to the Transmit Message Buffer.
  2477. *
  2478. * This function writes a CAN Message to the specified Transmit Message Buffer
  2479. * and changes the Message Buffer state to start CAN Message transmit. After
  2480. * that the function returns immediately.
  2481. *
  2482. * param base FlexCAN peripheral base address.
  2483. * param mbIdx The FlexCAN Message Buffer index.
  2484. * param pTxFrame Pointer to CAN message frame to be sent.
  2485. * retval kStatus_Success - Write Tx Message Buffer Successfully.
  2486. * retval kStatus_Fail - Tx Message Buffer is currently in use.
  2487. */
  2488. status_t FLEXCAN_WriteTxMb(CAN_Type *base, uint8_t mbIdx, const flexcan_frame_t *pTxFrame)
  2489. {
  2490. /* Assertion. */
  2491. assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  2492. assert(NULL != pTxFrame);
  2493. assert(pTxFrame->length <= 8U);
  2494. #if !defined(NDEBUG)
  2495. assert(!FLEXCAN_IsMbOccupied(base, mbIdx));
  2496. #endif
  2497. uint32_t cs_temp = 0;
  2498. status_t status;
  2499. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_6032) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_6032)
  2500. FLEXCAN_ERRATA_6032(base, &(base->MB[mbIdx].CS));
  2501. #endif
  2502. /* Check if Message Buffer is available. */
  2503. if (CAN_CS_CODE(kFLEXCAN_TxMbDataOrRemote) != (base->MB[mbIdx].CS & CAN_CS_CODE_MASK))
  2504. {
  2505. /* Inactive Tx Message Buffer. */
  2506. base->MB[mbIdx].CS = (base->MB[mbIdx].CS & ~CAN_CS_CODE_MASK) | CAN_CS_CODE(kFLEXCAN_TxMbInactive);
  2507. /* Fill Message ID field. */
  2508. base->MB[mbIdx].ID = pTxFrame->id;
  2509. /* Fill Message Format field. */
  2510. if ((uint32_t)kFLEXCAN_FrameFormatExtend == pTxFrame->format)
  2511. {
  2512. cs_temp |= CAN_CS_SRR_MASK | CAN_CS_IDE_MASK;
  2513. }
  2514. /* Fill Message Type field. */
  2515. if ((uint32_t)kFLEXCAN_FrameTypeRemote == pTxFrame->type)
  2516. {
  2517. cs_temp |= CAN_CS_RTR_MASK;
  2518. }
  2519. cs_temp |= CAN_CS_CODE(kFLEXCAN_TxMbDataOrRemote) | CAN_CS_DLC(pTxFrame->length);
  2520. /* Load Message Payload. */
  2521. base->MB[mbIdx].WORD0 = pTxFrame->dataWord0;
  2522. base->MB[mbIdx].WORD1 = pTxFrame->dataWord1;
  2523. /* Activate Tx Message Buffer. */
  2524. base->MB[mbIdx].CS = cs_temp;
  2525. #if ((defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) || \
  2526. (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829))
  2527. base->MB[FLEXCAN_GetFirstValidMb(base)].CS = CAN_CS_CODE(kFLEXCAN_TxMbInactive);
  2528. base->MB[FLEXCAN_GetFirstValidMb(base)].CS = CAN_CS_CODE(kFLEXCAN_TxMbInactive);
  2529. #endif
  2530. status = kStatus_Success;
  2531. }
  2532. else
  2533. {
  2534. /* Tx Message Buffer is activated, return immediately. */
  2535. status = kStatus_Fail;
  2536. }
  2537. return status;
  2538. }
  2539. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  2540. /*!
  2541. * brief Writes a FlexCAN FD Message to the Transmit Message Buffer.
  2542. *
  2543. * This function writes a CAN FD Message to the specified Transmit Message Buffer
  2544. * and changes the Message Buffer state to start CAN FD Message transmit. After
  2545. * that the function returns immediately.
  2546. *
  2547. * param base FlexCAN peripheral base address.
  2548. * param mbIdx The FlexCAN FD Message Buffer index.
  2549. * param pTxFrame Pointer to CAN FD message frame to be sent.
  2550. * retval kStatus_Success - Write Tx Message Buffer Successfully.
  2551. * retval kStatus_Fail - Tx Message Buffer is currently in use.
  2552. */
  2553. status_t FLEXCAN_WriteFDTxMb(CAN_Type *base, uint8_t mbIdx, const flexcan_fd_frame_t *pTxFrame)
  2554. {
  2555. /* Assertion. */
  2556. assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  2557. assert(NULL != pTxFrame);
  2558. #if !defined(NDEBUG)
  2559. assert(!FLEXCAN_IsMbOccupied(base, mbIdx));
  2560. #endif
  2561. status_t status;
  2562. uint32_t cs_temp = 0;
  2563. uint8_t cnt = 0;
  2564. uint32_t can_cs = 0;
  2565. uint8_t payload_dword = 1;
  2566. uint32_t dataSize = (base->FDCTRL & CAN_FDCTRL_MBDSR0_MASK) >> CAN_FDCTRL_MBDSR0_SHIFT;
  2567. #if ((defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) || \
  2568. (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829))
  2569. uint32_t availoffset = FLEXCAN_GetFDMailboxOffset(base, FLEXCAN_GetFirstValidMb(base));
  2570. #endif
  2571. volatile uint32_t *mbAddr = &(base->MB[0].CS);
  2572. uint32_t offset = FLEXCAN_GetFDMailboxOffset(base, mbIdx);
  2573. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_6032) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_6032)
  2574. FLEXCAN_ERRATA_6032(base, &(mbAddr[offset]));
  2575. #endif
  2576. can_cs = mbAddr[offset];
  2577. /* Check if Message Buffer is available. */
  2578. if (CAN_CS_CODE(kFLEXCAN_TxMbDataOrRemote) != (can_cs & CAN_CS_CODE_MASK))
  2579. {
  2580. /* Inactive Tx Message Buffer and Fill Message ID field. */
  2581. mbAddr[offset] = (can_cs & ~CAN_CS_CODE_MASK) | CAN_CS_CODE(kFLEXCAN_TxMbInactive);
  2582. mbAddr[offset + 1U] = pTxFrame->id;
  2583. /* Fill Message Format field. */
  2584. if ((uint32_t)kFLEXCAN_FrameFormatExtend == pTxFrame->format)
  2585. {
  2586. cs_temp |= CAN_CS_SRR_MASK | CAN_CS_IDE_MASK;
  2587. }
  2588. /* Fill Message Type field. */
  2589. if ((uint32_t)kFLEXCAN_FrameTypeRemote == pTxFrame->type)
  2590. {
  2591. cs_temp |= CAN_CS_RTR_MASK;
  2592. }
  2593. cs_temp |= CAN_CS_CODE(kFLEXCAN_TxMbDataOrRemote) | CAN_CS_DLC(pTxFrame->length) | CAN_CS_EDL(1) |
  2594. CAN_CS_BRS(pTxFrame->brs);
  2595. /* Calculate the DWORD number, dataSize 0/1/2/3 corresponds to 8/16/32/64
  2596. Bytes payload. */
  2597. for (cnt = 0; cnt < (dataSize + 1U); cnt++)
  2598. {
  2599. payload_dword *= 2U;
  2600. }
  2601. /* Load Message Payload and Activate Tx Message Buffer. */
  2602. for (cnt = 0; cnt < payload_dword; cnt++)
  2603. {
  2604. mbAddr[offset + 2U + cnt] = pTxFrame->dataWord[cnt];
  2605. }
  2606. mbAddr[offset] = cs_temp;
  2607. #if ((defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) || \
  2608. (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5829))
  2609. mbAddr[availoffset] = CAN_CS_CODE(kFLEXCAN_TxMbInactive);
  2610. mbAddr[availoffset] = CAN_CS_CODE(kFLEXCAN_TxMbInactive);
  2611. #endif
  2612. status = kStatus_Success;
  2613. }
  2614. else
  2615. {
  2616. /* Tx Message Buffer is activated, return immediately. */
  2617. status = kStatus_Fail;
  2618. }
  2619. return status;
  2620. }
  2621. #endif
  2622. /*!
  2623. * brief Reads a FlexCAN Message from Receive Message Buffer.
  2624. *
  2625. * This function reads a CAN message from a specified Receive Message Buffer.
  2626. * The function fills a receive CAN message frame structure with
  2627. * just received data and activates the Message Buffer again.
  2628. * The function returns immediately.
  2629. *
  2630. * param base FlexCAN peripheral base address.
  2631. * param mbIdx The FlexCAN Message Buffer index.
  2632. * param pRxFrame Pointer to CAN message frame structure for reception.
  2633. * retval kStatus_Success - Rx Message Buffer is full and has been read successfully.
  2634. * retval kStatus_FLEXCAN_RxOverflow - Rx Message Buffer is already overflowed and has been read successfully.
  2635. * retval kStatus_Fail - Rx Message Buffer is empty.
  2636. */
  2637. status_t FLEXCAN_ReadRxMb(CAN_Type *base, uint8_t mbIdx, flexcan_frame_t *pRxFrame)
  2638. {
  2639. /* Assertion. */
  2640. assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  2641. assert(NULL != pRxFrame);
  2642. #if !defined(NDEBUG)
  2643. assert(!FLEXCAN_IsMbOccupied(base, mbIdx));
  2644. #endif
  2645. uint32_t cs_temp;
  2646. uint32_t rx_code;
  2647. status_t status;
  2648. /* Read CS field of Rx Message Buffer to lock Message Buffer. */
  2649. cs_temp = base->MB[mbIdx].CS;
  2650. /* Get Rx Message Buffer Code field. */
  2651. rx_code = (cs_temp & CAN_CS_CODE_MASK) >> CAN_CS_CODE_SHIFT;
  2652. /* Check to see if Rx Message Buffer is full. */
  2653. if (((uint32_t)kFLEXCAN_RxMbFull == rx_code) || ((uint32_t)kFLEXCAN_RxMbOverrun == rx_code))
  2654. {
  2655. /* Store Message ID. */
  2656. pRxFrame->id = base->MB[mbIdx].ID & (CAN_ID_EXT_MASK | CAN_ID_STD_MASK);
  2657. /* Get the message ID and format. */
  2658. pRxFrame->format = (cs_temp & CAN_CS_IDE_MASK) != 0U ? (uint8_t)kFLEXCAN_FrameFormatExtend :
  2659. (uint8_t)kFLEXCAN_FrameFormatStandard;
  2660. /* Get the message type. */
  2661. pRxFrame->type =
  2662. (cs_temp & CAN_CS_RTR_MASK) != 0U ? (uint8_t)kFLEXCAN_FrameTypeRemote : (uint8_t)kFLEXCAN_FrameTypeData;
  2663. /* Get the message length. */
  2664. pRxFrame->length = (uint8_t)((cs_temp & CAN_CS_DLC_MASK) >> CAN_CS_DLC_SHIFT);
  2665. /* Get the time stamp. */
  2666. pRxFrame->timestamp = (uint16_t)((cs_temp & CAN_CS_TIME_STAMP_MASK) >> CAN_CS_TIME_STAMP_SHIFT);
  2667. /* Store Message Payload. */
  2668. pRxFrame->dataWord0 = base->MB[mbIdx].WORD0;
  2669. pRxFrame->dataWord1 = base->MB[mbIdx].WORD1;
  2670. /* Read free-running timer to unlock Rx Message Buffer. */
  2671. (void)base->TIMER;
  2672. if ((uint32_t)kFLEXCAN_RxMbFull == rx_code)
  2673. {
  2674. status = kStatus_Success;
  2675. }
  2676. else
  2677. {
  2678. status = kStatus_FLEXCAN_RxOverflow;
  2679. }
  2680. }
  2681. else
  2682. {
  2683. /* Read free-running timer to unlock Rx Message Buffer. */
  2684. (void)base->TIMER;
  2685. status = kStatus_Fail;
  2686. }
  2687. return status;
  2688. }
  2689. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  2690. /*!
  2691. * brief Reads a FlexCAN FD Message from Receive Message Buffer.
  2692. *
  2693. * This function reads a CAN FD message from a specified Receive Message Buffer.
  2694. * The function fills a receive CAN FD message frame structure with
  2695. * just received data and activates the Message Buffer again.
  2696. * The function returns immediately.
  2697. *
  2698. * param base FlexCAN peripheral base address.
  2699. * param mbIdx The FlexCAN FD Message Buffer index.
  2700. * param pRxFrame Pointer to CAN FD message frame structure for reception.
  2701. * retval kStatus_Success - Rx Message Buffer is full and has been read successfully.
  2702. * retval kStatus_FLEXCAN_RxOverflow - Rx Message Buffer is already overflowed and has been read successfully.
  2703. * retval kStatus_Fail - Rx Message Buffer is empty.
  2704. */
  2705. status_t FLEXCAN_ReadFDRxMb(CAN_Type *base, uint8_t mbIdx, flexcan_fd_frame_t *pRxFrame)
  2706. {
  2707. /* Assertion. */
  2708. assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  2709. assert(NULL != pRxFrame);
  2710. #if !defined(NDEBUG)
  2711. assert(!FLEXCAN_IsMbOccupied(base, mbIdx));
  2712. #endif
  2713. status_t status;
  2714. uint32_t cs_temp;
  2715. uint8_t rx_code;
  2716. uint8_t cnt = 0;
  2717. uint32_t can_id = 0;
  2718. uint32_t dataSize;
  2719. dataSize = (base->FDCTRL & CAN_FDCTRL_MBDSR0_MASK) >> CAN_FDCTRL_MBDSR0_SHIFT;
  2720. uint8_t payload_dword = 1;
  2721. volatile uint32_t *mbAddr = &(base->MB[0].CS);
  2722. uint32_t offset = FLEXCAN_GetFDMailboxOffset(base, mbIdx);
  2723. /* Read CS field of Rx Message Buffer to lock Message Buffer. */
  2724. cs_temp = mbAddr[offset];
  2725. can_id = mbAddr[offset + 1U];
  2726. /* Get Rx Message Buffer Code field. */
  2727. rx_code = (uint8_t)((cs_temp & CAN_CS_CODE_MASK) >> CAN_CS_CODE_SHIFT);
  2728. /* Check to see if Rx Message Buffer is full. */
  2729. if (((uint8_t)kFLEXCAN_RxMbFull == rx_code) || ((uint8_t)kFLEXCAN_RxMbOverrun == rx_code))
  2730. {
  2731. /* Store Message ID. */
  2732. pRxFrame->id = can_id & (CAN_ID_EXT_MASK | CAN_ID_STD_MASK);
  2733. /* Get the message ID and format. */
  2734. pRxFrame->format = (cs_temp & CAN_CS_IDE_MASK) != 0U ? (uint8_t)kFLEXCAN_FrameFormatExtend :
  2735. (uint8_t)kFLEXCAN_FrameFormatStandard;
  2736. /* Get the message type. */
  2737. pRxFrame->type =
  2738. (cs_temp & CAN_CS_RTR_MASK) != 0U ? (uint8_t)kFLEXCAN_FrameTypeRemote : (uint8_t)kFLEXCAN_FrameTypeData;
  2739. /* Get the message length. */
  2740. pRxFrame->length = (uint8_t)((cs_temp & CAN_CS_DLC_MASK) >> CAN_CS_DLC_SHIFT);
  2741. /* Get the time stamp. */
  2742. pRxFrame->timestamp = (uint16_t)((cs_temp & CAN_CS_TIME_STAMP_MASK) >> CAN_CS_TIME_STAMP_SHIFT);
  2743. /* Calculate the DWORD number, dataSize 0/1/2/3 corresponds to 8/16/32/64
  2744. Bytes payload. */
  2745. for (cnt = 0; cnt < (dataSize + 1U); cnt++)
  2746. {
  2747. payload_dword *= 2U;
  2748. }
  2749. /* Store Message Payload. */
  2750. for (cnt = 0; cnt < payload_dword; cnt++)
  2751. {
  2752. pRxFrame->dataWord[cnt] = mbAddr[offset + 2U + cnt];
  2753. }
  2754. /* Read free-running timer to unlock Rx Message Buffer. */
  2755. (void)base->TIMER;
  2756. if ((uint32_t)kFLEXCAN_RxMbFull == rx_code)
  2757. {
  2758. status = kStatus_Success;
  2759. }
  2760. else
  2761. {
  2762. status = kStatus_FLEXCAN_RxOverflow;
  2763. }
  2764. }
  2765. else
  2766. {
  2767. /* Read free-running timer to unlock Rx Message Buffer. */
  2768. (void)base->TIMER;
  2769. status = kStatus_Fail;
  2770. }
  2771. return status;
  2772. }
  2773. #endif
  2774. /*!
  2775. * brief Reads a FlexCAN Message from Legacy Rx FIFO.
  2776. *
  2777. * This function reads a CAN message from the FlexCAN Legacy Rx FIFO.
  2778. *
  2779. * param base FlexCAN peripheral base address.
  2780. * param pRxFrame Pointer to CAN message frame structure for reception.
  2781. * retval kStatus_Success - Read Message from Rx FIFO successfully.
  2782. * retval kStatus_Fail - Rx FIFO is not enabled.
  2783. */
  2784. status_t FLEXCAN_ReadRxFifo(CAN_Type *base, flexcan_frame_t *pRxFrame)
  2785. {
  2786. /* Assertion. */
  2787. assert(NULL != pRxFrame);
  2788. uint32_t cs_temp;
  2789. status_t status;
  2790. /* Check if Legacy Rx FIFO is Enabled. */
  2791. if (0U != (base->MCR & CAN_MCR_RFEN_MASK))
  2792. {
  2793. /* Read CS field of Rx Message Buffer to lock Message Buffer. */
  2794. cs_temp = base->MB[0].CS;
  2795. /* Read data from Rx FIFO output port. */
  2796. /* Store Message ID. */
  2797. pRxFrame->id = base->MB[0].ID & (CAN_ID_EXT_MASK | CAN_ID_STD_MASK);
  2798. /* Get the message ID and format. */
  2799. pRxFrame->format = (cs_temp & CAN_CS_IDE_MASK) != 0U ? (uint8_t)kFLEXCAN_FrameFormatExtend :
  2800. (uint8_t)kFLEXCAN_FrameFormatStandard;
  2801. /* Get the message type. */
  2802. pRxFrame->type =
  2803. (cs_temp & CAN_CS_RTR_MASK) != 0U ? (uint8_t)kFLEXCAN_FrameTypeRemote : (uint8_t)kFLEXCAN_FrameTypeData;
  2804. /* Get the message length. */
  2805. pRxFrame->length = (uint8_t)((cs_temp & CAN_CS_DLC_MASK) >> CAN_CS_DLC_SHIFT);
  2806. /* Get the time stamp. */
  2807. pRxFrame->timestamp = (uint16_t)((cs_temp & CAN_CS_TIME_STAMP_MASK) >> CAN_CS_TIME_STAMP_SHIFT);
  2808. /* Store Message Payload. */
  2809. pRxFrame->dataWord0 = base->MB[0].WORD0;
  2810. pRxFrame->dataWord1 = base->MB[0].WORD1;
  2811. /* Store ID Filter Hit Index. */
  2812. pRxFrame->idhit = (uint16_t)(base->RXFIR & CAN_RXFIR_IDHIT_MASK);
  2813. /* Read free-running timer to unlock Rx Message Buffer. */
  2814. (void)base->TIMER;
  2815. status = kStatus_Success;
  2816. }
  2817. else
  2818. {
  2819. status = kStatus_Fail;
  2820. }
  2821. return status;
  2822. }
  2823. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO)
  2824. /*!
  2825. * brief Reads a FlexCAN Message from Enhanced Rx FIFO.
  2826. *
  2827. * This function reads a CAN or CAN FD message from the FlexCAN Enhanced Rx FIFO.
  2828. *
  2829. * param base FlexCAN peripheral base address.
  2830. * param pRxFrame Pointer to CAN FD message frame structure for reception.
  2831. * retval kStatus_Success - Read Message from Rx FIFO successfully.
  2832. * retval kStatus_Fail - Rx FIFO is not enabled.
  2833. */
  2834. status_t FLEXCAN_ReadEnhancedRxFifo(CAN_Type *base, flexcan_fd_frame_t *pRxFrame)
  2835. {
  2836. /* Assertion. */
  2837. assert(NULL != pRxFrame);
  2838. status_t status;
  2839. uint32_t idHitOff;
  2840. /* Check if Enhanced Rx FIFO is Enabled. */
  2841. if (0U != (base->ERFCR & CAN_ERFCR_ERFEN_MASK))
  2842. {
  2843. /* Enhanced Rx FIFO ID HIT offset is changed dynamically according to data length code (DLC) . */
  2844. idHitOff = (DLC_LENGTH_DECODE(((flexcan_fd_frame_t *)E_RX_FIFO(base))->length) + 3U) / 4U + 3U;
  2845. /* Copy CAN FD Message from Enhanced Rx FIFO, should use the DLC value to identify the bytes that belong to the
  2846. * message which is being read. */
  2847. (void)memcpy((void *)pRxFrame, (void *)(uint32_t *)E_RX_FIFO(base), sizeof(uint32_t) * idHitOff);
  2848. pRxFrame->idhit = pRxFrame->dataWord[idHitOff - 3U];
  2849. /* Clear the unused frame data. */
  2850. for (uint32_t i = (idHitOff - 3U); i < 16U; i++)
  2851. {
  2852. pRxFrame->dataWord[i] = 0x0;
  2853. }
  2854. /* Clear data available flag to let FlexCAN know one frame has been read from the Enhanced Rx FIFO. */
  2855. base->ERFSR |= CAN_ERFSR_ERFDA_MASK;
  2856. status = kStatus_Success;
  2857. }
  2858. else
  2859. {
  2860. status = kStatus_Fail;
  2861. }
  2862. return status;
  2863. }
  2864. #endif
  2865. /*!
  2866. * brief Performs a polling send transaction on the CAN bus.
  2867. *
  2868. * note A transfer handle does not need to be created before calling this API.
  2869. *
  2870. * param base FlexCAN peripheral base pointer.
  2871. * param mbIdx The FlexCAN Message Buffer index.
  2872. * param pTxFrame Pointer to CAN message frame to be sent.
  2873. * retval kStatus_Success - Write Tx Message Buffer Successfully.
  2874. * retval kStatus_Fail - Tx Message Buffer is currently in use.
  2875. */
  2876. status_t FLEXCAN_TransferSendBlocking(CAN_Type *base, uint8_t mbIdx, flexcan_frame_t *pTxFrame)
  2877. {
  2878. status_t status;
  2879. /* Write Tx Message Buffer to initiate a data sending. */
  2880. if (kStatus_Success == FLEXCAN_WriteTxMb(base, mbIdx, (const flexcan_frame_t *)(uint32_t)pTxFrame))
  2881. {
  2882. /* Wait until CAN Message send out. */
  2883. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  2884. uint64_t u64flag = 1;
  2885. while (0U == FLEXCAN_GetMbStatusFlags(base, u64flag << mbIdx))
  2886. #else
  2887. uint32_t u32flag = 1;
  2888. while (0U == FLEXCAN_GetMbStatusFlags(base, u32flag << mbIdx))
  2889. #endif
  2890. {
  2891. }
  2892. /* Clean Tx Message Buffer Flag. */
  2893. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  2894. FLEXCAN_ClearMbStatusFlags(base, u64flag << mbIdx);
  2895. #else
  2896. FLEXCAN_ClearMbStatusFlags(base, u32flag << mbIdx);
  2897. #endif
  2898. /*After TX MB tranfered success, update the Timestamp from MB[mbIdx].CS register*/
  2899. pTxFrame->timestamp = (uint16_t)((base->MB[mbIdx].CS & CAN_CS_TIME_STAMP_MASK) >> CAN_CS_TIME_STAMP_SHIFT);
  2900. status = kStatus_Success;
  2901. }
  2902. else
  2903. {
  2904. status = kStatus_Fail;
  2905. }
  2906. return status;
  2907. }
  2908. /*!
  2909. * brief Performs a polling receive transaction on the CAN bus.
  2910. *
  2911. * note A transfer handle does not need to be created before calling this API.
  2912. *
  2913. * param base FlexCAN peripheral base pointer.
  2914. * param mbIdx The FlexCAN Message Buffer index.
  2915. * param pRxFrame Pointer to CAN message frame structure for reception.
  2916. * retval kStatus_Success - Rx Message Buffer is full and has been read successfully.
  2917. * retval kStatus_FLEXCAN_RxOverflow - Rx Message Buffer is already overflowed and has been read successfully.
  2918. * retval kStatus_Fail - Rx Message Buffer is empty.
  2919. */
  2920. status_t FLEXCAN_TransferReceiveBlocking(CAN_Type *base, uint8_t mbIdx, flexcan_frame_t *pRxFrame)
  2921. {
  2922. /* Wait until Rx Message Buffer non-empty. */
  2923. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  2924. uint64_t u64flag = 1;
  2925. while (0U == FLEXCAN_GetMbStatusFlags(base, u64flag << mbIdx))
  2926. #else
  2927. uint32_t u32flag = 1;
  2928. while (0U == FLEXCAN_GetMbStatusFlags(base, u32flag << mbIdx))
  2929. #endif
  2930. {
  2931. }
  2932. /* Clean Rx Message Buffer Flag. */
  2933. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  2934. FLEXCAN_ClearMbStatusFlags(base, u64flag << mbIdx);
  2935. #else
  2936. FLEXCAN_ClearMbStatusFlags(base, u32flag << mbIdx);
  2937. #endif
  2938. /* Read Received CAN Message. */
  2939. return FLEXCAN_ReadRxMb(base, mbIdx, pRxFrame);
  2940. }
  2941. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  2942. /*!
  2943. * brief Performs a polling send transaction on the CAN bus.
  2944. *
  2945. * note A transfer handle does not need to be created before calling this API.
  2946. *
  2947. * param base FlexCAN peripheral base pointer.
  2948. * param mbIdx The FlexCAN FD Message Buffer index.
  2949. * param pTxFrame Pointer to CAN FD message frame to be sent.
  2950. * retval kStatus_Success - Write Tx Message Buffer Successfully.
  2951. * retval kStatus_Fail - Tx Message Buffer is currently in use.
  2952. */
  2953. status_t FLEXCAN_TransferFDSendBlocking(CAN_Type *base, uint8_t mbIdx, flexcan_fd_frame_t *pTxFrame)
  2954. {
  2955. status_t status;
  2956. /* Write Tx Message Buffer to initiate a data sending. */
  2957. if (kStatus_Success == FLEXCAN_WriteFDTxMb(base, mbIdx, (const flexcan_fd_frame_t *)(uint32_t)pTxFrame))
  2958. {
  2959. /* Wait until CAN Message send out. */
  2960. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  2961. uint64_t u64flag = 1;
  2962. while (0U == FLEXCAN_GetMbStatusFlags(base, u64flag << mbIdx))
  2963. #else
  2964. uint32_t u32flag = 1;
  2965. while (0U == FLEXCAN_GetMbStatusFlags(base, u32flag << mbIdx))
  2966. #endif
  2967. {
  2968. }
  2969. /* Clean Tx Message Buffer Flag. */
  2970. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  2971. FLEXCAN_ClearMbStatusFlags(base, u64flag << mbIdx);
  2972. #else
  2973. FLEXCAN_ClearMbStatusFlags(base, u32flag << mbIdx);
  2974. #endif
  2975. /*After TX MB tranfered success, update the Timestamp from base->MB[offset for CAN FD].CS register*/
  2976. volatile uint32_t *mbAddr = &(base->MB[0].CS);
  2977. uint32_t offset = FLEXCAN_GetFDMailboxOffset(base, mbIdx);
  2978. pTxFrame->timestamp = (uint16_t)((mbAddr[offset] & CAN_CS_TIME_STAMP_MASK) >> CAN_CS_TIME_STAMP_SHIFT);
  2979. status = kStatus_Success;
  2980. }
  2981. else
  2982. {
  2983. status = kStatus_Fail;
  2984. }
  2985. return status;
  2986. }
  2987. /*!
  2988. * brief Performs a polling receive transaction on the CAN bus.
  2989. *
  2990. * note A transfer handle does not need to be created before calling this API.
  2991. *
  2992. * param base FlexCAN peripheral base pointer.
  2993. * param mbIdx The FlexCAN FD Message Buffer index.
  2994. * param pRxFrame Pointer to CAN FD message frame structure for reception.
  2995. * retval kStatus_Success - Rx Message Buffer is full and has been read successfully.
  2996. * retval kStatus_FLEXCAN_RxOverflow - Rx Message Buffer is already overflowed and has been read successfully.
  2997. * retval kStatus_Fail - Rx Message Buffer is empty.
  2998. */
  2999. status_t FLEXCAN_TransferFDReceiveBlocking(CAN_Type *base, uint8_t mbIdx, flexcan_fd_frame_t *pRxFrame)
  3000. {
  3001. /* Wait until Rx Message Buffer non-empty. */
  3002. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  3003. uint64_t u64flag = 1;
  3004. while (0U == FLEXCAN_GetMbStatusFlags(base, u64flag << mbIdx))
  3005. #else
  3006. uint32_t u32flag = 1;
  3007. while (0U == FLEXCAN_GetMbStatusFlags(base, u32flag << mbIdx))
  3008. #endif
  3009. {
  3010. }
  3011. /* Clean Rx Message Buffer Flag. */
  3012. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  3013. FLEXCAN_ClearMbStatusFlags(base, u64flag << mbIdx);
  3014. #else
  3015. FLEXCAN_ClearMbStatusFlags(base, u32flag << mbIdx);
  3016. #endif
  3017. /* Read Received CAN Message. */
  3018. return FLEXCAN_ReadFDRxMb(base, mbIdx, pRxFrame);
  3019. }
  3020. #endif
  3021. /*!
  3022. * brief Performs a polling receive transaction from Legacy Rx FIFO on the CAN bus.
  3023. *
  3024. * note A transfer handle does not need to be created before calling this API.
  3025. *
  3026. * param base FlexCAN peripheral base pointer.
  3027. * param pRxFrame Pointer to CAN message frame structure for reception.
  3028. * retval kStatus_Success - Read Message from Rx FIFO successfully.
  3029. * retval kStatus_Fail - Rx FIFO is not enabled.
  3030. */
  3031. status_t FLEXCAN_TransferReceiveFifoBlocking(CAN_Type *base, flexcan_frame_t *pRxFrame)
  3032. {
  3033. status_t rxFifoStatus;
  3034. /* Wait until Legacy Rx FIFO non-empty. */
  3035. while (0U == FLEXCAN_GetMbStatusFlags(base, (uint32_t)kFLEXCAN_RxFifoFrameAvlFlag))
  3036. {
  3037. }
  3038. /* Read data from Legacy Rx FIFO. */
  3039. rxFifoStatus = FLEXCAN_ReadRxFifo(base, pRxFrame);
  3040. /* Clean Rx Fifo available flag. */
  3041. FLEXCAN_ClearMbStatusFlags(base, (uint32_t)kFLEXCAN_RxFifoFrameAvlFlag);
  3042. return rxFifoStatus;
  3043. }
  3044. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO)
  3045. /*!
  3046. * brief Performs a polling receive transaction from Enhanced Rx FIFO on the CAN bus.
  3047. *
  3048. * note A transfer handle does not need to be created before calling this API.
  3049. *
  3050. * param base FlexCAN peripheral base pointer.
  3051. * param pRxFrame Pointer to CAN FD message frame structure for reception.
  3052. * retval kStatus_Success - Read Message from Rx FIFO successfully.
  3053. * retval kStatus_Fail - Rx FIFO is not enabled.
  3054. */
  3055. status_t FLEXCAN_TransferReceiveEnhancedFifoBlocking(CAN_Type *base, flexcan_fd_frame_t *pRxFrame)
  3056. {
  3057. status_t rxFifoStatus;
  3058. /* Wait until Enhanced Rx FIFO non-empty. */
  3059. while (0U == (FLEXCAN_GetStatusFlags(base) & (uint64_t)kFLEXCAN_ERxFifoDataAvlIntFlag))
  3060. {
  3061. }
  3062. /* Read data from Enhanced Rx FIFO */
  3063. rxFifoStatus = FLEXCAN_ReadEnhancedRxFifo(base, pRxFrame);
  3064. /* Clean Enhanced Rx Fifo data available flag. */
  3065. FLEXCAN_ClearStatusFlags(base, (uint64_t)kFLEXCAN_ERxFifoDataAvlIntFlag);
  3066. return rxFifoStatus;
  3067. }
  3068. #endif
  3069. /*!
  3070. * brief Initializes the FlexCAN handle.
  3071. *
  3072. * This function initializes the FlexCAN handle, which can be used for other FlexCAN
  3073. * transactional APIs. Usually, for a specified FlexCAN instance,
  3074. * call this API once to get the initialized handle.
  3075. *
  3076. * param base FlexCAN peripheral base address.
  3077. * param handle FlexCAN handle pointer.
  3078. * param callback The callback function.
  3079. * param userData The parameter of the callback function.
  3080. */
  3081. void FLEXCAN_TransferCreateHandle(CAN_Type *base,
  3082. flexcan_handle_t *handle,
  3083. flexcan_transfer_callback_t callback,
  3084. void *userData)
  3085. {
  3086. assert(NULL != handle);
  3087. uint8_t instance;
  3088. /* Clean FlexCAN transfer handle. */
  3089. (void)memset(handle, 0, sizeof(*handle));
  3090. /* Get instance from peripheral base address. */
  3091. instance = (uint8_t)FLEXCAN_GetInstance(base);
  3092. /* Save the context in global variables to support the double weak mechanism. */
  3093. s_flexcanHandle[instance] = handle;
  3094. /* Register Callback function. */
  3095. handle->callback = callback;
  3096. handle->userData = userData;
  3097. s_flexcanIsr = FLEXCAN_TransferHandleIRQ;
  3098. /* We Enable Error & Status interrupt here, because this interrupt just
  3099. * report current status of FlexCAN module through Callback function.
  3100. * It is insignificance without a available callback function.
  3101. */
  3102. if (handle->callback != NULL)
  3103. {
  3104. FLEXCAN_EnableInterrupts(
  3105. base, (uint32_t)kFLEXCAN_BusOffInterruptEnable | (uint32_t)kFLEXCAN_ErrorInterruptEnable |
  3106. (uint32_t)kFLEXCAN_RxWarningInterruptEnable | (uint32_t)kFLEXCAN_TxWarningInterruptEnable |
  3107. (uint32_t)kFLEXCAN_WakeUpInterruptEnable
  3108. #if (defined(FSL_FEATURE_FLEXCAN_HAS_PN_MODE) && FSL_FEATURE_FLEXCAN_HAS_PN_MODE)
  3109. | (uint64_t)kFLEXCAN_PNMatchWakeUpInterruptEnable |
  3110. (uint64_t)kFLEXCAN_PNTimeoutWakeUpInterruptEnable
  3111. #endif
  3112. #if (defined(FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL) && FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL)
  3113. | (uint64_t)kFLEXCAN_HostAccessNCErrorInterruptEnable |
  3114. (uint64_t)kFLEXCAN_FlexCanAccessNCErrorInterruptEnable |
  3115. (uint64_t)kFLEXCAN_HostOrFlexCanCErrorInterruptEnable
  3116. #endif
  3117. );
  3118. }
  3119. else
  3120. {
  3121. FLEXCAN_DisableInterrupts(
  3122. base, (uint32_t)kFLEXCAN_BusOffInterruptEnable | (uint32_t)kFLEXCAN_ErrorInterruptEnable |
  3123. (uint32_t)kFLEXCAN_RxWarningInterruptEnable | (uint32_t)kFLEXCAN_TxWarningInterruptEnable |
  3124. (uint32_t)kFLEXCAN_WakeUpInterruptEnable
  3125. #if (defined(FSL_FEATURE_FLEXCAN_HAS_PN_MODE) && FSL_FEATURE_FLEXCAN_HAS_PN_MODE)
  3126. | (uint64_t)kFLEXCAN_PNMatchWakeUpInterruptEnable |
  3127. (uint64_t)kFLEXCAN_PNTimeoutWakeUpInterruptEnable
  3128. #endif
  3129. #if (defined(FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL) && FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL)
  3130. | (uint64_t)kFLEXCAN_HostAccessNCErrorInterruptEnable |
  3131. (uint64_t)kFLEXCAN_FlexCanAccessNCErrorInterruptEnable |
  3132. (uint64_t)kFLEXCAN_HostOrFlexCanCErrorInterruptEnable
  3133. #endif
  3134. );
  3135. }
  3136. /* Enable interrupts in NVIC. */
  3137. (void)EnableIRQ((IRQn_Type)(s_flexcanRxWarningIRQ[instance]));
  3138. (void)EnableIRQ((IRQn_Type)(s_flexcanTxWarningIRQ[instance]));
  3139. (void)EnableIRQ((IRQn_Type)(s_flexcanWakeUpIRQ[instance]));
  3140. (void)EnableIRQ((IRQn_Type)(s_flexcanErrorIRQ[instance]));
  3141. (void)EnableIRQ((IRQn_Type)(s_flexcanBusOffIRQ[instance]));
  3142. (void)EnableIRQ((IRQn_Type)(s_flexcanMbIRQ[instance]));
  3143. }
  3144. /*!
  3145. * brief Sends a message using IRQ.
  3146. *
  3147. * This function sends a message using IRQ. This is a non-blocking function, which returns
  3148. * right away. When messages have been sent out, the send callback function is called.
  3149. *
  3150. * param base FlexCAN peripheral base address.
  3151. * param handle FlexCAN handle pointer.
  3152. * param pMbXfer FlexCAN Message Buffer transfer structure. See the #flexcan_mb_transfer_t.
  3153. * retval kStatus_Success Start Tx Message Buffer sending process successfully.
  3154. * retval kStatus_Fail Write Tx Message Buffer failed.
  3155. * retval kStatus_FLEXCAN_TxBusy Tx Message Buffer is in use.
  3156. */
  3157. status_t FLEXCAN_TransferSendNonBlocking(CAN_Type *base, flexcan_handle_t *handle, flexcan_mb_transfer_t *pMbXfer)
  3158. {
  3159. /* Assertion. */
  3160. assert(NULL != handle);
  3161. assert(NULL != pMbXfer);
  3162. assert(pMbXfer->mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  3163. #if !defined(NDEBUG)
  3164. assert(!FLEXCAN_IsMbOccupied(base, pMbXfer->mbIdx));
  3165. #endif
  3166. status_t status;
  3167. /* Check if Message Buffer is idle. */
  3168. if ((uint8_t)kFLEXCAN_StateIdle == handle->mbState[pMbXfer->mbIdx])
  3169. {
  3170. /* Distinguish transmit type. */
  3171. if ((uint32_t)kFLEXCAN_FrameTypeRemote == pMbXfer->frame->type)
  3172. {
  3173. handle->mbState[pMbXfer->mbIdx] = (uint8_t)kFLEXCAN_StateTxRemote;
  3174. }
  3175. else
  3176. {
  3177. handle->mbState[pMbXfer->mbIdx] = (uint8_t)kFLEXCAN_StateTxData;
  3178. }
  3179. if (kStatus_Success ==
  3180. FLEXCAN_WriteTxMb(base, pMbXfer->mbIdx, (const flexcan_frame_t *)(uint32_t)pMbXfer->frame))
  3181. {
  3182. /* Enable Message Buffer Interrupt. */
  3183. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  3184. uint64_t u64mask = 1;
  3185. FLEXCAN_EnableMbInterrupts(base, u64mask << pMbXfer->mbIdx);
  3186. #else
  3187. uint32_t u32mask = 1;
  3188. FLEXCAN_EnableMbInterrupts(base, u32mask << pMbXfer->mbIdx);
  3189. #endif
  3190. status = kStatus_Success;
  3191. }
  3192. else
  3193. {
  3194. handle->mbState[pMbXfer->mbIdx] = (uint8_t)kFLEXCAN_StateIdle;
  3195. status = kStatus_Fail;
  3196. }
  3197. }
  3198. else
  3199. {
  3200. status = kStatus_FLEXCAN_TxBusy;
  3201. }
  3202. return status;
  3203. }
  3204. /*!
  3205. * brief Receives a message using IRQ.
  3206. *
  3207. * This function receives a message using IRQ. This is non-blocking function, which returns
  3208. * right away. When the message has been received, the receive callback function is called.
  3209. *
  3210. * param base FlexCAN peripheral base address.
  3211. * param handle FlexCAN handle pointer.
  3212. * param pMbXfer FlexCAN Message Buffer transfer structure. See the #flexcan_mb_transfer_t.
  3213. * retval kStatus_Success - Start Rx Message Buffer receiving process successfully.
  3214. * retval kStatus_FLEXCAN_RxBusy - Rx Message Buffer is in use.
  3215. */
  3216. status_t FLEXCAN_TransferReceiveNonBlocking(CAN_Type *base, flexcan_handle_t *handle, flexcan_mb_transfer_t *pMbXfer)
  3217. {
  3218. status_t status;
  3219. /* Assertion. */
  3220. assert(NULL != handle);
  3221. assert(NULL != pMbXfer);
  3222. assert(pMbXfer->mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  3223. #if !defined(NDEBUG)
  3224. assert(!FLEXCAN_IsMbOccupied(base, pMbXfer->mbIdx));
  3225. #endif
  3226. /* Check if Message Buffer is idle. */
  3227. if ((uint8_t)kFLEXCAN_StateIdle == handle->mbState[pMbXfer->mbIdx])
  3228. {
  3229. handle->mbState[pMbXfer->mbIdx] = (uint8_t)kFLEXCAN_StateRxData;
  3230. /* Register Message Buffer. */
  3231. handle->mbFrameBuf[pMbXfer->mbIdx] = pMbXfer->frame;
  3232. /* Enable Message Buffer Interrupt. */
  3233. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  3234. uint64_t u64mask = 1;
  3235. FLEXCAN_EnableMbInterrupts(base, u64mask << pMbXfer->mbIdx);
  3236. #else
  3237. uint32_t u32mask = 1;
  3238. FLEXCAN_EnableMbInterrupts(base, u32mask << pMbXfer->mbIdx);
  3239. #endif
  3240. status = kStatus_Success;
  3241. }
  3242. else
  3243. {
  3244. status = kStatus_FLEXCAN_RxBusy;
  3245. }
  3246. return status;
  3247. }
  3248. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  3249. /*!
  3250. * brief Sends a message using IRQ.
  3251. *
  3252. * This function sends a message using IRQ. This is a non-blocking function, which returns
  3253. * right away. When messages have been sent out, the send callback function is called.
  3254. *
  3255. * param base FlexCAN peripheral base address.
  3256. * param handle FlexCAN handle pointer.
  3257. * param pMbXfer FlexCAN FD Message Buffer transfer structure. See the #flexcan_mb_transfer_t.
  3258. * retval kStatus_Success Start Tx Message Buffer sending process successfully.
  3259. * retval kStatus_Fail Write Tx Message Buffer failed.
  3260. * retval kStatus_FLEXCAN_TxBusy Tx Message Buffer is in use.
  3261. */
  3262. status_t FLEXCAN_TransferFDSendNonBlocking(CAN_Type *base, flexcan_handle_t *handle, flexcan_mb_transfer_t *pMbXfer)
  3263. {
  3264. /* Assertion. */
  3265. assert(NULL != handle);
  3266. assert(NULL != pMbXfer);
  3267. assert(pMbXfer->mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  3268. #if !defined(NDEBUG)
  3269. assert(!FLEXCAN_IsMbOccupied(base, pMbXfer->mbIdx));
  3270. #endif
  3271. status_t status;
  3272. /* Check if Message Buffer is idle. */
  3273. if ((uint8_t)kFLEXCAN_StateIdle == handle->mbState[pMbXfer->mbIdx])
  3274. {
  3275. /* Distinguish transmit type. */
  3276. if ((uint32_t)kFLEXCAN_FrameTypeRemote == pMbXfer->framefd->type)
  3277. {
  3278. handle->mbState[pMbXfer->mbIdx] = (uint8_t)kFLEXCAN_StateTxRemote;
  3279. }
  3280. else
  3281. {
  3282. handle->mbState[pMbXfer->mbIdx] = (uint8_t)kFLEXCAN_StateTxData;
  3283. }
  3284. if (kStatus_Success ==
  3285. FLEXCAN_WriteFDTxMb(base, pMbXfer->mbIdx, (const flexcan_fd_frame_t *)(uint32_t)pMbXfer->framefd))
  3286. {
  3287. /* Enable Message Buffer Interrupt. */
  3288. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  3289. uint64_t u64mask = 1;
  3290. FLEXCAN_EnableMbInterrupts(base, u64mask << pMbXfer->mbIdx);
  3291. #else
  3292. uint32_t u32mask = 1;
  3293. FLEXCAN_EnableMbInterrupts(base, u32mask << pMbXfer->mbIdx);
  3294. #endif
  3295. status = kStatus_Success;
  3296. }
  3297. else
  3298. {
  3299. handle->mbState[pMbXfer->mbIdx] = (uint8_t)kFLEXCAN_StateIdle;
  3300. status = kStatus_Fail;
  3301. }
  3302. }
  3303. else
  3304. {
  3305. status = kStatus_FLEXCAN_TxBusy;
  3306. }
  3307. return status;
  3308. }
  3309. /*!
  3310. * brief Receives a message using IRQ.
  3311. *
  3312. * This function receives a message using IRQ. This is non-blocking function, which returns
  3313. * right away. When the message has been received, the receive callback function is called.
  3314. *
  3315. * param base FlexCAN peripheral base address.
  3316. * param handle FlexCAN handle pointer.
  3317. * param pMbXfer FlexCAN FD Message Buffer transfer structure. See the #flexcan_mb_transfer_t.
  3318. * retval kStatus_Success - Start Rx Message Buffer receiving process successfully.
  3319. * retval kStatus_FLEXCAN_RxBusy - Rx Message Buffer is in use.
  3320. */
  3321. status_t FLEXCAN_TransferFDReceiveNonBlocking(CAN_Type *base, flexcan_handle_t *handle, flexcan_mb_transfer_t *pMbXfer)
  3322. {
  3323. /* Assertion. */
  3324. assert(NULL != handle);
  3325. assert(NULL != pMbXfer);
  3326. assert(pMbXfer->mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  3327. #if !defined(NDEBUG)
  3328. assert(!FLEXCAN_IsMbOccupied(base, pMbXfer->mbIdx));
  3329. #endif
  3330. status_t status;
  3331. /* Check if Message Buffer is idle. */
  3332. if ((uint8_t)kFLEXCAN_StateIdle == handle->mbState[pMbXfer->mbIdx])
  3333. {
  3334. handle->mbState[pMbXfer->mbIdx] = (uint8_t)kFLEXCAN_StateRxData;
  3335. /* Register Message Buffer. */
  3336. handle->mbFDFrameBuf[pMbXfer->mbIdx] = pMbXfer->framefd;
  3337. /* Enable Message Buffer Interrupt. */
  3338. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  3339. uint64_t u64mask = 1;
  3340. FLEXCAN_EnableMbInterrupts(base, u64mask << pMbXfer->mbIdx);
  3341. #else
  3342. uint32_t u32mask = 1;
  3343. FLEXCAN_EnableMbInterrupts(base, u32mask << pMbXfer->mbIdx);
  3344. #endif
  3345. status = kStatus_Success;
  3346. }
  3347. else
  3348. {
  3349. status = kStatus_FLEXCAN_RxBusy;
  3350. }
  3351. return status;
  3352. }
  3353. #endif
  3354. /*!
  3355. * brief Receives a message from Legacy Rx FIFO using IRQ.
  3356. *
  3357. * This function receives a message using IRQ. This is a non-blocking function, which returns
  3358. * right away. When all messages have been received, the receive callback function is called.
  3359. *
  3360. * param base FlexCAN peripheral base address.
  3361. * param handle FlexCAN handle pointer.
  3362. * param pFifoXfer FlexCAN Rx FIFO transfer structure. See the ref flexcan_fifo_transfer_t.
  3363. * retval kStatus_Success - Start Rx FIFO receiving process successfully.
  3364. * retval kStatus_FLEXCAN_RxFifoBusy - Rx FIFO is currently in use.
  3365. */
  3366. status_t FLEXCAN_TransferReceiveFifoNonBlocking(CAN_Type *base,
  3367. flexcan_handle_t *handle,
  3368. flexcan_fifo_transfer_t *pFifoXfer)
  3369. {
  3370. /* Assertion. */
  3371. assert(NULL != handle);
  3372. assert(NULL != pFifoXfer);
  3373. status_t status;
  3374. /* Check if Message Buffer is idle. */
  3375. if ((uint8_t)kFLEXCAN_StateIdle == handle->rxFifoState)
  3376. {
  3377. handle->rxFifoState = (uint8_t)kFLEXCAN_StateRxFifo;
  3378. /* Register Message Buffer. */
  3379. handle->rxFifoFrameBuf = pFifoXfer->frame;
  3380. /* Enable Message Buffer Interrupt. */
  3381. FLEXCAN_EnableMbInterrupts(base, (uint32_t)kFLEXCAN_RxFifoOverflowFlag | (uint32_t)kFLEXCAN_RxFifoWarningFlag |
  3382. (uint32_t)kFLEXCAN_RxFifoFrameAvlFlag);
  3383. status = kStatus_Success;
  3384. }
  3385. else
  3386. {
  3387. status = kStatus_FLEXCAN_RxFifoBusy;
  3388. }
  3389. return status;
  3390. }
  3391. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO)
  3392. /*!
  3393. * brief Receives a message from Enhanced Rx FIFO using IRQ.
  3394. *
  3395. * This function receives a message using IRQ. This is a non-blocking function, which returns
  3396. * right away. When all messages have been received, the receive callback function is called.
  3397. *
  3398. * param base FlexCAN peripheral base address.
  3399. * param handle FlexCAN handle pointer.
  3400. * param pFifoXfer FlexCAN Rx FIFO transfer structure. See the ref flexcan_fifo_transfer_t.
  3401. * retval kStatus_Success - Start Rx FIFO receiving process successfully.
  3402. * retval kStatus_FLEXCAN_RxFifoBusy - Rx FIFO is currently in use.
  3403. */
  3404. status_t FLEXCAN_TransferReceiveEnhancedFifoNonBlocking(CAN_Type *base,
  3405. flexcan_handle_t *handle,
  3406. flexcan_fifo_transfer_t *pFifoXfer)
  3407. {
  3408. /* Assertion. */
  3409. assert(NULL != handle);
  3410. assert(NULL != pFifoXfer);
  3411. status_t status;
  3412. uint32_t watermark = ((base->ERFCR & CAN_ERFCR_ERFWM_MASK) >> CAN_ERFCR_ERFWM_SHIFT) + 1U;
  3413. uint64_t irqMask =
  3414. (uint64_t)kFLEXCAN_ERxFifoUnderflowInterruptEnable | (uint64_t)kFLEXCAN_ERxFifoOverflowInterruptEnable;
  3415. /* Check if Enhanced Rx FIFO is idle. */
  3416. if ((uint8_t)kFLEXCAN_StateIdle == handle->rxFifoState)
  3417. {
  3418. handle->rxFifoState = (uint8_t)kFLEXCAN_StateRxFifo;
  3419. /* Register Message Buffer. */
  3420. handle->rxFifoFDFrameBuf = pFifoXfer->framefd;
  3421. handle->frameNum = pFifoXfer->frameNum;
  3422. handle->transferTotalNum = pFifoXfer->frameNum;
  3423. if (handle->transferTotalNum >= watermark)
  3424. {
  3425. /* Enable watermark interrupt. */
  3426. irqMask |= (uint64_t)kFLEXCAN_ERxFifoWatermarkInterruptEnable;
  3427. }
  3428. else
  3429. {
  3430. /* Enable data available interrupt. */
  3431. irqMask |= (uint64_t)kFLEXCAN_ERxFifoDataAvlInterruptEnable;
  3432. }
  3433. /* Enable Enhanced Rx FIFO Interrupt. */
  3434. FLEXCAN_EnableInterrupts(base, irqMask);
  3435. status = kStatus_Success;
  3436. }
  3437. else
  3438. {
  3439. status = kStatus_FLEXCAN_RxFifoBusy;
  3440. }
  3441. return status;
  3442. }
  3443. /*!
  3444. * brief Gets the Enhanced Rx Fifo transfer status during a interrupt non-blocking receive.
  3445. *
  3446. * param base FlexCAN peripheral base address.
  3447. * param handle FlexCAN handle pointer.
  3448. * param count Number of CAN messages receive so far by the non-blocking transaction.
  3449. * retval kStatus_InvalidArgument count is Invalid.
  3450. * retval kStatus_Success Successfully return the count.
  3451. */
  3452. status_t FLEXCAN_TransferGetReceiveEnhancedFifoCount(CAN_Type *base, flexcan_handle_t *handle, size_t *count)
  3453. {
  3454. assert(NULL != handle);
  3455. status_t result = kStatus_Success;
  3456. if (handle->rxFifoState == (uint32_t)kFLEXCAN_StateIdle)
  3457. {
  3458. result = kStatus_NoTransferInProgress;
  3459. }
  3460. else
  3461. {
  3462. *count = handle->transferTotalNum - handle->frameNum;
  3463. }
  3464. return result;
  3465. }
  3466. #endif
  3467. /*!
  3468. * brief Aborts the interrupt driven message send process.
  3469. *
  3470. * This function aborts the interrupt driven message send process.
  3471. *
  3472. * param base FlexCAN peripheral base address.
  3473. * param handle FlexCAN handle pointer.
  3474. * param mbIdx The FlexCAN Message Buffer index.
  3475. */
  3476. void FLEXCAN_TransferAbortSend(CAN_Type *base, flexcan_handle_t *handle, uint8_t mbIdx)
  3477. {
  3478. uint16_t timestamp;
  3479. /* Assertion. */
  3480. assert(NULL != handle);
  3481. assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  3482. #if !defined(NDEBUG)
  3483. assert(!FLEXCAN_IsMbOccupied(base, mbIdx));
  3484. #endif
  3485. /* Disable Message Buffer Interrupt. */
  3486. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  3487. uint64_t u64mask = 1;
  3488. FLEXCAN_DisableMbInterrupts(base, u64mask << mbIdx);
  3489. #else
  3490. uint32_t u32mask = 1;
  3491. FLEXCAN_DisableMbInterrupts(base, u32mask << mbIdx);
  3492. #endif
  3493. /* Update the TX frame 's time stamp by MB[mbIdx].cs. */
  3494. timestamp = (uint16_t)((base->MB[mbIdx].CS & CAN_CS_TIME_STAMP_MASK) >> CAN_CS_TIME_STAMP_SHIFT);
  3495. handle->timestamp[mbIdx] = timestamp;
  3496. /* Clean Message Buffer. */
  3497. FLEXCAN_SetTxMbConfig(base, mbIdx, true);
  3498. handle->mbState[mbIdx] = (uint8_t)kFLEXCAN_StateIdle;
  3499. }
  3500. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  3501. /*!
  3502. * brief Aborts the interrupt driven message send process.
  3503. *
  3504. * This function aborts the interrupt driven message send process.
  3505. *
  3506. * param base FlexCAN peripheral base address.
  3507. * param handle FlexCAN handle pointer.
  3508. * param mbIdx The FlexCAN FD Message Buffer index.
  3509. */
  3510. void FLEXCAN_TransferFDAbortSend(CAN_Type *base, flexcan_handle_t *handle, uint8_t mbIdx)
  3511. {
  3512. volatile uint32_t *mbAddr;
  3513. uint32_t offset;
  3514. uint16_t timestamp;
  3515. /* Assertion. */
  3516. assert(NULL != handle);
  3517. assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  3518. #if !defined(NDEBUG)
  3519. assert(!FLEXCAN_IsMbOccupied(base, mbIdx));
  3520. #endif
  3521. /* Disable Message Buffer Interrupt. */
  3522. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  3523. uint64_t u64mask = 1;
  3524. FLEXCAN_DisableMbInterrupts(base, u64mask << mbIdx);
  3525. #else
  3526. uint32_t u32mask = 1;
  3527. FLEXCAN_DisableMbInterrupts(base, u32mask << mbIdx);
  3528. #endif
  3529. /* Update the TX frame 's time stamp by base->MB[offset for CAN FD].CS. */
  3530. mbAddr = &(base->MB[0].CS);
  3531. offset = FLEXCAN_GetFDMailboxOffset(base, mbIdx);
  3532. timestamp = (uint16_t)((mbAddr[offset] & CAN_CS_TIME_STAMP_MASK) >> CAN_CS_TIME_STAMP_SHIFT);
  3533. handle->timestamp[mbIdx] = timestamp;
  3534. /* Clean Message Buffer. */
  3535. FLEXCAN_SetFDTxMbConfig(base, mbIdx, true);
  3536. handle->mbState[mbIdx] = (uint8_t)kFLEXCAN_StateIdle;
  3537. }
  3538. /*!
  3539. * brief Aborts the interrupt driven message receive process.
  3540. *
  3541. * This function aborts the interrupt driven message receive process.
  3542. *
  3543. * param base FlexCAN peripheral base address.
  3544. * param handle FlexCAN handle pointer.
  3545. * param mbIdx The FlexCAN FD Message Buffer index.
  3546. */
  3547. void FLEXCAN_TransferFDAbortReceive(CAN_Type *base, flexcan_handle_t *handle, uint8_t mbIdx)
  3548. {
  3549. /* Assertion. */
  3550. assert(NULL != handle);
  3551. assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  3552. #if !defined(NDEBUG)
  3553. assert(!FLEXCAN_IsMbOccupied(base, mbIdx));
  3554. #endif
  3555. /* Disable Message Buffer Interrupt. */
  3556. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  3557. uint64_t u64mask = 1;
  3558. FLEXCAN_DisableMbInterrupts(base, u64mask << mbIdx);
  3559. #else
  3560. uint32_t u32mask = 1;
  3561. FLEXCAN_DisableMbInterrupts(base, u32mask << mbIdx);
  3562. #endif
  3563. /* Un-register handle. */
  3564. handle->mbFDFrameBuf[mbIdx] = NULL;
  3565. handle->mbState[mbIdx] = (uint8_t)kFLEXCAN_StateIdle;
  3566. }
  3567. #endif
  3568. /*!
  3569. * brief Aborts the interrupt driven message receive process.
  3570. *
  3571. * This function aborts the interrupt driven message receive process.
  3572. *
  3573. * param base FlexCAN peripheral base address.
  3574. * param handle FlexCAN handle pointer.
  3575. * param mbIdx The FlexCAN Message Buffer index.
  3576. */
  3577. void FLEXCAN_TransferAbortReceive(CAN_Type *base, flexcan_handle_t *handle, uint8_t mbIdx)
  3578. {
  3579. /* Assertion. */
  3580. assert(NULL != handle);
  3581. assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK));
  3582. #if !defined(NDEBUG)
  3583. assert(!FLEXCAN_IsMbOccupied(base, mbIdx));
  3584. #endif
  3585. /* Disable Message Buffer Interrupt. */
  3586. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  3587. uint64_t u64mask = 1;
  3588. FLEXCAN_DisableMbInterrupts(base, (u64mask << mbIdx));
  3589. #else
  3590. uint32_t u32mask = 1;
  3591. FLEXCAN_DisableMbInterrupts(base, (u32mask << mbIdx));
  3592. #endif
  3593. /* Un-register handle. */
  3594. handle->mbFrameBuf[mbIdx] = NULL;
  3595. handle->mbState[mbIdx] = (uint8_t)kFLEXCAN_StateIdle;
  3596. }
  3597. /*!
  3598. * brief Aborts the interrupt driven message receive from Legacy Rx FIFO process.
  3599. *
  3600. * This function aborts the interrupt driven message receive from Legacy Rx FIFO process.
  3601. *
  3602. * param base FlexCAN peripheral base address.
  3603. * param handle FlexCAN handle pointer.
  3604. */
  3605. void FLEXCAN_TransferAbortReceiveFifo(CAN_Type *base, flexcan_handle_t *handle)
  3606. {
  3607. /* Assertion. */
  3608. assert(NULL != handle);
  3609. /* Check if Rx FIFO is enabled. */
  3610. if (0U != (base->MCR & CAN_MCR_RFEN_MASK))
  3611. {
  3612. /* Disable Rx Message FIFO Interrupts. */
  3613. FLEXCAN_DisableMbInterrupts(base, (uint32_t)kFLEXCAN_RxFifoOverflowFlag | (uint32_t)kFLEXCAN_RxFifoWarningFlag |
  3614. (uint32_t)kFLEXCAN_RxFifoFrameAvlFlag);
  3615. /* Un-register handle. */
  3616. handle->rxFifoFrameBuf = NULL;
  3617. }
  3618. handle->rxFifoState = (uint8_t)kFLEXCAN_StateIdle;
  3619. }
  3620. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO)
  3621. /*!
  3622. * brief Aborts the interrupt driven message receive from Enhanced Rx FIFO process.
  3623. *
  3624. * This function aborts the interrupt driven message receive from Rx FIFO process.
  3625. *
  3626. * param base FlexCAN peripheral base address.
  3627. * param handle FlexCAN handle pointer.
  3628. */
  3629. void FLEXCAN_TransferAbortReceiveEnhancedFifo(CAN_Type *base, flexcan_handle_t *handle)
  3630. {
  3631. /* Assertion. */
  3632. assert(NULL != handle);
  3633. /* Check if Enhanced Rx FIFO is enabled. */
  3634. if (0U != (base->ERFCR & CAN_ERFCR_ERFEN_MASK))
  3635. {
  3636. /* Disable all Rx Message FIFO interrupts. */
  3637. FLEXCAN_DisableInterrupts(base, (uint64_t)kFLEXCAN_ERxFifoUnderflowInterruptEnable |
  3638. (uint64_t)kFLEXCAN_ERxFifoOverflowInterruptEnable |
  3639. (uint64_t)kFLEXCAN_ERxFifoWatermarkInterruptEnable |
  3640. (uint64_t)kFLEXCAN_ERxFifoDataAvlInterruptEnable);
  3641. /* Un-register handle. */
  3642. handle->rxFifoFDFrameBuf = NULL;
  3643. /* Clear transfer count. */
  3644. handle->frameNum = 0U;
  3645. handle->transferTotalNum = 0U;
  3646. }
  3647. handle->rxFifoState = (uint8_t)kFLEXCAN_StateIdle;
  3648. }
  3649. #endif
  3650. /*!
  3651. * brief Gets the detail index of Mailbox's Timestamp by handle.
  3652. *
  3653. * Then function can only be used when calling non-blocking Data transfer (TX/RX) API,
  3654. * After TX/RX data transfer done (User can get the status by handler's callback function),
  3655. * we can get the detail index of Mailbox's timestamp by handle,
  3656. * Detail non-blocking data transfer API (TX/RX) contain.
  3657. * -FLEXCAN_TransferSendNonBlocking
  3658. * -FLEXCAN_TransferFDSendNonBlocking
  3659. * -FLEXCAN_TransferReceiveNonBlocking
  3660. * -FLEXCAN_TransferFDReceiveNonBlocking
  3661. * -FLEXCAN_TransferReceiveFifoNonBlocking
  3662. *
  3663. * param handle FlexCAN handle pointer.
  3664. * param mbIdx The FlexCAN FD Message Buffer index.
  3665. * return the index of mailbox 's timestamp stored in the handle.
  3666. *
  3667. */
  3668. uint32_t FLEXCAN_GetTimeStamp(flexcan_handle_t *handle, uint8_t mbIdx)
  3669. {
  3670. /* Assertion. */
  3671. assert(NULL != handle);
  3672. return (uint32_t)(handle->timestamp[mbIdx]);
  3673. }
  3674. /*!
  3675. * brief Check unhandle interrupt events
  3676. *
  3677. * param base FlexCAN peripheral base address.
  3678. * return TRUE if unhandled interrupt action exist, FALSE if no unhandlered interrupt action exist.
  3679. */
  3680. static bool FLEXCAN_CheckUnhandleInterruptEvents(CAN_Type *base)
  3681. {
  3682. uint64_t tempmask;
  3683. uint64_t tempflag;
  3684. bool fgRet = false;
  3685. /* Checking exist error or status flag. */
  3686. if (0U == (FLEXCAN_GetStatusFlags(base) & (FLEXCAN_ERROR_AND_STATUS_INIT_FLAG | FLEXCAN_WAKE_UP_FLAG)))
  3687. {
  3688. tempmask = (uint64_t)base->IMASK1;
  3689. tempflag = (uint64_t)base->IFLAG1;
  3690. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  3691. /* Checking whether exist MB interrupt status and legacy RX FIFO interrupt status. */
  3692. tempmask |= ((uint64_t)base->IMASK2) << 32;
  3693. tempflag |= ((uint64_t)base->IFLAG2) << 32;
  3694. #endif
  3695. fgRet = (0U != (tempmask & tempflag));
  3696. }
  3697. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO)
  3698. else if (0U == (FLEXCAN_GetStatusFlags(base) & FLEXCAN_MEMORY_ENHANCED_RX_FIFO_INIT_FLAG))
  3699. {
  3700. /* Checking whether exist enhanced RX FIFO interrupt status. */
  3701. tempmask = (uint64_t)base->ERFIER;
  3702. tempflag = (uint64_t)base->ERFSR;
  3703. fgRet = (0U != (tempmask & tempflag));
  3704. }
  3705. #endif
  3706. else
  3707. {
  3708. fgRet = true;
  3709. }
  3710. return fgRet;
  3711. }
  3712. /*!
  3713. * brief Sub Handler Data Trasfered Events
  3714. *
  3715. * param base FlexCAN peripheral base address.
  3716. * param handle FlexCAN handle pointer.
  3717. * param pResult Pointer to the Handle result.
  3718. *
  3719. * return the status after handle each data transfered event.
  3720. */
  3721. static status_t FLEXCAN_SubHandlerForDataTransfered(CAN_Type *base, flexcan_handle_t *handle, uint32_t *pResult)
  3722. {
  3723. status_t status = kStatus_FLEXCAN_UnHandled;
  3724. uint32_t result = 0xFFU;
  3725. /* For this implementation, we solve the Message with lowest MB index first. */
  3726. for (result = 0U; result < (uint32_t)FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base); result++)
  3727. {
  3728. /* Get the lowest unhandled Message Buffer */
  3729. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  3730. uint64_t u64flag = 1;
  3731. if (0U != FLEXCAN_GetMbStatusFlags(base, u64flag << result))
  3732. #else
  3733. uint32_t u32flag = 1;
  3734. if (0U != FLEXCAN_GetMbStatusFlags(base, u32flag << result))
  3735. #endif
  3736. {
  3737. if (FLEXCAN_IsMbIntEnabled(base, (uint8_t)result))
  3738. {
  3739. break;
  3740. }
  3741. }
  3742. }
  3743. /* find Message to deal with. */
  3744. if (result < (uint32_t)FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base))
  3745. {
  3746. /* Solve Legacy Rx FIFO interrupt. */
  3747. if (((uint8_t)kFLEXCAN_StateIdle != handle->rxFifoState) && (result <= (uint32_t)CAN_IFLAG1_BUF7I_SHIFT) &&
  3748. ((base->MCR & CAN_MCR_RFEN_MASK) != 0U))
  3749. {
  3750. uint32_t u32mask = 1;
  3751. switch (u32mask << result)
  3752. {
  3753. case kFLEXCAN_RxFifoOverflowFlag:
  3754. status = kStatus_FLEXCAN_RxFifoOverflow;
  3755. break;
  3756. case kFLEXCAN_RxFifoWarningFlag:
  3757. status = kStatus_FLEXCAN_RxFifoWarning;
  3758. break;
  3759. case kFLEXCAN_RxFifoFrameAvlFlag:
  3760. status = FLEXCAN_ReadRxFifo(base, handle->rxFifoFrameBuf);
  3761. if (kStatus_Success == status)
  3762. {
  3763. /* Align the current (index 0) rxfifo timestamp to the timestamp array by handle. */
  3764. handle->timestamp[0] = handle->rxFifoFrameBuf->timestamp;
  3765. status = kStatus_FLEXCAN_RxFifoIdle;
  3766. }
  3767. FLEXCAN_TransferAbortReceiveFifo(base, handle);
  3768. break;
  3769. default:
  3770. status = kStatus_FLEXCAN_UnHandled;
  3771. break;
  3772. }
  3773. }
  3774. else
  3775. {
  3776. /* Get current State of Message Buffer. */
  3777. switch (handle->mbState[result])
  3778. {
  3779. /* Solve Rx Data Frame. */
  3780. case (uint8_t)kFLEXCAN_StateRxData:
  3781. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  3782. if (0U != (base->MCR & CAN_MCR_FDEN_MASK))
  3783. {
  3784. status = FLEXCAN_ReadFDRxMb(base, (uint8_t)result, handle->mbFDFrameBuf[result]);
  3785. if (kStatus_Success == status)
  3786. {
  3787. /* Align the current index of RX MB timestamp to the timestamp array by handle. */
  3788. handle->timestamp[result] = handle->mbFDFrameBuf[result]->timestamp;
  3789. status = kStatus_FLEXCAN_RxIdle;
  3790. }
  3791. }
  3792. else
  3793. #endif
  3794. {
  3795. status = FLEXCAN_ReadRxMb(base, (uint8_t)result, handle->mbFrameBuf[result]);
  3796. if (kStatus_Success == status)
  3797. {
  3798. /* Align the current index of RX MB timestamp to the timestamp array by handle. */
  3799. handle->timestamp[result] = handle->mbFrameBuf[result]->timestamp;
  3800. status = kStatus_FLEXCAN_RxIdle;
  3801. }
  3802. }
  3803. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  3804. if (0U != (base->MCR & CAN_MCR_FDEN_MASK))
  3805. {
  3806. FLEXCAN_TransferFDAbortReceive(base, handle, (uint8_t)result);
  3807. }
  3808. else
  3809. #endif
  3810. {
  3811. FLEXCAN_TransferAbortReceive(base, handle, (uint8_t)result);
  3812. }
  3813. break;
  3814. /* Sove Rx Remote Frame. User need to Read the frame in Mail box in time by Read from MB API. */
  3815. case (uint8_t)kFLEXCAN_StateRxRemote:
  3816. status = kStatus_FLEXCAN_RxRemote;
  3817. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  3818. if (0U != (base->MCR & CAN_MCR_FDEN_MASK))
  3819. {
  3820. FLEXCAN_TransferFDAbortReceive(base, handle, (uint8_t)result);
  3821. }
  3822. else
  3823. #endif
  3824. {
  3825. FLEXCAN_TransferAbortReceive(base, handle, (uint8_t)result);
  3826. }
  3827. break;
  3828. /* Solve Tx Data Frame. */
  3829. case (uint8_t)kFLEXCAN_StateTxData:
  3830. status = kStatus_FLEXCAN_TxIdle;
  3831. #if (defined(FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE) && FSL_FEATURE_FLEXCAN_HAS_FLEXIBLE_DATA_RATE)
  3832. if (0U != (base->MCR & CAN_MCR_FDEN_MASK))
  3833. {
  3834. FLEXCAN_TransferFDAbortSend(base, handle, (uint8_t)result);
  3835. }
  3836. else
  3837. #endif
  3838. {
  3839. FLEXCAN_TransferAbortSend(base, handle, (uint8_t)result);
  3840. }
  3841. break;
  3842. /* Solve Tx Remote Frame. */
  3843. case (uint8_t)kFLEXCAN_StateTxRemote:
  3844. handle->mbState[result] = (uint8_t)kFLEXCAN_StateRxRemote;
  3845. status = kStatus_FLEXCAN_TxSwitchToRx;
  3846. break;
  3847. default:
  3848. status = kStatus_FLEXCAN_UnHandled;
  3849. break;
  3850. }
  3851. }
  3852. /* Clear resolved Message Buffer IRQ. */
  3853. #if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0)
  3854. uint64_t u64flag = 1;
  3855. FLEXCAN_ClearMbStatusFlags(base, u64flag << result);
  3856. #else
  3857. uint32_t u32flag = 1;
  3858. FLEXCAN_ClearMbStatusFlags(base, u32flag << result);
  3859. #endif
  3860. }
  3861. *pResult = result;
  3862. return status;
  3863. }
  3864. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO)
  3865. /*!
  3866. * brief Sub Handler Ehanced Rx FIFO event
  3867. *
  3868. * param base FlexCAN peripheral base address.
  3869. * param handle FlexCAN handle pointer.
  3870. * param flags FlexCAN interrupt flags.
  3871. *
  3872. * return the status after handle Ehanced Rx FIFO event.
  3873. */
  3874. static status_t FLEXCAN_SubHandlerForEhancedRxFifo(CAN_Type *base, flexcan_handle_t *handle, uint64_t flags)
  3875. {
  3876. uint32_t watermark = ((base->ERFCR & CAN_ERFCR_ERFWM_MASK) >> CAN_ERFCR_ERFWM_SHIFT) + 1U;
  3877. uint32_t transferFrames;
  3878. status_t status;
  3879. /* Solve Ehanced Rx FIFO interrupt. */
  3880. if ((0u != (flags & (uint64_t)kFLEXCAN_ERxFifoDataAvlIntFlag)) && (0u != (base->ERFIER & CAN_ERFIER_ERFDAIE_MASK)))
  3881. {
  3882. /* Whether still has CAN messages remaining to be received. */
  3883. if (handle->frameNum > 0U)
  3884. {
  3885. status = FLEXCAN_ReadEnhancedRxFifo(base, handle->rxFifoFDFrameBuf);
  3886. if (kStatus_Success == status)
  3887. {
  3888. handle->rxFifoFDFrameBuf++;
  3889. handle->frameNum--;
  3890. }
  3891. else
  3892. {
  3893. return status;
  3894. }
  3895. }
  3896. if (handle->frameNum == 0U)
  3897. {
  3898. /* Stop receiving Ehanced Rx FIFO when the transmission is over. */
  3899. FLEXCAN_TransferAbortReceiveEnhancedFifo(base, handle);
  3900. status = kStatus_FLEXCAN_RxFifoIdle;
  3901. }
  3902. else
  3903. {
  3904. /* Continue use data avaliable interrupt. */
  3905. status = kStatus_FLEXCAN_RxFifoBusy;
  3906. }
  3907. }
  3908. else if ((0u != (flags & (uint64_t)kFLEXCAN_ERxFifoWatermarkIntFlag)) &&
  3909. (0u != (base->ERFIER & CAN_ERFIER_ERFWMIIE_MASK)))
  3910. {
  3911. /* Whether the number of CAN messages remaining to be received is greater than the watermark. */
  3912. transferFrames = (handle->frameNum > watermark) ? watermark : handle->frameNum;
  3913. for (uint32_t i = 0; i < transferFrames; i++)
  3914. {
  3915. status = FLEXCAN_ReadEnhancedRxFifo(base, handle->rxFifoFDFrameBuf);
  3916. if (kStatus_Success == status)
  3917. {
  3918. handle->rxFifoFDFrameBuf++;
  3919. handle->frameNum--;
  3920. }
  3921. else
  3922. {
  3923. return status;
  3924. }
  3925. }
  3926. if (handle->frameNum == 0U)
  3927. {
  3928. /* Stop receiving Ehanced Rx FIFO when the transmission is over. */
  3929. FLEXCAN_TransferAbortReceiveEnhancedFifo(base, handle);
  3930. status = kStatus_FLEXCAN_RxFifoIdle;
  3931. }
  3932. else if (handle->frameNum < watermark)
  3933. {
  3934. /* Disable watermark interrupt and enable data avaliable interrupt. */
  3935. FLEXCAN_DisableInterrupts(base, (uint64_t)kFLEXCAN_ERxFifoWatermarkInterruptEnable);
  3936. FLEXCAN_EnableInterrupts(base, (uint64_t)kFLEXCAN_ERxFifoDataAvlInterruptEnable);
  3937. status = kStatus_FLEXCAN_RxFifoBusy;
  3938. }
  3939. else
  3940. {
  3941. /* Continue use watermark interrupt. */
  3942. status = kStatus_FLEXCAN_RxFifoBusy;
  3943. }
  3944. }
  3945. else if ((0u != (flags & (uint64_t)kFLEXCAN_ERxFifoUnderflowIntFlag)) &&
  3946. (0u != (base->ERFIER & CAN_ERFIER_ERFUFWIE_MASK)))
  3947. {
  3948. status = kStatus_FLEXCAN_RxFifoUnderflow;
  3949. FLEXCAN_ClearStatusFlags(base, (uint64_t)kFLEXCAN_ERxFifoUnderflowIntFlag);
  3950. }
  3951. else if ((0u != (flags & (uint64_t)kFLEXCAN_ERxFifoOverflowIntFlag)) &&
  3952. (0u != (base->ERFIER & CAN_ERFIER_ERFOVFIE_MASK)))
  3953. {
  3954. status = kStatus_FLEXCAN_RxOverflow;
  3955. FLEXCAN_ClearStatusFlags(base, (uint64_t)kFLEXCAN_ERxFifoOverflowIntFlag);
  3956. }
  3957. else
  3958. {
  3959. status = kStatus_FLEXCAN_UnHandled;
  3960. }
  3961. return status;
  3962. }
  3963. #endif
  3964. /*!
  3965. * brief FlexCAN IRQ handle function.
  3966. *
  3967. * This function handles the FlexCAN Error, the Message Buffer, and the Rx FIFO IRQ request.
  3968. *
  3969. * param base FlexCAN peripheral base address.
  3970. * param handle FlexCAN handle pointer.
  3971. */
  3972. void FLEXCAN_TransferHandleIRQ(CAN_Type *base, flexcan_handle_t *handle)
  3973. {
  3974. /* Assertion. */
  3975. assert(NULL != handle);
  3976. status_t status;
  3977. uint32_t mbNum = 0xFFU;
  3978. #if (defined(FSL_FEATURE_FLEXCAN_HAS_PN_MODE) && FSL_FEATURE_FLEXCAN_HAS_PN_MODE) || \
  3979. (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) || \
  3980. (defined(FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL) && FSL_FEATURE_FLEXCAN_HAS_MEMORY_ERROR_CONTROL)
  3981. uint64_t result = 0U;
  3982. #else
  3983. uint32_t result = 0U;
  3984. #endif
  3985. do
  3986. {
  3987. /* Get Current FlexCAN Module Error and Status. */
  3988. result = FLEXCAN_GetStatusFlags(base);
  3989. /* To handle FlexCAN Error and Status Interrupt first. */
  3990. if (0U != (result & FLEXCAN_ERROR_AND_STATUS_INIT_FLAG))
  3991. {
  3992. status = kStatus_FLEXCAN_ErrorStatus;
  3993. /* Clear FlexCAN Error and Status Interrupt. */
  3994. FLEXCAN_ClearStatusFlags(base, FLEXCAN_ERROR_AND_STATUS_INIT_FLAG);
  3995. }
  3996. else if (0U != (result & FLEXCAN_WAKE_UP_FLAG))
  3997. {
  3998. status = kStatus_FLEXCAN_WakeUp;
  3999. FLEXCAN_ClearStatusFlags(base, FLEXCAN_WAKE_UP_FLAG);
  4000. }
  4001. #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO)
  4002. else if ((0U != (result & FLEXCAN_MEMORY_ENHANCED_RX_FIFO_INIT_FLAG)) &&
  4003. (0u != (base->ERFIER & FLEXCAN_MEMORY_ENHANCED_RX_FIFO_INIT_MASK)))
  4004. {
  4005. status = FLEXCAN_SubHandlerForEhancedRxFifo(base, handle, result);
  4006. }
  4007. #endif
  4008. else
  4009. {
  4010. /* To handle Message Buffer or Legacy Rx FIFO transfer. */
  4011. status = FLEXCAN_SubHandlerForDataTransfered(base, handle, &mbNum);
  4012. result = mbNum;
  4013. }
  4014. /* Calling Callback Function if has one. */
  4015. if (handle->callback != NULL)
  4016. {
  4017. handle->callback(base, handle, status, result, handle->userData);
  4018. }
  4019. } while (FLEXCAN_CheckUnhandleInterruptEvents(base));
  4020. }
  4021. #if defined(CAN0)
  4022. void CAN0_DriverIRQHandler(void);
  4023. void CAN0_DriverIRQHandler(void)
  4024. {
  4025. assert(NULL != s_flexcanHandle[0]);
  4026. s_flexcanIsr(CAN0, s_flexcanHandle[0]);
  4027. SDK_ISR_EXIT_BARRIER;
  4028. }
  4029. #endif
  4030. #if defined(CAN1)
  4031. void CAN1_DriverIRQHandler(void);
  4032. void CAN1_DriverIRQHandler(void)
  4033. {
  4034. assert(NULL != s_flexcanHandle[1]);
  4035. s_flexcanIsr(CAN1, s_flexcanHandle[1]);
  4036. SDK_ISR_EXIT_BARRIER;
  4037. }
  4038. #endif
  4039. #if defined(CAN2)
  4040. void CAN2_DriverIRQHandler(void);
  4041. void CAN2_DriverIRQHandler(void)
  4042. {
  4043. assert(NULL != s_flexcanHandle[2]);
  4044. s_flexcanIsr(CAN2, s_flexcanHandle[2]);
  4045. SDK_ISR_EXIT_BARRIER;
  4046. }
  4047. #endif
  4048. #if defined(CAN3)
  4049. void CAN3_DriverIRQHandler(void);
  4050. void CAN3_DriverIRQHandler(void)
  4051. {
  4052. assert(NULL != s_flexcanHandle[3]);
  4053. s_flexcanIsr(CAN3, s_flexcanHandle[3]);
  4054. SDK_ISR_EXIT_BARRIER;
  4055. }
  4056. #endif
  4057. #if defined(CAN4)
  4058. void CAN4_DriverIRQHandler(void);
  4059. void CAN4_DriverIRQHandler(void)
  4060. {
  4061. assert(NULL != s_flexcanHandle[4]);
  4062. s_flexcanIsr(CAN4, s_flexcanHandle[4]);
  4063. SDK_ISR_EXIT_BARRIER;
  4064. }
  4065. #endif
  4066. #if defined(DMA__CAN0)
  4067. void DMA_FLEXCAN0_INT_DriverIRQHandler(void);
  4068. void DMA_FLEXCAN0_INT_DriverIRQHandler(void)
  4069. {
  4070. assert(NULL != s_flexcanHandle[FLEXCAN_GetInstance(DMA__CAN0)]);
  4071. s_flexcanIsr(DMA__CAN0, s_flexcanHandle[FLEXCAN_GetInstance(DMA__CAN0)]);
  4072. SDK_ISR_EXIT_BARRIER;
  4073. }
  4074. #endif
  4075. #if defined(DMA__CAN1)
  4076. void DMA_FLEXCAN1_INT_DriverIRQHandler(void);
  4077. void DMA_FLEXCAN1_INT_DriverIRQHandler(void)
  4078. {
  4079. assert(NULL != s_flexcanHandle[FLEXCAN_GetInstance(DMA__CAN1)]);
  4080. s_flexcanIsr(DMA__CAN1, s_flexcanHandle[FLEXCAN_GetInstance(DMA__CAN1)]);
  4081. SDK_ISR_EXIT_BARRIER;
  4082. }
  4083. #endif
  4084. #if defined(DMA__CAN2)
  4085. void DMA_FLEXCAN2_INT_DriverIRQHandler(void);
  4086. void DMA_FLEXCAN2_INT_DriverIRQHandler(void)
  4087. {
  4088. assert(NULL != s_flexcanHandle[FLEXCAN_GetInstance(DMA__CAN2)]);
  4089. s_flexcanIsr(DMA__CAN2, s_flexcanHandle[FLEXCAN_GetInstance(DMA__CAN2)]);
  4090. SDK_ISR_EXIT_BARRIER;
  4091. }
  4092. #endif
  4093. #if defined(ADMA__CAN0)
  4094. void ADMA_FLEXCAN0_INT_DriverIRQHandler(void);
  4095. void ADMA_FLEXCAN0_INT_DriverIRQHandler(void)
  4096. {
  4097. assert(NULL != s_flexcanHandle[FLEXCAN_GetInstance(ADMA__CAN0)]);
  4098. s_flexcanIsr(ADMA__CAN0, s_flexcanHandle[FLEXCAN_GetInstance(ADMA__CAN0)]);
  4099. SDK_ISR_EXIT_BARRIER;
  4100. }
  4101. #endif
  4102. #if defined(ADMA__CAN1)
  4103. void ADMA_FLEXCAN1_INT_DriverIRQHandler(void);
  4104. void ADMA_FLEXCAN1_INT_DriverIRQHandler(void)
  4105. {
  4106. assert(NULL != s_flexcanHandle[FLEXCAN_GetInstance(ADMA__CAN1)]);
  4107. s_flexcanIsr(ADMA__CAN1, s_flexcanHandle[FLEXCAN_GetInstance(ADMA__CAN1)]);
  4108. SDK_ISR_EXIT_BARRIER;
  4109. }
  4110. #endif
  4111. #if defined(ADMA__CAN2)
  4112. void ADMA_FLEXCAN2_INT_DriverIRQHandler(void);
  4113. void ADMA_FLEXCAN2_INT_DriverIRQHandler(void)
  4114. {
  4115. assert(NULL != s_flexcanHandle[FLEXCAN_GetInstance(ADMA__CAN2)]);
  4116. s_flexcanIsr(ADMA__CAN2, s_flexcanHandle[FLEXCAN_GetInstance(ADMA__CAN2)]);
  4117. SDK_ISR_EXIT_BARRIER;
  4118. }
  4119. #endif
  4120. #if defined(FLEXCAN1)
  4121. void CAN_FD1_DriverIRQHandler(void)
  4122. {
  4123. assert(NULL != s_flexcanHandle[1]);
  4124. s_flexcanIsr(FLEXCAN1, s_flexcanHandle[1]);
  4125. SDK_ISR_EXIT_BARRIER;
  4126. }
  4127. #endif
  4128. #if defined(FLEXCAN2)
  4129. void CAN_FD2_DriverIRQHandler(void)
  4130. {
  4131. assert(NULL != s_flexcanHandle[2]);
  4132. s_flexcanIsr(FLEXCAN1, s_flexcanHandle[2]);
  4133. SDK_ISR_EXIT_BARRIER;
  4134. }
  4135. #endif