[
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\r\n                       Version 3, 29 June 2007\r\n\r\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\r\n Everyone is permitted to copy and distribute verbatim copies\r\n of this license document, but changing it is not allowed.\r\n\r\n                            Preamble\r\n\r\n  The GNU General Public License is a free, copyleft license for\r\nsoftware and other kinds of works.\r\n\r\n  The licenses for most software and other practical works are designed\r\nto take away your freedom to share and change the works.  By contrast,\r\nthe GNU General Public License is intended to guarantee your freedom to\r\nshare and change all versions of a program--to make sure it remains free\r\nsoftware for all its users.  We, the Free Software Foundation, use the\r\nGNU General Public License for most of our software; it applies also to\r\nany other work released this way by its authors.  You can apply it to\r\nyour programs, too.\r\n\r\n  When we speak of free software, we are referring to freedom, not\r\nprice.  Our General Public Licenses are designed to make sure that you\r\nhave the freedom to distribute copies of free software (and charge for\r\nthem if you wish), that you receive source code or can get it if you\r\nwant it, that you can change the software or use pieces of it in new\r\nfree programs, and that you know you can do these things.\r\n\r\n  To protect your rights, we need to prevent others from denying you\r\nthese rights or asking you to surrender the rights.  Therefore, you have\r\ncertain responsibilities if you distribute copies of the software, or if\r\nyou modify it: responsibilities to respect the freedom of others.\r\n\r\n  For example, if you distribute copies of such a program, whether\r\ngratis or for a fee, you must pass on to the recipients the same\r\nfreedoms that you received.  You must make sure that they, too, receive\r\nor can get the source code.  And you must show them these terms so they\r\nknow their rights.\r\n\r\n  Developers that use the GNU GPL protect your rights with two steps:\r\n(1) assert copyright on the software, and (2) offer you this License\r\ngiving you legal permission to copy, distribute and/or modify it.\r\n\r\n  For the developers' and authors' protection, the GPL clearly explains\r\nthat there is no warranty for this free software.  For both users' and\r\nauthors' sake, the GPL requires that modified versions be marked as\r\nchanged, so that their problems will not be attributed erroneously to\r\nauthors of previous versions.\r\n\r\n  Some devices are designed to deny users access to install or run\r\nmodified versions of the software inside them, although the manufacturer\r\ncan do so.  This is fundamentally incompatible with the aim of\r\nprotecting users' freedom to change the software.  The systematic\r\npattern of such abuse occurs in the area of products for individuals to\r\nuse, which is precisely where it is most unacceptable.  Therefore, we\r\nhave designed this version of the GPL to prohibit the practice for those\r\nproducts.  If such problems arise substantially in other domains, we\r\nstand ready to extend this provision to those domains in future versions\r\nof the GPL, as needed to protect the freedom of users.\r\n\r\n  Finally, every program is threatened constantly by software patents.\r\nStates should not allow patents to restrict development and use of\r\nsoftware on general-purpose computers, but in those that do, we wish to\r\navoid the special danger that patents applied to a free program could\r\nmake it effectively proprietary.  To prevent this, the GPL assures that\r\npatents cannot be used to render the program non-free.\r\n\r\n  The precise terms and conditions for copying, distribution and\r\nmodification follow.\r\n\r\n                       TERMS AND CONDITIONS\r\n\r\n  0. Definitions.\r\n\r\n  \"This License\" refers to version 3 of the GNU General Public License.\r\n\r\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\r\nworks, such as semiconductor masks.\r\n\r\n  \"The Program\" refers to any copyrightable work licensed under this\r\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\r\n\"recipients\" may be individuals or organizations.\r\n\r\n  To \"modify\" a work means to copy from or adapt all or part of the work\r\nin a fashion requiring copyright permission, other than the making of an\r\nexact copy.  The resulting work is called a \"modified version\" of the\r\nearlier work or a work \"based on\" the earlier work.\r\n\r\n  A \"covered work\" means either the unmodified Program or a work based\r\non the Program.\r\n\r\n  To \"propagate\" a work means to do anything with it that, without\r\npermission, would make you directly or secondarily liable for\r\ninfringement under applicable copyright law, except executing it on a\r\ncomputer or modifying a private copy.  Propagation includes copying,\r\ndistribution (with or without modification), making available to the\r\npublic, and in some countries other activities as well.\r\n\r\n  To \"convey\" a work means any kind of propagation that enables other\r\nparties to make or receive copies.  Mere interaction with a user through\r\na computer network, with no transfer of a copy, is not conveying.\r\n\r\n  An interactive user interface displays \"Appropriate Legal Notices\"\r\nto the extent that it includes a convenient and prominently visible\r\nfeature that (1) displays an appropriate copyright notice, and (2)\r\ntells the user that there is no warranty for the work (except to the\r\nextent that warranties are provided), that licensees may convey the\r\nwork under this License, and how to view a copy of this License.  If\r\nthe interface presents a list of user commands or options, such as a\r\nmenu, a prominent item in the list meets this criterion.\r\n\r\n  1. Source Code.\r\n\r\n  The \"source code\" for a work means the preferred form of the work\r\nfor making modifications to it.  \"Object code\" means any non-source\r\nform of a work.\r\n\r\n  A \"Standard Interface\" means an interface that either is an official\r\nstandard defined by a recognized standards body, or, in the case of\r\ninterfaces specified for a particular programming language, one that\r\nis widely used among developers working in that language.\r\n\r\n  The \"System Libraries\" of an executable work include anything, other\r\nthan the work as a whole, that (a) is included in the normal form of\r\npackaging a Major Component, but which is not part of that Major\r\nComponent, and (b) serves only to enable use of the work with that\r\nMajor Component, or to implement a Standard Interface for which an\r\nimplementation is available to the public in source code form.  A\r\n\"Major Component\", in this context, means a major essential component\r\n(kernel, window system, and so on) of the specific operating system\r\n(if any) on which the executable work runs, or a compiler used to\r\nproduce the work, or an object code interpreter used to run it.\r\n\r\n  The \"Corresponding Source\" for a work in object code form means all\r\nthe source code needed to generate, install, and (for an executable\r\nwork) run the object code and to modify the work, including scripts to\r\ncontrol those activities.  However, it does not include the work's\r\nSystem Libraries, or general-purpose tools or generally available free\r\nprograms which are used unmodified in performing those activities but\r\nwhich are not part of the work.  For example, Corresponding Source\r\nincludes interface definition files associated with source files for\r\nthe work, and the source code for shared libraries and dynamically\r\nlinked subprograms that the work is specifically designed to require,\r\nsuch as by intimate data communication or control flow between those\r\nsubprograms and other parts of the work.\r\n\r\n  The Corresponding Source need not include anything that users\r\ncan regenerate automatically from other parts of the Corresponding\r\nSource.\r\n\r\n  The Corresponding Source for a work in source code form is that\r\nsame work.\r\n\r\n  2. Basic Permissions.\r\n\r\n  All rights granted under this License are granted for the term of\r\ncopyright on the Program, and are irrevocable provided the stated\r\nconditions are met.  This License explicitly affirms your unlimited\r\npermission to run the unmodified Program.  The output from running a\r\ncovered work is covered by this License only if the output, given its\r\ncontent, constitutes a covered work.  This License acknowledges your\r\nrights of fair use or other equivalent, as provided by copyright law.\r\n\r\n  You may make, run and propagate covered works that you do not\r\nconvey, without conditions so long as your license otherwise remains\r\nin force.  You may convey covered works to others for the sole purpose\r\nof having them make modifications exclusively for you, or provide you\r\nwith facilities for running those works, provided that you comply with\r\nthe terms of this License in conveying all material for which you do\r\nnot control copyright.  Those thus making or running the covered works\r\nfor you must do so exclusively on your behalf, under your direction\r\nand control, on terms that prohibit them from making any copies of\r\nyour copyrighted material outside their relationship with you.\r\n\r\n  Conveying under any other circumstances is permitted solely under\r\nthe conditions stated below.  Sublicensing is not allowed; section 10\r\nmakes it unnecessary.\r\n\r\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\r\n\r\n  No covered work shall be deemed part of an effective technological\r\nmeasure under any applicable law fulfilling obligations under article\r\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\r\nsimilar laws prohibiting or restricting circumvention of such\r\nmeasures.\r\n\r\n  When you convey a covered work, you waive any legal power to forbid\r\ncircumvention of technological measures to the extent such circumvention\r\nis effected by exercising rights under this License with respect to\r\nthe covered work, and you disclaim any intention to limit operation or\r\nmodification of the work as a means of enforcing, against the work's\r\nusers, your or third parties' legal rights to forbid circumvention of\r\ntechnological measures.\r\n\r\n  4. Conveying Verbatim Copies.\r\n\r\n  You may convey verbatim copies of the Program's source code as you\r\nreceive it, in any medium, provided that you conspicuously and\r\nappropriately publish on each copy an appropriate copyright notice;\r\nkeep intact all notices stating that this License and any\r\nnon-permissive terms added in accord with section 7 apply to the code;\r\nkeep intact all notices of the absence of any warranty; and give all\r\nrecipients a copy of this License along with the Program.\r\n\r\n  You may charge any price or no price for each copy that you convey,\r\nand you may offer support or warranty protection for a fee.\r\n\r\n  5. Conveying Modified Source Versions.\r\n\r\n  You may convey a work based on the Program, or the modifications to\r\nproduce it from the Program, in the form of source code under the\r\nterms of section 4, provided that you also meet all of these conditions:\r\n\r\n    a) The work must carry prominent notices stating that you modified\r\n    it, and giving a relevant date.\r\n\r\n    b) The work must carry prominent notices stating that it is\r\n    released under this License and any conditions added under section\r\n    7.  This requirement modifies the requirement in section 4 to\r\n    \"keep intact all notices\".\r\n\r\n    c) You must license the entire work, as a whole, under this\r\n    License to anyone who comes into possession of a copy.  This\r\n    License will therefore apply, along with any applicable section 7\r\n    additional terms, to the whole of the work, and all its parts,\r\n    regardless of how they are packaged.  This License gives no\r\n    permission to license the work in any other way, but it does not\r\n    invalidate such permission if you have separately received it.\r\n\r\n    d) If the work has interactive user interfaces, each must display\r\n    Appropriate Legal Notices; however, if the Program has interactive\r\n    interfaces that do not display Appropriate Legal Notices, your\r\n    work need not make them do so.\r\n\r\n  A compilation of a covered work with other separate and independent\r\nworks, which are not by their nature extensions of the covered work,\r\nand which are not combined with it such as to form a larger program,\r\nin or on a volume of a storage or distribution medium, is called an\r\n\"aggregate\" if the compilation and its resulting copyright are not\r\nused to limit the access or legal rights of the compilation's users\r\nbeyond what the individual works permit.  Inclusion of a covered work\r\nin an aggregate does not cause this License to apply to the other\r\nparts of the aggregate.\r\n\r\n  6. Conveying Non-Source Forms.\r\n\r\n  You may convey a covered work in object code form under the terms\r\nof sections 4 and 5, provided that you also convey the\r\nmachine-readable Corresponding Source under the terms of this License,\r\nin one of these ways:\r\n\r\n    a) Convey the object code in, or embodied in, a physical product\r\n    (including a physical distribution medium), accompanied by the\r\n    Corresponding Source fixed on a durable physical medium\r\n    customarily used for software interchange.\r\n\r\n    b) Convey the object code in, or embodied in, a physical product\r\n    (including a physical distribution medium), accompanied by a\r\n    written offer, valid for at least three years and valid for as\r\n    long as you offer spare parts or customer support for that product\r\n    model, to give anyone who possesses the object code either (1) a\r\n    copy of the Corresponding Source for all the software in the\r\n    product that is covered by this License, on a durable physical\r\n    medium customarily used for software interchange, for a price no\r\n    more than your reasonable cost of physically performing this\r\n    conveying of source, or (2) access to copy the\r\n    Corresponding Source from a network server at no charge.\r\n\r\n    c) Convey individual copies of the object code with a copy of the\r\n    written offer to provide the Corresponding Source.  This\r\n    alternative is allowed only occasionally and noncommercially, and\r\n    only if you received the object code with such an offer, in accord\r\n    with subsection 6b.\r\n\r\n    d) Convey the object code by offering access from a designated\r\n    place (gratis or for a charge), and offer equivalent access to the\r\n    Corresponding Source in the same way through the same place at no\r\n    further charge.  You need not require recipients to copy the\r\n    Corresponding Source along with the object code.  If the place to\r\n    copy the object code is a network server, the Corresponding Source\r\n    may be on a different server (operated by you or a third party)\r\n    that supports equivalent copying facilities, provided you maintain\r\n    clear directions next to the object code saying where to find the\r\n    Corresponding Source.  Regardless of what server hosts the\r\n    Corresponding Source, you remain obligated to ensure that it is\r\n    available for as long as needed to satisfy these requirements.\r\n\r\n    e) Convey the object code using peer-to-peer transmission, provided\r\n    you inform other peers where the object code and Corresponding\r\n    Source of the work are being offered to the general public at no\r\n    charge under subsection 6d.\r\n\r\n  A separable portion of the object code, whose source code is excluded\r\nfrom the Corresponding Source as a System Library, need not be\r\nincluded in conveying the object code work.\r\n\r\n  A \"User Product\" is either (1) a \"consumer product\", which means any\r\ntangible personal property which is normally used for personal, family,\r\nor household purposes, or (2) anything designed or sold for incorporation\r\ninto a dwelling.  In determining whether a product is a consumer product,\r\ndoubtful cases shall be resolved in favor of coverage.  For a particular\r\nproduct received by a particular user, \"normally used\" refers to a\r\ntypical or common use of that class of product, regardless of the status\r\nof the particular user or of the way in which the particular user\r\nactually uses, or expects or is expected to use, the product.  A product\r\nis a consumer product regardless of whether the product has substantial\r\ncommercial, industrial or non-consumer uses, unless such uses represent\r\nthe only significant mode of use of the product.\r\n\r\n  \"Installation Information\" for a User Product means any methods,\r\nprocedures, authorization keys, or other information required to install\r\nand execute modified versions of a covered work in that User Product from\r\na modified version of its Corresponding Source.  The information must\r\nsuffice to ensure that the continued functioning of the modified object\r\ncode is in no case prevented or interfered with solely because\r\nmodification has been made.\r\n\r\n  If you convey an object code work under this section in, or with, or\r\nspecifically for use in, a User Product, and the conveying occurs as\r\npart of a transaction in which the right of possession and use of the\r\nUser Product is transferred to the recipient in perpetuity or for a\r\nfixed term (regardless of how the transaction is characterized), the\r\nCorresponding Source conveyed under this section must be accompanied\r\nby the Installation Information.  But this requirement does not apply\r\nif neither you nor any third party retains the ability to install\r\nmodified object code on the User Product (for example, the work has\r\nbeen installed in ROM).\r\n\r\n  The requirement to provide Installation Information does not include a\r\nrequirement to continue to provide support service, warranty, or updates\r\nfor a work that has been modified or installed by the recipient, or for\r\nthe User Product in which it has been modified or installed.  Access to a\r\nnetwork may be denied when the modification itself materially and\r\nadversely affects the operation of the network or violates the rules and\r\nprotocols for communication across the network.\r\n\r\n  Corresponding Source conveyed, and Installation Information provided,\r\nin accord with this section must be in a format that is publicly\r\ndocumented (and with an implementation available to the public in\r\nsource code form), and must require no special password or key for\r\nunpacking, reading or copying.\r\n\r\n  7. Additional Terms.\r\n\r\n  \"Additional permissions\" are terms that supplement the terms of this\r\nLicense by making exceptions from one or more of its conditions.\r\nAdditional permissions that are applicable to the entire Program shall\r\nbe treated as though they were included in this License, to the extent\r\nthat they are valid under applicable law.  If additional permissions\r\napply only to part of the Program, that part may be used separately\r\nunder those permissions, but the entire Program remains governed by\r\nthis License without regard to the additional permissions.\r\n\r\n  When you convey a copy of a covered work, you may at your option\r\nremove any additional permissions from that copy, or from any part of\r\nit.  (Additional permissions may be written to require their own\r\nremoval in certain cases when you modify the work.)  You may place\r\nadditional permissions on material, added by you to a covered work,\r\nfor which you have or can give appropriate copyright permission.\r\n\r\n  Notwithstanding any other provision of this License, for material you\r\nadd to a covered work, you may (if authorized by the copyright holders of\r\nthat material) supplement the terms of this License with terms:\r\n\r\n    a) Disclaiming warranty or limiting liability differently from the\r\n    terms of sections 15 and 16 of this License; or\r\n\r\n    b) Requiring preservation of specified reasonable legal notices or\r\n    author attributions in that material or in the Appropriate Legal\r\n    Notices displayed by works containing it; or\r\n\r\n    c) Prohibiting misrepresentation of the origin of that material, or\r\n    requiring that modified versions of such material be marked in\r\n    reasonable ways as different from the original version; or\r\n\r\n    d) Limiting the use for publicity purposes of names of licensors or\r\n    authors of the material; or\r\n\r\n    e) Declining to grant rights under trademark law for use of some\r\n    trade names, trademarks, or service marks; or\r\n\r\n    f) Requiring indemnification of licensors and authors of that\r\n    material by anyone who conveys the material (or modified versions of\r\n    it) with contractual assumptions of liability to the recipient, for\r\n    any liability that these contractual assumptions directly impose on\r\n    those licensors and authors.\r\n\r\n  All other non-permissive additional terms are considered \"further\r\nrestrictions\" within the meaning of section 10.  If the Program as you\r\nreceived it, or any part of it, contains a notice stating that it is\r\ngoverned by this License along with a term that is a further\r\nrestriction, you may remove that term.  If a license document contains\r\na further restriction but permits relicensing or conveying under this\r\nLicense, you may add to a covered work material governed by the terms\r\nof that license document, provided that the further restriction does\r\nnot survive such relicensing or conveying.\r\n\r\n  If you add terms to a covered work in accord with this section, you\r\nmust place, in the relevant source files, a statement of the\r\nadditional terms that apply to those files, or a notice indicating\r\nwhere to find the applicable terms.\r\n\r\n  Additional terms, permissive or non-permissive, may be stated in the\r\nform of a separately written license, or stated as exceptions;\r\nthe above requirements apply either way.\r\n\r\n  8. Termination.\r\n\r\n  You may not propagate or modify a covered work except as expressly\r\nprovided under this License.  Any attempt otherwise to propagate or\r\nmodify it is void, and will automatically terminate your rights under\r\nthis License (including any patent licenses granted under the third\r\nparagraph of section 11).\r\n\r\n  However, if you cease all violation of this License, then your\r\nlicense from a particular copyright holder is reinstated (a)\r\nprovisionally, unless and until the copyright holder explicitly and\r\nfinally terminates your license, and (b) permanently, if the copyright\r\nholder fails to notify you of the violation by some reasonable means\r\nprior to 60 days after the cessation.\r\n\r\n  Moreover, your license from a particular copyright holder is\r\nreinstated permanently if the copyright holder notifies you of the\r\nviolation by some reasonable means, this is the first time you have\r\nreceived notice of violation of this License (for any work) from that\r\ncopyright holder, and you cure the violation prior to 30 days after\r\nyour receipt of the notice.\r\n\r\n  Termination of your rights under this section does not terminate the\r\nlicenses of parties who have received copies or rights from you under\r\nthis License.  If your rights have been terminated and not permanently\r\nreinstated, you do not qualify to receive new licenses for the same\r\nmaterial under section 10.\r\n\r\n  9. Acceptance Not Required for Having Copies.\r\n\r\n  You are not required to accept this License in order to receive or\r\nrun a copy of the Program.  Ancillary propagation of a covered work\r\noccurring solely as a consequence of using peer-to-peer transmission\r\nto receive a copy likewise does not require acceptance.  However,\r\nnothing other than this License grants you permission to propagate or\r\nmodify any covered work.  These actions infringe copyright if you do\r\nnot accept this License.  Therefore, by modifying or propagating a\r\ncovered work, you indicate your acceptance of this License to do so.\r\n\r\n  10. Automatic Licensing of Downstream Recipients.\r\n\r\n  Each time you convey a covered work, the recipient automatically\r\nreceives a license from the original licensors, to run, modify and\r\npropagate that work, subject to this License.  You are not responsible\r\nfor enforcing compliance by third parties with this License.\r\n\r\n  An \"entity transaction\" is a transaction transferring control of an\r\norganization, or substantially all assets of one, or subdividing an\r\norganization, or merging organizations.  If propagation of a covered\r\nwork results from an entity transaction, each party to that\r\ntransaction who receives a copy of the work also receives whatever\r\nlicenses to the work the party's predecessor in interest had or could\r\ngive under the previous paragraph, plus a right to possession of the\r\nCorresponding Source of the work from the predecessor in interest, if\r\nthe predecessor has it or can get it with reasonable efforts.\r\n\r\n  You may not impose any further restrictions on the exercise of the\r\nrights granted or affirmed under this License.  For example, you may\r\nnot impose a license fee, royalty, or other charge for exercise of\r\nrights granted under this License, and you may not initiate litigation\r\n(including a cross-claim or counterclaim in a lawsuit) alleging that\r\nany patent claim is infringed by making, using, selling, offering for\r\nsale, or importing the Program or any portion of it.\r\n\r\n  11. Patents.\r\n\r\n  A \"contributor\" is a copyright holder who authorizes use under this\r\nLicense of the Program or a work on which the Program is based.  The\r\nwork thus licensed is called the contributor's \"contributor version\".\r\n\r\n  A contributor's \"essential patent claims\" are all patent claims\r\nowned or controlled by the contributor, whether already acquired or\r\nhereafter acquired, that would be infringed by some manner, permitted\r\nby this License, of making, using, or selling its contributor version,\r\nbut do not include claims that would be infringed only as a\r\nconsequence of further modification of the contributor version.  For\r\npurposes of this definition, \"control\" includes the right to grant\r\npatent sublicenses in a manner consistent with the requirements of\r\nthis License.\r\n\r\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\r\npatent license under the contributor's essential patent claims, to\r\nmake, use, sell, offer for sale, import and otherwise run, modify and\r\npropagate the contents of its contributor version.\r\n\r\n  In the following three paragraphs, a \"patent license\" is any express\r\nagreement or commitment, however denominated, not to enforce a patent\r\n(such as an express permission to practice a patent or covenant not to\r\nsue for patent infringement).  To \"grant\" such a patent license to a\r\nparty means to make such an agreement or commitment not to enforce a\r\npatent against the party.\r\n\r\n  If you convey a covered work, knowingly relying on a patent license,\r\nand the Corresponding Source of the work is not available for anyone\r\nto copy, free of charge and under the terms of this License, through a\r\npublicly available network server or other readily accessible means,\r\nthen you must either (1) cause the Corresponding Source to be so\r\navailable, or (2) arrange to deprive yourself of the benefit of the\r\npatent license for this particular work, or (3) arrange, in a manner\r\nconsistent with the requirements of this License, to extend the patent\r\nlicense to downstream recipients.  \"Knowingly relying\" means you have\r\nactual knowledge that, but for the patent license, your conveying the\r\ncovered work in a country, or your recipient's use of the covered work\r\nin a country, would infringe one or more identifiable patents in that\r\ncountry that you have reason to believe are valid.\r\n\r\n  If, pursuant to or in connection with a single transaction or\r\narrangement, you convey, or propagate by procuring conveyance of, a\r\ncovered work, and grant a patent license to some of the parties\r\nreceiving the covered work authorizing them to use, propagate, modify\r\nor convey a specific copy of the covered work, then the patent license\r\nyou grant is automatically extended to all recipients of the covered\r\nwork and works based on it.\r\n\r\n  A patent license is \"discriminatory\" if it does not include within\r\nthe scope of its coverage, prohibits the exercise of, or is\r\nconditioned on the non-exercise of one or more of the rights that are\r\nspecifically granted under this License.  You may not convey a covered\r\nwork if you are a party to an arrangement with a third party that is\r\nin the business of distributing software, under which you make payment\r\nto the third party based on the extent of your activity of conveying\r\nthe work, and under which the third party grants, to any of the\r\nparties who would receive the covered work from you, a discriminatory\r\npatent license (a) in connection with copies of the covered work\r\nconveyed by you (or copies made from those copies), or (b) primarily\r\nfor and in connection with specific products or compilations that\r\ncontain the covered work, unless you entered into that arrangement,\r\nor that patent license was granted, prior to 28 March 2007.\r\n\r\n  Nothing in this License shall be construed as excluding or limiting\r\nany implied license or other defenses to infringement that may\r\notherwise be available to you under applicable patent law.\r\n\r\n  12. No Surrender of Others' Freedom.\r\n\r\n  If conditions are imposed on you (whether by court order, agreement or\r\notherwise) that contradict the conditions of this License, they do not\r\nexcuse you from the conditions of this License.  If you cannot convey a\r\ncovered work so as to satisfy simultaneously your obligations under this\r\nLicense and any other pertinent obligations, then as a consequence you may\r\nnot convey it at all.  For example, if you agree to terms that obligate you\r\nto collect a royalty for further conveying from those to whom you convey\r\nthe Program, the only way you could satisfy both those terms and this\r\nLicense would be to refrain entirely from conveying the Program.\r\n\r\n  13. Use with the GNU Affero General Public License.\r\n\r\n  Notwithstanding any other provision of this License, you have\r\npermission to link or combine any covered work with a work licensed\r\nunder version 3 of the GNU Affero General Public License into a single\r\ncombined work, and to convey the resulting work.  The terms of this\r\nLicense will continue to apply to the part which is the covered work,\r\nbut the special requirements of the GNU Affero General Public License,\r\nsection 13, concerning interaction through a network will apply to the\r\ncombination as such.\r\n\r\n  14. Revised Versions of this License.\r\n\r\n  The Free Software Foundation may publish revised and/or new versions of\r\nthe GNU General Public License from time to time.  Such new versions will\r\nbe similar in spirit to the present version, but may differ in detail to\r\naddress new problems or concerns.\r\n\r\n  Each version is given a distinguishing version number.  If the\r\nProgram specifies that a certain numbered version of the GNU General\r\nPublic License \"or any later version\" applies to it, you have the\r\noption of following the terms and conditions either of that numbered\r\nversion or of any later version published by the Free Software\r\nFoundation.  If the Program does not specify a version number of the\r\nGNU General Public License, you may choose any version ever published\r\nby the Free Software Foundation.\r\n\r\n  If the Program specifies that a proxy can decide which future\r\nversions of the GNU General Public License can be used, that proxy's\r\npublic statement of acceptance of a version permanently authorizes you\r\nto choose that version for the Program.\r\n\r\n  Later license versions may give you additional or different\r\npermissions.  However, no additional obligations are imposed on any\r\nauthor or copyright holder as a result of your choosing to follow a\r\nlater version.\r\n\r\n  15. Disclaimer of Warranty.\r\n\r\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\r\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\r\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\r\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\r\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\r\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\r\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\r\n\r\n  16. Limitation of Liability.\r\n\r\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\r\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\r\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\r\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\r\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\r\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\r\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\r\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\r\nSUCH DAMAGES.\r\n\r\n  17. Interpretation of Sections 15 and 16.\r\n\r\n  If the disclaimer of warranty and limitation of liability provided\r\nabove cannot be given local legal effect according to their terms,\r\nreviewing courts shall apply local law that most closely approximates\r\nan absolute waiver of all civil liability in connection with the\r\nProgram, unless a warranty or assumption of liability accompanies a\r\ncopy of the Program in return for a fee.\r\n\r\n                     END OF TERMS AND CONDITIONS\r\n\r\n            How to Apply These Terms to Your New Programs\r\n\r\n  If you develop a new program, and you want it to be of the greatest\r\npossible use to the public, the best way to achieve this is to make it\r\nfree software which everyone can redistribute and change under these terms.\r\n\r\n  To do so, attach the following notices to the program.  It is safest\r\nto attach them to the start of each source file to most effectively\r\nstate the exclusion of warranty; and each file should have at least\r\nthe \"copyright\" line and a pointer to where the full notice is found.\r\n\r\n    <one line to give the program's name and a brief idea of what it does.>\r\n    Copyright (C) <year>  <name of author>\r\n\r\n    This program is free software: you can redistribute it and/or modify\r\n    it under the terms of the GNU General Public License as published by\r\n    the Free Software Foundation, either version 3 of the License, or\r\n    (at your option) any later version.\r\n\r\n    This program is distributed in the hope that it will be useful,\r\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n    GNU General Public License for more details.\r\n\r\n    You should have received a copy of the GNU General Public License\r\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\r\n\r\nAlso add information on how to contact you by electronic and paper mail.\r\n\r\n  If the program does terminal interaction, make it output a short\r\nnotice like this when it starts in an interactive mode:\r\n\r\n    <program>  Copyright (C) <year>  <name of author>\r\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\r\n    This is free software, and you are welcome to redistribute it\r\n    under certain conditions; type `show c' for details.\r\n\r\nThe hypothetical commands `show w' and `show c' should show the appropriate\r\nparts of the General Public License.  Of course, your program's commands\r\nmight be different; for a GUI interface, you would use an \"about box\".\r\n\r\n  You should also get your employer (if you work as a programmer) or school,\r\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\r\nFor more information on this, and how to apply and follow the GNU GPL, see\r\n<https://www.gnu.org/licenses/>.\r\n\r\n  The GNU General Public License does not permit incorporating your program\r\ninto proprietary programs.  If your program is a subroutine library, you\r\nmay consider it more useful to permit linking proprietary applications with\r\nthe library.  If this is what you want to do, use the GNU Lesser General\r\nPublic License instead of this License.  But first, please read\r\n<https://www.gnu.org/licenses/why-not-lgpl.html>."
  },
  {
    "path": "README.md",
    "content": "![语言](https://img.shields.io/badge/语言-verilog_(IEEE1364_2001)-9A90FD.svg) ![仿真](https://img.shields.io/badge/仿真-iverilog-green.svg) ![部署](https://img.shields.io/badge/部署-quartus-blue.svg) ![部署](https://img.shields.io/badge/部署-vivado-FF1010.svg)\r\n\r\n[English](#en) | [中文](#cn)\r\n\r\n　\r\n\r\n<span id=\"en\">Verilog-UART</span>\r\n===========================\r\n\r\nThis repository contains 3 useful modules:\r\n\r\n* **UART Receiver**, [uart_rx.v](./RTL/uart_rx.v) , has a AXI-stream master port, which can receive UART data and output it by AXI-stream.\r\n* **UART Transmitter**, [uart_tx.v](./RTL/uart_tx.v) , has a AXI-stream slave port, which can receive AXI-stream data and output it by UART.\r\n* **UART to AXI4 master**, [uart2axi4.v](./RTL/uart2axi4.v) . It can receive UART commands from Host-PC, do AXI4 bus reading and writing, and feedback the results to the Host-PC. It is a powerful tool for debugging SoC systems.\r\n\r\nFeatures:\r\n\r\n- Standard AXI-stream / AXI4 interface.\r\n- Configurable TX/RX buffer\r\n- Configurable UART baud rate, parity bit, and stop bits\r\n- Fractional frequency division: When the clock frequency cannot be divided by the baud rate, the cycles of each bit are different, thus rounding up a more accurate baud rate.\r\n- Baud rate check report: During simulation, the baud rate accuracy will be printed using `$display`. If it is too imprecise, an error will be reported.\r\n\r\n　\r\n\r\n　\r\n\r\n# 1. UART Receiver: uart\\_rx\r\n\r\nThe code file of the UART receiver is [uart_rx.v](./RTL/uart_rx.v). This module has no sub modules.\r\n\r\nThe module definition is as follows:\r\n\r\n```verilog\r\nmodule uart_rx #(\r\n    // clock frequency\r\n    parameter  CLK_FREQ  = 50000000,     // clk frequency, Unit : Hz\r\n    // UART format\r\n    parameter  BAUD_RATE = 115200,       // Unit : Hz\r\n    parameter  PARITY    = \"NONE\",       // \"NONE\", \"ODD\", or \"EVEN\"\r\n    // RX fifo depth\r\n    parameter  FIFO_EA   = 0             // 0:no fifo   1,2:depth=4   3:depth=8   4:depth=16  ...  10:depth=1024   11:depth=2048  ...\r\n) (\r\n    input  wire        rstn,\r\n    input  wire        clk,\r\n    // UART RX input signal\r\n    input  wire        i_uart_rx,\r\n    // output AXI-stream master. Associated clock = clk. \r\n    input  wire        o_tready,\r\n    output reg         o_tvalid,\r\n    output reg  [ 7:0] o_tdata,\r\n    // report whether there's a overflow\r\n    output reg         o_overflow\r\n);\r\n```\r\n\r\n### 1.1 config parameters\r\n\r\n- `CLK_FREQ` is the frequency of `clk` . User must correctly config it to get correnct baud rate.\r\n- `BAUD_RATE` is UART baud rate.\r\n- `PARITY` can be \"NONE\", \"ODD\", or \"EVEN\"\r\n- `FIFO_EA` is for configuring RX fifo.\r\n  - `FIFO_EA=0` : no RX fifo, the receiving byte must be accepted by user immediately.\r\n  - `FIFO_EA=1,2` : fifo depth = 4;\r\n  - `FIFO_EA=3` : fifo depth = 8;\r\n  - `FIFO_EA=4` : fifo depth = 16;\r\n  - ……\r\n- When `FIFO_EA` is large (>8), it will be implemented by BRAM.\r\n\r\n### 1.2 Clock and reset\r\n\r\n`rstn` is low reset\r\n\r\n`clk` is clock, all signals will be and should be changed at rise-edge of `clk`\r\n\r\n### 1.3 UART signal\r\n\r\n`i_uart_rx` is UART input signal.\r\n\r\n### 1.4 AXI-stream master\r\n\r\n`o_tready` , `o_tvalid` , `o_tdata` belong to a AXI-stream master.\r\n\r\n- When `o_tvalid=1` , the valid receive byte will appear on `o_tdata`\r\n- If user is ready to accept a received byte, let `o_tready=1`\r\n- When `o_tvalid=1` and `o_tready=1` simultaneously, a handshake success and current data is successfully dequeued from module's internal FIFO. At next cycle, next receiving byte may appear on `o_tdata`\r\n\r\n> :warning: If there is no receive FIFO (`FIFO_EA=0`), the module will not wait for the user to accept the current byte. As long as a byte is received, it will cause `o_tvalid=1` for one cycle, and make the byte appear on `o_tdata` .\r\n\r\n### 1.5 `o_overflow` signal\r\n\r\nIf users frequently make `o_tready=0` , that is, if the data is not taken away in time, the received data may be stored more and more in module's FIFO. When the FIFO overflow, the newly enqueue bytes will be discarded, and a one-cycle-high-pulse will appear on `o_overflow` . In other cases, `o_overflow` keeps low.\r\n\r\n### 1.6 Baud rate checking\r\n\r\nDuring simulation, the module will print the time points and accuracy of the edges of each bit based on the user's configuration. If the accuracy is too poor (relative error>8%), the module will use `$error` to report an error, helping users detect configuration errors in advance.\r\n\r\nFor example, if we config `CLK_FREQ=5000000` (5MHz) , `BAUD_RATE=115200` , `PARITY=\"ODD\"` , it will print report:\r\n\r\n```\r\nuart_rx :           parity = ODD\r\nuart_rx :     clock period = 200 ns   (5000000    Hz)\r\nuart_rx : baud rate period = 8681 ns   (115200     Hz)\r\nuart_rx :      baud cycles = 43\r\nuart_rx : baud cycles frac = 4\r\nuart_rx :             __      ____ ____ ____ ____ ____ ____ ____ ____________\r\nuart_rx :        wave   \\____/____X____X____X____X____X____X____X____X____/\r\nuart_rx :        bits   | S  | B0 | B1 | B2 | B3 | B4 | B5 | B6 | B7 | P   |\r\nuart_rx : time_points  t0   t1   t2   t3   t4   t5   t6   t7   t8   t9   t10\r\nuart_rx :\r\nuart_rx : t1 - t0 = 8681 ns (ideal)  8600 +- 200 ns (actual).   error=281 ns   relative_error=3.232%\r\nuart_rx : t2 - t0 = 17361 ns (ideal)  17400 +- 200 ns (actual).   error=239 ns   relative_error=2.752%\r\nuart_rx : t3 - t0 = 26042 ns (ideal)  26000 +- 200 ns (actual).   error=242 ns   relative_error=2.784%\r\nuart_rx : t4 - t0 = 34722 ns (ideal)  34800 +- 200 ns (actual).   error=278 ns   relative_error=3.200%\r\nuart_rx : t5 - t0 = 43403 ns (ideal)  43400 +- 200 ns (actual).   error=203 ns   relative_error=2.336%\r\nuart_rx : t6 - t0 = 52083 ns (ideal)  52000 +- 200 ns (actual).   error=283 ns   relative_error=3.264%\r\nuart_rx : t7 - t0 = 60764 ns (ideal)  60800 +- 200 ns (actual).   error=236 ns   relative_error=2.720%\r\nuart_rx : t8 - t0 = 69444 ns (ideal)  69400 +- 200 ns (actual).   error=244 ns   relative_error=2.816%\r\nuart_rx : t9 - t0 = 78125 ns (ideal)  78200 +- 200 ns (actual).   error=275 ns   relative_error=3.168%\r\nuart_rx : t10- t0 = 86806 ns (ideal)  86800 +- 200 ns (actual).   error=206 ns   relative_error=2.368%\r\n```\r\n\r\n　\r\n\r\n　\r\n\r\n# 2. UART Transmitter: uart\\_tx\r\n\r\nThe code file of the UART Transmitter is [uart_tx.v](./RTL/uart_tx.v). This module has no sub modules.\r\n\r\nThe module definition is as follows:\r\n\r\n```verilog\r\nmodule uart_tx #(\r\n    // clock frequency\r\n    parameter  CLK_FREQ                  = 50000000,     // clk frequency, Unit : Hz\r\n    // UART format\r\n    parameter  BAUD_RATE                 = 115200,       // Unit : Hz\r\n    parameter  PARITY                    = \"NONE\",       // \"NONE\", \"ODD\", or \"EVEN\"\r\n    parameter  STOP_BITS                 = 2,            // can be 1, 2, 3, 4, ...\r\n    // AXI stream data width\r\n    parameter  BYTE_WIDTH                = 1,            // can be 1, 2, 3, 4, ...\r\n    // TX fifo depth\r\n    parameter  FIFO_EA                   = 0,            // 0:no fifo   1,2:depth=4   3:depth=8   4:depth=16  ...  10:depth=1024   11:depth=2048  ...\r\n    // do you want to send extra byte after each AXI-stream transfer or packet?\r\n    parameter  EXTRA_BYTE_AFTER_TRANSFER = \"\",           // specify a extra byte to send after each AXI-stream transfer. when =\"\", do not send this extra byte\r\n    parameter  EXTRA_BYTE_AFTER_PACKET   = \"\"            // specify a extra byte to send after each AXI-stream packet  . when =\"\", do not send this extra byte\r\n) (\r\n    input  wire                    rstn,\r\n    input  wire                    clk,\r\n    // input  stream : AXI-stream slave. Associated clock = clk\r\n    output wire                    i_tready,\r\n    input  wire                    i_tvalid,\r\n    input  wire [8*BYTE_WIDTH-1:0] i_tdata,\r\n    input  wire [  BYTE_WIDTH-1:0] i_tkeep,\r\n    input  wire                    i_tlast,\r\n    // UART TX output signal\r\n    output reg                     o_uart_tx\r\n);\r\n```\r\n\r\n### 2.2 config parameters\r\n\r\n- `CLK_FREQ` is the frequency of `clk` . User must correctly config it to get correnct baud rate.\r\n- `BAUD_RATE` is UART baud rate.\r\n- `PARITY` can be \"NONE\", \"ODD\", or \"EVEN\"\r\n- `STOP_BITS` is the number of stop bits '1'\r\n- `BYTE_WIDTH` is the byte-width of AXI-stream slave's data (`i_tdata`)\r\n- `FIFO_EA` is for configuring TX fifo.\r\n  - `FIFO_EA=0` : no TX fifo. For each successful handshake of data, we must wait for the UART transmission to complete before shaking the next data.\r\n  - `FIFO_EA=1,2` : fifo depth = 4;\r\n  - `FIFO_EA=3` : fifo depth = 8;\r\n  - `FIFO_EA=4` : fifo depth = 16;\r\n  - ……\r\n- When `FIFO_EA` is large (>8), it will be implemented by BRAM.\r\n\r\n- `EXTRA_BYTE_AFTER_TRANSFER` is to configure whether an extra byte needs to be sent through UART every time an AXI-stream transfer (i.e. a successful handshake)\r\n  - If you don't want to send the extra byte, just let `EXTRA_BYTE_AFTER_TRANSFER=\"\"`\r\n  - If you want to send the extra byte, such as the space byte \" \", let  `EXTRA_BYTE_AFTER_TRANSFER=\" \"`\r\n- `EXTRA_BYTE_AFTER_PACKET` is to configure whether an extra byte needs to be sent through UART at the end of each AXI-stream packet (i.e. `i_tlast=1` when a successful handshake)\r\n  - If you don't want to send the extra byte, just let `EXTRA_BYTE_AFTER_PACKET=\"\"`\r\n  - If you want to send the extra byte, such as the new-line byte \"\\n\", let `EXTRA_BYTE_AFTER_PACKET=\"\\n\"`\r\n\r\n### 2.2 Clock and reset\r\n\r\n`rstn` is low reset\r\n\r\n`clk` is clock, all signals will be and should be changed at rise-edge of `clk`\r\n\r\n### 2.3 UART signal\r\n\r\n`o_uart_tx` is UART output signal.\r\n\r\n### 2.4 AXI-stream slave\r\n\r\n`i_tready` , `i_tvalid` , `i_tdata` , `i_tdata` , `i_tkeep` , `t_tlast` belong to AXI-stream slave interface.\r\n\r\n- `i_tready=1` means the module yet has FIFO space. `i_tready=0` means the module has no more FIFO space for accept more data.\r\n- `i_tvalid=1` means the user want to enqueue a data to TX FIFO. Meanwhile, `i_tdata`, `i_tkeep` , `i_tlast` must valid.\r\n- When `i_tvalid=1` and `i_tready=1` simultaneously, a handshake success, a data is successfully enqueue to FIFO.\r\n- `i_tkeep` is byte-enable signal :\r\n  - `i_tkeep[0]` means `i_tdata[7:0]` byte is valid, and will be send on UART, otherwise it will not be send.\r\n  - `i_tkeep[1]` means `i_tdata[15:8]` byte is valid, and will be send on UART, otherwise it will not be send.\r\n  - `i_tkeep[2]` means `i_tdata[23:16]` byte is valid, and will be send on UART, otherwise it will not be send.\r\n  - ......\r\n- `i_tlast` is the packet border indicator of AXI-stream. When sending a data, if `i_tlast=1`\r\n  - If `EXTRA_BYTE_AFTER_PACKET` specify a extra byte, UART will send this extra byte.\r\n  - If `EXTRA_BYTE_AFTER_PACKET=\"\"` did not specify a extra byte, UART will not send this extra byte. In other words, at this point, `i_tlast` has no effect whether it is 0 or 1.\r\n\r\n### 2.5 Baud rate checking\r\n\r\nDuring simulation, the module will print the time points and accuracy of the edges of each bit based on the user's configuration. If the accuracy is too poor (relative error>3%), the module will use `$error` to report an error, helping users detect configuration errors in advance.\r\n\r\n　\r\n\r\n　\r\n\r\n# 3. UART to AXI4 master (uart2axi4)\r\n\r\nThe code file is [RTL/uart2axi4.v](./RTL/uart2axi4.v). This module will call [uart_tx.v](./RTL/uart_tx.v) and  [uart_rx.v](./RTL/uart_rx.v)\r\n\r\nThis module is an AXI4 master that can receive UART commands from the upper computer, complete AXI4 bus reading and writing, and provide the results to the upper computer. It is a powerful tool for debugging SoC systems.\r\n\r\nThe module definition is as follows:\r\n\r\n```verilog\r\nmodule uart2axi4 #(\r\n    // clock frequency\r\n    parameter  CLK_FREQ   = 50000000,     // clk frequency, Unit : Hz\r\n    // UART format\r\n    parameter  BAUD_RATE  = 115200,       // Unit : Hz\r\n    parameter  PARITY     = \"NONE\",       // \"NONE\", \"ODD\", or \"EVEN\"\r\n    // AXI4 config\r\n    parameter  BYTE_WIDTH = 2,            // data width (bytes)\r\n    parameter  A_WIDTH    = 32            // address width (bits)\r\n) (\r\n    input  wire                    rstn,\r\n    input  wire                    clk,\r\n    // AXI4 master ----------------------\r\n    input  wire                    awready,  // AW\r\n    output wire                    awvalid,\r\n    output wire      [A_WIDTH-1:0] awaddr,\r\n    output wire             [ 7:0] awlen,\r\n    input  wire                    wready,   // W\r\n    output wire                    wvalid,\r\n    output wire                    wlast,\r\n    output wire [8*BYTE_WIDTH-1:0] wdata,\r\n    output wire                    bready,   // B\r\n    input  wire                    bvalid,\r\n    input  wire                    arready,  // AR\r\n    output wire                    arvalid,\r\n    output wire      [A_WIDTH-1:0] araddr,\r\n    output wire             [ 7:0] arlen,\r\n    output wire                    rready,   // R\r\n    input  wire                    rvalid,\r\n    input  wire                    rlast,\r\n    input  wire [8*BYTE_WIDTH-1:0] rdata,\r\n    // UART ----------------------\r\n    input  wire                    i_uart_rx,\r\n    output wire                    o_uart_tx\r\n);\r\n```\r\n\r\n### 3.1 config parameters\r\n\r\n- `CLK_FREQ` is the frequency of `clk` . User must correctly config it to get correnct baud rate.\r\n- `BAUD_RATE` is UART baud rate.\r\n- `PARITY` can be \"NONE\", \"ODD\", or \"EVEN\"\r\n- `BYTE_WIDTH` is the byte-width of AXI4's data (`wdata` and `rdata`)\r\n- `A_WIDTH` is the bit-width of AXI's address (`awaddr1` and `araddr`)\r\n\r\n### 3.2 Clock and reset\r\n\r\n`rstn` is low reset\r\n\r\n`clk` is clock, all signals will be and should be changed at rise-edge of `clk`\r\n\r\n### 3.3 UART signal\r\n\r\n`o_uart_tx` is UART output signal.\r\n\r\n`i_uart_rx` is UART input signal.\r\n\r\n### 3.4 AXI4 master port\r\n\r\nThis module has an AXI4 master interface that can read and write AXI4 bus. We will not provide a detailed explanation of AXI4 timing here, please refer to https://www.xilinx.com/products/intellectual-property/axi.html\r\n\r\n### 3.5 UART Command Format\r\n\r\nTo read and write to the AXI4 bus, a 'command-response' format is required:\r\n\r\n- Command: The Host-PC sends commands to `uart2axi4` module through `i_uart_rx`;\r\n\r\n- Execution: This module performs AXI4 read and write;\r\n\r\n- Response: This module response message through `o_uart_tx` , it will be send to Host-PC.\r\n\r\nEach command and response only contains printable ASCII characters and ends with carriage-return \"\\r\", new-line \"\\n\", or carriage return+new-line \"\\r\\n\".\r\n\r\n#### Write Command\r\n\r\nFor AXI4 write operation, you should send command like:\r\n\r\n```\r\nw[address in hex] [write data 0 in hex] [write data 1 in hex] [write data 2 in hex] ... (end with \"\\n\")\r\n```\r\n\r\nWrite data must at least 1 and at most 256. These data will be written in one AXI4 burst.\r\n\r\nFor example:\r\n\r\n```\r\nw123 456 789 abc def 4321\r\n```\r\n\r\nmeans write address=0x0123, burst length=5, the 5 data are: 0x0456, 0x0789, 0x0abc, 0xdef, 0x4321.\r\n\r\nFor write command, the module will response \"okay\", \"ok\", or \"o\"\r\n\r\n#### Read Command\r\n\r\nFor AXI4 read operation, you should send command like:\r\n\r\n```\r\nr[address in hex] [read burst length] (end with \"\\n\")\r\n```\r\n\r\nThe range of read burst length is 1-100 (note that hexadecimal values need to be sent, corresponding to decimal values of 1-256)\r\n\r\nFor example:\r\n\r\n```\r\nr123 a\r\n```\r\n\r\nmeans read address=0x123, burst length=0xa=10\r\n\r\nfor this command, the module may response:\r\n\r\n```\r\n0000 0000 0000 0000 0000 0000 0000 0000 0000 0000\r\n```\r\n\r\nwhich means the ten read data are all 0x0000\r\n\r\n#### Invalid Command\r\n\r\nIf the command format is undefined, the module will response \"invalid\", \"inva\", \"in\", or \"i\"\r\n\r\n　\r\n\r\n　\r\n\r\n\r\n# 4. RTL Simulation\r\n\r\nThe simulation related files are all in the SIM folder.\r\n\r\n### 4.1 Simulation for uart_tx and uart_rx\r\n\r\nThis simulation connect module `uart_tx` and module `uart_rx` , let `uart_tx` sending increase bytes via UART, and `uart_rx` will receive these bytes.\r\n\r\nfiles:\r\n\r\n- tb_axis_inc_source.v is an AXI-stream master to send increase bytes on AXI-stream, its AXI-stream will connect on `uart_tx` 's AXI-stream slave.\r\n- tb_uart.v is simulation top.\r\n- tb_uart_run_iverilog.bat is the command script to run iverilog command\r\n\r\nBefore using iverilog for simulation, you should install it, see [iverilog_usage](https://github.com/WangXuan95/WangXuan95/blob/main/iverilog_usage/iverilog_usage.md)\r\n\r\nThen double-click tb_uart_run_iverilog.bat to run simulation (on Windows), Then you can open dump.vcd to see the waveform.\r\n\r\n### 4.2 Simulation for uart2axi4\r\n\r\nThis simulation sends a write command and a read command to uart2axi4.\r\n\r\nfiles:\r\n\r\n- tb_uart2axi4.v is simulation top.\r\n- tb_uart2axi4_run_iverilog.bat is the command script to run iverilog command.\r\n\r\nBefore using iverilog for simulation, you should install it, see [iverilog_usage](https://github.com/WangXuan95/WangXuan95/blob/main/iverilog_usage/iverilog_usage.md)\r\n\r\nThen double-click tb_uart2axi4_run_iverilog.bat to run simulation (on Windows), Then you can open dump.vcd to see the waveform.\r\n\r\n　\r\n\r\n　\r\n\r\n　\r\n\r\n　\r\n\r\n　\r\n\r\n\r\n<span id=\"cn\">Verilog-UART</span>\r\n===========================\r\n\r\n本库包含 3 个 Verilog 模块：\r\n\r\n* **UART接收器**：[uart_rx.v](./RTL/uart_rx.v) , 具有一个 AXI-stream master 口，解析 UART 协议并将数据通过 AXI-stream 发送出去。\r\n* **UART发送器**：[uart_tx.v](./RTL/uart_tx.v) , 具有一个 AXI-stream slave 口，接受 AXI-stream 数据并通过 UART 发送出去。\r\n* **UART to AXI4 master**：[uart2axi4.v](./RTL/uart2axi4.v) , 它能接收上位机的 UART 命令，完成 AXI4 总线读写，并将结果反馈给上位机。是调试 SoC 系统的有力工具。\r\n\r\n特点：\r\n\r\n- 标准的 AXI 接口\r\n- 可配置是否开启发送/接收 FIFO 以及 FIFO 的深度\r\n- 可配置的 UART 波特率、校验位、停止位\r\n- 分数分频：当时钟频率不能整除波特率时，各个 bit 的周期不一样，从而凑出一个更加接近的波特率。\r\n- 波特率检查报告：仿真时会用 `$display` 打印波特率精确度。如果过于不精确则报错。\r\n\r\n　\r\n\r\n　\r\n\r\n# 1. UART接收器 uart_rx\r\n\r\nUART接收器的代码文件是 [uart_rx.v](./RTL/uart_rx.v) 。该模块没有子模块。\r\n\r\n定义如下：\r\n\r\n```verilog\r\nmodule uart_rx #(\r\n    // clock frequency\r\n    parameter  CLK_FREQ  = 50000000,     // clk frequency, Unit : Hz\r\n    // UART format\r\n    parameter  BAUD_RATE = 115200,       // Unit : Hz\r\n    parameter  PARITY    = \"NONE\",       // \"NONE\", \"ODD\", or \"EVEN\"\r\n    // RX fifo depth\r\n    parameter  FIFO_EA   = 0             // 0:no fifo   1,2:depth=4   3:depth=8   4:depth=16  ...  10:depth=1024   11:depth=2048  ...\r\n) (\r\n    input  wire        rstn,\r\n    input  wire        clk,\r\n    // UART RX input signal\r\n    input  wire        i_uart_rx,\r\n    // output AXI-stream master. Associated clock = clk. \r\n    input  wire        o_tready,\r\n    output reg         o_tvalid,\r\n    output reg  [ 7:0] o_tdata,\r\n    // report whether there's a overflow\r\n    output reg         o_overflow\r\n);\r\n```\r\n\r\n### 1.1 parameter 配置\r\n\r\n- `CLK_FREQ` 是时钟 `clk` 的频率，用户必须正确配置它，从而产生正确的波特率。\r\n- `BAUD_RATE` 是 UART 波特率\r\n- `PARITY` 决定了校验位，`\"NONE\"`是无校验位，`\"ODD\"`是奇校验位，`\"EVEN\"`是偶校验位。\r\n- `FIFO_EA` 用来配置接收缓存：\r\n  - `FIFO_EA=0` 代表无接收缓存，收到的字节必须立刻被用户处理，否则就会丢弃。\r\n  - `FIFO_EA=1,2` 代表接收缓存大小=4；\r\n  - `FIFO_EA=3` 代表接收缓存大小=8；\r\n  - `FIFO_EA=4` 代表接收缓存大小=16；\r\n  - ……\r\n\r\n- 当 `FIFO_EA` 较大 (通常是>8)，FIFO 会用 BRAM 实现。\r\n\r\n### 1.2 时钟和复位\r\n\r\n`rstn` 是低电平复位。\r\n\r\n`clk` 是时钟。所有信号的采样和改变都要在 `clk` 的上升沿进行。\r\n\r\n### 1.3 UART 信号\r\n\r\n`i_uart_rx` 是 UART 输入信号\r\n\r\n### 1.4 AXI-stream master\r\n\r\n`o_tready` , `o_tvalid` , `o_tdata`  构成了 AXI-stream master 接口\r\n\r\n- `o_tvalid=1` 时，`o_tdata` 上会产生有效的接收到的字节，\r\n- 如果用户能够接收当前字节，就让 `o_tready=1` 。\r\n- 当 `o_tvalid` 和 `o_tready` 都是1时，握手成功，当前字节成功从模块的缓存中拿出。\r\n- 当握手成功时，在下一周期：\r\n  - 若缓存中还有收到的字节，则 `o_tvalid=1` ， `o_tdata` 上出现下一个收到的字节\r\n  - 若缓存暂时空了，则 `o_tvalid=0`\r\n\r\n>  :warning: 如果没有接收缓存（参数 `FIFO_EA=0` ），则模块不会等待用户是否能接受当前的字节，只要收到一个字节就让 `o_tvalid=1` 一个周期，并让该字节出现在 `o_tdata` 上。\r\n\r\n### 1.5 溢出信号 `o_overflow` \r\n\r\n如果用户经常让 `o_tready=0` ，也即不及时拿走数据，则接受数据会在模块里的缓存里越攒越多，当缓存溢出时，新接收到的字节会被丢弃，并在 `o_overflow` 信号上产生一个周期的高电平脉冲。否则 `o_overflow` 一直保持 0 。\r\n\r\n### 1.6 波特率检查\r\n\r\n在仿真时，模块会根据用户的配置，打印各个 bit 的边沿的时间点以及其精确度。如果精度太差 (相对误差>8%) ，模块会使用 `$error` 系统调用报错，帮助用户提前发现配置错误。\r\n\r\n例如，如果我们配置 `CLK_FREQ=5000000` (5MHz) ，`BAUD_RATE=115200` , `PARITY=\"ODD\"`，则仿真会打印如下报告：\r\n\r\n```\r\nuart_rx :           parity = ODD\r\nuart_rx :     clock period = 200 ns   (5000000    Hz)\r\nuart_rx : baud rate period = 8681 ns   (115200     Hz)\r\nuart_rx :      baud cycles = 43\r\nuart_rx : baud cycles frac = 4\r\nuart_rx :             __      ____ ____ ____ ____ ____ ____ ____ ____________\r\nuart_rx :        wave   \\____/____X____X____X____X____X____X____X____X____/\r\nuart_rx :        bits   | S  | B0 | B1 | B2 | B3 | B4 | B5 | B6 | B7 | P   |\r\nuart_rx : time_points  t0   t1   t2   t3   t4   t5   t6   t7   t8   t9   t10\r\nuart_rx :\r\nuart_rx : t1 - t0 = 8681 ns (ideal)  8600 +- 200 ns (actual).   error=281 ns   relative_error=3.232%\r\nuart_rx : t2 - t0 = 17361 ns (ideal)  17400 +- 200 ns (actual).   error=239 ns   relative_error=2.752%\r\nuart_rx : t3 - t0 = 26042 ns (ideal)  26000 +- 200 ns (actual).   error=242 ns   relative_error=2.784%\r\nuart_rx : t4 - t0 = 34722 ns (ideal)  34800 +- 200 ns (actual).   error=278 ns   relative_error=3.200%\r\nuart_rx : t5 - t0 = 43403 ns (ideal)  43400 +- 200 ns (actual).   error=203 ns   relative_error=2.336%\r\nuart_rx : t6 - t0 = 52083 ns (ideal)  52000 +- 200 ns (actual).   error=283 ns   relative_error=3.264%\r\nuart_rx : t7 - t0 = 60764 ns (ideal)  60800 +- 200 ns (actual).   error=236 ns   relative_error=2.720%\r\nuart_rx : t8 - t0 = 69444 ns (ideal)  69400 +- 200 ns (actual).   error=244 ns   relative_error=2.816%\r\nuart_rx : t9 - t0 = 78125 ns (ideal)  78200 +- 200 ns (actual).   error=275 ns   relative_error=3.168%\r\nuart_rx : t10- t0 = 86806 ns (ideal)  86800 +- 200 ns (actual).   error=206 ns   relative_error=2.368%\r\n```\r\n\r\n　\r\n\r\n　\r\n\r\n# 2. UART发送器 uart_tx\r\n\r\nUART发送器的代码文件是 [RTL/uart_tx.v](./RTL/uart_tx.v) 。该模块没有子模块。\r\n\r\n该模块的定义如下：\r\n\r\n```verilog\r\nmodule uart_tx #(\r\n    // clock frequency\r\n    parameter  CLK_FREQ                  = 50000000,     // clk frequency, Unit : Hz\r\n    // UART format\r\n    parameter  BAUD_RATE                 = 115200,       // Unit : Hz\r\n    parameter  PARITY                    = \"NONE\",       // \"NONE\", \"ODD\", or \"EVEN\"\r\n    parameter  STOP_BITS                 = 2,            // can be 1, 2, 3, 4, ...\r\n    // AXI stream data width\r\n    parameter  BYTE_WIDTH                = 1,            // can be 1, 2, 3, 4, ...\r\n    // TX fifo depth\r\n    parameter  FIFO_EA                   = 0,            // 0:no fifo   1,2:depth=4   3:depth=8   4:depth=16  ...  10:depth=1024   11:depth=2048  ...\r\n    // do you want to send extra byte after each AXI-stream transfer or packet?\r\n    parameter  EXTRA_BYTE_AFTER_TRANSFER = \"\",           // specify a extra byte to send after each AXI-stream transfer. when =\"\", do not send this extra byte\r\n    parameter  EXTRA_BYTE_AFTER_PACKET   = \"\"            // specify a extra byte to send after each AXI-stream packet  . when =\"\", do not send this extra byte\r\n) (\r\n    input  wire                    rstn,\r\n    input  wire                    clk,\r\n    // input  stream : AXI-stream slave. Associated clock = clk\r\n    output wire                    i_tready,\r\n    input  wire                    i_tvalid,\r\n    input  wire [8*BYTE_WIDTH-1:0] i_tdata,\r\n    input  wire [  BYTE_WIDTH-1:0] i_tkeep,\r\n    input  wire                    i_tlast,\r\n    // UART TX output signal\r\n    output reg                     o_uart_tx\r\n);\r\n```\r\n\r\n### 2.1 parameter 配置\r\n\r\n- `CLK_FREQ` 是时钟 `clk` 的频率，用户必须正确配置它，从而产生正确的波特率。\r\n- `BAUD_RATE` 是 UART 波特率\r\n- `PARITY` 决定了校验位，`\"NONE\"`是无校验位，`\"ODD\"`是奇校验位，`\"EVEN\"`是偶校验位。\r\n- `STOP_BITS` 是停止位数量，决定了模块会在发送完每字节后发送多少个停止位。\r\n- `BYTE_WIDTH` 是 AXI-stream slave 接口的字节宽度 (也即 `i_tdata` 的字节数)\r\n- `FIFO_EA` 用来配置发送缓存：\r\n  - `FIFO_EA=0` 代表无发送缓存，AXI-stream 每握手成功一个数据，都必须等待发送完成，才能握手下一个数据\r\n  - `FIFO_EA=1,2` 代表接收缓存大小=4；\r\n  - `FIFO_EA=3` 代表接收缓存大小=8；\r\n  - `FIFO_EA=4` 代表接收缓存大小=16；\r\n  - ……\r\n- 当 `FIFO_EA` 较大 (通常是>8)，FIFO 会用 BRAM 实现。\r\n- `EXTRA_BYTE_AFTER_TRANSFER` 用来配置每次 AXI-stream transfer (也即握手成功一次) 时，是否要通过 UART 发送一个额外的字节\r\n  - 如果不想发送额外的字节，就让 `EXTRA_BYTE_AFTER_TRANSFER=\"\"`\r\n  - 如果想发送额外的字节，比如空格字节 \" \"，就让 `EXTRA_BYTE_AFTER_TRANSFER=\" \"`\r\n\r\n- `EXTRA_BYTE_AFTER_PACKET` 用来配置每次 AXI-stream packet (也即握手成功一次且 `tlast=1`) 时，是否要通过 UART 发送一个额外的字节\r\n  - 如果不想发送额外的字节，就让 `EXTRA_BYTE_AFTER_PACKET=\"\"`\r\n  - 如果想发送额外的字节，比如回车字节 \"\\n\"，就让 `EXTRA_BYTE_AFTER_PACKET=\"\\n\"`\r\n\r\n### 2.2 时钟和复位\r\n\r\n`rstn` 是低电平复位。\r\n\r\n`clk` 是时钟。所有信号的采样和改变都要在 `clk` 的上升沿进行。\r\n\r\n### 2.3 UART 信号\r\n\r\n`o_uart_tx` 是 UART 输出信号\r\n\r\n### 2.4 AXI-stream slave\r\n\r\n`i_tready` , `i_tvalid` , `i_tdata` , `i_tkeep` , `i_tlast` 构成了 AXI-stream slave 接口：\r\n\r\n- `i_tready=1` 代表模块内部缓存还有空间，可以接受数据。`i_tready=0` 代表模块内部缓存没空间了，无法接收数据。\r\n- `i_tvalid=1` 代表用户想要发送一个数据到发送缓存里，同时 `i_tdata` , `i_tkeep` , `i_tlast` 需要有效。\r\n- `i_tvalid` 和 `i_tready` 都是 1 时，握手成功，当前数据被成功存入缓存。\r\n- `i_tdata` 的字节宽度通过参数 `BYTE_WIDTH` 来配置。\r\n- `i_tdata` 遵循小端序，其低位字节先被发送，高位字节后被发送。\r\n- `i_tkeep` 是字节有效信号：\r\n  - `i_tkeep[0]=0` 代表 `i_tdata[7:0]` 这个字节有效，需要发送。否则不会发送；\r\n  - `i_tkeep[1]=1` 代表 `i_tdata[15:8]` 这个字节有效，需要发送。否则不会发送；\r\n  - `i_tkeep[2]=1` 代表 `i_tdata[23:16]` 这个字节有效，需要发送。否则不会发送；\r\n  - ……\r\n- `i_tlast` 是 AXI-stream 的 packet 分界信号。当发送一个数据时，如果 `i_tlast=1` ：\r\n  - 如果 `EXTRA_BYTE_AFTER_PACKET` 指定了一个字节，UART 会额外发送这个字节；\r\n  - 如果 `EXTRA_BYTE_AFTER_PACKET=\"\"` ，不发送额外字节。换句话说，此时 `i_tlast` 无论是 0 还是 1 都没有任何影响。\r\n\r\n### 2.5 波特率检查\r\n\r\n在仿真时，模块会根据用户的配置，打印各个 bit 的边沿的时间点以及其精确度。如果精度太差 (相对误差>3%) ，模块会使用 `$error` 系统调用报错，帮助用户提前发现配置错误。\r\n\r\n在前面 `uart_rx` 模块中已经对波特率检查举例，这里不再举例。\r\n\r\n　\r\n\r\n　\r\n\r\n\r\n# 3. UART to AXI4 master (uart2axi4)\r\n\r\n代码文件是 [RTL/uart2axi4.v](./RTL/uart2axi4.v) 。该模块会调用 [RTL/uart_tx.v](./RTL/uart_tx.v) 和  [RTL/uart_rx.v](./RTL/uart_rx.v) 。\r\n\r\n该模块是一个 AXI4 master，它能接收上位机的 UART 命令，完成 AXI4 总线读写，并将结果反馈给上位机。是调试 SoC 系统的有力工具。\r\n\r\n模块定义如下：\r\n\r\n```verilog\r\nmodule uart2axi4 #(\r\n    // clock frequency\r\n    parameter  CLK_FREQ   = 50000000,     // clk frequency, Unit : Hz\r\n    // UART format\r\n    parameter  BAUD_RATE  = 115200,       // Unit : Hz\r\n    parameter  PARITY     = \"NONE\",       // \"NONE\", \"ODD\", or \"EVEN\"\r\n    // AXI4 config\r\n    parameter  BYTE_WIDTH = 2,            // data width (bytes)\r\n    parameter  A_WIDTH    = 32            // address width (bits)\r\n) (\r\n    input  wire                    rstn,\r\n    input  wire                    clk,\r\n    // AXI4 master ----------------------\r\n    input  wire                    awready,  // AW\r\n    output wire                    awvalid,\r\n    output wire      [A_WIDTH-1:0] awaddr,\r\n    output wire             [ 7:0] awlen,\r\n    input  wire                    wready,   // W\r\n    output wire                    wvalid,\r\n    output wire                    wlast,\r\n    output wire [8*BYTE_WIDTH-1:0] wdata,\r\n    output wire                    bready,   // B\r\n    input  wire                    bvalid,\r\n    input  wire                    arready,  // AR\r\n    output wire                    arvalid,\r\n    output wire      [A_WIDTH-1:0] araddr,\r\n    output wire             [ 7:0] arlen,\r\n    output wire                    rready,   // R\r\n    input  wire                    rvalid,\r\n    input  wire                    rlast,\r\n    input  wire [8*BYTE_WIDTH-1:0] rdata,\r\n    // UART ----------------------\r\n    input  wire                    i_uart_rx,\r\n    output wire                    o_uart_tx\r\n);\r\n```\r\n\r\n### 3.1 parameter 配置\r\n\r\n- `CLK_FREQ` 是时钟 `clk` 的频率，用户必须正确配置它，从而产生正确的波特率。\r\n- `BAUD_RATE` 是 UART 波特率\r\n- `PARITY` 决定了校验位，`\"NONE\"`是无校验位，`\"ODD\"`是奇校验位，`\"EVEN\"`是偶校验位。\r\n- `BYTE_WIDTH` 是 AXI4 的宽度 (`wdata` 和 `rdata` 的字节宽度)\r\n- `A_WIDTH` 是 AXI4 的地址宽度 (`awaddr` 和 `araddr` 的位宽)\r\n\r\n### 3.2 时钟和复位\r\n\r\n`rstn` 是低电平复位。\r\n\r\n`clk` 是时钟。所有信号的采样和改变都要在 `clk` 的上升沿进行。\r\n\r\n### 3.3 UART 信号\r\n\r\n`o_uart_tx` 是 UART 输出信号 (连接上位机的 UART-RX)\r\n\r\n`i_uart_rx` 是 UART 输入信号 (连接上位机的 UART-TX)\r\n\r\n### 3.4 AXI4 master\r\n\r\n该模块有一个 AXI4 master 接口，可读写 AXI4 总线。这里不对 AXI4 时序做详解，详见 https://www.xilinx.com/products/intellectual-property/axi.html\r\n\r\n### 3.5 UART 命令格式\r\n\r\n要读写 AXI4 总线，需要进行一次 \"命令-响应\" ：\r\n\r\n- 命令：上位机通过 UART 发送命令给该模块的 `i_uart_rx` ；\r\n- 执行：该模块执行 AXI4 读写；\r\n- 响应：该模块通过 `o_uart_tx` 发送一个反馈信息给上位机的 UART 。\r\n\r\n每个命令和响应都只包含可打印的 ASCII 字符，且以 回车 \"\\r\" 、换行 \"\\n\" 、或 回车+换行 \"\\r\\n\" 结尾。\r\n\r\n#### 写命令\r\n\r\n要进行 AXI4 写操作，格式如下：\r\n\r\n```\r\nw[地址的十六进制值] [写数据0的十六进制值] [写数据1的十六进制值] [写数据2的十六进制值] ... (注意命令要用\"\\n\"结尾)\r\n```\r\n\r\n其中写数据最少1个，最多256个。这些数据会在一次 AXI4 burst 内写完。\r\n\r\n例如：\r\n\r\n```\r\nw123 456 789 abc def 4321\r\n```\r\n\r\n代表写地址=0x0123，突发长度=5，写入的5个数据为 0x0456, 0x0789, 0x0abc, 0xdef, 0x4321 。\r\n\r\n对于写命令，模块会响应 \"okay\" , \"ok\" , 或 \"o\"\r\n\r\n### 读命令\r\n\r\n要进行 AXI4 读操作，格式如下：\r\n\r\n```\r\nr[地址的十六进制值] [读突发长度] (注意命令要用\"\\n\"结尾)\r\n```\r\n\r\n其中读突发长度的取值范围为 1~100 (注意需要发送十六进制值，对应的十进制值为1~256)\r\n\r\n例如：\r\n\r\n```\r\nr123 a\r\n```\r\n\r\n代表读地址=0x123，突发长度=0xa=10。\r\n\r\n对于读命令，模块会响应读到的数据 + \"\\n\" ，各个数据之间用空格 \" \" 隔开。\r\n\r\n例如，上述命令可能会响应：\r\n\r\n```\r\n0000 0000 0000 0000 0000 0000 0000 0000 0000 0000\r\n```\r\n\r\n代表读到的10个数据都是 0x0000\r\n\r\n### 非法命令\r\n\r\n如果命令格式错误，模块会响应 \"invalid\" , \"inva\" , “in\" , 或者 \"i\"\r\n\r\n　\r\n\r\n　\r\n\r\n# 4. 仿真\r\n\r\n仿真相关的文件都在 SIM 文件夹中。\r\n\r\n### 4.1 针对 uart_tx 和 uart_rx 模块的仿真\r\n\r\n该仿真将 uart_tx 和 uart_rx 连起来，让 uart_tx 发送递增的字节，uart_rx 会解析出这些字节。\r\n\r\n相关文件\r\n\r\n- tb_axis_inc_source.v 是个 AXI-master ，产生递增的字节。它会连接到 uart_tx 的 AXI-slave 上。\r\n- tb_uart.v 是仿真的顶层。\r\n- tb_uart_run_iverilog.bat 包含了运行 iverilog 仿真的命令。\r\n\r\n使用 iverilog 进行仿真前，需要安装 iverilog ，见：[iverilog_usage](https://github.com/WangXuan95/WangXuan95/blob/main/iverilog_usage/iverilog_usage.md)\r\n\r\n然后双击 tb_uart_run_iverilog.bat 运行仿真 (仅Windows)，然后可以打开生成的 dump.vcd 文件查看波形。\r\n\r\n### 4.2 针对 uart2axi4 模块的仿真\r\n\r\n该仿真发送一个写命令和一个读命令给 uart2axi4 。\r\n\r\n相关文件\r\n\r\n- tb_uart2axi4.v 是仿真的顶层。\r\n- tb_uart2axi4_run_iverilog.bat 包含了运行 iverilog 仿真的命令。\r\n\r\n使用 iverilog 进行仿真前，需要安装 iverilog ，见：[iverilog_usage](https://github.com/WangXuan95/WangXuan95/blob/main/iverilog_usage/iverilog_usage.md)\r\n\r\n然后双击 tb_uart2axi4_run_iverilog.bat 运行仿真 (仅Windows)，然后可以打开生成的 dump.vcd 文件查看波形。\r\n"
  },
  {
    "path": "RTL/uart2axi4.v",
    "content": "\r\n//--------------------------------------------------------------------------------------------------------\r\n// Module  : uart2axi4\r\n// Type    : synthesizable\r\n// Standard: Verilog 2001 (IEEE1364-2001)\r\n// Function: convert UART command to AXI4 read/write action\r\n//--------------------------------------------------------------------------------------------------------\r\n\r\nmodule uart2axi4 #(\r\n    // clock frequency\r\n    parameter  CLK_FREQ   = 50000000,     // clk frequency, Unit : Hz\r\n    // UART format\r\n    parameter  BAUD_RATE  = 115200,       // Unit : Hz\r\n    parameter  PARITY     = \"NONE\",       // \"NONE\", \"ODD\", or \"EVEN\"\r\n    // AXI4 config\r\n    parameter  BYTE_WIDTH = 2,            // data width (bytes)\r\n    parameter  A_WIDTH    = 32            // address width (bits)\r\n) (\r\n    input  wire                    rstn,\r\n    input  wire                    clk,\r\n    // AXI4 master ----------------------\r\n    input  wire                    awready,  // AW\r\n    output wire                    awvalid,\r\n    output wire      [A_WIDTH-1:0] awaddr,\r\n    output wire             [ 7:0] awlen,\r\n    input  wire                    wready,   // W\r\n    output wire                    wvalid,\r\n    output wire                    wlast,\r\n    output wire [8*BYTE_WIDTH-1:0] wdata,\r\n    output wire                    bready,   // B\r\n    input  wire                    bvalid,\r\n    input  wire                    arready,  // AR\r\n    output wire                    arvalid,\r\n    output wire      [A_WIDTH-1:0] araddr,\r\n    output wire             [ 7:0] arlen,\r\n    output wire                    rready,   // R\r\n    input  wire                    rvalid,\r\n    input  wire                    rlast,\r\n    input  wire [8*BYTE_WIDTH-1:0] rdata,\r\n    // UART ----------------------\r\n    input  wire                    i_uart_rx,\r\n    output wire                    o_uart_tx\r\n);\r\n\r\n\r\n\r\nwire                   rx_valid;\r\nwire            [ 7:0] rx_byte;\r\n\r\nuart_rx #(\r\n    .CLK_FREQ                  ( CLK_FREQ             ),\r\n    .BAUD_RATE                 ( BAUD_RATE            ),\r\n    .PARITY                    ( PARITY               ),\r\n    .FIFO_EA                   ( 0                    )\r\n) u_uart_rx (\r\n    .rstn                      ( rstn                 ),\r\n    .clk                       ( clk                  ),\r\n    .i_uart_rx                 ( i_uart_rx            ),\r\n    .o_tready                  ( 1'b1                 ),\r\n    .o_tvalid                  ( rx_valid             ),\r\n    .o_tdata                   ( rx_byte              ),\r\n    .o_overflow                (                      )\r\n);\r\n\r\nwire                   rx_space   = (rx_valid && (rx_byte == 8'h20));                        // \" \"\r\nwire                   rx_newline = (rx_valid && (rx_byte == 8'h0D || rx_byte == 8'h0A));    // \\r, \\n\r\nwire                   rx_char_w  = (rx_valid && (rx_byte == 8'h57 || rx_byte == 8'h77));    // W, w\r\nwire                   rx_char_r  = (rx_valid && (rx_byte == 8'h52 || rx_byte == 8'h72));    // R, r\r\nwire                   rx_is_hex  = (rx_valid && ((rx_byte>=8'h30 && rx_byte<=8'h39) || (rx_byte>=8'h41 && rx_byte<=8'h46) || (rx_byte>=8'h61 && rx_byte<=8'h66)));    // 0~9, A~F, a~f\r\nwire            [ 3:0] rx_hex     = (rx_byte>=8'h30 && rx_byte<=8'h39) ? rx_byte[3:0] : (rx_byte[3:0] + 4'd9);\r\n\r\n\r\n\r\nreg                    rwtype = 1'b0;\r\nreg      [A_WIDTH-1:0] addr   = 0;\r\nreg             [ 8:0] len    = 9'h0;\r\nreg                    wwen   = 1'b0;\r\nreg [8*BYTE_WIDTH-1:0] wwdata = 0;\r\nreg             [ 7:0] wraddr = 8'h0;\r\n\r\n\r\nlocalparam      [ 3:0] S_IDLE        = 4'd0,\r\n                       S_PARSE_ADDR  = 4'd1,\r\n                       S_PARSE_LEN   = 4'd2,\r\n                       S_PARSE_WDATA = 4'd3,\r\n                       S_AXI_RADDR   = 4'd4,\r\n                       S_AXI_WADDR   = 4'd5,\r\n                       S_AXI_RDATA   = 4'd6,\r\n                       S_AXI_WDATA   = 4'd7,\r\n                       S_AXI_B       = 4'd8,\r\n                       S_W_DONE      = 4'd9,\r\n                       S_INVALID     = 4'd10,\r\n                       S_FAILED      = 4'd11;\r\n\r\nreg             [ 3:0] state  = S_IDLE;\r\n\r\n\r\nalways @ (posedge clk or negedge rstn)\r\n    if (~rstn) begin\r\n        rwtype <= 1'b0;\r\n        addr   <= 0;\r\n        len    <= 9'h0;\r\n        wwen   <= 1'b0;\r\n        wwdata <= 0;\r\n        wraddr <= 8'h0;\r\n        state  <= S_IDLE;\r\n    end else begin\r\n        case (state)\r\n            \r\n            S_IDLE : begin\r\n                rwtype <= rx_char_w;\r\n                addr   <= 0;\r\n                len    <= 9'h0;\r\n                wwen   <= 1'b0;\r\n                wwdata <= 0;\r\n                wraddr <= 8'h0;\r\n                if (rx_char_w | rx_char_r)\r\n                    state <= S_PARSE_ADDR;\r\n                else if (rx_space | rx_newline)\r\n                    state <= S_IDLE;\r\n                else if (rx_valid)\r\n                    state <= S_INVALID;\r\n            end\r\n            \r\n            S_PARSE_ADDR :\r\n                if (rx_is_hex) begin\r\n                    addr <= (addr << 4);\r\n                    addr[3:0] <= rx_hex;\r\n                end else if (rx_space)\r\n                    state <= rwtype ? S_PARSE_WDATA : S_PARSE_LEN;\r\n                else if (rx_newline)\r\n                    state <= S_FAILED;\r\n                else if (rx_valid)\r\n                    state <= S_INVALID;\r\n            \r\n            S_PARSE_LEN :\r\n                if (rx_is_hex) begin\r\n                    len   <= (len << 4);\r\n                    len[3:0] <= rx_hex;\r\n                end else if (rx_newline) begin\r\n                    len   <= (len >= 9'h100) ? 9'hFF : (len == 9'h0) ? 9'h0 : (len - 9'h1);\r\n                    state <= S_AXI_RADDR;\r\n                end else if (rx_space) begin\r\n                    state <= S_PARSE_LEN;\r\n                end else if (rx_valid) begin\r\n                    state <= S_INVALID;\r\n                end\r\n            \r\n            S_PARSE_WDATA :\r\n                if (rx_is_hex) begin\r\n                    wwen   <= 1'b1;\r\n                    wwdata <= (wwdata << 4);\r\n                    wwdata[3:0] <= rx_hex;\r\n                end else if (rx_space) begin\r\n                    wwen  <= 1'b0;\r\n                    if (wwen) begin\r\n                        wwdata <= 0;\r\n                        len    <= len + 9'd1;\r\n                    end\r\n                end else if (rx_newline) begin\r\n                    if (wwen) begin\r\n                        state <= (               len <  9'h100) ? S_AXI_WADDR : S_FAILED;\r\n                    end else begin\r\n                        state <= (len >= 9'd0 && len <= 9'd100) ? S_AXI_WADDR : S_FAILED;\r\n                        len   <= len - 9'd1;\r\n                    end\r\n                end else if (rx_valid) begin\r\n                    state <= S_INVALID;\r\n                end\r\n            \r\n            S_AXI_RADDR :\r\n                if (arready)\r\n                    state <= S_AXI_RDATA;\r\n            \r\n            S_AXI_WADDR :\r\n                if (awready)\r\n                    state <= S_AXI_WDATA;\r\n            \r\n            S_AXI_RDATA : \r\n                if (rvalid) begin\r\n                    len <= len - 9'd1;\r\n                    if (rlast || (len==9'd0))\r\n                        state <= S_IDLE;\r\n                end\r\n            \r\n            S_AXI_WDATA :\r\n                if (wready) begin\r\n                    wraddr <= wraddr + 8'd1;\r\n                    if (wraddr >= len[7:0])\r\n                        state <= S_AXI_B;\r\n                end\r\n            \r\n            S_AXI_B :\r\n                if (bvalid)\r\n                    state <= S_W_DONE;\r\n            \r\n            S_W_DONE :\r\n                state <= S_IDLE;\r\n            \r\n            S_INVALID :\r\n                if (rx_newline)\r\n                    state <= S_FAILED;\r\n            \r\n            default : // S_FAILED :\r\n                state <= S_IDLE;\r\n                \r\n        endcase\r\n    end\r\n\r\n\r\nreg [8*BYTE_WIDTH-1:0] wbuf [0:255];\r\n\r\nalways @ (posedge clk)\r\n    if ( (state == S_PARSE_WDATA) && (rx_space || rx_newline) && wwen )\r\n        wbuf[len[7:0]] <= wwdata;\r\n\r\nwire            [ 7:0] wraddr_next = (wvalid & wready) ? (wraddr + 8'd1) : wraddr;\r\nreg [8*BYTE_WIDTH-1:0] wrdata;\r\n\r\nalways @ (posedge clk)\r\n    wrdata <= wbuf[wraddr_next];\r\n\r\n\r\n\r\nassign arvalid = (state == S_AXI_RADDR);\r\nassign araddr  = addr;\r\nassign arlen   = len[7:0];\r\n\r\nassign awvalid = (state == S_AXI_WADDR);\r\nassign awaddr  = addr;\r\nassign awlen   = len[7:0];\r\n\r\nassign rready  = (state == S_AXI_RDATA);\r\n\r\nassign wvalid  = (state == S_AXI_WDATA);\r\nassign wlast   = (wraddr >= len[7:0]);\r\nassign wdata   = wrdata;\r\n\r\nassign bready  = 1'b1;        // (state == S_AXI_B)\r\n\r\n\r\n\r\n\r\n\r\nfunction  [7:0] toHex;\r\n    input [3:0] val;\r\nbegin\r\n    toHex = (val <= 4'd9) ? {4'h3, val} : {4'd6, 1'b0, val[2:0]-3'h1};\r\nend\r\nendfunction\r\n\r\n\r\nwire                      tx_w_done = (state == S_W_DONE);\r\nwire                      tx_failed = (state == S_FAILED);\r\nwire                      tx_number = (rvalid & rready);\r\n\r\nwire [8*2*BYTE_WIDTH-1:0] tx_data_failed = 64'h20_64_69_6C_61_76_6E_69;                                            // \"invalid\"\r\nwire [8*2*BYTE_WIDTH-1:0] tx_data_w_done = 64'h20_20_20_20_79_61_6B_6F;                                            // \"okay\"\r\nwire [8*2*BYTE_WIDTH-1:0] tx_data_number;\r\n\r\nwire                      tx_valid  = tx_failed | tx_w_done | tx_number;\r\nwire [8*2*BYTE_WIDTH-1:0] tx_data   = tx_failed ? tx_data_failed : tx_w_done ? tx_data_w_done : tx_data_number;\r\nwire                      tx_last   = tx_failed ?           1'b1 : tx_w_done ?           1'b1 : (rlast || (len==9'd0));\r\n\r\n\r\ngenerate genvar i;\r\n    for (i=0; i<2*BYTE_WIDTH; i=i+1) begin : gen_tx_tdata\r\n        assign tx_data_number[8*i +: 8] = toHex(rdata[4*(2*BYTE_WIDTH-1-i) +: 4]);\r\n    end\r\nendgenerate\r\n\r\n\r\n\r\nuart_tx #(\r\n    .CLK_FREQ                  ( CLK_FREQ               ),\r\n    .BAUD_RATE                 ( BAUD_RATE              ),\r\n    .PARITY                    ( PARITY                 ),\r\n    .STOP_BITS                 ( 4                      ),\r\n    .BYTE_WIDTH                ( 2 * BYTE_WIDTH         ),\r\n    .FIFO_EA                   ( 9                      ),\r\n    .EXTRA_BYTE_AFTER_TRANSFER ( \" \"                    ),\r\n    .EXTRA_BYTE_AFTER_PACKET   ( \"\\n\"                   )\r\n) u_uart_tx (\r\n    .rstn                      ( rstn                   ),\r\n    .clk                       ( clk                    ),\r\n    .i_tready                  (                        ),\r\n    .i_tvalid                  ( tx_valid               ),\r\n    .i_tdata                   ( tx_data                ),\r\n    .i_tkeep                   ( {(2*BYTE_WIDTH){1'b1}} ),\r\n    .i_tlast                   ( tx_last                ),\r\n    .o_uart_tx                 ( o_uart_tx              )\r\n);\r\n\r\n\r\nendmodule\r\n"
  },
  {
    "path": "RTL/uart_rx.v",
    "content": "\r\n//--------------------------------------------------------------------------------------------------------\r\n// Module  : uart_rx\r\n// Type    : synthesizable, IP's top\r\n// Standard: Verilog 2001 (IEEE1364-2001)\r\n// Function: input  UART signal,\r\n//           output AXI-stream (1 byte data width)\r\n//--------------------------------------------------------------------------------------------------------\r\n\r\nmodule uart_rx #(\r\n    // clock frequency\r\n    parameter  CLK_FREQ  = 50000000,     // clk frequency, Unit : Hz\r\n    // UART format\r\n    parameter  BAUD_RATE = 115200,       // Unit : Hz\r\n    parameter  PARITY    = \"NONE\",       // \"NONE\", \"ODD\", or \"EVEN\"\r\n    // RX fifo depth\r\n    parameter  FIFO_EA   = 0             // 0:no fifo   1,2:depth=4   3:depth=8   4:depth=16  ...  10:depth=1024   11:depth=2048  ...\r\n) (\r\n    input  wire        rstn,\r\n    input  wire        clk,\r\n    // UART RX input signal\r\n    input  wire        i_uart_rx,\r\n    // output AXI-stream master. Associated clock = clk. \r\n    input  wire        o_tready,\r\n    output reg         o_tvalid,\r\n    output reg  [ 7:0] o_tdata,\r\n    // report whether there's a overflow\r\n    output reg         o_overflow\r\n);\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// Generate fractional precise upper limit for counter\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\nlocalparam  BAUD_CYCLES      = ( (CLK_FREQ*10*2 + BAUD_RATE) / (BAUD_RATE*2) ) / 10 ;\r\nlocalparam  BAUD_CYCLES_FRAC = ( (CLK_FREQ*10*2 + BAUD_RATE) / (BAUD_RATE*2) ) % 10 ;\r\n\r\nlocalparam           HALF_BAUD_CYCLES =  BAUD_CYCLES    / 2;\r\nlocalparam  THREE_QUARTER_BAUD_CYCLES = (BAUD_CYCLES*3) / 4;\r\n\r\nlocalparam [9:0] ADDITION_CYCLES = (BAUD_CYCLES_FRAC == 0) ? 10'b0000000000 :\r\n                                   (BAUD_CYCLES_FRAC == 1) ? 10'b0000010000 :\r\n                                   (BAUD_CYCLES_FRAC == 2) ? 10'b0010000100 :\r\n                                   (BAUD_CYCLES_FRAC == 3) ? 10'b0010010010 :\r\n                                   (BAUD_CYCLES_FRAC == 4) ? 10'b0101001010 :\r\n                                   (BAUD_CYCLES_FRAC == 5) ? 10'b0101010101 :\r\n                                   (BAUD_CYCLES_FRAC == 6) ? 10'b1010110101 :\r\n                                   (BAUD_CYCLES_FRAC == 7) ? 10'b1101101101 :\r\n                                   (BAUD_CYCLES_FRAC == 8) ? 10'b1101111011 :\r\n                                  /*BAUD_CYCLES_FRAC == 9)*/ 10'b1111101111 ;\r\n\r\nwire [31:0] cycles [9:0];\r\n\r\nassign cycles[0] = BAUD_CYCLES + (ADDITION_CYCLES[0] ? 1 : 0);\r\nassign cycles[1] = BAUD_CYCLES + (ADDITION_CYCLES[1] ? 1 : 0);\r\nassign cycles[2] = BAUD_CYCLES + (ADDITION_CYCLES[2] ? 1 : 0);\r\nassign cycles[3] = BAUD_CYCLES + (ADDITION_CYCLES[3] ? 1 : 0);\r\nassign cycles[4] = BAUD_CYCLES + (ADDITION_CYCLES[4] ? 1 : 0);\r\nassign cycles[5] = BAUD_CYCLES + (ADDITION_CYCLES[5] ? 1 : 0);\r\nassign cycles[6] = BAUD_CYCLES + (ADDITION_CYCLES[6] ? 1 : 0);\r\nassign cycles[7] = BAUD_CYCLES + (ADDITION_CYCLES[7] ? 1 : 0);\r\nassign cycles[8] = BAUD_CYCLES + (ADDITION_CYCLES[8] ? 1 : 0);\r\nassign cycles[9] = BAUD_CYCLES + (ADDITION_CYCLES[9] ? 1 : 0);\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// Input beat\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\nreg        rx_d1 = 1'b0;\r\n\r\nalways @ (posedge clk or negedge rstn)\r\n    if (~rstn)\r\n        rx_d1 <= 1'b0;\r\n    else\r\n        rx_d1 <= i_uart_rx;\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// count continuous '1'\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\nreg [31:0] count1 = 0;\r\n\r\nalways @ (posedge clk or negedge rstn)\r\n    if (~rstn) begin\r\n        count1 <= 0;\r\n    end else begin\r\n        if (rx_d1)\r\n            count1 <= (count1 < 'hFFFFFFFF) ? (count1 + 1) : count1;\r\n        else\r\n            count1 <= 0;\r\n    end\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// main FSM\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\nlocalparam [ 3:0] TOTAL_BITS_MINUS1 = (PARITY == \"ODD\" || PARITY == \"EVEN\") ? 4'd9 : 4'd8;\r\n\r\nlocalparam [ 1:0] S_IDLE     = 2'd0 ,\r\n                  S_RX       = 2'd1 ,\r\n                  S_STOP_BIT = 2'd2 ;\r\n\r\nreg        [ 1:0] state   = S_IDLE;\r\nreg        [ 8:0] rxbits  = 9'b0;\r\nreg        [ 3:0] rxcnt   = 4'd0;\r\nreg        [31:0] cycle   = 1;\r\nreg        [32:0] countp  = 33'h1_0000_0000;       // countp>=0x100000000 means '1' is majority       , countp<0x100000000 means '0' is majority\r\nwire              rxbit   = countp[32];            // countp>=0x100000000 corresponds to countp[32]==1, countp<0x100000000 corresponds to countp[32]==0\r\n\r\nwire [ 7:0] rbyte   = (PARITY == \"ODD\" ) ? rxbits[7:0] : \r\n                      (PARITY == \"EVEN\") ? rxbits[7:0] : \r\n                    /*(PARITY == \"NONE\")*/ rxbits[8:1] ;\r\n\r\nwire parity_correct = (PARITY == \"ODD\" ) ? ((~(^(rbyte))) == rxbits[8]) : \r\n                      (PARITY == \"EVEN\") ? (  (^(rbyte))  == rxbits[8]) : \r\n                    /*(PARITY == \"NONE\")*/      1'b1                    ;\r\n\r\n\r\nalways @ (posedge clk or negedge rstn)\r\n    if (~rstn) begin\r\n        state    <= S_IDLE;\r\n        rxbits   <= 9'b0;\r\n        rxcnt    <= 4'd0;\r\n        cycle    <= 1;\r\n        countp   <= 33'h1_0000_0000;\r\n    end else begin\r\n        case (state)\r\n            S_IDLE : begin\r\n                if ((count1 >= THREE_QUARTER_BAUD_CYCLES) && (rx_d1 == 1'b0))  // receive a '0' which is followed by continuous '1' for half baud cycles\r\n                    state <= S_RX;\r\n                rxcnt  <= 4'd0;\r\n                cycle  <= 2;                                                   // we've already receive a '0', so here cycle  = 2\r\n                countp <= (33'h1_0000_0000 - 33'd1);                           // we've already receive a '0', so here countp = initial_value - 1\r\n            end\r\n            \r\n            S_RX :\r\n                if ( cycle < cycles[rxcnt] ) begin                             // cycle loop from 1 to cycles[rxcnt]\r\n                    cycle  <= cycle + 1;\r\n                    countp <= rx_d1 ? (countp + 33'd1) : (countp - 33'd1);\r\n                end else begin\r\n                    cycle  <= 1;                                               // reset counter\r\n                    countp <= 33'h1_0000_0000;                                 // reset counter\r\n                    \r\n                    if ( rxcnt < TOTAL_BITS_MINUS1 ) begin                     // rxcnt loop from 0 to TOTAL_BITS_MINUS1\r\n                        rxcnt <= rxcnt + 4'd1;\r\n                        if ((rxcnt == 4'd0) && (rxbit == 1'b1))                // except start bit, but get '1'\r\n                            state <= S_IDLE;                                   // RX failed, back to IDLE\r\n                    end else begin\r\n                        rxcnt <= 4'd0;\r\n                        state <= S_STOP_BIT;\r\n                    end\r\n                    \r\n                    rxbits <= {rxbit, rxbits[8:1]};                            // put current rxbit to MSB of rxbits, and right shift other bits\r\n                end\r\n            \r\n            default :  // S_STOP_BIT\r\n                if ( cycle < THREE_QUARTER_BAUD_CYCLES) begin                  // cycle loop from 1 to THREE_QUARTER_BAUD_CYCLES\r\n                    cycle <= cycle + 1;\r\n                end else begin\r\n                    cycle <= 1;                                                // reset counter\r\n                    state <= S_IDLE;                                           // back to IDLE\r\n                end\r\n        endcase\r\n    end\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// RX result byte\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\nreg       f_tvalid = 1'b0;\r\nreg [7:0] f_tdata  = 8'h0;\r\n\r\nalways @ (posedge clk or negedge rstn)\r\n    if (~rstn) begin\r\n        f_tvalid <= 1'b0;\r\n        f_tdata  <= 8'h0;\r\n    end else begin\r\n        f_tvalid <= 1'b0;\r\n        f_tdata  <= 8'h0;\r\n        if (state == S_STOP_BIT) begin\r\n            if ( cycle < THREE_QUARTER_BAUD_CYCLES) begin\r\n            end else begin\r\n                if ((count1 >= HALF_BAUD_CYCLES) && parity_correct) begin  // stop bit have enough '1', and parity correct\r\n                    f_tvalid <= 1'b1;\r\n                    f_tdata  <= rbyte;                                     // received a correct byte, output it\r\n                end\r\n            end\r\n        end\r\n    end\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// RX fifo\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\nwire f_tready;\r\n\r\ngenerate if (FIFO_EA <= 0) begin          // no RX fifo\r\n    \r\n    assign       f_tready = o_tready;\r\n    always @ (*) o_tvalid = f_tvalid;\r\n    always @ (*) o_tdata  = f_tdata;\r\n\r\nend else begin                            // TX fifo\r\n\r\n    localparam        EA     = (FIFO_EA <= 2) ? 2 : FIFO_EA;\r\n\r\n    reg  [7:0] buffer [ ((1<<EA)-1) : 0 ];\r\n\r\n    localparam [EA:0] A_ZERO = {{EA{1'b0}}, 1'b0};\r\n    localparam [EA:0] A_ONE  = {{EA{1'b0}}, 1'b1};\r\n\r\n    reg  [EA:0] wptr      = A_ZERO;\r\n    reg  [EA:0] wptr_d1   = A_ZERO;\r\n    reg  [EA:0] wptr_d2   = A_ZERO;\r\n    reg  [EA:0] rptr      = A_ZERO;\r\n    wire [EA:0] rptr_next = (o_tvalid & o_tready) ? (rptr+A_ONE) : rptr;\r\n\r\n    assign f_tready = ( wptr != {~rptr[EA], rptr[EA-1:0]} );\r\n\r\n    always @ (posedge clk or negedge rstn)\r\n        if (~rstn) begin\r\n            wptr    <= A_ZERO;\r\n            wptr_d1 <= A_ZERO;\r\n            wptr_d2 <= A_ZERO;\r\n        end else begin\r\n            if (f_tvalid & f_tready)\r\n                wptr <= wptr + A_ONE;\r\n            wptr_d1 <= wptr;\r\n            wptr_d2 <= wptr_d1;\r\n        end\r\n\r\n    always @ (posedge clk)\r\n        if (f_tvalid & f_tready)\r\n            buffer[wptr[EA-1:0]] <= f_tdata;\r\n\r\n    always @ (posedge clk or negedge rstn)\r\n        if (~rstn) begin\r\n            rptr <= A_ZERO;\r\n            o_tvalid <= 1'b0;\r\n        end else begin\r\n            rptr <= rptr_next;\r\n            o_tvalid <= (rptr_next != wptr_d2);\r\n        end\r\n\r\n    always @ (posedge clk)\r\n        o_tdata <= buffer[rptr_next[EA-1:0]];\r\n\r\n    initial o_tvalid = 1'b0;\r\n    initial o_tdata  = 8'h0;\r\nend endgenerate\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// detect RX fifo overflow\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\ninitial o_overflow = 1'b0;\r\n\r\nalways @ (posedge clk or negedge rstn)\r\n    if (~rstn)\r\n        o_overflow <= 1'b0;\r\n    else\r\n        o_overflow <= (f_tvalid & (~f_tready));\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// parameter checking\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\ninitial begin\r\n    if (BAUD_CYCLES < 10) begin $error(\"invalid parameter : BAUD_CYCLES < 10, please use a faster driving clock\"); $stop; end\r\n    \r\n    $display(\"uart_rx :           parity = %s\" , PARITY );\r\n    $display(\"uart_rx :     clock period = %.0f ns   (%-10d Hz)\" , 1000000000.0/CLK_FREQ  , CLK_FREQ );\r\n    $display(\"uart_rx : baud rate period = %.0f ns   (%-10d Hz)\" , 1000000000.0/BAUD_RATE , BAUD_RATE);\r\n    $display(\"uart_rx :      baud cycles = %-10d\"    , BAUD_CYCLES );\r\n    $display(\"uart_rx : baud cycles frac = %-10d\"    , BAUD_CYCLES_FRAC  );\r\n    \r\n    if (PARITY == \"ODD\" || PARITY == \"EVEN\") begin\r\n        $display(\"uart_rx :             __      ____ ____ ____ ____ ____ ____ ____ ____________ \");\r\n        $display(\"uart_rx :        wave   \\\\____/____X____X____X____X____X____X____X____X____/   \");\r\n        $display(\"uart_rx :        bits   | S  | B0 | B1 | B2 | B3 | B4 | B5 | B6 | B7 | P  |   \");\r\n        $display(\"uart_rx : time_points  t0   t1   t2   t3   t4   t5   t6   t7   t8   t9   t10  \");\r\n        $display(\"uart_rx :\");\r\n    end else begin\r\n        $display(\"uart_rx :             __      ____ ____ ____ ____ ____ ____ ____ _______ \");\r\n        $display(\"uart_rx :        wave   \\\\____/____X____X____X____X____X____X____X____/   \");\r\n        $display(\"uart_rx :        bits   | S  | B0 | B1 | B2 | B3 | B4 | B5 | B6 | B7 |   \");\r\n        $display(\"uart_rx : time_points  t0   t1   t2   t3   t4   t5   t6   t7   t8   t9   \");\r\n        $display(\"uart_rx :\");\r\n    end\r\nend\r\n\r\ngenerate genvar index;\r\n    for (index=0; index<=9; index=index+1) begin : print_and_check_time\r\n        localparam cycles_acc = ( (index >= 0) ? (BAUD_CYCLES + (ADDITION_CYCLES[0] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 1) ? (BAUD_CYCLES + (ADDITION_CYCLES[1] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 2) ? (BAUD_CYCLES + (ADDITION_CYCLES[2] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 3) ? (BAUD_CYCLES + (ADDITION_CYCLES[3] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 4) ? (BAUD_CYCLES + (ADDITION_CYCLES[4] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 5) ? (BAUD_CYCLES + (ADDITION_CYCLES[5] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 6) ? (BAUD_CYCLES + (ADDITION_CYCLES[6] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 7) ? (BAUD_CYCLES + (ADDITION_CYCLES[7] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 8) ? (BAUD_CYCLES + (ADDITION_CYCLES[8] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 9) ? (BAUD_CYCLES + (ADDITION_CYCLES[9] ? 1 : 0)) : 0 ) ;\r\n        \r\n        localparam real ideal_time_ns  = ((index+1)*1000000000.0/BAUD_RATE);\r\n        localparam real actual_time_ns = (cycles_acc*1000000000.0/CLK_FREQ);\r\n        localparam real uncertainty    = (1000000000.0/CLK_FREQ);\r\n        localparam real error          = ( (ideal_time_ns>actual_time_ns) ? (ideal_time_ns-actual_time_ns) : (-ideal_time_ns+actual_time_ns) ) + uncertainty;\r\n        localparam real relative_error_percent = (error / (1000000000.0/BAUD_RATE)) * 100.0;\r\n        \r\n        initial if (PARITY == \"ODD\" || PARITY == \"EVEN\" || index < 9) begin\r\n            $display(\"uart_rx : t%-2d- t0 = %.0f ns (ideal)  %.0f +- %.0f ns (actual).   error=%.0f ns   relative_error=%.3f%%\" ,\r\n                (index+1) ,\r\n                ideal_time_ns ,\r\n                actual_time_ns,\r\n                uncertainty,\r\n                error,\r\n                relative_error_percent\r\n            );\r\n            \r\n            if ( relative_error_percent > 8.0 ) begin $error(\"relative_error is too large\"); $stop; end   // if relative error larger than 8%\r\n        end\r\n    end\r\nendgenerate\r\n\r\n\r\nendmodule\r\n"
  },
  {
    "path": "RTL/uart_tx.v",
    "content": "\r\n//--------------------------------------------------------------------------------------------------------\r\n// Module  : uart_tx\r\n// Type    : synthesizable, IP's top\r\n// Standard: Verilog 2001 (IEEE1364-2001)\r\n// Function: input  AXI-stream (configurable data width),\r\n//           output UART signal\r\n//--------------------------------------------------------------------------------------------------------\r\n\r\nmodule uart_tx #(\r\n    // clock frequency\r\n    parameter  CLK_FREQ                  = 50000000,     // clk frequency, Unit : Hz\r\n    // UART format\r\n    parameter  BAUD_RATE                 = 115200,       // Unit : Hz\r\n    parameter  PARITY                    = \"NONE\",       // \"NONE\", \"ODD\", or \"EVEN\"\r\n    parameter  STOP_BITS                 = 2,            // can be 1, 2, 3, 4, ...\r\n    // AXI stream data width\r\n    parameter  BYTE_WIDTH                = 1,            // can be 1, 2, 3, 4, ...\r\n    // TX fifo depth\r\n    parameter  FIFO_EA                   = 0,            // 0:no fifo   1,2:depth=4   3:depth=8   4:depth=16  ...  10:depth=1024   11:depth=2048  ...\r\n    // do you want to send extra byte after each AXI-stream transfer or packet?\r\n    parameter  EXTRA_BYTE_AFTER_TRANSFER = \"\",           // specify a extra byte to send after each AXI-stream transfer. when =\"\", do not send this extra byte\r\n    parameter  EXTRA_BYTE_AFTER_PACKET   = \"\"            // specify a extra byte to send after each AXI-stream packet  . when =\"\", do not send this extra byte\r\n) (\r\n    input  wire                    rstn,\r\n    input  wire                    clk,\r\n    // input  stream : AXI-stream slave. Associated clock = clk\r\n    output wire                    i_tready,\r\n    input  wire                    i_tvalid,\r\n    input  wire [8*BYTE_WIDTH-1:0] i_tdata,\r\n    input  wire [  BYTE_WIDTH-1:0] i_tkeep,\r\n    input  wire                    i_tlast,\r\n    // UART TX output signal\r\n    output reg                     o_uart_tx\r\n);\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// TX fifo\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\nwire                    f_tready;\r\nreg                     f_tvalid;\r\nreg  [8*BYTE_WIDTH-1:0] f_tdata;\r\nreg  [  BYTE_WIDTH-1:0] f_tkeep;\r\nreg                     f_tlast;\r\n\r\ngenerate if (FIFO_EA <= 0) begin          // no TX fifo\r\n\r\n    assign       i_tready = f_tready;\r\n    always @ (*) f_tvalid = i_tvalid;\r\n    always @ (*) f_tdata  = i_tdata;\r\n    always @ (*) f_tkeep  = i_tkeep;\r\n    always @ (*) f_tlast  = i_tlast;\r\n\r\nend else begin                            // TX fifo\r\n\r\n    localparam        EA     = (FIFO_EA<=2) ? 2 : FIFO_EA;\r\n    localparam        DW     = ( 1 + BYTE_WIDTH + 8*BYTE_WIDTH );     // 1-bit tlast, (BYTE_WIDTH)-bit tkeep, (8*BYTE_WIDTH)-bit tdata\r\n    \r\n    reg  [DW-1:0] buffer [ ((1<<EA)-1) : 0 ];\r\n    \r\n    localparam [EA:0] A_ZERO = {{EA{1'b0}}, 1'b0};\r\n    localparam [EA:0] A_ONE  = {{EA{1'b0}}, 1'b1};\r\n\r\n    reg  [EA:0] wptr      = A_ZERO;\r\n    reg  [EA:0] wptr_d1   = A_ZERO;\r\n    reg  [EA:0] wptr_d2   = A_ZERO;\r\n    reg  [EA:0] rptr      = A_ZERO;\r\n    wire [EA:0] rptr_next = (f_tvalid & f_tready) ? (rptr+A_ONE) : rptr;\r\n    \r\n    assign i_tready = ( wptr != {~rptr[EA], rptr[EA-1:0]} );\r\n\r\n    always @ (posedge clk or negedge rstn)\r\n        if (~rstn) begin\r\n            wptr    <= A_ZERO;\r\n            wptr_d1 <= A_ZERO;\r\n            wptr_d2 <= A_ZERO;\r\n        end else begin\r\n            if (i_tvalid & i_tready)\r\n                wptr <= wptr + A_ONE;\r\n            wptr_d1 <= wptr;\r\n            wptr_d2 <= wptr_d1;\r\n        end\r\n\r\n    always @ (posedge clk)\r\n        if (i_tvalid & i_tready)\r\n            buffer[wptr[EA-1:0]] <= {i_tlast, i_tkeep, i_tdata};\r\n\r\n    always @ (posedge clk or negedge rstn)\r\n        if (~rstn) begin\r\n            rptr <= A_ZERO;\r\n            f_tvalid <= 1'b0;\r\n        end else begin\r\n            rptr <= rptr_next;\r\n            f_tvalid <= (rptr_next != wptr_d2);\r\n        end\r\n\r\n    always @ (posedge clk)\r\n        {f_tlast, f_tkeep, f_tdata} <= buffer[rptr_next[EA-1:0]];\r\n    \r\n    initial {f_tvalid, f_tlast, f_tkeep, f_tdata} = 0;\r\n    \r\nend endgenerate\r\n\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// Generate fractional precise upper limit for counter\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\nlocalparam      BAUD_CYCLES              = ( (CLK_FREQ*10*2 + BAUD_RATE) / (BAUD_RATE*2) ) / 10 ;\r\nlocalparam      BAUD_CYCLES_FRAC         = ( (CLK_FREQ*10*2 + BAUD_RATE) / (BAUD_RATE*2) ) % 10 ;\r\nlocalparam      STOP_BIT_CYCLES          = (BAUD_CYCLES_FRAC == 0) ? BAUD_CYCLES : (BAUD_CYCLES + 1);\r\n\r\nlocalparam [9:0] ADDITION_CYCLES = (BAUD_CYCLES_FRAC == 0) ? 10'b0000000000 :\r\n                                   (BAUD_CYCLES_FRAC == 1) ? 10'b0000010000 :\r\n                                   (BAUD_CYCLES_FRAC == 2) ? 10'b0010000100 :\r\n                                   (BAUD_CYCLES_FRAC == 3) ? 10'b0010010010 :\r\n                                   (BAUD_CYCLES_FRAC == 4) ? 10'b0101001010 :\r\n                                   (BAUD_CYCLES_FRAC == 5) ? 10'b0101010101 :\r\n                                   (BAUD_CYCLES_FRAC == 6) ? 10'b1010110101 :\r\n                                   (BAUD_CYCLES_FRAC == 7) ? 10'b1101101101 :\r\n                                   (BAUD_CYCLES_FRAC == 8) ? 10'b1101111011 :\r\n                                  /*BAUD_CYCLES_FRAC == 9)*/ 10'b1111101111 ;\r\n\r\nwire [31:0] cycles [9:0];\r\n\r\nassign cycles[0] = BAUD_CYCLES + (ADDITION_CYCLES[0] ? 1 : 0);\r\nassign cycles[1] = BAUD_CYCLES + (ADDITION_CYCLES[1] ? 1 : 0);\r\nassign cycles[2] = BAUD_CYCLES + (ADDITION_CYCLES[2] ? 1 : 0);\r\nassign cycles[3] = BAUD_CYCLES + (ADDITION_CYCLES[3] ? 1 : 0);\r\nassign cycles[4] = BAUD_CYCLES + (ADDITION_CYCLES[4] ? 1 : 0);\r\nassign cycles[5] = BAUD_CYCLES + (ADDITION_CYCLES[5] ? 1 : 0);\r\nassign cycles[6] = BAUD_CYCLES + (ADDITION_CYCLES[6] ? 1 : 0);\r\nassign cycles[7] = BAUD_CYCLES + (ADDITION_CYCLES[7] ? 1 : 0);\r\nassign cycles[8] = BAUD_CYCLES + (ADDITION_CYCLES[8] ? 1 : 0);\r\nassign cycles[9] = BAUD_CYCLES + (ADDITION_CYCLES[9] ? 1 : 0);\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// \r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\nlocalparam [BYTE_WIDTH-1:0] ZERO_KEEP   = 0;\r\n\r\nlocalparam           [31:0] PARITY_BITS = (PARITY == \"ODD\" || PARITY == \"EVEN\") ? 1 : 0;\r\nlocalparam           [31:0] TOTAL_BITS  = (STOP_BITS >= ('hFFFFFFFF-9-PARITY_BITS)) ? 'hFFFFFFFF : (PARITY_BITS+STOP_BITS+9);\r\n\r\nlocalparam           [ 0:0] BYTE_T_EN   = (EXTRA_BYTE_AFTER_TRANSFER == \"\") ? 1'b0 : 1'b1;\r\nlocalparam           [ 0:0] BYTE_B_EN   = (EXTRA_BYTE_AFTER_PACKET   == \"\") ? 1'b0 : 1'b1;\r\nlocalparam           [ 7:0] BYTE_T      =  EXTRA_BYTE_AFTER_TRANSFER;\r\nlocalparam           [ 7:0] BYTE_P      =  EXTRA_BYTE_AFTER_PACKET;\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// function for calculate parity bit\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\nfunction  [0:0] get_parity;\r\n    input [7:0] data;\r\nbegin\r\n    get_parity = (PARITY == \"ODD\" ) ? (~(^(data[7:0]))) : \r\n                 (PARITY == \"EVEN\") ?   (^(data[7:0]))  : \r\n               /*(PARITY == \"NONE\")*/      1'b1         ;\r\nend\r\nendfunction\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// main FSM\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\nlocalparam [       1:0] S_IDLE     = 2'b01 ,       // only in state S_IDLE, state[0]==1, the goal is to make f_tready pure register-out\r\n                        S_PREPARE  = 2'b00 ,\r\n                        S_TX       = 2'b10 ;\r\n\r\nreg  [             1:0] state      = S_IDLE;       // FSM state register\r\n\r\nreg  [8*BYTE_WIDTH-1:0] data       = 0;\r\nreg  [  BYTE_WIDTH-1:0] keep       = 0;\r\nreg                     byte_t_en  = 1'b0;\r\nreg                     byte_p_en  = 1'b0;\r\nreg  [             9:0] txbits     = 10'b0;\r\nreg  [            31:0] txcnt      = 0;\r\nreg  [            31:0] cycle      = 1;\r\n\r\n\r\nalways @ (posedge clk or negedge rstn)\r\n    if (~rstn) begin\r\n        state      <= S_IDLE;\r\n        data       <= 0;\r\n        keep       <= 0;\r\n        byte_t_en  <= 1'b0;\r\n        byte_p_en  <= 1'b0;\r\n        txbits     <= 10'b0;\r\n        txcnt      <= 0;\r\n        cycle      <= 1;\r\n    end else begin\r\n        case (state)\r\n            S_IDLE : begin\r\n                state      <= f_tvalid ? S_PREPARE : S_IDLE;\r\n                data       <= f_tdata;\r\n                keep       <= f_tkeep;\r\n                byte_t_en  <= BYTE_T_EN;\r\n                byte_p_en  <= BYTE_B_EN & f_tlast;\r\n                txbits     <= 10'b0;\r\n                txcnt      <= 0;\r\n                cycle      <= 1;\r\n            end\r\n            \r\n            S_PREPARE : begin\r\n                data <= (data >> 8);\r\n                keep <= (keep >> 1);\r\n                if          ( keep[0] == 1'b1   ) begin\r\n                    txbits     <= {get_parity(data[7:0]), data[7:0], 1'b0};\r\n                    state      <= S_TX;\r\n                end else if ( keep != ZERO_KEEP ) begin\r\n                    state      <= S_PREPARE;\r\n                end else if ( byte_t_en         ) begin\r\n                    byte_t_en <= 1'b0;\r\n                    txbits     <= {get_parity(BYTE_T), BYTE_T, 1'b0};\r\n                    state      <= S_TX;\r\n                end else if ( byte_p_en         ) begin\r\n                    byte_p_en <= 1'b0;\r\n                    txbits     <= {get_parity(BYTE_P), BYTE_P, 1'b0};\r\n                    state      <= S_TX;\r\n                end else begin\r\n                    state      <= S_IDLE;\r\n                end\r\n                txcnt <= 0;\r\n                cycle <= 1;\r\n            end\r\n            \r\n            default : begin  // S_TX\r\n                if (keep[0] == 1'b0) begin\r\n                    data <= (data >> 8);\r\n                    keep <= (keep >> 1);\r\n                end\r\n                if ( cycle < ((txcnt<=9) ? cycles[txcnt] : STOP_BIT_CYCLES) ) begin      // cycle loop from 1 to ((txcnt<=9) ? cycles[txcnt] : STOP_BIT_CYCLES)\r\n                    cycle  <= cycle + 1;\r\n                end else begin\r\n                    cycle  <= 1;\r\n                    txbits <= {1'b1, txbits[9:1]};                                       // right shift txbits, and fill '1' to MSB\r\n                    if ( txcnt < (TOTAL_BITS-1) ) begin                                  // txcnt loop from 0 to (TOTAL_BITS-1)\r\n                        txcnt <= txcnt + 1;\r\n                    end else begin\r\n                        txcnt <= 0;\r\n                        state <= S_PREPARE;\r\n                    end\r\n                end\r\n            end\r\n        endcase\r\n    end\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// generate UART output\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\ninitial o_uart_tx = 1'b1;\r\n\r\nalways @ (posedge clk or negedge rstn)\r\n    if (~rstn)\r\n        o_uart_tx <= 1'b1;\r\n    else\r\n        o_uart_tx <= (state == S_TX) ? txbits[0] : 1'b1;\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// generate AXI-stream TREADY\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\nassign f_tready = state[0];   // (state == S_IDLE)\r\n\r\n\r\n\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n// parameter checking\r\n//---------------------------------------------------------------------------------------------------------------------------------------------------------------\r\ninitial begin\r\n    if (BYTE_WIDTH <= 0) begin $error(\"invalid parameter : BYTE_WIDTH<=0\"); $stop; end\r\n    if (STOP_BITS  <= 0) begin $error(\"invalid parameter : STOP_BITS <=0\"); $stop; end\r\n    if (BAUD_CYCLES < 1) begin $error(\"invalid parameter : BAUD_CYCLES < 1, please use a faster driving clock\"); $stop; end\r\n    \r\n    $display(\"uart_tx :           parity = %s\" , PARITY );\r\n    $display(\"uart_tx :     clock period = %.0f ns   (%-10d Hz)\" , 1000000000.0/CLK_FREQ  , CLK_FREQ );\r\n    $display(\"uart_tx : baud rate period = %.0f ns   (%-10d Hz)\" , 1000000000.0/BAUD_RATE , BAUD_RATE);\r\n    $display(\"uart_tx :      baud cycles = %-10d\"   , BAUD_CYCLES );\r\n    $display(\"uart_tx : baud cycles frac = %-10d\"   , BAUD_CYCLES_FRAC  );\r\n    \r\n    if (PARITY == \"ODD\" || PARITY == \"EVEN\") begin\r\n        $display(\"uart_tx :             __      ____ ____ ____ ____ ____ ____ ____ ____________ \");\r\n        $display(\"uart_tx :        wave   \\\\____/____X____X____X____X____X____X____X____X____/   \");\r\n        $display(\"uart_tx :        bits   | S  | B0 | B1 | B2 | B3 | B4 | B5 | B6 | B7 | P  |   \");\r\n        $display(\"uart_tx : time_points  t0   t1   t2   t3   t4   t5   t6   t7   t8   t9   t10  \");\r\n        $display(\"uart_tx :\");\r\n    end else begin\r\n        $display(\"uart_tx :             __      ____ ____ ____ ____ ____ ____ ____ _______ \");\r\n        $display(\"uart_tx :        wave   \\\\____/____X____X____X____X____X____X____X____/   \");\r\n        $display(\"uart_tx :        bits   | S  | B0 | B1 | B2 | B3 | B4 | B5 | B6 | B7 |   \");\r\n        $display(\"uart_tx : time_points  t0   t1   t2   t3   t4   t5   t6   t7   t8   t9   \");\r\n        $display(\"uart_tx :\");\r\n    end\r\nend\r\n\r\ngenerate genvar index, i;\r\n    for (index=0; index<=9; index=index+1) begin : print_and_check_time\r\n        localparam cycles_acc = ( (index >= 0) ? (BAUD_CYCLES + (ADDITION_CYCLES[0] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 1) ? (BAUD_CYCLES + (ADDITION_CYCLES[1] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 2) ? (BAUD_CYCLES + (ADDITION_CYCLES[2] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 3) ? (BAUD_CYCLES + (ADDITION_CYCLES[3] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 4) ? (BAUD_CYCLES + (ADDITION_CYCLES[4] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 5) ? (BAUD_CYCLES + (ADDITION_CYCLES[5] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 6) ? (BAUD_CYCLES + (ADDITION_CYCLES[6] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 7) ? (BAUD_CYCLES + (ADDITION_CYCLES[7] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 8) ? (BAUD_CYCLES + (ADDITION_CYCLES[8] ? 1 : 0)) : 0 )\r\n                              + ( (index >= 9) ? (BAUD_CYCLES + (ADDITION_CYCLES[9] ? 1 : 0)) : 0 ) ;\r\n        \r\n        localparam real ideal_time_ns  = ((index+1)*1000000000.0/BAUD_RATE);\r\n        localparam real actual_time_ns = (cycles_acc*1000000000.0/CLK_FREQ);\r\n        localparam real error          = (ideal_time_ns>actual_time_ns) ? (ideal_time_ns-actual_time_ns) : (-ideal_time_ns+actual_time_ns);\r\n        localparam real relative_error_percent = (error / (1000000000.0/BAUD_RATE)) * 100.0;\r\n        \r\n        initial if (PARITY == \"ODD\" || PARITY == \"EVEN\" || index < 9) begin\r\n            $display(\"uart_tx : t%-2d- t0 = %.0f ns (ideal)  %.0f ns (actual).   error=%.0f ns   relative_error=%.3f%%\" ,\r\n                (index+1) ,\r\n                ideal_time_ns ,\r\n                actual_time_ns,\r\n                error,\r\n                relative_error_percent\r\n            );\r\n            \r\n            if ( relative_error_percent > 3.0 ) begin $error(\"relative_error is too large\"); $stop; end   // if relative error larger than 3%\r\n        end\r\n    end\r\nendgenerate\r\n\r\n\r\nendmodule\r\n"
  },
  {
    "path": "SIM/tb_axis_inc_source.v",
    "content": "\r\nmodule tb_axis_inc_source # (\r\n    parameter    BYTE_WIDTH = 4\r\n) (\r\n    input  wire                    rstn,\r\n    input  wire                    clk,\r\n    // AXI-stream master\r\n    input  wire                    o_tready,\r\n    output reg                     o_tvalid,\r\n    output reg  [8*BYTE_WIDTH-1:0] o_tdata,\r\n    output reg  [  BYTE_WIDTH-1:0] o_tkeep,\r\n    output reg                     o_tlast\r\n);\r\n\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// function : generate random unsigned integer\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\nfunction  [31:0] randuint;\r\n    input [31:0] min;\r\n    input [31:0] max;\r\nbegin\r\n    randuint = $random;\r\n    if ( min != 0 || max != 'hFFFFFFFF )\r\n        randuint = (randuint % (1+max-min)) + min;\r\nend\r\nendfunction\r\n\r\n\r\n\r\ninitial {o_tvalid, o_tdata, o_tkeep, o_tlast} = 0;\r\n\r\nreg [BYTE_WIDTH-1:0] keep = 0;\r\nreg [7:0] next_byte = 8'h0;\r\n\r\nreg [31:0] delay = 100000;\r\n\r\ninteger i;\r\n\r\nalways @ (posedge clk or negedge rstn)\r\n    if (~rstn) begin\r\n        {o_tvalid, o_tdata, o_tkeep, o_tlast} <= 0;\r\n        next_byte = 8'h0;\r\n        delay <= 100000;\r\n    end else begin\r\n        if (delay > 0) begin\r\n            delay <= delay - 1;\r\n        end else begin\r\n            if (o_tready | ~o_tvalid) begin\r\n                if ( randuint(0,4) == 0 ) begin\r\n                    o_tvalid <= 1'b1;\r\n                    keep = randuint(0, 'hFFFFFFFF);\r\n                    for (i=0; i<BYTE_WIDTH; i=i+1) begin\r\n                        if (keep[i]) begin\r\n                            o_tdata[i*8 +: 8] <= next_byte;\r\n                            next_byte = next_byte + 8'd1;\r\n                        end\r\n                    end\r\n                    o_tkeep <= keep;\r\n                    o_tlast <= (randuint(0,100) == 0);\r\n                end else begin\r\n                    o_tvalid <= 1'b0;\r\n                end\r\n            end\r\n        end\r\n    end\r\n\r\n\r\nendmodule \r\n"
  },
  {
    "path": "SIM/tb_uart.v",
    "content": "\r\n//--------------------------------------------------------------------------------------------------------\r\n// Module  : tb_uart\r\n// Type    : simulation, top\r\n// Standard: Verilog 2001 (IEEE1364-2001)\r\n// Function: testbench for uart_tx and uart_rx\r\n//--------------------------------------------------------------------------------------------------------\r\n\r\n`timescale 1ps/1ps\r\n\r\nmodule tb_uart ();\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// parameters (you can modify them)\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\nlocalparam TX_CLK_FREQ         = 4000000;\r\nlocalparam RX_CLK_FREQ         = 5000000;\r\nlocalparam UART_BAUD_RATE      = 115200;\r\nlocalparam UART_PARITY         = \"ODD\";\r\nlocalparam UART_STOP_BITS      = 1;\r\nlocalparam TX_AXIS_BYTE_WIDTH  = 2;\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// UART signal\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\nwire uart_signal;\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// generate reset and clock\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\nreg rstn  = 1'b0;\r\nreg txclk = 1'b1;\r\nreg rxclk = 1'b1;\r\nalways #(1000000000000 / 2 / TX_CLK_FREQ) txclk = ~txclk;\r\nalways #(1000000000000 / 2 / RX_CLK_FREQ) rxclk = ~rxclk;\r\ninitial begin repeat(4) @(posedge txclk); rstn<=1'b1; end\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// generate an AXI-stream source's behavior for uart_rx\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\nwire                            tx_tready;\r\nwire                            tx_tvalid;\r\nwire [TX_AXIS_BYTE_WIDTH*8-1:0] tx_tdata;\r\nwire [TX_AXIS_BYTE_WIDTH  -1:0] tx_tkeep;\r\nwire                            tx_tlast;\r\n\r\ntb_axis_inc_source # (\r\n    .BYTE_WIDTH                ( TX_AXIS_BYTE_WIDTH   )\r\n) u_tb_axis_inc_source (\r\n    .rstn                      ( rstn                 ),\r\n    .clk                       ( txclk                ),\r\n    .o_tready                  ( tx_tready            ),\r\n    .o_tvalid                  ( tx_tvalid            ),\r\n    .o_tdata                   ( tx_tdata             ),\r\n    .o_tkeep                   ( tx_tkeep             ),\r\n    .o_tlast                   ( tx_tlast             )\r\n);\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// design under test : UART TX\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\nuart_tx #(\r\n    .CLK_FREQ                  ( TX_CLK_FREQ          ),\r\n    .BAUD_RATE                 ( UART_BAUD_RATE       ),\r\n    .PARITY                    ( UART_PARITY          ),\r\n    .STOP_BITS                 ( UART_STOP_BITS       ),\r\n    .BYTE_WIDTH                ( TX_AXIS_BYTE_WIDTH   ),\r\n    .FIFO_EA                   ( 0                    ),\r\n    .EXTRA_BYTE_AFTER_TRANSFER ( \"\"                   ),\r\n    .EXTRA_BYTE_AFTER_PACKET   ( \"\"                   )\r\n) u_uart_tx (\r\n    .rstn                      ( rstn                 ),\r\n    .clk                       ( txclk                ),\r\n    .i_tready                  ( tx_tready            ),\r\n    .i_tvalid                  ( tx_tvalid            ),\r\n    .i_tdata                   ( tx_tdata             ),\r\n    .i_tkeep                   ( tx_tkeep             ),\r\n    .i_tlast                   ( tx_tlast             ),\r\n    .o_uart_tx                 ( uart_signal          )\r\n);\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// design under test : UART RX\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\nwire       rx_tready = 1'b1;\r\nwire       rx_tvalid;\r\nwire [7:0] rx_tdata;\r\n\r\nwire       rx_overflow;\r\n\r\nuart_rx #(\r\n    .CLK_FREQ                  ( RX_CLK_FREQ          ),\r\n    .BAUD_RATE                 ( UART_BAUD_RATE       ),\r\n    .PARITY                    ( UART_PARITY          ),\r\n    .FIFO_EA                   ( 1                    )\r\n) u_uart_rx (\r\n    .rstn                      ( rstn                 ),\r\n    .clk                       ( rxclk                ),\r\n    .i_uart_rx                 ( uart_signal          ),\r\n    .o_tready                  ( rx_tready            ),\r\n    .o_tvalid                  ( rx_tvalid            ),\r\n    .o_tdata                   ( rx_tdata             ),\r\n    .o_overflow                ( rx_overflow          )\r\n);\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// print UART RX result\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\nreg [7:0] expect_byte = 8'h0;\r\nalways @ (posedge rxclk or negedge rstn)\r\n    if (~rstn) begin\r\n        expect_byte <= 8'h0;\r\n    end else begin\r\n        if (rx_tvalid & rx_tready) begin \r\n            $write(\"%02x \", rx_tdata);\r\n            if (rx_tdata !== expect_byte) begin\r\n                $display(\"***error : RX data not increase\");\r\n                $stop;\r\n            end\r\n            expect_byte <= expect_byte + 8'h1;\r\n        end\r\n    end\r\n\r\nalways @ (posedge rxclk)\r\n    if (rx_overflow)\r\n        $display(\"\\nrx overflow\");\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// simulation control\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\ninitial begin repeat (1000000) @(posedge txclk); $finish;  end            // simulation for 1000000 clock cycles\r\ninitial $dumpvars(0, tb_uart);\r\n\r\n\r\nendmodule\r\n"
  },
  {
    "path": "SIM/tb_uart2axi4.v",
    "content": "\r\n//--------------------------------------------------------------------------------------------------------\r\n// Module  : tb_uart2axi4\r\n// Type    : simulation, top\r\n// Standard: Verilog 2001 (IEEE1364-2001)\r\n// Function: testbench for uart_tx and uart_rx\r\n//--------------------------------------------------------------------------------------------------------\r\n\r\n`timescale 1ps/1ps\r\n\r\nmodule tb_uart2axi4 ();\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// simulation control\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\ninitial begin repeat (1000000) @(posedge clk); $finish;  end            // simulation for 1000000 clock cycles\r\ninitial $dumpvars(1, tb_uart2axi4);\r\ninitial $dumpvars(1, u_uart2axi4);\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// parameters\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\nlocalparam CLK_FREQ            = 16000000;\r\nlocalparam UART_BAUD_RATE      = 115200;\r\nlocalparam UART_PARITY         = \"NONE\";\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// generate reset and clock\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\nreg rstn  = 1'b0;\r\nreg clk   = 1'b1;\r\nalways #(1000000000000 / 2 / CLK_FREQ   ) clk   = ~clk;\r\ninitial begin repeat(4) @(posedge clk); rstn<=1'b1; end\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// signals\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\nwire        uart_from_dut;\r\nwire        uart_to_dut;\r\n\r\nwire        en_from_dut;\r\nwire [ 7:0] byte_from_dut;\r\n\r\nreg         en_to_dut   = 1'b0;\r\nreg  [ 7:0] byte_to_dut = 8'h0;\r\n\r\n\r\nalways @ (posedge clk)\r\n    if (en_from_dut)\r\n        $write(\"%c\", byte_from_dut);\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// generate data to DUT\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\ninitial begin\r\n    while  (~rstn) @(posedge clk);\r\n    repeat (10000) @(posedge clk);\r\n    \r\n    @(posedge clk) en_to_dut   <= 1'b1;\r\n                   byte_to_dut <= \"W\";\r\n    @(posedge clk) byte_to_dut <= \"1\";\r\n    @(posedge clk) byte_to_dut <= \"2\";\r\n    @(posedge clk) byte_to_dut <= \"F\";\r\n    @(posedge clk) byte_to_dut <= \" \";\r\n    @(posedge clk) byte_to_dut <= \"A\";\r\n    @(posedge clk) byte_to_dut <= \"B\";\r\n    @(posedge clk) byte_to_dut <= \"C\";\r\n    @(posedge clk) byte_to_dut <= \" \";\r\n    @(posedge clk) byte_to_dut <= \"3\";\r\n    @(posedge clk) byte_to_dut <= \"2\";\r\n    @(posedge clk) byte_to_dut <= \" \";\r\n    @(posedge clk) byte_to_dut <= \"9\";\r\n    @(posedge clk) byte_to_dut <= \"8\";\r\n    @(posedge clk) byte_to_dut <= \"7\";\r\n    @(posedge clk) byte_to_dut <= \"6\";\r\n    @(posedge clk) byte_to_dut <= \"\\n\";\r\n    \r\n    @(posedge clk) byte_to_dut <= \"R\";\r\n    @(posedge clk) byte_to_dut <= \"1\";\r\n    @(posedge clk) byte_to_dut <= \"2\";\r\n    @(posedge clk) byte_to_dut <= \"F\";\r\n    @(posedge clk) byte_to_dut <= \" \";\r\n    @(posedge clk) byte_to_dut <= \"4\";\r\n    @(posedge clk) byte_to_dut <= \"\\n\";\r\n    \r\n    @(posedge clk) byte_to_dut <= \"R\";\r\n    @(posedge clk) byte_to_dut <= \"1\";\r\n    @(posedge clk) byte_to_dut <= \"2\";\r\n    @(posedge clk) byte_to_dut <= \"0\";\r\n    @(posedge clk) byte_to_dut <= \"\\n\";\r\n    \r\n    @(posedge clk) en_to_dut   <= 1'b0;\r\n    \r\n    repeat (1000000) @(posedge clk);\r\n    $stop;\r\nend\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// for generate UART TX for uart2axi4, and receive UART RX for uart2axi4\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\nuart_tx #(\r\n    .CLK_FREQ                  ( CLK_FREQ             ),\r\n    .BAUD_RATE                 ( UART_BAUD_RATE       ),\r\n    .PARITY                    ( UART_PARITY          ),\r\n    .STOP_BITS                 ( 1                    ),\r\n    .BYTE_WIDTH                ( 1                    ),\r\n    .FIFO_EA                   ( 18                   ),\r\n    .EXTRA_BYTE_AFTER_TRANSFER ( \"\"                   ),\r\n    .EXTRA_BYTE_AFTER_PACKET   ( \"\"                   )\r\n) u_uart_tx (\r\n    .rstn                      ( rstn                 ),\r\n    .clk                       ( clk                  ),\r\n    .i_tready                  (                      ),\r\n    .i_tvalid                  ( en_to_dut            ),\r\n    .i_tdata                   ( byte_to_dut          ),\r\n    .i_tkeep                   ( 1'b1                 ),\r\n    .i_tlast                   ( 1'b0                 ),\r\n    .o_uart_tx                 ( uart_to_dut          )\r\n);\r\n\r\nuart_rx #(\r\n    .CLK_FREQ                  ( CLK_FREQ             ),\r\n    .BAUD_RATE                 ( UART_BAUD_RATE       ),\r\n    .PARITY                    ( UART_PARITY          ),\r\n    .FIFO_EA                   ( 0                    )\r\n) u_uart_rx (\r\n    .rstn                      ( rstn                 ),\r\n    .clk                       ( clk                  ),\r\n    .i_uart_rx                 ( uart_from_dut        ),\r\n    .o_tready                  ( 1'b1                 ),\r\n    .o_tvalid                  ( en_from_dut          ),\r\n    .o_tdata                   ( byte_from_dut        ),\r\n    .o_overflow                (                      )\r\n);\r\n\r\n\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\n// design under test (DUT)\r\n//-----------------------------------------------------------------------------------------------------------------------------\r\nuart2axi4 #(\r\n    .CLK_FREQ                  ( CLK_FREQ             ),\r\n    .BAUD_RATE                 ( UART_BAUD_RATE       ),\r\n    .PARITY                    ( UART_PARITY          ),\r\n    .BYTE_WIDTH                ( 4                    )\r\n) u_uart2axi4 (\r\n    .rstn                      ( rstn                 ),\r\n    .clk                       ( clk                  ),\r\n    // AXI4 master ----------------------\r\n    .awready                   ( 1'b1                 ),\r\n    .awvalid                   (                      ),\r\n    .awaddr                    (                      ),\r\n    .awlen                     (                      ),\r\n    .wready                    ( 1'b1                 ),\r\n    .wvalid                    (                      ),\r\n    .wlast                     (                      ),\r\n    .wdata                     (                      ),\r\n    .bready                    (                      ),\r\n    .bvalid                    ( 1'b1                 ),\r\n    .arready                   ( 1'b1                 ),\r\n    .arvalid                   (                      ),\r\n    .araddr                    (                      ),\r\n    .arlen                     (                      ),\r\n    .rready                    (                      ),\r\n    .rvalid                    ( 1'b1                 ),\r\n    .rlast                     ( 1'b0                 ),\r\n    .rdata                     ( 'h12345678           ),\r\n    // UART ----------------------\r\n    .i_uart_rx                 ( uart_to_dut          ),\r\n    .o_uart_tx                 ( uart_from_dut        )\r\n);\r\n\r\n\r\nendmodule\r\n"
  },
  {
    "path": "SIM/tb_uart2axi4_run_iverilog.bat",
    "content": "del sim.out dump.vcd\r\niverilog  -g2001  -o sim.out  tb_uart2axi4.v  ../RTL/uart2axi4.v  ../RTL/uart_tx.v  ../RTL/uart_rx.v\r\nvvp -n sim.out\r\ndel sim.out\r\npause"
  },
  {
    "path": "SIM/tb_uart_run_iverilog.bat",
    "content": "del sim.out dump.vcd\r\niverilog  -g2001  -o sim.out  tb_uart.v  tb_axis_inc_source.v  ../RTL/uart_tx.v  ../RTL/uart_rx.v\r\nvvp -n sim.out\r\ndel sim.out\r\npause"
  }
]