From 42bed23e571ed177b093a3f711c3ee3e01b68b11 Mon Sep 17 00:00:00 2001 From: Ewen McNeill Date: Thu, 17 Jan 2019 10:51:12 +1300 Subject: [PATCH 01/31] Update tinyprog to match tinyprog 1.0.23 tinyprog 1.0.23 was uploaded on 2018-09-22 to: https://pypi.org/project/tinyprog/#files https://files.pythonhosted.org/packages/98/d3/5b68b7123bf8b750543df9da2a5678b940ccb229502190194a95264d40b8/tinyprog-1.0.23-py2-none-any.whl but not uploaded to: https://github.com/tinyfpga/TinyFPGA-Bootloader/tree/master/programmer/tinyprog with several fixes for: https://discourse.tinyfpga.com/t/issues-with-tinyprog-u-on-bx/628 but only installable on Python 2.7 (see https://github.com/tinyfpga/TinyFPGA-Bootloader/issues/25) --- programmer/tinyprog/__init__.py | 64 ++++++++++++++++++++++++++++----- 1 file changed, 56 insertions(+), 8 deletions(-) diff --git a/programmer/tinyprog/__init__.py b/programmer/tinyprog/__init__.py index 104eed6..a369c7a 100644 --- a/programmer/tinyprog/__init__.py +++ b/programmer/tinyprog/__init__.py @@ -14,6 +14,12 @@ use_libusb = False use_pyserial = False +def pretty_hex(data): + output = "" + for i in range(0, len(data), 16): + output += " ".join(["%02x" % ord(x) for x in data[i:i+16]]) + "\n" + return output + def to_int(value): try: return ord(value) @@ -268,11 +274,11 @@ def program_security_register_page(self, page, data): def read_security_register_page(self, page): return self.cmd(self.security_page_read_cmd, addr=page << (8 + self.security_page_bit_offset), data=b'\x00', read_len=255) - def read(self, addr, length, disable_progress=True): + def read(self, addr, length, disable_progress=True, max_length = 255): data = b'' with tqdm(desc=" Reading", unit="B", unit_scale=True, total=length, disable=disable_progress) as pbar: while length > 0: - read_length = min(255, length) + read_length = min(max_length, length) data += self.cmd(0x0b, addr, b'\x00', read_len=read_length) self.progress(read_length) addr += read_length @@ -358,12 +364,12 @@ def _write(self, addr, data): self.wait_while_busy() self.progress(len(data)) - def write(self, addr, data, disable_progress=True): + def write(self, addr, data, disable_progress=True, max_length = 256): offset = 0 with tqdm(desc=" Writing", unit="B", unit_scale=True, total=len(data), disable=disable_progress) as pbar: while offset < len(data): dist_to_256_byte_boundary = 256 - (addr & 0xff) - write_length = min(256, len(data) - offset, dist_to_256_byte_boundary) + write_length = min(max_length, len(data) - offset, dist_to_256_byte_boundary) write_data = data[offset : offset+write_length] self._write(addr, write_data) @@ -371,7 +377,7 @@ def write(self, addr, data, disable_progress=True): addr += write_length pbar.update(write_length) - def program(self, addr, data): + def program_fast(self, addr, data): self.erase(addr, len(data), disable_progress=False) self.write(addr, data, disable_progress=False) read_back = self.read(addr, len(data), disable_progress=False) @@ -380,14 +386,49 @@ def program(self, addr, data): self.progress("Success!") return True else: - self.progress("Failure!") + read_back_file = open("readback.bin", "wb") + read_back_file.write(read_back) + read_back_file.close() + self.progress("FAILED!") return False + def program_sectors(self, addr, data): + sector_size = 4 * 1024 + + with tqdm(desc=" Programming and Verifying", unit="B", unit_scale=True, total=len(data)) as pbar: + for offset in range(0, len(data), sector_size): + current_addr = addr + offset + current_write_data = data[offset:offset + sector_size] + self.erase(current_addr, sector_size, disable_progress=True) + + minor_sector_size = 256 + for minor_offset in range(0, 4 * 1024, minor_sector_size): + minor_write_data = current_write_data[minor_offset:minor_offset+minor_sector_size] + self.write(current_addr + minor_offset, minor_write_data, disable_progress=True, max_length=256) + minor_read_data = self.read(current_addr + minor_offset, len(minor_write_data), disable_progress=True, max_length=255) + + pbar.update(len(minor_write_data)) + + if minor_read_data != minor_write_data: + print("") + print("Offset: %d" % (current_addr + minor_offset)) + print("Readback Data:") + print(pretty_hex(minor_read_data)) + print("Write Data:") + print(pretty_hex(minor_write_data)) + self.progress("FAILED!") + return False + + + self.progress("Success!") + return True + + def boot(self): try: self.ser.write(b"\x00") self.ser.flush() - except SerialTimeoutException as e: + except: # we might get a writeTimeoutError and that's OK. Sometimes the # bootloader will reboot before it finishes sending out the USB ACK # for the boot command data packet. @@ -416,4 +457,11 @@ def program_bitstream(self, addr, bitstream): self.progress("Waking up SPI flash") self.wake() self.progress(str(len(bitstream)) + " bytes to program") - return self.program(addr, bitstream) + return self.program_sectors(addr, bitstream) + + + def program_bitstream_fast(self, addr, bitstream): + self.progress("Waking up SPI flash") + self.wake() + self.progress(str(len(bitstream)) + " bytes to program") + return self.program_fast(addr, bitstream) From a62544836d0c064746a1d69385b16f57d283c1ac Mon Sep 17 00:00:00 2001 From: Ewen McNeill Date: Thu, 17 Jan 2019 10:57:41 +1300 Subject: [PATCH 02/31] tinyprog: Bump version to 1.0.23 Bump version to match code re-imported from Python 2 wheel at: https://pypi.org/project/tinyprog/#files https://files.pythonhosted.org/packages/98/d3/5b68b7123bf8b750543df9da2a5678b940ccb229502190194a95264d40b8/tinyprog-1.0.23-py2-none-any.whl --- programmer/setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programmer/setup.py b/programmer/setup.py index 39f15f5..db81148 100644 --- a/programmer/setup.py +++ b/programmer/setup.py @@ -11,7 +11,7 @@ 'packaging', 'pyusb' ], - version = '1.0.22b1', + version = '1.0.23', description = 'Programmer for FPGA boards using the TinyFPGA USB Bootloader (http://tinyfpga.com)', author = 'Luke Valenty', author_email = 'luke@tinyfpga.com', From 87be847bc74ce44b02a63d64150b686de9e6bedf Mon Sep 17 00:00:00 2001 From: Tim 'mithro' Ansell Date: Thu, 17 Jan 2019 15:32:13 +1300 Subject: [PATCH 03/31] tinyprog: Upgrade packaging to latest standards. * Add README.md to the rendering. * Add MANIFEST.ini * Add tox.ini for testing in Python versions. --- programmer/LICENSE | 674 +++++++++++++++++++++++++++++++++++++++++ programmer/MANIFEST.in | 8 + programmer/setup.cfg | 4 + programmer/setup.py | 20 +- programmer/tox.ini | 23 ++ 5 files changed, 727 insertions(+), 2 deletions(-) create mode 100644 programmer/LICENSE create mode 100644 programmer/MANIFEST.in create mode 100644 programmer/tox.ini diff --git a/programmer/LICENSE b/programmer/LICENSE new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/programmer/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/programmer/MANIFEST.in b/programmer/MANIFEST.in new file mode 100644 index 0000000..f077c9a --- /dev/null +++ b/programmer/MANIFEST.in @@ -0,0 +1,8 @@ +# Include the README +include *.md + +# Include the license file +include LICENSE + +include *.toml +include .coveragerc diff --git a/programmer/setup.cfg b/programmer/setup.cfg index b88034e..e701345 100644 --- a/programmer/setup.cfg +++ b/programmer/setup.cfg @@ -1,2 +1,6 @@ [metadata] description-file = README.md +license_files = LICENSE + +[bdist_wheel] +universal=1 diff --git a/programmer/setup.py b/programmer/setup.py index db81148..db3524f 100644 --- a/programmer/setup.py +++ b/programmer/setup.py @@ -1,4 +1,8 @@ from setuptools import setup, find_packages + +with open("README.md", "r") as fh: + long_description = fh.read() + setup( name = 'tinyprog', packages = find_packages(), @@ -13,17 +17,29 @@ ], version = '1.0.23', description = 'Programmer for FPGA boards using the TinyFPGA USB Bootloader (http://tinyfpga.com)', + long_description=long_description, + long_description_content_type="text/markdown", author = 'Luke Valenty', author_email = 'luke@tinyfpga.com', url = 'https://github.com/tinyfpga/TinyFPGA-Bootloader/', - keywords = ['fpga', 'tinyfpga', 'programmer'], + project_urls={ + 'Documentation': 'https://packaging.python.org/tutorials/distributing-packages/', + 'Source': 'https://github.com/tinyfpga/TinyFPGA-Bootloader/tree/master/programmer', + 'Tracker': 'https://github.com/tinyfpga/TinyFPGA-Bootloader/issues', + }, + license='GPLv3+', + keywords = ['fpga', 'tinyfpga', 'programmer', 'lattice', 'ice40'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', - 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', + 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3' + 'Programming Language :: Python :: 3.5' + 'Programming Language :: Python :: 3.6' + 'Programming Language :: Python :: 3.7' ], entry_points = { 'console_scripts': [ diff --git a/programmer/tox.ini b/programmer/tox.ini new file mode 100644 index 0000000..84e426a --- /dev/null +++ b/programmer/tox.ini @@ -0,0 +1,23 @@ +[tox] +envlist = py{27,34,35,36,37} + +[testenv] +basepython = + py27: python2.7 + py34: python3.4 + py35: python3.5 + py36: python3.6 + py37: python3.7 +deps = + check-manifest + flake8 + pytest +commands = + check-manifest --ignore tox.ini,tests* + python setup.py check -m -s + flake8 . + py.test tests + +[flake8] +exclude = .tox,*.egg,build,data +select = E,W,F From f79629e8946b5828992890d39bda45afe2edc587 Mon Sep 17 00:00:00 2001 From: Tim 'mithro' Ansell Date: Thu, 17 Jan 2019 15:52:05 +1300 Subject: [PATCH 04/31] tinyprog: Using setuptools_scm to generate version number. --- programmer/pyproject.toml | 3 +++ programmer/setup.py | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 programmer/pyproject.toml diff --git a/programmer/pyproject.toml b/programmer/pyproject.toml new file mode 100644 index 0000000..73989aa --- /dev/null +++ b/programmer/pyproject.toml @@ -0,0 +1,3 @@ +# pyproject.toml +[build-system] +requires = ["setuptools>=30.3.0", "wheel", "setuptools_scm"] diff --git a/programmer/setup.py b/programmer/setup.py index db3524f..55d40b8 100644 --- a/programmer/setup.py +++ b/programmer/setup.py @@ -15,7 +15,8 @@ 'packaging', 'pyusb' ], - version = '1.0.23', + use_scm_version={"root": "..", "relative_to": __file__, 'git_describe_command': r'git describe --dirty --tags --long --match tinyprog-*.*'}, + setup_requires=['setuptools_scm'], description = 'Programmer for FPGA boards using the TinyFPGA USB Bootloader (http://tinyfpga.com)', long_description=long_description, long_description_content_type="text/markdown", From 137ca2963c830c35e0e69cbeb376163f755ebff0 Mon Sep 17 00:00:00 2001 From: Tim 'mithro' Ansell Date: Thu, 17 Jan 2019 15:59:18 +1300 Subject: [PATCH 05/31] tinyprog: Improving gitignore. --- programmer/.gitignore | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/programmer/.gitignore b/programmer/.gitignore index 559442b..c3fb741 100644 --- a/programmer/.gitignore +++ b/programmer/.gitignore @@ -1,10 +1,15 @@ -.cache -.coverage +# general things to ignore +htmlcov/ +build/ +dist/ +*egg* +*.py[cod] +__pycache__/ +*.so +*~ + +# due to using tox and pytest .tox +.coverage .pytest_cache -*.pyc -__pycache__ -htmlcov -build -dist -*.egg-info +.cache From 1d9e8cb0064a2752d5ef3b8c5ba322d7611b56f5 Mon Sep 17 00:00:00 2001 From: Tim 'mithro' Ansell Date: Thu, 17 Jan 2019 16:17:33 +1300 Subject: [PATCH 06/31] tinyprog: Convert README.md into UTF-8 --- programmer/README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/programmer/README.md b/programmer/README.md index 54d0b2c..1e040c1 100644 --- a/programmer/README.md +++ b/programmer/README.md @@ -63,9 +63,9 @@ tinyprog --com COM14 --program "..\boards\TinyFPGA_BX\fw.bin" Programming at addr 028000 Waking up SPI flash 298940 bytes to program - Erasing: 100%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 299k/299k [00:01<00:00, 223kB/s] - Writing: 100%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 299k/299k [00:01<00:00, 235kB/s] - Reading: 100%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 299k/299k [00:00<00:00, 490kB/s] + Erasing: 100%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 299k/299k [00:01<00:00, 223kB/s] + Writing: 100%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 299k/299k [00:01<00:00, 235kB/s] + Reading: 100%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 299k/299k [00:00<00:00, 490kB/s] Success! ``` @@ -82,9 +82,9 @@ tinyprog --id e5 --program "..\boards\TinyFPGA_BX\fw.bin" Programming at addr 028000 Waking up SPI flash 298940 bytes to program - Erasing: 100%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 299k/299k [00:01<00:00, 223kB/s] - Writing: 100%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 299k/299k [00:01<00:00, 235kB/s] - Reading: 100%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 299k/299k [00:00<00:00, 490kB/s] + Erasing: 100%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 299k/299k [00:01<00:00, 223kB/s] + Writing: 100%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 299k/299k [00:01<00:00, 235kB/s] + Reading: 100%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 299k/299k [00:00<00:00, 490kB/s] Success! ``` From 7d17e7485f2c7332c05ba28d9527a901b5f72109 Mon Sep 17 00:00:00 2001 From: Tim 'mithro' Ansell Date: Thu, 17 Jan 2019 16:18:52 +1300 Subject: [PATCH 07/31] tinyprog: Decode README as utf-8 --- programmer/setup.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/programmer/setup.py b/programmer/setup.py index 55d40b8..6965253 100644 --- a/programmer/setup.py +++ b/programmer/setup.py @@ -1,7 +1,7 @@ from setuptools import setup, find_packages -with open("README.md", "r") as fh: - long_description = fh.read() +with open("README.md", "rb") as fh: + long_description = fh.read().decode('utf-8') setup( name = 'tinyprog', From ab2ee95a03261b179314cab525d922af0fd402a2 Mon Sep 17 00:00:00 2001 From: Tim 'mithro' Ansell Date: Thu, 17 Jan 2019 15:34:18 +1300 Subject: [PATCH 08/31] travis: Adding testing of tinyprog. --- .travis.yml | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..d672bd1 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,22 @@ +language: python + +matrix: + include: + - python: 2.7 + env: TOXENV=py27 + - python: 3.4 + env: TOXENV=py34 + - python: 3.5 + env: TOXENV=py35 + - python: 3.6 + env: TOXENV=py36 + +install: + - cd programmer + - pip install tox + +script: + - tox + +notifications: + email: false From 89ffa31caf41129f2ac93ff349666ef9ad1e82f1 Mon Sep 17 00:00:00 2001 From: Tim 'mithro' Ansell Date: Thu, 17 Jan 2019 16:18:21 +1300 Subject: [PATCH 09/31] travis: Make sure to use the latest version of tox. --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d672bd1..ca623fb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,7 +13,7 @@ matrix: install: - cd programmer - - pip install tox + - pip install --upgrade tox script: - tox From 652a7b7714020fc3c077ac5ddfe05709830bcb5b Mon Sep 17 00:00:00 2001 From: Tim 'mithro' Ansell Date: Thu, 17 Jan 2019 16:22:46 +1300 Subject: [PATCH 10/31] tinyprog: Fix .coveragerc --- programmer/.coveragerc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programmer/.coveragerc b/programmer/.coveragerc index 80b4b74..8884d0e 100644 --- a/programmer/.coveragerc +++ b/programmer/.coveragerc @@ -1,6 +1,6 @@ [paths] source = - tinyfpgab/ + tinyprog/ [run] branch = True From 1eef8f7e45828d6387e19b9e23ed5cc26aee8c60 Mon Sep 17 00:00:00 2001 From: Tim 'mithro' Ansell Date: Thu, 17 Jan 2019 16:59:08 +1300 Subject: [PATCH 11/31] tinyprog: Make output flake8 clean. --- programmer/setup.py | 51 +++---- programmer/tinyprog/__init__.py | 158 ++++++++++++---------- programmer/tinyprog/__main__.py | 205 ++++++++++++++++++----------- programmer/tinyprog/data_tables.py | 18 +++ programmer/tox.ini | 7 +- 5 files changed, 265 insertions(+), 174 deletions(-) create mode 100644 programmer/tinyprog/data_tables.py diff --git a/programmer/setup.py b/programmer/setup.py index 6965253..f5ed4a0 100644 --- a/programmer/setup.py +++ b/programmer/setup.py @@ -4,36 +4,41 @@ long_description = fh.read().decode('utf-8') setup( - name = 'tinyprog', - packages = find_packages(), + name='tinyprog', + packages=find_packages(), install_requires=[ - 'pyserial>=3,<4', - 'jsonmerge>=1.4.0,<2', - 'intelhex>=2.2.1,<3', - 'tqdm>=4.19.5,<5', - 'six', - 'packaging', - 'pyusb' + 'pyserial>=3,<4', 'jsonmerge>=1.4.0,<2', 'intelhex>=2.2.1,<3', + 'tqdm>=4.19.5,<5', 'six', 'packaging', 'pyusb' ], - use_scm_version={"root": "..", "relative_to": __file__, 'git_describe_command': r'git describe --dirty --tags --long --match tinyprog-*.*'}, + use_scm_version={ + "root": "..", + "relative_to": __file__, + 'git_describe_command': + r'git describe --dirty --tags --long --match tinyprog-*.*', + }, setup_requires=['setuptools_scm'], - description = 'Programmer for FPGA boards using the TinyFPGA USB Bootloader (http://tinyfpga.com)', + description="""\ +Programmer for FPGA boards using the TinyFPGA USB Bootloader +(http://tinyfpga.com). +""", long_description=long_description, long_description_content_type="text/markdown", - author = 'Luke Valenty', - author_email = 'luke@tinyfpga.com', - url = 'https://github.com/tinyfpga/TinyFPGA-Bootloader/', + author='Luke Valenty', + author_email='luke@tinyfpga.com', + url='https://github.com/tinyfpga/TinyFPGA-Bootloader/', project_urls={ - 'Documentation': 'https://packaging.python.org/tutorials/distributing-packages/', - 'Source': 'https://github.com/tinyfpga/TinyFPGA-Bootloader/tree/master/programmer', - 'Tracker': 'https://github.com/tinyfpga/TinyFPGA-Bootloader/issues', + 'Documentation': + 'https://packaging.python.org/tutorials/distributing-packages/', + 'Source': + 'https://github.com/tinyfpga/TinyFPGA-Bootloader/tree/master/programmer', # noqa + 'Tracker': + 'https://github.com/tinyfpga/TinyFPGA-Bootloader/issues', }, license='GPLv3+', - keywords = ['fpga', 'tinyfpga', 'programmer', 'lattice', 'ice40'], + keywords=['fpga', 'tinyfpga', 'programmer', 'lattice', 'ice40'], classifiers=[ 'Development Status :: 5 - Production/Stable', - 'Environment :: Console', - 'Intended Audience :: Developers', + 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', @@ -42,9 +47,5 @@ 'Programming Language :: Python :: 3.6' 'Programming Language :: Python :: 3.7' ], - entry_points = { - 'console_scripts': [ - 'tinyprog = tinyprog.__main__:main' - ] - }, + entry_points={'console_scripts': ['tinyprog = tinyprog.__main__:main']}, ) diff --git a/programmer/tinyprog/__init__.py b/programmer/tinyprog/__init__.py index a369c7a..94bd07d 100644 --- a/programmer/tinyprog/__init__.py +++ b/programmer/tinyprog/__init__.py @@ -1,31 +1,36 @@ -import struct import json -import jsonmerge +import platform import re -from intelhex import IntelHex -from tqdm import tqdm +import struct + from functools import reduce -import six -from serial.serialutil import SerialTimeoutException -from serial.tools.list_ports import comports + +import jsonmerge import serial -import platform +from intelhex import IntelHex +from serial.tools.list_ports import comports +from tqdm import tqdm + +from .data_tables import bit_reverse_table use_libusb = False use_pyserial = False + def pretty_hex(data): output = "" for i in range(0, len(data), 16): - output += " ".join(["%02x" % ord(x) for x in data[i:i+16]]) + "\n" + output += " ".join(["%02x" % ord(x) for x in data[i:i + 16]]) + "\n" return output + def to_int(value): try: return ord(value) - except: + except ValueError: return int(value) + def get_ports(device_id): """ Return ports for all devices with the given device_id. @@ -49,7 +54,9 @@ def get_ports(device_id): # MacOS is not playing nicely with the serial drivers for the bootloader if platform.system() != "Darwin" or use_pyserial: # get serial ports first - ports += [SerialPort(p[0]) for p in comports() if device_id in p[2].lower()] + ports += [ + SerialPort(p[0]) for p in comports() if device_id in p[2].lower() + ] return ports @@ -63,7 +70,8 @@ def __str__(self): return self.port_name def __enter__(self): - self.ser = serial.Serial(self.port_name, timeout=1.0, writeTimeout=1.0).__enter__() + self.ser = serial.Serial( + self.port_name, timeout=1.0, writeTimeout=1.0).__enter__() def __exit__(self, exc_type, exc_val, exc_tb): self.ser.__exit__(exc_type, exc_val, exc_tb) @@ -109,26 +117,6 @@ def read(self, length): return "" -bit_reverse_table = bytearray([ - 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, - 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, - 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, - 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, - 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, - 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA, - 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, - 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, - 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1, - 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, - 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, - 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD, - 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, - 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, - 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, - 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF -]) - - def _mirror_byte(b): return bit_reverse_table[to_int(b)] @@ -149,7 +137,7 @@ def __init__(self, prog): def _parse_json(self, data): try: return json.loads(bytes(data).decode("utf-8")) - except: + except Exception: return None def _resolve_pointers(self, meta): @@ -160,9 +148,12 @@ def _resolve_pointers(self, meta): return [self._resolve_pointers(v) for v in meta] if isinstance(meta, (str, bytes)): - m = re.search(r"^\s*@\s*0x(?P[A-Fa-f0-9]+)\s*\+\s*(?P\d+)\s*$", meta) + m = re.search( + r"^\s*@\s*0x(?P[A-Fa-f0-9]+)\s*\+\s*(?P\d+)\s*$", + meta) if m: - data = self.prog.read(int(m.group("addr"), 16), int(m.group("len"))) + data = self.prog.read( + int(m.group("addr"), 16), int(m.group("len"))) return json.loads(bytes(data).decode("utf-8")) else: return meta @@ -172,9 +163,18 @@ def _resolve_pointers(self, meta): def _read_metadata(self): import math meta_roots = ( - [self._parse_json(self.prog.read_security_register_page(p).replace(b"\x00", b"").replace(b"\xff", b"")) for p in [1, 2, 3]] + - [self._parse_json(self.prog.read(int(math.pow(2, p) - (4 * 1024)), (4 * 1024)).replace(b"\x00", b"").replace(b"\xff", b"")) for p in [17, 18, 19, 20, 21, 22, 23, 24]] - ) + [ + self._parse_json( + self.prog.read_security_register_page(p).replace( + b"\x00", b"").replace(b"\xff", b"")) + for p in [1, 2, 3] + ] + [ + self._parse_json( + self.prog.read( + int(math.pow(2, p) - (4 * 1024)), (4 * 1024)).replace( + b"\x00", b"").replace(b"\xff", b"")) + for p in [17, 18, 19, 20, 21, 22, 23, 24] + ]) meta_roots = [root for root in meta_roots if root is not None] if len(meta_roots) > 0: meta = reduce(jsonmerge.merge, meta_roots) @@ -192,7 +192,9 @@ def userdata_addr_range(self): def _get_addr_range(self, name): addr_str = self.root[u"bootmeta"][u"addrmap"][name] - m = re.search(r"^\s*0x(?P[A-Fa-f0-9]+)\s*-\s*0x(?P[A-Fa-f0-9]+)\s*$", addr_str) + m = re.search( + r"^\s*0x(?P[A-Fa-f0-9]+)\s*-\s*0x(?P[A-Fa-f0-9]+)\s*$", + addr_str) if m: return int(m.group("start"), 16), int(m.group("end"), 16) else: @@ -202,7 +204,6 @@ def uuid(self): return str(self.root[u"boardmeta"][u"uuid"]) - class TinyProg(object): def __init__(self, ser, progress=None): self.ser = ser @@ -222,7 +223,7 @@ def __init__(self, ser, progress=None): self.security_page_write_cmd = 0x62 self.security_page_read_cmd = 0x68 self.security_page_erase_cmd = 0x64 - + else: # Adesto self.security_page_bit_offset = 0 @@ -240,11 +241,10 @@ def is_bootloader_active(self): return False def cmd(self, opcode, addr=None, data=b'', read_len=0): - #print("type of data is %s" % type(data)) - #assert isinstance(data, bytes) addr = b'' if addr is None else struct.pack('>I', addr)[1:] write_string = bytearray([opcode]) + addr + data - cmd_write_string = b'\x01' + struct.pack(' 0: read_length = min(max_length, length) data += self.cmd(0x0b, addr, b'\x00', read_len=read_length) @@ -298,7 +307,7 @@ def wait_while_busy(self): def _erase(self, addr, length): opcode = { - 4 * 1024: 0x20, + 4 * 1024: 0x20, 32 * 1024: 0x52, 64 * 1024: 0xd8, }[length] @@ -309,10 +318,12 @@ def _erase(self, addr, length): def erase(self, addr, length, disable_progress=True): possible_lengths = (1, 4 * 1024, 32 * 1024, 64 * 1024) - with tqdm(desc=" Erasing", unit="B", unit_scale=True, total=length, disable=disable_progress) as pbar: + with tqdm(desc=" Erasing", unit="B", unit_scale=True, total=length, + disable=disable_progress) as pbar: while length > 0: - erase_length = max(p for p in possible_lengths - if p <= length and addr % p == 0) + erase_length = max( + p for p in possible_lengths + if p <= length and addr % p == 0) if erase_length == 1: # there are no opcode to erase that much @@ -364,14 +375,17 @@ def _write(self, addr, data): self.wait_while_busy() self.progress(len(data)) - def write(self, addr, data, disable_progress=True, max_length = 256): + def write(self, addr, data, disable_progress=True, max_length=256): offset = 0 - with tqdm(desc=" Writing", unit="B", unit_scale=True, total=len(data), disable=disable_progress) as pbar: + with tqdm(desc=" Writing", unit="B", unit_scale=True, + total=len(data), disable=disable_progress) as pbar: while offset < len(data): dist_to_256_byte_boundary = 256 - (addr & 0xff) - write_length = min(max_length, len(data) - offset, dist_to_256_byte_boundary) - write_data = data[offset : offset+write_length] - + write_length = min( + max_length, + len(data) - offset, dist_to_256_byte_boundary) + write_data = data[offset:offset + write_length] + self._write(addr, write_data) offset += write_length addr += write_length @@ -395,7 +409,8 @@ def program_fast(self, addr, data): def program_sectors(self, addr, data): sector_size = 4 * 1024 - with tqdm(desc=" Programming and Verifying", unit="B", unit_scale=True, total=len(data)) as pbar: + with tqdm(desc=" Programming and Verifying", unit="B", + unit_scale=True, total=len(data)) as pbar: for offset in range(0, len(data), sector_size): current_addr = addr + offset current_write_data = data[offset:offset + sector_size] @@ -403,10 +418,19 @@ def program_sectors(self, addr, data): minor_sector_size = 256 for minor_offset in range(0, 4 * 1024, minor_sector_size): - minor_write_data = current_write_data[minor_offset:minor_offset+minor_sector_size] - self.write(current_addr + minor_offset, minor_write_data, disable_progress=True, max_length=256) - minor_read_data = self.read(current_addr + minor_offset, len(minor_write_data), disable_progress=True, max_length=255) - + minor_write_data = current_write_data[ + minor_offset:minor_offset + minor_sector_size] + self.write( + current_addr + minor_offset, + minor_write_data, + disable_progress=True, + max_length=256) + minor_read_data = self.read( + current_addr + minor_offset, + len(minor_write_data), + disable_progress=True, + max_length=255) + pbar.update(len(minor_write_data)) if minor_read_data != minor_write_data: @@ -419,16 +443,14 @@ def program_sectors(self, addr, data): self.progress("FAILED!") return False - self.progress("Success!") return True - def boot(self): try: self.ser.write(b"\x00") self.ser.flush() - except: + except Exception: # we might get a writeTimeoutError and that's OK. Sometimes the # bootloader will reboot before it finishes sending out the USB ACK # for the boot command data packet. @@ -441,7 +463,8 @@ def slurp(self, filename): elif filename.endswith('.hex'): with open(filename, 'rb') as f: - return bytes("".join(chr(int(i, 16)) for i in f.read().split())) + return bytes( + "".join(chr(int(i, 16)) for i in f.read().split())) elif filename.endswith('.mcs'): ih = IntelHex() @@ -459,7 +482,6 @@ def program_bitstream(self, addr, bitstream): self.progress(str(len(bitstream)) + " bytes to program") return self.program_sectors(addr, bitstream) - def program_bitstream_fast(self, addr, bitstream): self.progress("Waking up SPI flash") self.wake() diff --git a/programmer/tinyprog/__main__.py b/programmer/tinyprog/__main__.py index 4988554..7981b5b 100644 --- a/programmer/tinyprog/__main__.py +++ b/programmer/tinyprog/__main__.py @@ -1,13 +1,16 @@ -from tinyprog import TinyProg, get_ports -import tinyprog -from six.moves.urllib.request import urlopen -from six.moves import input import sys import argparse import json -from packaging import version import time +from six.moves.urllib.request import urlopen +from six.moves import input + +import tinyprog + +from tinyprog import TinyProg, get_ports + + # adapted from http://code.activestate.com/recipes/577058/ def query_user(question, default="no"): """Ask a yes/no question via raw_input() and return their answer. @@ -20,8 +23,7 @@ def query_user(question, default="no"): The "answer" return value is True for "yes" or False for "no". """ - valid = {"yes": True, "y": True, "ye": True, - "no": False, "n": False} + valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "yes": @@ -39,8 +41,9 @@ def query_user(question, default="no"): elif choice in valid: return valid[choice] else: - sys.stdout.write("Please respond with 'yes' or 'no' " - "(or 'y' or 'n').\n") + sys.stdout.write( + "Please respond with 'yes' or 'no' " + "(or 'y' or 'n').\n") def strict_query_user(question): @@ -63,16 +66,12 @@ def get_port_by_uuid(device, uuid): if p.meta.uuid().startswith(uuid): return port - except: + except Exception: pass return None def check_for_new_bootloader(): - #ports = [p[0] for p in comports() if "1d50:6130" in p[2].lower()] - - # download bootloader update information - #bootloader_update_info = urlopen(m[u"bootmeta"][u"update"] + "/bootloader.json").read() return [] @@ -99,16 +98,19 @@ def check_if_overwrite_bootloader(addr, length, userdata_range): uend = userdata_range[1] if addr < ustart or addr + length >= uend: - print("") - print(" !!! WARNING !!!") - print("") - print(" The address given may overwrite the USB bootloader. Without the") - print(" USB bootloader the board will no longer be able to be programmed") - print(" over the USB interface. Without the USB bootloader, the board can") - print(" only be programmed via the SPI flash interface on the bottom of") - print(" the board") - print("") - retval = strict_query_user(" Are you sure you want to continue? Type in 'yes' to overwrite bootloader.") + print("""\ + + !!! WARNING !!! + + The address given may overwrite the USB bootloader. Without the + USB bootloader the board will no longer be able to be programmed + over the USB interface. Without the USB bootloader, the board can + only be programmed via the SPI flash interface on the bottom of + the board +""") + retval = strict_query_user( + " Are you sure you want to continue?" + "Type in 'yes' to overwrite bootloader.") print("") return retval @@ -125,7 +127,8 @@ def perform_bootloader_update(port): uuid = m[u"boardmeta"][u"uuid"] # download bootloader update information - bootloader_update_info = json.loads(urlopen(m[u"bootmeta"][u"update"] + "/bootloader.json").read()) + bootloader_update_info = json.loads( + urlopen(m[u"bootmeta"][u"update"] + "/bootloader.json").read()) # ask permission to update the board print("") @@ -137,13 +140,14 @@ def perform_bootloader_update(port): print(" is available for this board:") print_board(port, m) print("") - + if query_user(" Would you like to perform the update?"): #################### - # STAGE ONE + # STAGE ONE #################### print(" Fetching stage one...") - bitstream = urlopen(bootloader_update_info[u"stage_one_url"]).read() + bitstream = urlopen( + bootloader_update_info[u"stage_one_url"]).read() print(" Programming stage one...") userimage_addr = p.meta.userimage_addr_range()[0] @@ -170,12 +174,12 @@ def perform_bootloader_update(port): if new_port is not None: print("connected!") break - + with new_port: p = TinyProg(new_port) #################### - # STAGE TWO + # STAGE TWO #################### print(" Fetching stage two...") bitstream = urlopen(bootloader_update_info[u"stage_two_url"]).read() @@ -193,7 +197,9 @@ def perform_bootloader_update(port): def print_board(port, m): if isinstance(m, dict) and u"boardmeta" in m: print("") - print(" %s: %s %s" % (port, m[u"boardmeta"][u"name"], m[u"boardmeta"][u"hver"])) + print( + " %s: %s %s" % + (port, m[u"boardmeta"][u"name"], m[u"boardmeta"][u"hver"])) print(" UUID: %s" % m[u"boardmeta"][u"uuid"]) print(" FPGA: %s" % m[u"boardmeta"][u"fpga"]) else: @@ -211,31 +217,63 @@ def parse_int(str_value): parser = argparse.ArgumentParser() - parser.add_argument("-l", "--list", action="store_true", - help="list connected and active FPGA boards") - parser.add_argument("-p", "--program", type=str, - help="program FPGA board with the given user bitstream") - parser.add_argument("-u", "--program-userdata", type=str, - help="program FPGA board with the given user data") - parser.add_argument("--program-image", type=str, - help="program FPGA board with a combined user bitstream and data") - parser.add_argument("-b", "--boot", action="store_true", - help="command the FPGA board to exit the " - "bootloader and load the user configuration") + parser.add_argument( + "-l", + "--list", + action="store_true", + help="list connected and active FPGA boards") + parser.add_argument( + "-p", + "--program", + type=str, + help="program FPGA board with the given user bitstream") + parser.add_argument( + "-u", + "--program-userdata", + type=str, + help="program FPGA board with the given user data") + parser.add_argument( + "--program-image", + type=str, + help="program FPGA board with a combined user bitstream and data") + parser.add_argument( + "-b", + "--boot", + action="store_true", + help="command the FPGA board to exit the " + "bootloader and load the user configuration") parser.add_argument("-c", "--com", type=str, help="serial port name") parser.add_argument("-i", "--id", type=str, help="FPGA board ID") - parser.add_argument("-d", "--device", type=str, default="1d50:6130", - help="device id (vendor:product); default is (1d50:6130)") - parser.add_argument("-a", "--addr", type=str, - help="force the address to write the bitstream to") - parser.add_argument("-m", "--meta", action="store_true", - help="dump out the metadata for all connected boards in JSON") - parser.add_argument("--update-bootloader", action="store_true", - help="check for new bootloader and update eligible connected boards") - parser.add_argument("--libusb", action="store_true", - help="try using libusb to connect to boards without a serial driver attached") - parser.add_argument("--pyserial", action="store_true", - help="use pyserial to connect to boards") + parser.add_argument( + "-d", + "--device", + type=str, + default="1d50:6130", + help="device id (vendor:product); default is (1d50:6130)") + parser.add_argument( + "-a", + "--addr", + type=str, + help="force the address to write the bitstream to") + parser.add_argument( + "-m", + "--meta", + action="store_true", + help="dump out the metadata for all connected boards in JSON") + parser.add_argument( + "--update-bootloader", + action="store_true", + help="check for new bootloader and update eligible connected boards") + parser.add_argument( + "--libusb", + action="store_true", + help="""\ +try using libusb to connect to boards without a serial driver attached""" + ) + parser.add_argument( + "--pyserial", + action="store_true", + help="use pyserial to connect to boards") args = parser.parse_args() @@ -264,9 +302,8 @@ def parse_int(str_value): print("") print(" TinyProg CLI") print(" ------------") - - print(" Using device id {}".format(device)) + print(" Using device id {}".format(device)) # find port to use active_port = None @@ -277,19 +314,24 @@ def parse_int(str_value): active_port = get_port_by_uuid(device, args.id) elif not active_boards: - print(" No port was specified and no active bootloaders found.") - print(" Activate bootloader by pressing the reset button.") + print("""\ + No port was specified and no active bootloaders found. + Activate bootloader by pressing the reset button. +""") sys.exit(1) elif len(active_boards) == 1: - print(" Only one board with active bootloader, using it.") + print("""\ + Only one board with active bootloader, using it. +""") active_port = active_boards[0] else: - print(" Please choose a board with the -c or -i option. Using first board in list.") + print("""\ + Please choose a board with the -c or -i option. Using first board in list. +""") active_port = active_boards[0] - # list boards if args.list or active_port is None: print(" Boards with active bootloaders:") @@ -300,24 +342,26 @@ def parse_int(str_value): print_board(port, m) if len(active_boards) == 0: - print(" No active bootloaders found. Check USB connections") - print(" and press reset button to activate bootloader.") + print("""\ + No active bootloaders found. Check USB connections + and press reset button to activate bootloader.""") if args.update_bootloader: boards_needing_update = ( - check_for_wrong_tinyfpga_bx_vidpid() + - check_for_new_bootloader() - ) + check_for_wrong_tinyfpga_bx_vidpid() + check_for_new_bootloader()) if len(boards_needing_update) == 0: - print(" All connected and active boards are up to date!") + print("""\ + All connected and active boards are up to date!""") else: for port in boards_needing_update: perform_bootloader_update(port) # program the flash memory - if (args.program is not None) or (args.program_userdata is not None) or (args.program_image is not None): + if (args.program is not None) or (args.program_userdata is not None) or ( + args.program_image is not None): boot_fpga = False + def progress(info): if isinstance(info, str): print(" " + str(info)) @@ -326,10 +370,11 @@ def progress(info): fpga = TinyProg(active_port, progress) if args.program is not None: - print(" Programming " + str(active_port) + " with " + str(args.program)) + print(" Programming %s with %s".format( + active_port, args.program)) bitstream = fpga.slurp(args.program) - + if args.addr is not None: addr = parse_int(args.addr) else: @@ -342,16 +387,18 @@ def progress(info): print(" Bootloader not active") sys.exit(1) - if check_if_overwrite_bootloader(addr, len(bitstream), fpga.meta.userimage_addr_range()): + if check_if_overwrite_bootloader( + addr, len(bitstream), + fpga.meta.userimage_addr_range()): boot_fpga = True print(" Programming at addr {:06x}".format(addr)) if not fpga.program_bitstream(addr, bitstream): sys.exit(1) - # program user flash area if args.program_userdata is not None: - print(" Programming " + str(active_port) + " with " + str(args.program_userdata)) + print(" Programming %s with %s".format( + active_port, args.program_userdata)) bitstream = fpga.slurp(args.program_userdata) @@ -367,16 +414,17 @@ def progress(info): print(" Bootloader not active") sys.exit(1) - if check_if_overwrite_bootloader(addr, len(bitstream), fpga.meta.userdata_addr_range()): + if check_if_overwrite_bootloader( + addr, len(bitstream), fpga.meta.userdata_addr_range()): boot_fpga = True print(" Programming at addr {:06x}".format(addr)) if not fpga.program_bitstream(addr, bitstream): sys.exit(1) - # program user image and data area if args.program_image is not None: - print(" Programming " + str(active_port) + " with " + str(args.program_image)) + print(" Programming %s with %s".format( + active_port, args.program_image)) bitstream = fpga.slurp(args.program_image) @@ -392,7 +440,10 @@ def progress(info): print(" Bootloader not active") sys.exit(1) - if check_if_overwrite_bootloader(addr, len(bitstream), (fpga.meta.userimage_addr_range()[0], fpga.meta.userdata_addr_range()[1])): + if check_if_overwrite_bootloader( + addr, len(bitstream), + (fpga.meta.userimage_addr_range()[0], + fpga.meta.userdata_addr_range()[1])): boot_fpga = True print(" Programming at addr {:06x}".format(addr)) if not fpga.program_bitstream(addr, bitstream): diff --git a/programmer/tinyprog/data_tables.py b/programmer/tinyprog/data_tables.py new file mode 100644 index 0000000..a1d95e4 --- /dev/null +++ b/programmer/tinyprog/data_tables.py @@ -0,0 +1,18 @@ +bit_reverse_table = bytearray([ + 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, + 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, + 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, + 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, + 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, + 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA, + 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, + 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, + 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1, + 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, + 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, + 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD, + 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, + 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, + 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, + 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF +]) diff --git a/programmer/tox.ini b/programmer/tox.ini index 84e426a..b59dc6f 100644 --- a/programmer/tox.ini +++ b/programmer/tox.ini @@ -11,12 +11,11 @@ basepython = deps = check-manifest flake8 - pytest + flake8-import-order commands = - check-manifest --ignore tox.ini,tests* + check-manifest --ignore tox.ini python setup.py check -m -s - flake8 . - py.test tests + flake8 --exclude=data_tables.py setup.py tinyprog [flake8] exclude = .tox,*.egg,build,data From 246d1064b414b5684755b1d624c5b6d53c01d7dd Mon Sep 17 00:00:00 2001 From: Tim 'mithro' Ansell Date: Thu, 17 Jan 2019 17:23:39 +1300 Subject: [PATCH 12/31] tinyprog: Actually run tinyprog program with tox. Also add a tinyprog --version argument to get the tinyprog version that is currently installed. --- programmer/tinyprog/__init__.py | 8 ++++++++ programmer/tinyprog/__main__.py | 9 +++++++-- programmer/tox.ini | 4 ++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/programmer/tinyprog/__init__.py b/programmer/tinyprog/__init__.py index 94bd07d..894a6e0 100644 --- a/programmer/tinyprog/__init__.py +++ b/programmer/tinyprog/__init__.py @@ -4,6 +4,7 @@ import struct from functools import reduce +from pkg_resources import get_distribution, DistributionNotFound import jsonmerge import serial @@ -13,6 +14,13 @@ from .data_tables import bit_reverse_table +try: + __version__ = get_distribution(__name__).version +except DistributionNotFound: + # package is not installed + pass + + use_libusb = False use_pyserial = False diff --git a/programmer/tinyprog/__main__.py b/programmer/tinyprog/__main__.py index 7981b5b..af573ff 100644 --- a/programmer/tinyprog/__main__.py +++ b/programmer/tinyprog/__main__.py @@ -7,7 +7,6 @@ from six.moves import input import tinyprog - from tinyprog import TinyProg, get_ports @@ -216,7 +215,10 @@ def parse_int(str_value): return int(str_value) parser = argparse.ArgumentParser() - + parser.add_argument( + "--version", + action="store_true", + help="Print the tinyprog version.") parser.add_argument( "-l", "--list", @@ -276,6 +278,9 @@ def parse_int(str_value): help="use pyserial to connect to boards") args = parser.parse_args() + if args.version: + print("tinyprog %s" % tinyprog.__version__) + sys.exit(0) device = args.device.lower().replace(':', '') if len(device) != 8 or not all(c in '0123456789abcdef' for c in device): diff --git a/programmer/tox.ini b/programmer/tox.ini index b59dc6f..5ab4006 100644 --- a/programmer/tox.ini +++ b/programmer/tox.ini @@ -16,6 +16,10 @@ commands = check-manifest --ignore tox.ini python setup.py check -m -s flake8 --exclude=data_tables.py setup.py tinyprog + python setup.py --version + python setup.py install + tinyprog --help + tinyprog --version [flake8] exclude = .tox,*.egg,build,data From 7dc5368eba86559c282b29a7f68f990ba1848bc2 Mon Sep 17 00:00:00 2001 From: Tim 'mithro' Ansell Date: Thu, 17 Jan 2019 18:08:04 +1300 Subject: [PATCH 13/31] tinyprog: Write a version.txt file --- programmer/.gitignore | 1 + programmer/setup.py | 18 ++++++++++++++++-- programmer/tinyprog/__init__.py | 6 ++++++ programmer/tinyprog/__main__.py | 3 ++- programmer/tox.ini | 4 ++-- 5 files changed, 27 insertions(+), 5 deletions(-) diff --git a/programmer/.gitignore b/programmer/.gitignore index c3fb741..25fe328 100644 --- a/programmer/.gitignore +++ b/programmer/.gitignore @@ -7,6 +7,7 @@ dist/ __pycache__/ *.so *~ +tinyprog/full_version.py # due to using tox and pytest .tox diff --git a/programmer/setup.py b/programmer/setup.py index f5ed4a0..8631c5a 100644 --- a/programmer/setup.py +++ b/programmer/setup.py @@ -1,5 +1,20 @@ +import os +import subprocess +import sys from setuptools import setup, find_packages +GIT_DESCRIBE_CMD = 'git describe --dirty --tags --long --match tinyprog-*.*' + +full_version_path = os.path.join( + os.path.dirname(__file__), "tinyprog", "full_version.py") +try: + full_version = subprocess.check_output(GIT_DESCRIBE_CMD, shell=True) + with open(full_version_path, "w") as fh: + fh.write('__full_version__ = "%s"\n' % full_version.strip()) +except subprocess.CalledProcessError as e: + sys.stderr.write(str(e)) + sys.stderr.write('\n') + with open("README.md", "rb") as fh: long_description = fh.read().decode('utf-8') @@ -13,8 +28,7 @@ use_scm_version={ "root": "..", "relative_to": __file__, - 'git_describe_command': - r'git describe --dirty --tags --long --match tinyprog-*.*', + 'git_describe_command': GIT_DESCRIBE_CMD, }, setup_requires=['setuptools_scm'], description="""\ diff --git a/programmer/tinyprog/__init__.py b/programmer/tinyprog/__init__.py index 894a6e0..53d7dfb 100644 --- a/programmer/tinyprog/__init__.py +++ b/programmer/tinyprog/__init__.py @@ -20,6 +20,12 @@ # package is not installed pass +try: + from .full_version import __full_version__ + assert __full_version__ +except (ImportError, AssertionError): + __full_version__ = "unknown" + use_libusb = False use_pyserial = False diff --git a/programmer/tinyprog/__main__.py b/programmer/tinyprog/__main__.py index af573ff..cc90bc2 100644 --- a/programmer/tinyprog/__main__.py +++ b/programmer/tinyprog/__main__.py @@ -279,7 +279,8 @@ def parse_int(str_value): args = parser.parse_args() if args.version: - print("tinyprog %s" % tinyprog.__version__) + print("tinyprog %s (%s)" % ( + tinyprog.__version__, tinyprog.__full_version__)) sys.exit(0) device = args.device.lower().replace(':', '') diff --git a/programmer/tox.ini b/programmer/tox.ini index 5ab4006..26f55f5 100644 --- a/programmer/tox.ini +++ b/programmer/tox.ini @@ -13,10 +13,10 @@ deps = flake8 flake8-import-order commands = - check-manifest --ignore tox.ini + python setup.py --version + check-manifest --ignore tox.ini,tinyprog/full_version.py python setup.py check -m -s flake8 --exclude=data_tables.py setup.py tinyprog - python setup.py --version python setup.py install tinyprog --help tinyprog --version From 19073dd694bb5ce4e8bcb737e044cd53e895e9ba Mon Sep 17 00:00:00 2001 From: Tim 'mithro' Ansell Date: Thu, 17 Jan 2019 17:12:38 +1300 Subject: [PATCH 14/31] travis: Deploy dev version on travis. --- .travis.yml | 23 +++++++++++++++-- programmer/.push-to-pypi.sh | 50 +++++++++++++++++++++++++++++++++++++ programmer/MANIFEST.in | 1 + 3 files changed, 72 insertions(+), 2 deletions(-) create mode 100755 programmer/.push-to-pypi.sh diff --git a/.travis.yml b/.travis.yml index ca623fb..30046a6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,22 +1,41 @@ language: python -matrix: +jobs: include: - - python: 2.7 + - stage: test + python: 2.7 env: TOXENV=py27 + name: "Python 2.7" - python: 3.4 env: TOXENV=py34 + name: "Python 3.4" - python: 3.5 env: TOXENV=py35 + name: "Python 3.5" - python: 3.6 env: TOXENV=py36 + name: "Python 3.6" + - stage: deploy + python: 3.6 + name: "Upload dev version to PyPi" + script: ./.push-to-pypi.sh + +stages: + - test + - name: deploy + if: branch = master install: + - git fetch --tags - cd programmer - pip install --upgrade tox + - pip install --upgrade setuptools_scm script: - tox notifications: email: false + +git: + depth: false diff --git a/programmer/.push-to-pypi.sh b/programmer/.push-to-pypi.sh new file mode 100755 index 0000000..ab2791a --- /dev/null +++ b/programmer/.push-to-pypi.sh @@ -0,0 +1,50 @@ +#!/bin/bash + +if [ -z "$PYPI_USERNAME" ]; then + echo "\$PYPI_USERNAME not set." + echo "Not uploading to PyPi." + exit 0 +fi + +if [ -z "$PYPI_PASSWORD" ]; then + echo "\$PYPI_PASSWORD not set." + echo "Not uploading to PyPi." + exit 0 +fi + +if [ "$TRAVIS_BRANCH" != "master" ]; then + echo "Not on 'master' branch (on $TRAVIS_BRANCH)." + echo "Not uploading to PyPi." + exit 0 +fi + +set -x +set -e + +if [ ! -e ~/.pypirc ]; then + cat > ~/.pypirc < Date: Thu, 17 Jan 2019 21:22:39 +1300 Subject: [PATCH 15/31] tinyprog: Fixing issues from ewen's review. --- programmer/tinyprog/__init__.py | 14 +++++++++++--- programmer/tinyprog/__main__.py | 6 +++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/programmer/tinyprog/__init__.py b/programmer/tinyprog/__init__.py index 53d7dfb..9cdad13 100644 --- a/programmer/tinyprog/__init__.py +++ b/programmer/tinyprog/__init__.py @@ -39,9 +39,17 @@ def pretty_hex(data): def to_int(value): + """ + >>> to_int('A') + 65 + >>> to_int(0xff) + 256 + >>> list(to_int(i) for i in ['T', 'i', 'n', 'y', 0xff, 0, 0]) + [84, 105, 110, 121, 255, 0, 0] + """ try: return ord(value) - except ValueError: + except (ValueError, TypeError): return int(value) @@ -151,7 +159,7 @@ def __init__(self, prog): def _parse_json(self, data): try: return json.loads(bytes(data).decode("utf-8")) - except Exception: + except BaseException: return None def _resolve_pointers(self, meta): @@ -464,7 +472,7 @@ def boot(self): try: self.ser.write(b"\x00") self.ser.flush() - except Exception: + except BaseException: # we might get a writeTimeoutError and that's OK. Sometimes the # bootloader will reboot before it finishes sending out the USB ACK # for the boot command data packet. diff --git a/programmer/tinyprog/__main__.py b/programmer/tinyprog/__main__.py index cc90bc2..d9e5cff 100644 --- a/programmer/tinyprog/__main__.py +++ b/programmer/tinyprog/__main__.py @@ -376,7 +376,7 @@ def progress(info): fpga = TinyProg(active_port, progress) if args.program is not None: - print(" Programming %s with %s".format( + print(" Programming %s with %s" % ( active_port, args.program)) bitstream = fpga.slurp(args.program) @@ -403,7 +403,7 @@ def progress(info): # program user flash area if args.program_userdata is not None: - print(" Programming %s with %s".format( + print(" Programming %s with %s" % ( active_port, args.program_userdata)) bitstream = fpga.slurp(args.program_userdata) @@ -429,7 +429,7 @@ def progress(info): # program user image and data area if args.program_image is not None: - print(" Programming %s with %s".format( + print(" Programming %s with %s" % ( active_port, args.program_image)) bitstream = fpga.slurp(args.program_image) From 087fe135facb23e56190b3af57448bc7de88f439 Mon Sep 17 00:00:00 2001 From: Tim 'mithro' Ansell Date: Fri, 18 Jan 2019 01:07:13 +1300 Subject: [PATCH 16/31] travis: Upgrade pip, setuptools and wheel. --- .travis.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.travis.yml b/.travis.yml index 30046a6..5c9691b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -28,8 +28,12 @@ stages: install: - git fetch --tags - cd programmer + - pip install --upgrade pip - pip install --upgrade tox + - pip install --upgrade setuptools - pip install --upgrade setuptools_scm + - pip install --upgrade wheel + - pip install --upgrade twine script: - tox From a651be16a8aef14c2559ad3d858ea70d88d9fd41 Mon Sep 17 00:00:00 2001 From: Ewen McNeill Date: Fri, 18 Jan 2019 11:15:12 +1300 Subject: [PATCH 17/31] setup.py: generate single line description= The Summary: field (from description=) needs to be a single line, so replace newlines with spaces, and strip trailing white space. --- programmer/setup.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/programmer/setup.py b/programmer/setup.py index 8631c5a..2306392 100644 --- a/programmer/setup.py +++ b/programmer/setup.py @@ -18,6 +18,13 @@ with open("README.md", "rb") as fh: long_description = fh.read().decode('utf-8') +short_description = """ +Programmer for FPGA boards using the TinyFPGA USB Bootloader + (http://tinyfpga.com). +""".replace("\n", "").replace("\r", "").strip() +# short description should not have newlines or start/ending spaces. +assert len(short_description.splitlines()) == 1 + setup( name='tinyprog', packages=find_packages(), @@ -31,10 +38,7 @@ 'git_describe_command': GIT_DESCRIBE_CMD, }, setup_requires=['setuptools_scm'], - description="""\ -Programmer for FPGA boards using the TinyFPGA USB Bootloader -(http://tinyfpga.com). -""", + description=short_description, long_description=long_description, long_description_content_type="text/markdown", author='Luke Valenty', From 4f9064adfd06a3052cc41db7573c3a92e149d173 Mon Sep 17 00:00:00 2001 From: Tim 'mithro' Ansell Date: Fri, 18 Jan 2019 12:24:13 +1300 Subject: [PATCH 18/31] tinyprog: Missing commas on the classifiers. --- programmer/setup.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/programmer/setup.py b/programmer/setup.py index 2306392..1cf457a 100644 --- a/programmer/setup.py +++ b/programmer/setup.py @@ -60,10 +60,10 @@ 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3' - 'Programming Language :: Python :: 3.5' - 'Programming Language :: Python :: 3.6' - 'Programming Language :: Python :: 3.7' + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', ], entry_points={'console_scripts': ['tinyprog = tinyprog.__main__:main']}, ) From 8cc27e5ef05651db14eb73c94dd863812da78a64 Mon Sep 17 00:00:00 2001 From: Tim 'mithro' Ansell Date: Fri, 18 Jan 2019 12:35:59 +1300 Subject: [PATCH 19/31] tinyprog: Small update to README title. --- programmer/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programmer/README.md b/programmer/README.md index 1e040c1..59f82e8 100644 --- a/programmer/README.md +++ b/programmer/README.md @@ -1,4 +1,4 @@ -# Programmer +# TinyFPGA CLI Programmer ## GUI From 50edcb9576e909931ddd0976e1cb34bf8b2355bb Mon Sep 17 00:00:00 2001 From: Sylvain Munaut Date: Sun, 2 Sep 2018 15:44:02 +0200 Subject: [PATCH 20/31] common: Make sure RAM inference works with yosys icecube doesn't care about init values, but yosys does and you can't satisfy them with HW RAM module. So here we remove all the init values and we make sure the reads are not dependent on the reset line Signed-off-by: Sylvain Munaut --- common/usb_fs_in_pe.v | 7 ++++--- common/usb_fs_out_pe.v | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/common/usb_fs_in_pe.v b/common/usb_fs_in_pe.v index d999de4..da64b84 100644 --- a/common/usb_fs_in_pe.v +++ b/common/usb_fs_in_pe.v @@ -51,7 +51,7 @@ module usb_fs_in_pe #( // Data payload to send if any output tx_data_avail, input tx_data_get, - output reg [7:0] tx_data = 0 + output reg [7:0] tx_data ); //////////////////////////////////////////////////////////////////////////////// @@ -344,6 +344,9 @@ module usb_fs_in_pe #( endcase end + always @(posedge clk) + tx_data <= in_data_buffer[buffer_get_addr]; + integer j; always @(posedge clk) begin if (reset) begin @@ -352,8 +355,6 @@ module usb_fs_in_pe #( end else begin in_xfr_state <= in_xfr_state_next; - tx_data <= in_data_buffer[buffer_get_addr]; - if (setup_token_received) begin data_toggle[rx_endp] <= 1; end diff --git a/common/usb_fs_out_pe.v b/common/usb_fs_out_pe.v index 2e43be5..c9307af 100644 --- a/common/usb_fs_out_pe.v +++ b/common/usb_fs_out_pe.v @@ -14,7 +14,7 @@ module usb_fs_out_pe #( output [NUM_OUT_EPS-1:0] out_ep_data_avail, output reg [NUM_OUT_EPS-1:0] out_ep_setup = 0, input [NUM_OUT_EPS-1:0] out_ep_data_get, - output reg [7:0] out_ep_data = 0, + output reg [7:0] out_ep_data, input [NUM_OUT_EPS-1:0] out_ep_stall, output reg [NUM_OUT_EPS-1:0] out_ep_acked = 0, From 1b6dfd84d24046c52856fc3bad67542ebee75061 Mon Sep 17 00:00:00 2001 From: Sylvain Munaut Date: Sun, 2 Sep 2018 15:42:14 +0200 Subject: [PATCH 21/31] common/serial: Fix syntax error Signed-off-by: Sylvain Munaut --- common/serial.v | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/serial.v b/common/serial.v index 360d204..b776c70 100644 --- a/common/serial.v +++ b/common/serial.v @@ -11,7 +11,7 @@ module width_adapter #( output data_out_put, input data_out_free, - output [OUTPUT_WIDTH-1:0] data_out, + output [OUTPUT_WIDTH-1:0] data_out ); generate From 483cdf64ff0456b09cce2a59f1d1d9ecba254d65 Mon Sep 17 00:00:00 2001 From: Sylvain Munaut Date: Sun, 2 Sep 2018 15:46:17 +0200 Subject: [PATCH 22/31] common: Make sure to always assign all 'reg's in processes to avoid latches If you don't assign all 'reg's in a process, this effectively describes a latch, and the HW doesn't have any HW latches which leads yosys to create a logic loop, which is definitely not good in FPGA ! Signed-off-by: Sylvain Munaut --- common/usb_fs_in_arb.v | 6 ++---- common/usb_fs_in_pe.v | 4 ++++ common/usb_fs_out_pe.v | 4 ++++ 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/common/usb_fs_in_arb.v b/common/usb_fs_in_arb.v index a331406..186a272 100644 --- a/common/usb_fs_in_arb.v +++ b/common/usb_fs_in_arb.v @@ -20,6 +20,8 @@ module usb_fs_in_arb #( always @* begin grant = 0; + arb_in_ep_data <= 0; + for (i = 0; i < NUM_IN_EPS; i = i + 1) begin in_ep_grant[i] <= 0; @@ -29,9 +31,5 @@ module usb_fs_in_arb #( grant = 1; end end - - if (!grant) begin - arb_in_ep_data <= 0; - end end endmodule diff --git a/common/usb_fs_in_pe.v b/common/usb_fs_in_pe.v index da64b84..16b9faf 100644 --- a/common/usb_fs_in_pe.v +++ b/common/usb_fs_in_pe.v @@ -166,6 +166,8 @@ module usb_fs_in_pe #( always @* begin in_ep_acked[ep_num] <= 0; + ep_state_next[ep_num] <= ep_state[ep_num]; + if (in_ep_stall[ep_num]) begin ep_state_next[ep_num] <= STALL; @@ -277,9 +279,11 @@ module usb_fs_in_pe #( reg rollback_in_xfr; always @* begin + in_xfr_state_next <= in_xfr_state; in_xfr_start <= 0; in_xfr_end <= 0; tx_pkt_start <= 0; + tx_pid <= 4'b0000; rollback_in_xfr <= 0; case (in_xfr_state) diff --git a/common/usb_fs_out_pe.v b/common/usb_fs_out_pe.v index c9307af..26d0802 100644 --- a/common/usb_fs_out_pe.v +++ b/common/usb_fs_out_pe.v @@ -154,6 +154,8 @@ module usb_fs_out_pe #( for (ep_num = 0; ep_num < NUM_OUT_EPS; ep_num = ep_num + 1) begin always @* begin + ep_state_next[ep_num] <= ep_state[ep_num]; + if (out_ep_stall[ep_num]) begin ep_state_next[ep_num] <= STALL; @@ -272,7 +274,9 @@ module usb_fs_out_pe #( //////////////////////////////////////////////////////////////////////////////// always @* begin + out_ep_acked <= 0; out_xfr_start <= 0; + out_xfr_state_next <= out_xfr_state; tx_pkt_start <= 0; tx_pid <= 0; new_pkt_end <= 0; From 50f16d0817b8941fa3077e7754063a1926e5f178 Mon Sep 17 00:00:00 2001 From: Trammell hudson Date: Sun, 13 Jan 2019 18:16:03 -0500 Subject: [PATCH 23/31] silence warnings --- common/usb_fs_in_pe.v | 8 ++++---- common/usb_fs_rx.v | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/common/usb_fs_in_pe.v b/common/usb_fs_in_pe.v index 16b9faf..4ce36a7 100644 --- a/common/usb_fs_in_pe.v +++ b/common/usb_fs_in_pe.v @@ -100,9 +100,9 @@ module usb_fs_in_pe #( integer i = 0; initial begin for (i = 0; i < NUM_IN_EPS; i = i + 1) begin - ep_put_addr[i] = 0; - ep_get_addr[i] = 0; - ep_state[i] = 0; + ep_put_addr[i] <= 0; + ep_get_addr[i] <= 0; + ep_state[i] <= 0; end end @@ -400,4 +400,4 @@ module usb_fs_in_pe #( end end -endmodule \ No newline at end of file +endmodule diff --git a/common/usb_fs_rx.v b/common/usb_fs_rx.v index 8c73f68..3ea598d 100644 --- a/common/usb_fs_rx.v +++ b/common/usb_fs_rx.v @@ -224,7 +224,7 @@ module usb_fs_rx ( end end - assign dvalid = dvalid_raw && !(bitstuff_history == 6'b111111); + wire dvalid = dvalid_raw && !(bitstuff_history == 6'b111111); //////////////////////////////////////////////////////////////////////////////// From 50144c08348c46c6f2a52e470787370e5dbe9c52 Mon Sep 17 00:00:00 2001 From: Trammell hudson Date: Fri, 18 Jan 2019 13:22:59 -0500 Subject: [PATCH 24/31] TinyFPGA_BX: enable some IO pins --- boards/TinyFPGA_BX/pins.pcf | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/boards/TinyFPGA_BX/pins.pcf b/boards/TinyFPGA_BX/pins.pcf index 2a024b7..913676c 100644 --- a/boards/TinyFPGA_BX/pins.pcf +++ b/boards/TinyFPGA_BX/pins.pcf @@ -8,9 +8,9 @@ #set_io pin_3 B1 #set_io pin_4 C2 #set_io pin_5 C1 -#set_io pin_6 D2 +set_io -nowarn pin_6 D2 #set_io pin_7 D1 -#set_io pin_8 E2 +set_io -nowarn pin_8 E2 #set_io pin_9 E1 #set_io pin_10 G2 #set_io pin_11 H1 From a0676aaeba0413db6568641b50950a35bf713144 Mon Sep 17 00:00:00 2001 From: Trammell hudson Date: Fri, 18 Jan 2019 13:27:39 -0500 Subject: [PATCH 25/31] TinyFPGA_BX: use clock crossing strobe to bridge the 48 MHz USB clock --- boards/TinyFPGA_BX/bootloader.v | 190 +++++++++++++++- boards/TinyFPGA_BX/fifo.v | 391 ++++++++++++++++++++++++++++++++ boards/TinyFPGA_BX/uart.v | 305 +++++++++++++++++++++++++ boards/TinyFPGA_BX/util.v | 220 ++++++++++++++++++ common/strobe.v | 32 +++ common/tinyfpga_bootloader.v | 24 +- common/usb_fs_in_pe.v | 8 + common/usb_fs_out_pe.v | 12 +- common/usb_fs_pe.v | 16 +- common/usb_fs_rx.v | 70 +++--- common/usb_fs_tx.v | 58 ++--- 11 files changed, 1255 insertions(+), 71 deletions(-) create mode 100644 boards/TinyFPGA_BX/fifo.v create mode 100644 boards/TinyFPGA_BX/uart.v create mode 100644 boards/TinyFPGA_BX/util.v create mode 100644 common/strobe.v diff --git a/boards/TinyFPGA_BX/bootloader.v b/boards/TinyFPGA_BX/bootloader.v index 89e3f2b..114aec0 100644 --- a/boards/TinyFPGA_BX/bootloader.v +++ b/boards/TinyFPGA_BX/bootloader.v @@ -1,3 +1,7 @@ +`include "util.v" +`include "fifo.v" +`include "uart.v" + module bootloader ( input pin_clk, @@ -10,8 +14,12 @@ module bootloader ( input pin_29_miso, output pin_30_cs, output pin_31_mosi, - output pin_32_sck + output pin_32_sck, + + output pin_8 // uart ); + wire serial_tx = pin_8; + //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////// @@ -20,6 +28,8 @@ module bootloader ( //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// wire clk_48mhz; + wire lock; + wire reset = !lock; SB_PLL40_CORE #( .DIVR(4'b0000), @@ -43,13 +53,17 @@ module bootloader ( .RESETB(1'b1), .BYPASS(1'b0), .LATCHINPUTVALUE(), - .LOCK(), + .LOCK(lock), .SDI(), .SDO(), .SCLK() ); - + reg clk_24mhz; + reg clk_12mhz; + always @(posedge clk_48mhz) clk_24mhz = !clk_24mhz; + always @(posedge clk_24mhz) clk_12mhz = !clk_12mhz; + wire clk = !clk_48mhz; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// @@ -74,16 +88,183 @@ module bootloader ( //////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// - wire reset; wire usb_p_tx; wire usb_n_tx; wire usb_p_rx; wire usb_n_rx; wire usb_tx_en; +`ifdef NONONO + + wire bit_strobe; + wire pkt_start; + wire pkt_start; + wire pkt_end; + wire [3:0] pid; + wire [6:0] addr; + wire [3:0] endp; + wire [10:0] frame_num; + wire rx_data_put; + wire [7:0] rx_data; + wire valid_packet; + + usb_fs_rx usb( + .clk_48mhz(clk_48mhz), + .clk(clk), + .reset(reset), + .dp(usb_p_rx), + .dn(usb_n_rx), + .bit_strobe(bit_strobe), + .pkt_start(pkt_start), + .pkt_end(pkt_end), + .pid(pid), + .addr(addr), + .endp(endp), + .frame_num(frame_num), + .rx_data_put(rx_data_put), + .rx_data(rx_data), + .valid_packet(valid_packet) + ); + + assign usb_tx_en = 0; + + parameter FIFO_WIDTH = 24; + reg [FIFO_WIDTH-1:0] fifo_write_data; + reg fifo_write_strobe; + wire [FIFO_WIDTH-1:0] fifo_read_data; + reg fifo_read_strobe; + wire fifo_data_available; + + fifo_bram #(.WIDTH(FIFO_WIDTH)) uart_fifo( + .reset(reset), + .write_clk(clk), + .write_strobe(fifo_write_strobe), + .write_data(fifo_write_data), + .read_clk(clk), + .read_strobe(fifo_read_strobe), + .read_data(fifo_read_data), + .data_available(fifo_data_available) + ); + + always @(posedge clk) + begin + fifo_write_strobe <= 0; + + if (pkt_start) begin + fifo_write_strobe <= 1; + fifo_write_data <= { + 4'hA, + 20'b0, + }; + end else + if (rx_data_put) begin + fifo_write_strobe <= 1; + fifo_write_data <= { + pkt_start ? 4'hA : 4'hB, // 4 + 12'b0, // 12 + rx_data // 8 + }; + end else + if (pkt_end) begin + fifo_write_strobe <= 1; + fifo_write_data <= { + valid_packet ? 4'hC : 4'hF, + pid, // 4 + 1'b0, addr, // 1 + 7 + frame_num[7:0] // 8 + }; + end + end +`endif + + reg uart_strobe; + reg [7:0] uart_data; + wire uart_ready; + + wire clk_1; + divide_by_n #(.N(16)) div48(clk_48mhz, reset, clk_1); + + uart_tx_fifo uart_tx( + .clk(clk), + .reset(reset), + .baud_x1(clk_1), + .data(uart_data), + .data_strobe(uart_strobe), + .serial(serial_tx) + ); + +/* + reg [FIFO_WIDTH-1:0] hexdata; + reg [7:0] len; + reg [12:0] counter; + + always @(posedge clk) + begin + uart_strobe <= 0; + fifo_read_strobe <= 0; + counter <= counter + 1; + pin_led <= 0; + + if (!uart_ready + || uart_strobe + || counter != 0 + ) begin + // nothing + end else + begin + uart_data <= "A"; + uart_strobe <= 1; + pin_led <= 1; + end + end +*/ +/* + always @(posedge clk) + begin + uart_strobe <= 0; + fifo_read_strobe <= 0; + counter <= counter + 1; + pin_led <= 0; + + if (len == 0 + && fifo_data_available + && !fifo_read_strobe) begin + len <= 8; + hexdata <= fifo_read_data; + fifo_read_strobe <= 1; + pin_led <= 1; + end else + if (!uart_ready + || uart_strobe + || counter != 0 + ) begin + // nothing + end else + if (len == 1) begin + uart_data <= "\n"; + uart_strobe <= 1; + len <= 0; + end else + if (len == 2) begin + uart_data <= "\r"; + uart_strobe <= 1; + len <= 1; + end else + if (len != 0) begin + uart_data <= hexdigit(hexdata[FIFO_WIDTH-1:FIFO_WIDTH-4]); + uart_strobe <= 1; + hexdata <= { hexdata[FIFO_WIDTH-5:0], 4'b0 }; + len <= len - 1; + end + end +*/ + tinyfpga_bootloader tinyfpga_bootloader_inst ( .clk_48mhz(clk_48mhz), + .clk(clk), .reset(reset), + .uart_data(uart_data), + .uart_strobe(uart_strobe), .usb_p_tx(usb_p_tx), .usb_n_tx(usb_n_tx), .usb_p_rx(usb_p_rx), @@ -103,5 +284,4 @@ module bootloader ( assign usb_p_rx = usb_tx_en ? 1'b1 : pin_usbp; assign usb_n_rx = usb_tx_en ? 1'b0 : pin_usbn; - assign reset = 1'b0; endmodule diff --git a/boards/TinyFPGA_BX/fifo.v b/boards/TinyFPGA_BX/fifo.v new file mode 100644 index 0000000..304ad9a --- /dev/null +++ b/boards/TinyFPGA_BX/fifo.v @@ -0,0 +1,391 @@ + +/** 256 Kb SPRAM, organized 16 K x 16 bits */ +module spram( + input clk, + input reset = 0, + input cs = 1, + input [DEPTH-1:0] addr, + input write_strobe, + input [15:0] write_data, + output [15:0] read_data +); + parameter DEPTH = 16; + + wire [15:0] read_data_0; + wire [15:0] read_data_1; + wire [15:0] read_data_2; + wire [15:0] read_data_3; + + wire cs0, cs1, cs2, cs3; +/* + generate if (DEPTH == 14) + assign cs0 = cs; + assign cs1 = 0; + assign cs2 = 0; + assign cs3 = 0; + endgenerate + generate if (DEPTH == 15) + assign cs0 = cs & addr[14] == 1'b0; + assign cs1 = cs & addr[14] == 1'b1; + assign cs2 = 0; + assign cs3 = 0; + endgenerate +*/ + generate if (DEPTH == 16) + assign cs0 = cs && addr[15:14] == 2'b00; + assign cs1 = cs && addr[15:14] == 2'b01; + assign cs2 = cs && addr[15:14] == 2'b10; + assign cs3 = cs && addr[15:14] == 2'b11; + endgenerate + + assign read_data = + cs0 ? read_data_0 : + cs1 ? read_data_1 : + cs2 ? read_data_2 : + read_data_3; + + SB_SPRAM256KA spram0( + .DATAOUT(read_data_0), + .ADDRESS(addr[13:0]), + .DATAIN(write_data), + .MASKWREN(4'b1111), + .WREN(write_strobe), + .CHIPSELECT(cs0 && !reset), + .CLOCK(clk), + + // if we cared about power, maybe we would adjust these + .STANDBY(1'b0), + .SLEEP(1'b0), + .POWEROFF(1'b1) + ); + + generate if (DEPTH > 14) + SB_SPRAM256KA spram1( + .DATAOUT(read_data_1), + .ADDRESS(addr[13:0]), + .DATAIN(write_data), + .MASKWREN(4'b1111), + .WREN(write_strobe), + .CHIPSELECT(cs1 && !reset), + .CLOCK(clk), + + // if we cared about power, maybe we would adjust these + .STANDBY(1'b0), + .SLEEP(1'b0), + .POWEROFF(1'b1) + ); + endgenerate + + generate if (DEPTH > 15) + + SB_SPRAM256KA spram2( + .DATAOUT(read_data_2), + .ADDRESS(addr[13:0]), + .DATAIN(write_data), + .MASKWREN(4'b1111), + .WREN(write_strobe), + .CHIPSELECT(cs2 && !reset), + .CLOCK(clk), + + // if we cared about power, maybe we would adjust these + .STANDBY(1'b0), + .SLEEP(1'b0), + .POWEROFF(1'b1) + ); + + SB_SPRAM256KA spram3( + .DATAOUT(read_data_3), + .ADDRESS(addr[13:0]), + .DATAIN(write_data), + .MASKWREN(4'b1111), + .WREN(write_strobe), + .CHIPSELECT(cs3 && !reset), + .CLOCK(clk), + + // if we cared about power, maybe we would adjust these + .STANDBY(1'b0), + .SLEEP(1'b0), + .POWEROFF(1'b1) + ); + endgenerate +endmodule + + +module fifo_spram( + input clk, + input reset, + input [WIDTH-1:0] write_data, + input write_strobe, + output [WIDTH-1:0] read_data, + input read_strobe, + output data_available +); + parameter WIDTH = 16; + parameter DEPTH = 16; // 14 == one SPRAM deep, 15 == two deep, 16 == four + reg [DEPTH-1:0] write_ptr = 0; + reg [DEPTH-1:0] read_ptr = 0; + assign data_available = read_ptr != write_ptr; + + spram #( + .DEPTH(DEPTH) + ) buf0( + .clk(clk), + .reset(reset), + .write_strobe(write_strobe), + .addr(write_strobe ? write_ptr : read_ptr), + .write_data(write_data[15:0]), + .read_data(read_data[15:0]), + ); + + generate if (WIDTH > 16) + spram #( + .DEPTH(DEPTH) + ) buf1( + .clk(clk), + .reset(reset), + .write_strobe(write_strobe), + .addr(write_strobe ? write_ptr : read_ptr), + .write_data(write_data[31:16]), + .read_data(read_data[31:16]), + ); + endgenerate + + generate if (WIDTH > 32) + spram #( + .DEPTH(DEPTH) + ) buf2( + .clk(clk), + .reset(reset), + .write_strobe(write_strobe), + .addr(write_strobe ? write_ptr : read_ptr), + .write_data(write_data[47:32]), + .read_data(read_data[47:32]), + ); + endgenerate + + generate if (WIDTH > 48) + spram #( + .DEPTH(DEPTH) + ) buf3( + .clk(clk), + .reset(reset), + .write_strobe(write_strobe), + .addr(write_strobe ? write_ptr : read_ptr), + .write_data(write_data[63:48]), + .read_data(read_data[63:48]), + ); + endgenerate + + always @(posedge clk) + begin + if (write_strobe) + write_ptr <= write_ptr + 1; + + if (read_strobe) + read_ptr <= read_ptr + 1; + end +endmodule + + + +module fifo_bram( + input reset, + input write_clk, + input write_strobe, + input [WIDTH-1:0] write_data, + input read_clk, + input read_strobe, + output [WIDTH-1:0] read_data, + output data_available +); + parameter WIDTH = 16; // one block RAM wide + parameter DEPTH = 8; // one block RAM deep + reg [DEPTH-1:0] read_ptr; + reg [DEPTH-1:0] write_ptr; + + reg [WIDTH-1:0] fifo[(1 << DEPTH)-1:0]; + + assign read_data = fifo[read_ptr]; + + reg data_available_0; + reg data_available_1; + //reg data_available; + assign data_available = read_ptr != write_ptr; + + always @(posedge read_clk) + begin + if (reset) + read_ptr <= 0; + else + if (read_strobe) + read_ptr <= read_ptr + 1; + + //data_available <= read_ptr != write_ptr; + //data_available <= data_available_0; + //data_available <= data_available_1; + end + + always @(posedge write_clk) + begin + if (reset) + write_ptr <= 0; + else + if (write_strobe) begin + fifo[write_ptr] <= write_data; + write_ptr <= write_ptr + 1; + end + end +endmodule + + +module fifo_combo( + input reset, + input write_clk, + input write_strobe, + input [WIDTH-1:0] write_data, + input read_clk, + input read_strobe, + output [WIDTH-1:0] read_data, + output data_available +); + parameter WIDTH = 16; + +`define NO_SPRAM +`ifdef NO_SPRAM + parameter DEPTH = 12; + // just wire it up + fifo_bram #( + .WIDTH(WIDTH), + .DEPTH(DEPTH) + ) fifo0( + .reset(reset), + .write_clk(write_clk), + .write_strobe(write_strobe), + .write_data(write_data), + .read_clk(read_clk), + .read_strobe(read_strobe), + .read_data(read_data), + .data_available(data_available) + ); +`else + parameter DEPTH = 16; + wire [WIDTH-1:0] fifo0_read_data; + reg fifo0_read_strobe; + wire fifo0_data_available; + reg fifo1_write_strobe; + + fifo_bram #( + .WIDTH(WIDTH), + ) fifo0( + .reset(reset), + .write_clk(write_clk), + .write_strobe(write_strobe), + .write_data(write_data), + .read_clk(read_clk), + .read_strobe(fifo0_read_strobe), + .read_data(fifo0_read_data), + .data_available(fifo0_data_available) + ); + + fifo_spram #( + .WIDTH(WIDTH), + .DEPTH(DEPTH) + ) fifo1( + .reset(reset), + .clk(read_clk), + //.write_data(32'hA55AB00F), + .write_data(fifo0_read_data), + .write_strobe(fifo1_write_strobe), + .read_data(read_data), + .read_strobe(read_strobe), + .data_available(data_available) + ); + + reg [3:0] counter; + + always @(posedge read_clk) begin + fifo0_read_strobe <= 0; + fifo1_write_strobe <= 0; + counter <= counter + 1; + + if (reset) begin + // nothing + end else + if (fifo0_data_available + && !fifo0_read_strobe + && !fifo1_write_strobe + && !read_strobe // don't move if the user is also moving + && counter == 0 + ) begin + // move data from fifo0 into fifo1 + fifo0_read_strobe <= 1; + fifo1_write_strobe <= 1; + end + end +`endif +endmodule + +module fifo_bram_16to8( + input read_clk, + input write_clk, + input reset, + output data_available, + input [16-1:0] write_data, + input write_strobe, + output [8-1:0] read_data, + input read_strobe +); + + reg [BITS-1:0] write_ptr; + reg [BITS-1:0] read_ptr; + + // reads from the SPRAM are 16-bits at a time, + // so we have to pick which byte of the word should be extracted +`undef BUFFER +`ifdef BUFFER + parameter BITS = 13; + reg [15:0] buffer[(1 << BITS)-1:0]; + wire [15:0] rdata_16 = buffer[read_ptr[BITS-1:1]]; +`else + parameter BITS = 8; + wire [15:0] rdata_16; +SB_RAM40_4K #(.READ_MODE(0), .WRITE_MODE(0)) ram256x16_inst ( +.RDATA(rdata_16[15:0]), +.RADDR({ 4'b0, read_ptr[BITS-1:1] }), +.RCLK(read_clk), +.RCLKE(!reset), +.RE(1), +.WADDR({ 4'b0, write_ptr[BITS-1:1] }), +.WCLK(write_clk), +.WCLKE(!reset), +.WDATA(write_data[15:0]), +.WE(write_strobe), +.MASK(16'h0) +); +`endif + assign data_available = read_ptr != write_ptr; + assign read_data = (!read_ptr[0]) ? rdata_16[15:8] : rdata_16[7:0]; + + always @(posedge read_clk) + begin + if (reset) begin + read_ptr <= 0; + end else + if (read_strobe) begin + read_ptr <= read_ptr + 1; + end + end + + always @(posedge write_clk) + begin + if (reset) begin + write_ptr <= 0; + end else + if (write_strobe) begin +`ifdef BUFFER + buffer[write_ptr[BITS-1:1]] <= write_data; +`endif + write_ptr <= write_ptr + 2; + end + end +endmodule diff --git a/boards/TinyFPGA_BX/uart.v b/boards/TinyFPGA_BX/uart.v new file mode 100644 index 0000000..39f1e12 --- /dev/null +++ b/boards/TinyFPGA_BX/uart.v @@ -0,0 +1,305 @@ + /* + * uart.v - High-speed serial support. Includes a baud generator, UART, + * and a simple RFC1662-inspired packet framing protocol. + * + * This module is designed a 3 Mbaud serial port. + * This is the highest data rate supported by + * the popular FT232 USB-to-serial chip. + * + * Copyright (C) 2009 Micah Dowty + * (C) 2018 Trammell Hudson + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + + +/* + * Byte transmitter, RS-232 8-N-1 + * + * Transmits on 'serial'. When 'ready' goes high, we can accept another byte. + * It should be supplied on 'data' with a pulse on 'data_strobe'. + */ + +module uart_tx( + input clk, + input reset, + input baud_x1, + output serial, + output reg ready, + input [7:0] data, + input data_strobe +); + + /* + * Left-to-right shift register. + * Loaded with data, start bit, and stop bit. + * + * The stop bit doubles as a flag to tell us whether data has been + * loaded; we initialize the whole shift register to zero on reset, + * and when the register goes zero again, it's ready for more data. + */ + reg [7+1+1:0] shiftreg; + + /* + * Serial output register. This is like an extension of the + * shift register, but we never load it separately. This gives + * us one bit period of latency to prepare the next byte. + * + * This register is inverted, so we can give it a reset value + * of zero and still keep the 'serial' output high when idle. + */ + reg serial_r; + assign serial = !serial_r; + + //assign ready = (shiftreg == 0); + + /* + * State machine + */ + + always @(posedge clk) + if (reset) begin + shiftreg <= 0; + serial_r <= 0; + end + else if (data_strobe) begin + shiftreg <= { + 1'b1, // stop bit + data, + 1'b0 // start bit (inverted) + }; + ready <= 0; + end + else if (baud_x1) begin + if (shiftreg == 0) + begin + /* Idle state is idle high, serial_r is inverted */ + serial_r <= 0; + ready <= 1; + end else + serial_r <= !shiftreg[0]; + // shift the output register down + shiftreg <= {1'b0, shiftreg[7+1+1:1]}; + end else + ready <= (shiftreg == 0); + +endmodule + + +/* + * Byte receiver, RS-232 8-N-1 + * + * Receives on 'serial'. When a properly framed byte is + * received, 'data_strobe' pulses while the byte is on 'data'. + * + * Error bytes are ignored. + */ + +module uart_rx(clk, reset, baud_x4, + serial, data, data_strobe); + + input clk, reset, baud_x4, serial; + output [7:0] data; + output data_strobe; + + /* + * Synchronize the serial input to this clock domain + */ + wire serial_sync; + d_flipflop_pair input_dff(clk, reset, serial, serial_sync); + + /* + * State machine: Four clocks per bit, 10 total bits. + */ + reg [8:0] shiftreg; + reg [5:0] state; + reg data_strobe; + wire [3:0] bit_count = state[5:2]; + wire [1:0] bit_phase = state[1:0]; + + wire sampling_phase = (bit_phase == 1); + wire start_bit = (bit_count == 0 && sampling_phase); + wire stop_bit = (bit_count == 9 && sampling_phase); + + wire waiting_for_start = (state == 0 && serial_sync == 1); + + wire error = ( (start_bit && serial_sync == 1) || + (stop_bit && serial_sync == 0) ); + + assign data = shiftreg[7:0]; + + always @(posedge clk or posedge reset) + if (reset) begin + state <= 0; + data_strobe <= 0; + end + else if (baud_x4) begin + + if (waiting_for_start || error || stop_bit) + state <= 0; + else + state <= state + 1; + + if (bit_phase == 1) + shiftreg <= { serial_sync, shiftreg[8:1] }; + + data_strobe <= stop_bit && !error; + + end + else begin + data_strobe <= 0; + end + +endmodule + + +/* + * Output UART with a SPRAM RAM FIFO queue. + * + * Add bytes to the queue and they will be printed when the line is idle. + */ +module uart_tx_fifo( + input clk, + input reset, + input baud_x1, + input [7:0] data, + input data_strobe, + output serial +); + parameter NUM = 32; + + wire uart_txd_ready; // high the UART is ready to take a new byte + reg uart_txd_strobe; // pulse when we have a new byte to transmit + reg [7:0] uart_txd; + + uart_tx txd( + .clk(clk), + .reset(reset), + .baud_x1(baud_x1), + .serial(serial), + .ready(uart_txd_ready), + .data(uart_txd), + .data_strobe(uart_txd_strobe) + ); + + wire fifo_available; + wire fifo_read_strobe; + wire [7:0] fifo_read_data; + + fifo_bram #(.WIDTH(8)) buffer( + .read_clk(clk), + .write_clk(clk), + .reset(reset), + .write_data(data), + .write_strobe(data_strobe), + .data_available(fifo_available), + .read_data(fifo_read_data), + .read_strobe(fifo_read_strobe) + ); + + // drain the fifo into the serial port + reg [3:0] counter; + always @(posedge clk) + begin + uart_txd_strobe <= 0; + fifo_read_strobe <= 0; + counter <= counter + 1; + + if (fifo_available + && uart_txd_ready + && !data_strobe // only single port port RAM + && !uart_txd_strobe // don't TX twice on one byte + && counter == 0 + ) begin + fifo_read_strobe <= 1; + uart_txd_strobe <= 1; + uart_txd <= fifo_read_data; + end + end +endmodule + + +module uart_tx_hexdump( + input clk, + input reset = 0, + input strobe, + input [31:0] data, + input [3:0] len, + input space, + input newline, + output ready, + input uart_txd_ready, + output uart_txd_strobe, + output [7:0] uart_txd +); + reg [3:0] digits; + reg [31:0] bytes; + reg [7:0] uart_txd; + reg in_progress = 0; + reg [8:0] counter; + + assign ready = !in_progress; + + always @(posedge clk) + begin + uart_txd_strobe <= 0; + + if (reset) begin + // nothing to do + in_progress <= 0; + end else + if (strobe) begin + digits <= len; + bytes <= data; + in_progress <= 1; + end else + if (uart_txd_strobe + || !uart_txd_ready + || !in_progress + || counter != 0 + ) begin + // nothing to do until uart is ready + // or we're in progress with an output + counter <= counter + 1; + end else + if (digits != 0) + begin + // time to generate a hex value! + uart_txd_strobe <= 1; + uart_txd <= hexdigit(bytes[31:28]); + + bytes <= { bytes[27:0], 4'b0 }; + digits <= digits - 1; + end else + begin + // after all the digits, output any whitespace + if (space) begin + uart_txd_strobe <= 1; + uart_txd <= " "; + end else + if (newline) begin + uart_txd_strobe <= 1; + uart_txd <= "\n"; + end + + in_progress <= 0; + counter <= 0; + end + end +endmodule diff --git a/boards/TinyFPGA_BX/util.v b/boards/TinyFPGA_BX/util.v new file mode 100644 index 0000000..ec69fc7 --- /dev/null +++ b/boards/TinyFPGA_BX/util.v @@ -0,0 +1,220 @@ +/** \file + * Utility modules. + */ + +`define CLOG2(x) \ + x <= 2 ? 1 : \ + x <= 4 ? 2 : \ + x <= 8 ? 3 : \ + x <= 16 ? 4 : \ + x <= 32 ? 5 : \ + x <= 64 ? 6 : \ + x <= 128 ? 7 : \ + x <= 256 ? 8 : \ + x <= 512 ? 9 : \ + x <= 1024 ? 10 : \ + x <= 2048 ? 11 : \ + x <= 4096 ? 12 : \ + x <= 8192 ? 13 : \ + x <= 16384 ? 14 : \ + x <= 32768 ? 15 : \ + x <= 65536 ? 16 : \ + -1 + +function [7:0] hexdigit; + input [3:0] x; + begin + hexdigit = + x == 0 ? "0" : + x == 1 ? "1" : + x == 2 ? "2" : + x == 3 ? "3" : + x == 4 ? "4" : + x == 5 ? "5" : + x == 6 ? "6" : + x == 7 ? "7" : + x == 8 ? "8" : + x == 9 ? "9" : + x == 10 ? "a" : + x == 11 ? "b" : + x == 12 ? "c" : + x == 13 ? "d" : + x == 14 ? "e" : + x == 15 ? "f" : + "?"; + end +endfunction + +module divide_by_n( + input clk, + input reset, + output reg out +); + parameter N = 2; + + reg [`CLOG2(N)-1:0] counter; + + always @(posedge clk) + begin + out <= 0; + + if (reset) + counter <= 0; + else + if (counter == 0) + begin + out <= 1; + counter <= N - 1; + end else + counter <= counter - 1; + end +endmodule + + +module fifo( + input clk, + input reset, + output data_available, + input [WIDTH-1:0] write_data, + input write_strobe, + output [WIDTH-1:0] read_data, + input read_strobe +); + parameter WIDTH = 8; + parameter NUM = 256; + + reg [WIDTH-1:0] buffer[0:NUM-1]; + reg [`CLOG2(NUM)-1:0] write_ptr; + reg [`CLOG2(NUM)-1:0] read_ptr; + + assign read_data = buffer[read_ptr]; + assign data_available = read_ptr != write_ptr; + + always @(posedge clk) begin + if (reset) begin + write_ptr <= 0; + read_ptr <= 0; + end else begin + if (write_strobe) begin + buffer[write_ptr] <= write_data; + write_ptr <= write_ptr + 1; + end + if (read_strobe) begin + read_ptr <= read_ptr + 1; + end + end + end +endmodule + + +module pwm( + input clk, + input [BITS-1:0] bright, + output out +); + parameter BITS = 8; + + reg [BITS-1:0] counter; + always @(posedge clk) + begin + counter <= counter + 1; + out <= counter < bright; + end + +endmodule + + +/************************************************************************ + * + * Random utility modules. + * + * Micah Dowty + * + ************************************************************************/ + + +module d_flipflop(clk, reset, d_in, d_out); + input clk, reset, d_in; + output d_out; + + reg d_out; + + always @(posedge clk or posedge reset) + if (reset) begin + d_out <= 0; + end + else begin + d_out <= d_in; + end +endmodule + + +module d_flipflop_pair(clk, reset, d_in, d_out); + input clk, reset, d_in; + output d_out; + wire intermediate; + + d_flipflop dff1(clk, reset, d_in, intermediate); + d_flipflop dff2(clk, reset, intermediate, d_out); +endmodule + + +/* + * A set/reset flipflop which is set on sync_set and reset by sync_reset. + */ +module set_reset_flipflop(clk, reset, sync_set, sync_reset, out); + input clk, reset, sync_set, sync_reset; + output out; + reg out; + + always @(posedge clk or posedge reset) + if (reset) + out <= 0; + else if (sync_set) + out <= 1; + else if (sync_reset) + out <= 0; +endmodule + + +/* + * Pulse stretcher. + * + * When the input goes high, the output goes high + * for as long as the input is high, or as long as + * it takes our timer to roll over- whichever is + * longer. + */ +module pulse_stretcher(clk, reset, in, out); + parameter BITS = 20; + + input clk, reset, in; + output out; + reg out; + + reg [BITS-1:0] counter; + + always @(posedge clk or posedge reset) + if (reset) begin + out <= 0; + counter <= 0; + end + else if (counter == 0) begin + out <= in; + counter <= in ? 1 : 0; + end + else if (&counter) begin + if (in) begin + out <= 1; + end + else begin + out <= 0; + counter <= 0; + end + end + else begin + out <= 1; + counter <= counter + 1; + end +endmodule + diff --git a/common/strobe.v b/common/strobe.v new file mode 100644 index 0000000..2ec4bbb --- /dev/null +++ b/common/strobe.v @@ -0,0 +1,32 @@ +module strobe( + input clk_in, + input clk_out, + input strobe_in, + output strobe_out, + input [WIDTH-1:0] data_in, + output [WIDTH-1:0] data_out +); + parameter WIDTH = 1; +`define CLOCK_CROSS +`ifdef CLOCK_CROSS + reg flag; + reg [2:0] sync; + reg [WIDTH-1:0] data; + + always @(posedge clk_in) begin + flag <= flag ^ strobe_in; + if (strobe_in) + data <= data_in; + end + + always @(posedge clk_out) + sync <= { sync[1:0], flag }; + + assign strobe_out = sync[1] ^ sync[0]; + assign data_out = data; + //assign data_out = data_in; +`else + assign strobe_out = strobe_in; + assign data_out = data_in; +`endif +endmodule diff --git a/common/tinyfpga_bootloader.v b/common/tinyfpga_bootloader.v index 578ca22..155327e 100644 --- a/common/tinyfpga_bootloader.v +++ b/common/tinyfpga_bootloader.v @@ -1,7 +1,11 @@ module tinyfpga_bootloader ( input clk_48mhz, + input clk, input reset, + output uart_strobe, + output [7:0] uart_data, + // USB lines. Split into input vs. output and oe control signal to maintain // highest level of compatibility with synthesis tools. output usb_p_tx, @@ -26,6 +30,7 @@ module tinyfpga_bootloader ( // function. output boot ); + //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////// @@ -38,7 +43,7 @@ module tinyfpga_bootloader ( reg [5:0] ns_cnt = 0; wire ns_rst = (ns_cnt == 48); - always @(posedge clk_48mhz) begin + always @(posedge clk) begin if (ns_rst) begin ns_cnt <= 0; end else begin @@ -48,7 +53,7 @@ module tinyfpga_bootloader ( reg [9:0] us_cnt = 0; wire us_rst = (us_cnt == 1000); - always @(posedge clk_48mhz) begin + always @(posedge clk) begin if (us_rst) begin us_cnt <= 0; end else if (ns_rst) begin @@ -57,7 +62,7 @@ module tinyfpga_bootloader ( end reg count_down = 0; - always @(posedge clk_48mhz) begin + always @(posedge clk) begin if (us_rst) begin if (count_down) begin if (led_pwm == 0) begin @@ -74,7 +79,7 @@ module tinyfpga_bootloader ( end end end - always @(posedge clk_48mhz) pwm_cnt <= pwm_cnt + 1'b1; + always @(posedge clk) pwm_cnt <= pwm_cnt + 1'b1; assign led = led_pwm > pwm_cnt; @@ -136,7 +141,7 @@ module tinyfpga_bootloader ( assign boot = host_presence_timeout || boot_to_user_design; usb_serial_ctrl_ep ctrl_ep_inst ( - .clk(clk_48mhz), + .clk(clk), .reset(reset), .dev_addr(dev_addr), @@ -163,7 +168,7 @@ module tinyfpga_bootloader ( ); usb_spi_bridge_ep usb_spi_bridge_ep_inst ( - .clk(clk_48mhz), + .clk(clk), .reset(reset), // out endpoint interface @@ -204,8 +209,11 @@ module tinyfpga_bootloader ( .NUM_OUT_EPS(5'd2), .NUM_IN_EPS(5'd3) ) usb_fs_pe_inst ( - .clk(clk_48mhz), + .clk_48mhz(clk_48mhz), + .clk(clk), .reset(reset), + .uart_strobe(uart_strobe), + .uart_data(uart_data), .usb_p_tx(usb_p_tx), .usb_n_tx(usb_n_tx), @@ -246,7 +254,7 @@ module tinyfpga_bootloader ( // host presence detection //////////////////////////////////////////////////////////////////////////////// - always @(posedge clk_48mhz) begin + always @(posedge clk) begin if (sof_valid) begin host_presence_timer <= 0; host_presence_timeout <= 0; diff --git a/common/usb_fs_in_pe.v b/common/usb_fs_in_pe.v index 4ce36a7..99b3b6c 100644 --- a/common/usb_fs_in_pe.v +++ b/common/usb_fs_in_pe.v @@ -5,6 +5,8 @@ module usb_fs_in_pe #( ) ( input clk, input reset, + output uart_strobe, + output [7:0] uart_data, input [NUM_IN_EPS-1:0] reset_ep, input [6:0] dev_addr, @@ -353,11 +355,17 @@ module usb_fs_in_pe #( integer j; always @(posedge clk) begin + uart_strobe <= 0; + if (reset) begin in_xfr_state <= IDLE; end else begin in_xfr_state <= in_xfr_state_next; + if (in_xfr_state != in_xfr_state_next) begin + uart_strobe <= 1; + uart_data <= in_xfr_state_next + "A"; + end if (setup_token_received) begin data_toggle[rx_endp] <= 1; diff --git a/common/usb_fs_out_pe.v b/common/usb_fs_out_pe.v index 26d0802..012e66b 100644 --- a/common/usb_fs_out_pe.v +++ b/common/usb_fs_out_pe.v @@ -5,6 +5,8 @@ module usb_fs_out_pe #( ) ( input clk, input reset, + output uart_strobe, + output [7:0] uart_data, input [NUM_OUT_EPS-1:0] reset_ep, input [6:0] dev_addr, @@ -287,7 +289,6 @@ module usb_fs_out_pe #( if (out_token_received || setup_token_received) begin out_xfr_state_next <= RCVD_OUT; out_xfr_start <= 1; - end else begin out_xfr_state_next <= IDLE; end @@ -296,7 +297,6 @@ module usb_fs_out_pe #( RCVD_OUT : begin if (rx_pkt_start) begin out_xfr_state_next <= RCVD_DATA_START; - end else begin out_xfr_state_next <= RCVD_OUT; end @@ -355,10 +355,18 @@ module usb_fs_out_pe #( integer j; always @(posedge clk) begin + uart_strobe <= 0; + if (reset) begin out_xfr_state <= IDLE; end else begin out_xfr_state <= out_xfr_state_next; + if (out_xfr_state != out_xfr_state_next) begin + uart_strobe <= 1; + uart_data <= out_xfr_state_next + "A"; + if (out_xfr_state == RCVD_DATA_END) + uart_data <= "0" + tx_pid; + end if (out_xfr_start) begin current_endp <= rx_endp; diff --git a/common/usb_fs_pe.v b/common/usb_fs_pe.v index dadb719..924bdff 100644 --- a/common/usb_fs_pe.v +++ b/common/usb_fs_pe.v @@ -2,9 +2,11 @@ module usb_fs_pe #( parameter [4:0] NUM_OUT_EPS = 1, parameter [4:0] NUM_IN_EPS = 1 ) ( + input clk_48mhz, input clk, input [6:0] dev_addr, - + output uart_strobe, + output [7:0] uart_data, //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// @@ -123,6 +125,8 @@ module usb_fs_pe #( .NUM_IN_EPS(NUM_IN_EPS) ) usb_fs_in_pe_inst ( .clk(clk), + //.uart_strobe(uart_strobe), + //.uart_data(uart_data), .reset(reset), .reset_ep({NUM_IN_EPS{1'b0}}), .dev_addr(dev_addr), @@ -159,6 +163,8 @@ module usb_fs_pe #( .clk(clk), .reset(reset), .reset_ep({NUM_OUT_EPS{1'b0}}), + .uart_strobe(uart_strobe), + .uart_data(uart_data), .dev_addr(dev_addr), // endpoint interface @@ -187,7 +193,8 @@ module usb_fs_pe #( ); usb_fs_rx usb_fs_rx_inst ( - .clk_48mhz(clk), + .clk_48mhz(clk_48mhz), + .clk(clk), .reset(reset), .dp(usb_p_rx), .dn(usb_n_rx), @@ -218,7 +225,8 @@ module usb_fs_pe #( ); usb_fs_tx usb_fs_tx_inst ( - .clk_48mhz(clk), + .clk_48mhz(clk_48mhz), + .clk(clk), .reset(reset), .bit_strobe(bit_strobe), .oe(usb_tx_en), @@ -231,4 +239,4 @@ module usb_fs_pe #( .tx_data_get(tx_data_get), .tx_data(tx_data) ); -endmodule \ No newline at end of file +endmodule diff --git a/common/usb_fs_rx.v b/common/usb_fs_rx.v index 3ea598d..19ea976 100644 --- a/common/usb_fs_rx.v +++ b/common/usb_fs_rx.v @@ -1,36 +1,39 @@ module usb_fs_rx ( // A 48MHz clock is required to recover the clock from the incoming data. input clk_48mhz, + input clk, input reset, // USB data+ and data- lines. input dp, input dn, - // pulse on every bit transition. + // pulse on every bit transition in clk_48mhz output bit_strobe, - // Pulse on beginning of new packet. + // Pulse on beginning of new packet in clk. output pkt_start, - // Pulse on end of current packet. + // Pulse on end of current packet in clk. output pkt_end, // Most recent packet decoded. output [3:0] pid, - output reg [6:0] addr = 0, - output reg [3:0] endp = 0, - output reg [10:0] frame_num = 0, + output [6:0] addr, + output [3:0] endp, + output [10:0] frame_num, - // Pulse on valid data on rx_data. + // Pulse on valid data on rx_data in clk. output rx_data_put, output [7:0] rx_data, // Most recent packet passes PID and CRC checks output valid_packet ); - wire clk = clk_48mhz; - + wire [3:0] pid_48; + reg [6:0] addr_48; + reg [3:0] endp_48; + reg [10:0] frame_num_48; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////// @@ -51,7 +54,7 @@ module usb_fs_rx ( reg [3:0] dpair_q = 0; - always @(posedge clk) begin + always @(posedge clk_48mhz) begin dpair_q[3:0] <= {dpair_q[1:0], dp, dn}; end @@ -78,7 +81,7 @@ module usb_fs_rx ( wire [1:0] dpair = dpair_q[3:2]; - always @(posedge clk) begin + always @(posedge clk_48mhz) begin case (line_state) // if we are in a transition state, then we can sample the pair and // move to the next corresponding line state @@ -122,7 +125,7 @@ module usb_fs_rx ( wire line_state_valid = (bit_phase == 1); assign bit_strobe = (bit_phase == 2); - always @(posedge clk) begin + always @(posedge clk_48mhz) begin // keep track of phase within each bit if (line_state == DT) begin bit_phase <= 0; @@ -165,7 +168,7 @@ module usb_fs_rx ( end end - always @(posedge clk) begin + always @(posedge clk_48mhz) begin if (reset) begin line_history <= 6'b101010; packet_valid <= 0; @@ -214,7 +217,7 @@ module usb_fs_rx ( reg [5:0] bitstuff_history = 0; - always @(posedge clk) begin + always @(posedge clk_48mhz) begin if (reset || packet_end) begin bitstuff_history <= 6'b000000; end else begin @@ -237,7 +240,7 @@ module usb_fs_rx ( wire pid_valid = full_pid[4:1] == ~full_pid[8:5]; wire pid_complete = full_pid[0]; - always @(posedge clk) begin + always @(posedge clk_48mhz) begin if (packet_start) begin full_pid <= 9'b100000000; end @@ -253,7 +256,7 @@ module usb_fs_rx ( reg [4:0] crc5 = 0; wire crc5_valid = crc5 == 5'b01100; wire crc5_invert = din ^ crc5[4]; - always @(posedge clk) begin + always @(posedge clk_48mhz) begin if (packet_start) begin crc5 <= 5'b11111; end @@ -274,7 +277,7 @@ module usb_fs_rx ( wire crc16_valid = crc16 == 16'b1000000000001101; wire crc16_invert = din ^ crc16[15]; - always @(posedge clk) begin + always @(posedge clk_48mhz) begin if (packet_start) begin crc16 <= 16'b1111111111111111; end @@ -319,7 +322,7 @@ module usb_fs_rx ( reg [11:0] token_payload = 0; wire token_payload_done = token_payload[0]; - always @(posedge clk) begin + always @(posedge clk_48mhz) begin if (packet_start) begin token_payload <= 12'b100000000000; end @@ -329,17 +332,32 @@ module usb_fs_rx ( end end - always @(posedge clk) begin + always @(posedge clk_48mhz) begin if (token_payload_done && pkt_is_token) begin - addr <= token_payload[7:1]; - endp <= token_payload[11:8]; - frame_num <= token_payload[11:1]; + addr_48 <= token_payload[7:1]; + endp_48 <= token_payload[11:8]; + frame_num_48 <= token_payload[11:1]; end end - assign pkt_start = packet_start; - assign pkt_end = packet_end; - assign pid = full_pid[4:1]; + //assign pkt_start = packet_start; + //assign pkt_end = packet_end; + strobe pkt_start_strobe(clk_48mhz, clk, packet_start, pkt_start); + + // at the end of the packet, capture the parameters + strobe #(.WIDTH(26)) pkt_end_strobe( + clk_48mhz, clk, + packet_end, pkt_end, + //{ pid_48, addr_48, endp_48, frame_num_48 }, + //{ pid, addr, endp, frame_num }, + ); + assign pid_48 = full_pid[4:1]; + + assign pid = pid_48; + assign addr = addr_48; + assign endp = endp_48; + assign frame_num = frame_num_48; + //assign addr = token_payload[7:1]; //assign endp = token_payload[11:8]; //assign frame_num = token_payload[11:1]; @@ -353,7 +371,7 @@ module usb_fs_rx ( assign rx_data_put = rx_data_buffer_full; assign rx_data = rx_data_buffer[8:1]; - always @(posedge clk) begin + always @(posedge clk_48mhz) begin if (packet_start || rx_data_buffer_full) begin rx_data_buffer <= 9'b100000000; end diff --git a/common/usb_fs_tx.v b/common/usb_fs_tx.v index c9ba07a..a9ae0d9 100644 --- a/common/usb_fs_tx.v +++ b/common/usb_fs_tx.v @@ -2,9 +2,10 @@ module usb_fs_tx ( // A 48MHz clock is required to receive USB data at 12MHz // it's simpler to juse use 48MHz everywhere input clk_48mhz, + input clk, input reset, - // bit strobe from rx to align with senders clock + // bit strobe from rx to align with senders clock (in clk_48mhz domain) input bit_strobe, // output enable to take ownership of bus and data out @@ -12,28 +13,32 @@ module usb_fs_tx ( output reg dp = 0, output reg dn = 0, - // pulse to initiate new packet transmission + // pulse to initiate new packet transmission in clk domain input pkt_start, output pkt_end, - // pid to send + // pid to send (clk domain) input [3:0] pid, // tx logic pulls data until there is nothing available input tx_data_avail, - output reg tx_data_get = 0, + output tx_data_get, input [7:0] tx_data ); - wire clk = clk_48mhz; - + // convert pkt_start to clk_48mhz domain // save packet parameters at pkt_start - reg [3:0] pidq = 0; - - always @(posedge clk) begin - if (pkt_start) begin - pidq <= pid; - end - end + wire pkt_start_48; + wire [3:0] pidq; + strobe #(.WIDTH(4)) pkt_start_strobe( + clk, clk_48mhz, + pkt_start, pkt_start_48, + pid, pidq + ); + + // convert tx_data_get from 48 to clk + //wire tx_data_get_48 = tx_data_get; + reg tx_data_get_48; + strobe tx_data_get_strobe(clk_48mhz, clk, tx_data_get_48, tx_data_get); reg [7:0] data_shift_reg = 0; reg [7:0] oe_shift_reg = 0; @@ -58,14 +63,15 @@ module usb_fs_tx ( reg bitstuff_qqqq = 0; - always @(posedge clk) begin + always @(posedge clk_48mhz) begin bitstuff_q <= bitstuff; bitstuff_qq <= bitstuff_q; bitstuff_qqq <= bitstuff_qq; bitstuff_qqqq <= bitstuff_qqq; end - assign pkt_end = bit_strobe && se0_shift_reg[1:0] == 2'b01; + wire pkt_end_48 = bit_strobe && se0_shift_reg[1:0] == 2'b01; + strobe pkt_end_strobe(clk_48mhz, pkt_end_48, clk, pkt_end); reg data_payload = 0; @@ -79,10 +85,10 @@ module usb_fs_tx ( reg [15:0] crc16 = 0; - always @(posedge clk) begin + always @(posedge clk_48mhz) begin case (pkt_state) IDLE : begin - if (pkt_start) begin + if (pkt_start_48) begin pkt_state <= SYNC; end end @@ -115,20 +121,20 @@ module usb_fs_tx ( if (tx_data_avail) begin pkt_state <= DATA_OR_CRC16_0; data_payload <= 1; - tx_data_get <= 1; + tx_data_get_48 <= 1; data_shift_reg <= tx_data; oe_shift_reg <= 8'b11111111; se0_shift_reg <= 8'b00000000; end else begin pkt_state <= CRC16_1; data_payload <= 0; - tx_data_get <= 0; + tx_data_get_48 <= 0; data_shift_reg <= ~{crc16[8], crc16[9], crc16[10], crc16[11], crc16[12], crc16[13], crc16[14], crc16[15]}; oe_shift_reg <= 8'b11111111; se0_shift_reg <= 8'b00000000; end end else begin - tx_data_get <= 0; + tx_data_get_48 <= 0; end end @@ -156,7 +162,7 @@ module usb_fs_tx ( byte_strobe <= 0; end - if (pkt_start) begin + if (pkt_start_48) begin bit_count <= 1; bit_history_q <= 0; @@ -184,12 +190,12 @@ module usb_fs_tx ( // calculate crc16 wire crc16_invert = serial_tx_data ^ crc16[15]; - always @(posedge clk) begin - if (pkt_start) begin + always @(posedge clk_48mhz) begin + if (pkt_start_48) begin crc16 <= 16'b1111111111111111; end - if (bit_strobe && data_payload && !bitstuff_qqqq && !pkt_start) begin + if (bit_strobe && data_payload && !bitstuff_qqqq && !pkt_start_48) begin crc16[15] <= crc16[14] ^ crc16_invert; crc16[14] <= crc16[13]; crc16[13] <= crc16[12]; @@ -213,8 +219,8 @@ module usb_fs_tx ( // nrzi and differential driving - always @(posedge clk) begin - if (pkt_start) begin + always @(posedge clk_48mhz) begin + if (pkt_start_48) begin // J dp <= 1; dn <= 0; From ea370fe93b1b084de733d8c54ec911da6cbc6566 Mon Sep 17 00:00:00 2001 From: Trammell hudson Date: Fri, 18 Jan 2019 14:25:23 -0500 Subject: [PATCH 26/31] usb_fs_rx: Document clock domains --- common/usb_fs_rx.v | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/common/usb_fs_rx.v b/common/usb_fs_rx.v index 19ea976..652c367 100644 --- a/common/usb_fs_rx.v +++ b/common/usb_fs_rx.v @@ -8,26 +8,26 @@ module usb_fs_rx ( input dp, input dn, - // pulse on every bit transition in clk_48mhz + // pulse on every bit transition (clk_48mhz domain) output bit_strobe, - // Pulse on beginning of new packet in clk. + // Pulse on beginning of new packet (clk domain) output pkt_start, - // Pulse on end of current packet in clk. + // Pulse on end of current packet (clk domain) output pkt_end, - // Most recent packet decoded. + // Most recent packet decoded (clk domain) output [3:0] pid, output [6:0] addr, output [3:0] endp, output [10:0] frame_num, - // Pulse on valid data on rx_data in clk. + // Pulse on valid data on rx_data (clk domain) output rx_data_put, output [7:0] rx_data, - // Most recent packet passes PID and CRC checks + // Most recent packet passes PID and CRC checks (clk domain) output valid_packet ); wire [3:0] pid_48; @@ -312,12 +312,13 @@ module usb_fs_rx ( // TODO: need to check for data packet babble // TODO: do i need to check for bitstuff error? - assign valid_packet = pid_valid && ( + wire valid_packet_48 = pid_valid && ( (pkt_is_handshake) || (pkt_is_data && crc16_valid) || (pkt_is_token && crc5_valid) ); + strobe valid_packet_strobe(clk_48mhz, clk, valid_packet_48, valid_packet); reg [11:0] token_payload = 0; wire token_payload_done = token_payload[0]; @@ -368,8 +369,14 @@ module usb_fs_rx ( //assign rx_data_put = dvalid && pid_complete && pkt_is_data; reg [8:0] rx_data_buffer = 0; wire rx_data_buffer_full = rx_data_buffer[0]; - assign rx_data_put = rx_data_buffer_full; - assign rx_data = rx_data_buffer[8:1]; + //assign rx_data_put = rx_data_buffer_full; + //assign rx_data = rx_data_buffer[8:1]; + + strobe #(.WIDTH(8)) rx_data_put_strobe( + clk_48mhz, clk, + rx_data_buffer_full, rx_data_put, + rx_data_buffer[8:1], rx_data + ); always @(posedge clk_48mhz) begin if (packet_start || rx_data_buffer_full) begin From e44d6d25d3ee38f6aa6896bc9326bf8c6778b5b5 Mon Sep 17 00:00:00 2001 From: Trammell hudson Date: Fri, 18 Jan 2019 16:51:25 -0500 Subject: [PATCH 27/31] Clock crossing success - endpoint runs at 12 Mhz --- boards/TinyFPGA_BX/Makefile | 6 ++- boards/TinyFPGA_BX/bootloader.v | 66 ++++++++++++++++++++++++++++----- boards/TinyFPGA_BX/pins.pcf | 12 +++--- common/strobe.v | 29 +++++++++++++-- common/tinyfpga_bootloader.v | 8 +++- common/usb_fs_out_pe.v | 8 +++- common/usb_fs_pe.v | 12 ++++-- common/usb_fs_rx.v | 26 ++++++++----- common/usb_fs_tx.v | 10 ++++- 9 files changed, 137 insertions(+), 40 deletions(-) diff --git a/boards/TinyFPGA_BX/Makefile b/boards/TinyFPGA_BX/Makefile index 6ea0de9..b325935 100644 --- a/boards/TinyFPGA_BX/Makefile +++ b/boards/TinyFPGA_BX/Makefile @@ -22,11 +22,15 @@ PKG = cm81 all: $(PROJ).rpt fw.bin +%.json: %.v ../../common/*.v + yosys -q -p 'synth_ice40 -top $(PROJ) -json $@' $^ %.blif: %.v ../../common/*.v - yosys -p 'synth_ice40 -top $(PROJ) -blif $@' $^ + yosys -q -p 'synth_ice40 -top $(PROJ) -blif $@' $^ %.asc: $(PIN_DEF) %.blif arachne-pnr -d 8k -P $(PKG) -o $@ -p $^ +no-%.asc: $(PIN_DEF) %.json + nextpnr-ice40 -d 8k -P $(PKG) -o $@ -p $^ %.bin: %.asc icepack $< $@ diff --git a/boards/TinyFPGA_BX/bootloader.v b/boards/TinyFPGA_BX/bootloader.v index 114aec0..6307584 100644 --- a/boards/TinyFPGA_BX/bootloader.v +++ b/boards/TinyFPGA_BX/bootloader.v @@ -16,9 +16,14 @@ module bootloader ( output pin_31_mosi, output pin_32_sck, - output pin_8 // uart + output pin_2, // debug + output pin_3, // debug + output pin_4, // debug + output pin_5, // debug + output pin_9 // uart ); - wire serial_tx = pin_8; + wire serial_tx = pin_9; + wire [3:0] debug = { pin_5, pin_4, pin_3, pin_2 }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// @@ -60,10 +65,18 @@ module bootloader ( ); reg clk_24mhz; - reg clk_12mhz; always @(posedge clk_48mhz) clk_24mhz = !clk_24mhz; + + reg clk_12mhz; always @(posedge clk_24mhz) clk_12mhz = !clk_12mhz; - wire clk = !clk_48mhz; + + wire clk = clk_12mhz; // half speed clock + //wire clk = !clk_48mhz; // invert the clock for testing + + // generate a 3 MHz clock for the baud rate + wire clk_1; + divide_by_n #(.N(16)) div48(clk_48mhz, reset, clk_1); + //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// @@ -176,23 +189,43 @@ module bootloader ( end end `endif + reg hello_done; + reg hello_strobe; + reg [63:0] hello_msg = "\n\r!OLLEH"; + reg [3:0] hello_counter; + reg [7:0] hello_data; + always @(posedge clk) begin + hello_strobe <= 0; + + if (reset) begin + hello_counter <= 0; + hello_done <= 0; + end else + if (hello_counter == 8) + hello_done <= 1; + else + if (!hello_strobe) begin + hello_data <= hello_msg[hello_counter*8+7:hello_counter*8]; + hello_counter <= hello_counter + 1; + hello_strobe <= 1; + end + end + reg uart_strobe; reg [7:0] uart_data; wire uart_ready; - wire clk_1; - divide_by_n #(.N(16)) div48(clk_48mhz, reset, clk_1); - uart_tx_fifo uart_tx( .clk(clk), .reset(reset), .baud_x1(clk_1), - .data(uart_data), - .data_strobe(uart_strobe), + .data(hello_done ? uart_data : hello_data), + .data_strobe(hello_done ? uart_strobe : hello_strobe), .serial(serial_tx) ); + /* reg [FIFO_WIDTH-1:0] hexdata; reg [7:0] len; @@ -270,7 +303,8 @@ module bootloader ( .usb_p_rx(usb_p_rx), .usb_n_rx(usb_n_rx), .usb_tx_en(usb_tx_en), - .led(pin_led), + //.led(pin_5), + .debug(debug), .spi_miso(pin_29_miso), .spi_cs(pin_30_cs), .spi_mosi(pin_31_mosi), @@ -284,4 +318,16 @@ module bootloader ( assign usb_p_rx = usb_tx_en ? 1'b1 : pin_usbp; assign usb_n_rx = usb_tx_en ? 1'b0 : pin_usbn; + + // our own counter pattern for now + reg [5:0] pattern = 5'b10100; + reg [22:0] counter; + assign pin_led = pattern[0]; + + always @(posedge clk) begin + counter <= counter + 1; + if (counter == 0) + pattern <= { pattern[0], pattern[5:1] }; + end + endmodule diff --git a/boards/TinyFPGA_BX/pins.pcf b/boards/TinyFPGA_BX/pins.pcf index 913676c..2736b3a 100644 --- a/boards/TinyFPGA_BX/pins.pcf +++ b/boards/TinyFPGA_BX/pins.pcf @@ -3,15 +3,15 @@ # Package: CM81 ############################################################################### -#set_io pin_1 A2 -#set_io pin_2 A1 -#set_io pin_3 B1 -#set_io pin_4 C2 -#set_io pin_5 C1 +set_io -nowarn pin_1 A2 +set_io -nowarn pin_2 A1 +set_io -nowarn pin_3 B1 +set_io -nowarn pin_4 C2 +set_io -nowarn pin_5 C1 set_io -nowarn pin_6 D2 #set_io pin_7 D1 set_io -nowarn pin_8 E2 -#set_io pin_9 E1 +set_io -nowarn pin_9 E1 #set_io pin_10 G2 #set_io pin_11 H1 #set_io pin_12 J1 diff --git a/common/strobe.v b/common/strobe.v index 2ec4bbb..2791ad9 100644 --- a/common/strobe.v +++ b/common/strobe.v @@ -7,26 +7,47 @@ module strobe( output [WIDTH-1:0] data_out ); parameter WIDTH = 1; + parameter DELAY = 2; // 2 for metastability, larger for testing + `define CLOCK_CROSS `ifdef CLOCK_CROSS reg flag; - reg [2:0] sync; + reg prev_strobe; + reg [DELAY:0] sync; reg [WIDTH-1:0] data; + // flip the flag and clock in the data when strobe is high always @(posedge clk_in) begin + //if ((strobe_in && !prev_strobe) + //|| (!strobe_in && prev_strobe)) flag <= flag ^ strobe_in; + if (strobe_in) data <= data_in; + + prev_strobe <= strobe_in; end + // shift through a chain of flipflop to ensure stability always @(posedge clk_out) - sync <= { sync[1:0], flag }; + sync <= { sync[DELAY-1:0], flag }; - assign strobe_out = sync[1] ^ sync[0]; + assign strobe_out = sync[DELAY] ^ sync[DELAY-1]; assign data_out = data; - //assign data_out = data_in; `else assign strobe_out = strobe_in; assign data_out = data_in; `endif endmodule + + +module dflip( + input clk, + input in, + output out +); + reg [2:0] d; + always @(posedge clk) + d <= { d[1:0], in }; + assign out = d[2]; +endmodule diff --git a/common/tinyfpga_bootloader.v b/common/tinyfpga_bootloader.v index 155327e..033d896 100644 --- a/common/tinyfpga_bootloader.v +++ b/common/tinyfpga_bootloader.v @@ -19,6 +19,9 @@ module tinyfpga_bootloader ( // bootloader indicator light, pulses on and off when bootloader is active output led, + // debug connection for oscilloscope debugging + output [3:0] debug, + // connection to SPI flash output spi_cs, output spi_sck, @@ -80,7 +83,7 @@ module tinyfpga_bootloader ( end end always @(posedge clk) pwm_cnt <= pwm_cnt + 1'b1; - assign led = led_pwm > pwm_cnt; + //assign led = led_pwm > pwm_cnt; @@ -214,6 +217,7 @@ module tinyfpga_bootloader ( .reset(reset), .uart_strobe(uart_strobe), .uart_data(uart_data), + .debug(debug), .usb_p_tx(usb_p_tx), .usb_n_tx(usb_n_tx), @@ -266,4 +270,4 @@ module tinyfpga_bootloader ( host_presence_timeout <= 1; end end -endmodule \ No newline at end of file +endmodule diff --git a/common/usb_fs_out_pe.v b/common/usb_fs_out_pe.v index 012e66b..715fba0 100644 --- a/common/usb_fs_out_pe.v +++ b/common/usb_fs_out_pe.v @@ -356,6 +356,10 @@ module usb_fs_out_pe #( integer j; always @(posedge clk) begin uart_strobe <= 0; + if (rx_pkt_start && !uart_strobe) begin + uart_strobe <= 1; + uart_data <= "R"; + end if (reset) begin out_xfr_state <= IDLE; @@ -363,7 +367,7 @@ module usb_fs_out_pe #( out_xfr_state <= out_xfr_state_next; if (out_xfr_state != out_xfr_state_next) begin uart_strobe <= 1; - uart_data <= out_xfr_state_next + "A"; + uart_data <= out_xfr_state_next + "0"; if (out_xfr_state == RCVD_DATA_END) uart_data <= "0" + tx_pid; end @@ -418,4 +422,4 @@ module usb_fs_out_pe #( end end -endmodule \ No newline at end of file +endmodule diff --git a/common/usb_fs_pe.v b/common/usb_fs_pe.v index 924bdff..c330995 100644 --- a/common/usb_fs_pe.v +++ b/common/usb_fs_pe.v @@ -7,6 +7,7 @@ module usb_fs_pe #( input [6:0] dev_addr, output uart_strobe, output [7:0] uart_data, + output [3:0] debug, //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// @@ -70,6 +71,8 @@ module usb_fs_pe #( // in pe interface wire [7:0] arb_in_ep_data; +assign debug[3] = usb_tx_en; + // rx interface wire bit_strobe; wire rx_pkt_start; @@ -125,8 +128,8 @@ module usb_fs_pe #( .NUM_IN_EPS(NUM_IN_EPS) ) usb_fs_in_pe_inst ( .clk(clk), - //.uart_strobe(uart_strobe), - //.uart_data(uart_data), + .uart_strobe(uart_strobe), + .uart_data(uart_data), .reset(reset), .reset_ep({NUM_IN_EPS{1'b0}}), .dev_addr(dev_addr), @@ -163,8 +166,8 @@ module usb_fs_pe #( .clk(clk), .reset(reset), .reset_ep({NUM_OUT_EPS{1'b0}}), - .uart_strobe(uart_strobe), - .uart_data(uart_data), + //.uart_strobe(uart_strobe), + //.uart_data(uart_data), .dev_addr(dev_addr), // endpoint interface @@ -196,6 +199,7 @@ module usb_fs_pe #( .clk_48mhz(clk_48mhz), .clk(clk), .reset(reset), + .debug(debug), .dp(usb_p_rx), .dn(usb_n_rx), .bit_strobe(bit_strobe), diff --git a/common/usb_fs_rx.v b/common/usb_fs_rx.v index 652c367..74e0c61 100644 --- a/common/usb_fs_rx.v +++ b/common/usb_fs_rx.v @@ -3,8 +3,9 @@ module usb_fs_rx ( input clk_48mhz, input clk, input reset, + output [3:0] debug, - // USB data+ and data- lines. + // USB data+ and data- lines (clk_48mhz domain) input dp, input dn, @@ -318,7 +319,8 @@ module usb_fs_rx ( (pkt_is_token && crc5_valid) ); - strobe valid_packet_strobe(clk_48mhz, clk, valid_packet_48, valid_packet); + // valid is level, not a strobe + dflip valid_buffer(clk, valid_packet_48, valid_packet); reg [11:0] token_payload = 0; wire token_payload_done = token_payload[0]; @@ -344,20 +346,24 @@ module usb_fs_rx ( //assign pkt_start = packet_start; //assign pkt_end = packet_end; strobe pkt_start_strobe(clk_48mhz, clk, packet_start, pkt_start); + assign debug[0] = valid_packet_48; + assign debug[1] = valid_packet; + assign debug[2] = din; + //assign debug[3] = bit_strobe; // at the end of the packet, capture the parameters strobe #(.WIDTH(26)) pkt_end_strobe( clk_48mhz, clk, packet_end, pkt_end, - //{ pid_48, addr_48, endp_48, frame_num_48 }, - //{ pid, addr, endp, frame_num }, + { pid_48, addr_48, endp_48, frame_num_48 }, + { pid, addr, endp, frame_num }, ); assign pid_48 = full_pid[4:1]; - assign pid = pid_48; - assign addr = addr_48; - assign endp = endp_48; - assign frame_num = frame_num_48; + //assign pid = pid_48; + //assign addr = addr_48; + //assign endp = endp_48; + //assign frame_num = frame_num_48; //assign addr = token_payload[7:1]; //assign endp = token_payload[11:8]; @@ -372,7 +378,9 @@ module usb_fs_rx ( //assign rx_data_put = rx_data_buffer_full; //assign rx_data = rx_data_buffer[8:1]; - strobe #(.WIDTH(8)) rx_data_put_strobe( + // convert the rx_data_put to clk domain + //dflip rx_data_put_flop(clk, rx_data_buffer_full, rx_data_put); + strobe #(.WIDTH(8)) rx_data_strobe( clk_48mhz, clk, rx_data_buffer_full, rx_data_put, rx_data_buffer[8:1], rx_data diff --git a/common/usb_fs_tx.v b/common/usb_fs_tx.v index a9ae0d9..723f318 100644 --- a/common/usb_fs_tx.v +++ b/common/usb_fs_tx.v @@ -13,8 +13,10 @@ module usb_fs_tx ( output reg dp = 0, output reg dn = 0, - // pulse to initiate new packet transmission in clk domain + // pulse to initiate new packet transmission (clk domain) input pkt_start, + + // pulse to indicate end of packet transmission (clk domain) output pkt_end, // pid to send (clk domain) @@ -35,6 +37,10 @@ module usb_fs_tx ( pid, pidq ); + wire tx_data_avail_48; + dflip tx_data_avail_buffer(clk_48mhz, tx_data_avail, tx_data_avail_48); + //wire tx_data_avail_48 = tx_data_avail; + // convert tx_data_get from 48 to clk //wire tx_data_get_48 = tx_data_get; reg tx_data_get_48; @@ -118,7 +124,7 @@ module usb_fs_tx ( DATA_OR_CRC16_0 : begin if (byte_strobe) begin - if (tx_data_avail) begin + if (tx_data_avail_48) begin pkt_state <= DATA_OR_CRC16_0; data_payload <= 1; tx_data_get_48 <= 1; From 324eae5fa76006aa5381a081f7982a214001e3c3 Mon Sep 17 00:00:00 2001 From: Trammell hudson Date: Fri, 18 Jan 2019 16:58:26 -0500 Subject: [PATCH 28/31] Clock crossing: cleanup uart debugging code --- boards/TinyFPGA_BX/bootloader.v | 221 +------------------------------- common/tinyfpga_bootloader.v | 12 +- common/usb_fs_in_pe.v | 8 -- common/usb_fs_out_pe.v | 14 -- common/usb_fs_pe.v | 10 -- common/usb_fs_rx.v | 18 +-- 6 files changed, 4 insertions(+), 279 deletions(-) diff --git a/boards/TinyFPGA_BX/bootloader.v b/boards/TinyFPGA_BX/bootloader.v index 6307584..61917c0 100644 --- a/boards/TinyFPGA_BX/bootloader.v +++ b/boards/TinyFPGA_BX/bootloader.v @@ -1,7 +1,3 @@ -`include "util.v" -`include "fifo.v" -`include "uart.v" - module bootloader ( input pin_clk, @@ -15,16 +11,7 @@ module bootloader ( output pin_30_cs, output pin_31_mosi, output pin_32_sck, - - output pin_2, // debug - output pin_3, // debug - output pin_4, // debug - output pin_5, // debug - output pin_9 // uart ); - wire serial_tx = pin_9; - wire [3:0] debug = { pin_5, pin_4, pin_3, pin_2 }; - //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////// @@ -71,12 +58,6 @@ module bootloader ( always @(posedge clk_24mhz) clk_12mhz = !clk_12mhz; wire clk = clk_12mhz; // half speed clock - //wire clk = !clk_48mhz; // invert the clock for testing - - // generate a 3 MHz clock for the baud rate - wire clk_1; - divide_by_n #(.N(16)) div48(clk_48mhz, reset, clk_1); - //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// @@ -107,204 +88,16 @@ module bootloader ( wire usb_n_rx; wire usb_tx_en; -`ifdef NONONO - - wire bit_strobe; - wire pkt_start; - wire pkt_start; - wire pkt_end; - wire [3:0] pid; - wire [6:0] addr; - wire [3:0] endp; - wire [10:0] frame_num; - wire rx_data_put; - wire [7:0] rx_data; - wire valid_packet; - - usb_fs_rx usb( - .clk_48mhz(clk_48mhz), - .clk(clk), - .reset(reset), - .dp(usb_p_rx), - .dn(usb_n_rx), - .bit_strobe(bit_strobe), - .pkt_start(pkt_start), - .pkt_end(pkt_end), - .pid(pid), - .addr(addr), - .endp(endp), - .frame_num(frame_num), - .rx_data_put(rx_data_put), - .rx_data(rx_data), - .valid_packet(valid_packet) - ); - - assign usb_tx_en = 0; - - parameter FIFO_WIDTH = 24; - reg [FIFO_WIDTH-1:0] fifo_write_data; - reg fifo_write_strobe; - wire [FIFO_WIDTH-1:0] fifo_read_data; - reg fifo_read_strobe; - wire fifo_data_available; - - fifo_bram #(.WIDTH(FIFO_WIDTH)) uart_fifo( - .reset(reset), - .write_clk(clk), - .write_strobe(fifo_write_strobe), - .write_data(fifo_write_data), - .read_clk(clk), - .read_strobe(fifo_read_strobe), - .read_data(fifo_read_data), - .data_available(fifo_data_available) - ); - - always @(posedge clk) - begin - fifo_write_strobe <= 0; - - if (pkt_start) begin - fifo_write_strobe <= 1; - fifo_write_data <= { - 4'hA, - 20'b0, - }; - end else - if (rx_data_put) begin - fifo_write_strobe <= 1; - fifo_write_data <= { - pkt_start ? 4'hA : 4'hB, // 4 - 12'b0, // 12 - rx_data // 8 - }; - end else - if (pkt_end) begin - fifo_write_strobe <= 1; - fifo_write_data <= { - valid_packet ? 4'hC : 4'hF, - pid, // 4 - 1'b0, addr, // 1 + 7 - frame_num[7:0] // 8 - }; - end - end -`endif - reg hello_done; - reg hello_strobe; - reg [63:0] hello_msg = "\n\r!OLLEH"; - reg [3:0] hello_counter; - reg [7:0] hello_data; - always @(posedge clk) begin - hello_strobe <= 0; - - if (reset) begin - hello_counter <= 0; - hello_done <= 0; - end else - if (hello_counter == 8) - hello_done <= 1; - else - if (!hello_strobe) begin - hello_data <= hello_msg[hello_counter*8+7:hello_counter*8]; - hello_counter <= hello_counter + 1; - hello_strobe <= 1; - end - end - - - reg uart_strobe; - reg [7:0] uart_data; - wire uart_ready; - - uart_tx_fifo uart_tx( - .clk(clk), - .reset(reset), - .baud_x1(clk_1), - .data(hello_done ? uart_data : hello_data), - .data_strobe(hello_done ? uart_strobe : hello_strobe), - .serial(serial_tx) - ); - - -/* - reg [FIFO_WIDTH-1:0] hexdata; - reg [7:0] len; - reg [12:0] counter; - - always @(posedge clk) - begin - uart_strobe <= 0; - fifo_read_strobe <= 0; - counter <= counter + 1; - pin_led <= 0; - - if (!uart_ready - || uart_strobe - || counter != 0 - ) begin - // nothing - end else - begin - uart_data <= "A"; - uart_strobe <= 1; - pin_led <= 1; - end - end -*/ -/* - always @(posedge clk) - begin - uart_strobe <= 0; - fifo_read_strobe <= 0; - counter <= counter + 1; - pin_led <= 0; - - if (len == 0 - && fifo_data_available - && !fifo_read_strobe) begin - len <= 8; - hexdata <= fifo_read_data; - fifo_read_strobe <= 1; - pin_led <= 1; - end else - if (!uart_ready - || uart_strobe - || counter != 0 - ) begin - // nothing - end else - if (len == 1) begin - uart_data <= "\n"; - uart_strobe <= 1; - len <= 0; - end else - if (len == 2) begin - uart_data <= "\r"; - uart_strobe <= 1; - len <= 1; - end else - if (len != 0) begin - uart_data <= hexdigit(hexdata[FIFO_WIDTH-1:FIFO_WIDTH-4]); - uart_strobe <= 1; - hexdata <= { hexdata[FIFO_WIDTH-5:0], 4'b0 }; - len <= len - 1; - end - end -*/ - tinyfpga_bootloader tinyfpga_bootloader_inst ( .clk_48mhz(clk_48mhz), .clk(clk), .reset(reset), - .uart_data(uart_data), - .uart_strobe(uart_strobe), .usb_p_tx(usb_p_tx), .usb_n_tx(usb_n_tx), .usb_p_rx(usb_p_rx), .usb_n_rx(usb_n_rx), .usb_tx_en(usb_tx_en), - //.led(pin_5), - .debug(debug), + .led(pin_led), .spi_miso(pin_29_miso), .spi_cs(pin_30_cs), .spi_mosi(pin_31_mosi), @@ -318,16 +111,4 @@ module bootloader ( assign usb_p_rx = usb_tx_en ? 1'b1 : pin_usbp; assign usb_n_rx = usb_tx_en ? 1'b0 : pin_usbn; - - // our own counter pattern for now - reg [5:0] pattern = 5'b10100; - reg [22:0] counter; - assign pin_led = pattern[0]; - - always @(posedge clk) begin - counter <= counter + 1; - if (counter == 0) - pattern <= { pattern[0], pattern[5:1] }; - end - endmodule diff --git a/common/tinyfpga_bootloader.v b/common/tinyfpga_bootloader.v index 033d896..7b43ee3 100644 --- a/common/tinyfpga_bootloader.v +++ b/common/tinyfpga_bootloader.v @@ -3,9 +3,6 @@ module tinyfpga_bootloader ( input clk, input reset, - output uart_strobe, - output [7:0] uart_data, - // USB lines. Split into input vs. output and oe control signal to maintain // highest level of compatibility with synthesis tools. output usb_p_tx, @@ -19,9 +16,6 @@ module tinyfpga_bootloader ( // bootloader indicator light, pulses on and off when bootloader is active output led, - // debug connection for oscilloscope debugging - output [3:0] debug, - // connection to SPI flash output spi_cs, output spi_sck, @@ -83,8 +77,7 @@ module tinyfpga_bootloader ( end end always @(posedge clk) pwm_cnt <= pwm_cnt + 1'b1; - //assign led = led_pwm > pwm_cnt; - + assign led = led_pwm > pwm_cnt; //////////////////////////////////////////////////////////////////////////////// @@ -215,9 +208,6 @@ module tinyfpga_bootloader ( .clk_48mhz(clk_48mhz), .clk(clk), .reset(reset), - .uart_strobe(uart_strobe), - .uart_data(uart_data), - .debug(debug), .usb_p_tx(usb_p_tx), .usb_n_tx(usb_n_tx), diff --git a/common/usb_fs_in_pe.v b/common/usb_fs_in_pe.v index 99b3b6c..4ce36a7 100644 --- a/common/usb_fs_in_pe.v +++ b/common/usb_fs_in_pe.v @@ -5,8 +5,6 @@ module usb_fs_in_pe #( ) ( input clk, input reset, - output uart_strobe, - output [7:0] uart_data, input [NUM_IN_EPS-1:0] reset_ep, input [6:0] dev_addr, @@ -355,17 +353,11 @@ module usb_fs_in_pe #( integer j; always @(posedge clk) begin - uart_strobe <= 0; - if (reset) begin in_xfr_state <= IDLE; end else begin in_xfr_state <= in_xfr_state_next; - if (in_xfr_state != in_xfr_state_next) begin - uart_strobe <= 1; - uart_data <= in_xfr_state_next + "A"; - end if (setup_token_received) begin data_toggle[rx_endp] <= 1; diff --git a/common/usb_fs_out_pe.v b/common/usb_fs_out_pe.v index 715fba0..dba7112 100644 --- a/common/usb_fs_out_pe.v +++ b/common/usb_fs_out_pe.v @@ -5,8 +5,6 @@ module usb_fs_out_pe #( ) ( input clk, input reset, - output uart_strobe, - output [7:0] uart_data, input [NUM_OUT_EPS-1:0] reset_ep, input [6:0] dev_addr, @@ -355,22 +353,10 @@ module usb_fs_out_pe #( integer j; always @(posedge clk) begin - uart_strobe <= 0; - if (rx_pkt_start && !uart_strobe) begin - uart_strobe <= 1; - uart_data <= "R"; - end - if (reset) begin out_xfr_state <= IDLE; end else begin out_xfr_state <= out_xfr_state_next; - if (out_xfr_state != out_xfr_state_next) begin - uart_strobe <= 1; - uart_data <= out_xfr_state_next + "0"; - if (out_xfr_state == RCVD_DATA_END) - uart_data <= "0" + tx_pid; - end if (out_xfr_start) begin current_endp <= rx_endp; diff --git a/common/usb_fs_pe.v b/common/usb_fs_pe.v index c330995..dee04c6 100644 --- a/common/usb_fs_pe.v +++ b/common/usb_fs_pe.v @@ -5,9 +5,6 @@ module usb_fs_pe #( input clk_48mhz, input clk, input [6:0] dev_addr, - output uart_strobe, - output [7:0] uart_data, - output [3:0] debug, //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// @@ -71,8 +68,6 @@ module usb_fs_pe #( // in pe interface wire [7:0] arb_in_ep_data; -assign debug[3] = usb_tx_en; - // rx interface wire bit_strobe; wire rx_pkt_start; @@ -128,8 +123,6 @@ assign debug[3] = usb_tx_en; .NUM_IN_EPS(NUM_IN_EPS) ) usb_fs_in_pe_inst ( .clk(clk), - .uart_strobe(uart_strobe), - .uart_data(uart_data), .reset(reset), .reset_ep({NUM_IN_EPS{1'b0}}), .dev_addr(dev_addr), @@ -166,8 +159,6 @@ assign debug[3] = usb_tx_en; .clk(clk), .reset(reset), .reset_ep({NUM_OUT_EPS{1'b0}}), - //.uart_strobe(uart_strobe), - //.uart_data(uart_data), .dev_addr(dev_addr), // endpoint interface @@ -199,7 +190,6 @@ assign debug[3] = usb_tx_en; .clk_48mhz(clk_48mhz), .clk(clk), .reset(reset), - .debug(debug), .dp(usb_p_rx), .dn(usb_n_rx), .bit_strobe(bit_strobe), diff --git a/common/usb_fs_rx.v b/common/usb_fs_rx.v index 74e0c61..fed9906 100644 --- a/common/usb_fs_rx.v +++ b/common/usb_fs_rx.v @@ -3,7 +3,6 @@ module usb_fs_rx ( input clk_48mhz, input clk, input reset, - output [3:0] debug, // USB data+ and data- lines (clk_48mhz domain) input dp, @@ -343,15 +342,10 @@ module usb_fs_rx ( end end - //assign pkt_start = packet_start; - //assign pkt_end = packet_end; + // cross the packet start signal to the endpoint clk domain strobe pkt_start_strobe(clk_48mhz, clk, packet_start, pkt_start); - assign debug[0] = valid_packet_48; - assign debug[1] = valid_packet; - assign debug[2] = din; - //assign debug[3] = bit_strobe; - // at the end of the packet, capture the parameters + // at the end of the packet, capture the parameters to the clk domain strobe #(.WIDTH(26)) pkt_end_strobe( clk_48mhz, clk, packet_end, pkt_end, @@ -360,11 +354,6 @@ module usb_fs_rx ( ); assign pid_48 = full_pid[4:1]; - //assign pid = pid_48; - //assign addr = addr_48; - //assign endp = endp_48; - //assign frame_num = frame_num_48; - //assign addr = token_payload[7:1]; //assign endp = token_payload[11:8]; //assign frame_num = token_payload[11:1]; @@ -375,11 +364,8 @@ module usb_fs_rx ( //assign rx_data_put = dvalid && pid_complete && pkt_is_data; reg [8:0] rx_data_buffer = 0; wire rx_data_buffer_full = rx_data_buffer[0]; - //assign rx_data_put = rx_data_buffer_full; - //assign rx_data = rx_data_buffer[8:1]; // convert the rx_data_put to clk domain - //dflip rx_data_put_flop(clk, rx_data_buffer_full, rx_data_put); strobe #(.WIDTH(8)) rx_data_strobe( clk_48mhz, clk, rx_data_buffer_full, rx_data_put, From 8a6bc3aca69f5f41a05010f763706823195df5f0 Mon Sep 17 00:00:00 2001 From: Trammell hudson Date: Fri, 18 Jan 2019 16:59:38 -0500 Subject: [PATCH 29/31] Clock crossing: cleanup uart debugging code and helpers --- boards/TinyFPGA_BX/fifo.v | 391 -------------------------------------- boards/TinyFPGA_BX/uart.v | 305 ----------------------------- boards/TinyFPGA_BX/util.v | 220 --------------------- 3 files changed, 916 deletions(-) delete mode 100644 boards/TinyFPGA_BX/fifo.v delete mode 100644 boards/TinyFPGA_BX/uart.v delete mode 100644 boards/TinyFPGA_BX/util.v diff --git a/boards/TinyFPGA_BX/fifo.v b/boards/TinyFPGA_BX/fifo.v deleted file mode 100644 index 304ad9a..0000000 --- a/boards/TinyFPGA_BX/fifo.v +++ /dev/null @@ -1,391 +0,0 @@ - -/** 256 Kb SPRAM, organized 16 K x 16 bits */ -module spram( - input clk, - input reset = 0, - input cs = 1, - input [DEPTH-1:0] addr, - input write_strobe, - input [15:0] write_data, - output [15:0] read_data -); - parameter DEPTH = 16; - - wire [15:0] read_data_0; - wire [15:0] read_data_1; - wire [15:0] read_data_2; - wire [15:0] read_data_3; - - wire cs0, cs1, cs2, cs3; -/* - generate if (DEPTH == 14) - assign cs0 = cs; - assign cs1 = 0; - assign cs2 = 0; - assign cs3 = 0; - endgenerate - generate if (DEPTH == 15) - assign cs0 = cs & addr[14] == 1'b0; - assign cs1 = cs & addr[14] == 1'b1; - assign cs2 = 0; - assign cs3 = 0; - endgenerate -*/ - generate if (DEPTH == 16) - assign cs0 = cs && addr[15:14] == 2'b00; - assign cs1 = cs && addr[15:14] == 2'b01; - assign cs2 = cs && addr[15:14] == 2'b10; - assign cs3 = cs && addr[15:14] == 2'b11; - endgenerate - - assign read_data = - cs0 ? read_data_0 : - cs1 ? read_data_1 : - cs2 ? read_data_2 : - read_data_3; - - SB_SPRAM256KA spram0( - .DATAOUT(read_data_0), - .ADDRESS(addr[13:0]), - .DATAIN(write_data), - .MASKWREN(4'b1111), - .WREN(write_strobe), - .CHIPSELECT(cs0 && !reset), - .CLOCK(clk), - - // if we cared about power, maybe we would adjust these - .STANDBY(1'b0), - .SLEEP(1'b0), - .POWEROFF(1'b1) - ); - - generate if (DEPTH > 14) - SB_SPRAM256KA spram1( - .DATAOUT(read_data_1), - .ADDRESS(addr[13:0]), - .DATAIN(write_data), - .MASKWREN(4'b1111), - .WREN(write_strobe), - .CHIPSELECT(cs1 && !reset), - .CLOCK(clk), - - // if we cared about power, maybe we would adjust these - .STANDBY(1'b0), - .SLEEP(1'b0), - .POWEROFF(1'b1) - ); - endgenerate - - generate if (DEPTH > 15) - - SB_SPRAM256KA spram2( - .DATAOUT(read_data_2), - .ADDRESS(addr[13:0]), - .DATAIN(write_data), - .MASKWREN(4'b1111), - .WREN(write_strobe), - .CHIPSELECT(cs2 && !reset), - .CLOCK(clk), - - // if we cared about power, maybe we would adjust these - .STANDBY(1'b0), - .SLEEP(1'b0), - .POWEROFF(1'b1) - ); - - SB_SPRAM256KA spram3( - .DATAOUT(read_data_3), - .ADDRESS(addr[13:0]), - .DATAIN(write_data), - .MASKWREN(4'b1111), - .WREN(write_strobe), - .CHIPSELECT(cs3 && !reset), - .CLOCK(clk), - - // if we cared about power, maybe we would adjust these - .STANDBY(1'b0), - .SLEEP(1'b0), - .POWEROFF(1'b1) - ); - endgenerate -endmodule - - -module fifo_spram( - input clk, - input reset, - input [WIDTH-1:0] write_data, - input write_strobe, - output [WIDTH-1:0] read_data, - input read_strobe, - output data_available -); - parameter WIDTH = 16; - parameter DEPTH = 16; // 14 == one SPRAM deep, 15 == two deep, 16 == four - reg [DEPTH-1:0] write_ptr = 0; - reg [DEPTH-1:0] read_ptr = 0; - assign data_available = read_ptr != write_ptr; - - spram #( - .DEPTH(DEPTH) - ) buf0( - .clk(clk), - .reset(reset), - .write_strobe(write_strobe), - .addr(write_strobe ? write_ptr : read_ptr), - .write_data(write_data[15:0]), - .read_data(read_data[15:0]), - ); - - generate if (WIDTH > 16) - spram #( - .DEPTH(DEPTH) - ) buf1( - .clk(clk), - .reset(reset), - .write_strobe(write_strobe), - .addr(write_strobe ? write_ptr : read_ptr), - .write_data(write_data[31:16]), - .read_data(read_data[31:16]), - ); - endgenerate - - generate if (WIDTH > 32) - spram #( - .DEPTH(DEPTH) - ) buf2( - .clk(clk), - .reset(reset), - .write_strobe(write_strobe), - .addr(write_strobe ? write_ptr : read_ptr), - .write_data(write_data[47:32]), - .read_data(read_data[47:32]), - ); - endgenerate - - generate if (WIDTH > 48) - spram #( - .DEPTH(DEPTH) - ) buf3( - .clk(clk), - .reset(reset), - .write_strobe(write_strobe), - .addr(write_strobe ? write_ptr : read_ptr), - .write_data(write_data[63:48]), - .read_data(read_data[63:48]), - ); - endgenerate - - always @(posedge clk) - begin - if (write_strobe) - write_ptr <= write_ptr + 1; - - if (read_strobe) - read_ptr <= read_ptr + 1; - end -endmodule - - - -module fifo_bram( - input reset, - input write_clk, - input write_strobe, - input [WIDTH-1:0] write_data, - input read_clk, - input read_strobe, - output [WIDTH-1:0] read_data, - output data_available -); - parameter WIDTH = 16; // one block RAM wide - parameter DEPTH = 8; // one block RAM deep - reg [DEPTH-1:0] read_ptr; - reg [DEPTH-1:0] write_ptr; - - reg [WIDTH-1:0] fifo[(1 << DEPTH)-1:0]; - - assign read_data = fifo[read_ptr]; - - reg data_available_0; - reg data_available_1; - //reg data_available; - assign data_available = read_ptr != write_ptr; - - always @(posedge read_clk) - begin - if (reset) - read_ptr <= 0; - else - if (read_strobe) - read_ptr <= read_ptr + 1; - - //data_available <= read_ptr != write_ptr; - //data_available <= data_available_0; - //data_available <= data_available_1; - end - - always @(posedge write_clk) - begin - if (reset) - write_ptr <= 0; - else - if (write_strobe) begin - fifo[write_ptr] <= write_data; - write_ptr <= write_ptr + 1; - end - end -endmodule - - -module fifo_combo( - input reset, - input write_clk, - input write_strobe, - input [WIDTH-1:0] write_data, - input read_clk, - input read_strobe, - output [WIDTH-1:0] read_data, - output data_available -); - parameter WIDTH = 16; - -`define NO_SPRAM -`ifdef NO_SPRAM - parameter DEPTH = 12; - // just wire it up - fifo_bram #( - .WIDTH(WIDTH), - .DEPTH(DEPTH) - ) fifo0( - .reset(reset), - .write_clk(write_clk), - .write_strobe(write_strobe), - .write_data(write_data), - .read_clk(read_clk), - .read_strobe(read_strobe), - .read_data(read_data), - .data_available(data_available) - ); -`else - parameter DEPTH = 16; - wire [WIDTH-1:0] fifo0_read_data; - reg fifo0_read_strobe; - wire fifo0_data_available; - reg fifo1_write_strobe; - - fifo_bram #( - .WIDTH(WIDTH), - ) fifo0( - .reset(reset), - .write_clk(write_clk), - .write_strobe(write_strobe), - .write_data(write_data), - .read_clk(read_clk), - .read_strobe(fifo0_read_strobe), - .read_data(fifo0_read_data), - .data_available(fifo0_data_available) - ); - - fifo_spram #( - .WIDTH(WIDTH), - .DEPTH(DEPTH) - ) fifo1( - .reset(reset), - .clk(read_clk), - //.write_data(32'hA55AB00F), - .write_data(fifo0_read_data), - .write_strobe(fifo1_write_strobe), - .read_data(read_data), - .read_strobe(read_strobe), - .data_available(data_available) - ); - - reg [3:0] counter; - - always @(posedge read_clk) begin - fifo0_read_strobe <= 0; - fifo1_write_strobe <= 0; - counter <= counter + 1; - - if (reset) begin - // nothing - end else - if (fifo0_data_available - && !fifo0_read_strobe - && !fifo1_write_strobe - && !read_strobe // don't move if the user is also moving - && counter == 0 - ) begin - // move data from fifo0 into fifo1 - fifo0_read_strobe <= 1; - fifo1_write_strobe <= 1; - end - end -`endif -endmodule - -module fifo_bram_16to8( - input read_clk, - input write_clk, - input reset, - output data_available, - input [16-1:0] write_data, - input write_strobe, - output [8-1:0] read_data, - input read_strobe -); - - reg [BITS-1:0] write_ptr; - reg [BITS-1:0] read_ptr; - - // reads from the SPRAM are 16-bits at a time, - // so we have to pick which byte of the word should be extracted -`undef BUFFER -`ifdef BUFFER - parameter BITS = 13; - reg [15:0] buffer[(1 << BITS)-1:0]; - wire [15:0] rdata_16 = buffer[read_ptr[BITS-1:1]]; -`else - parameter BITS = 8; - wire [15:0] rdata_16; -SB_RAM40_4K #(.READ_MODE(0), .WRITE_MODE(0)) ram256x16_inst ( -.RDATA(rdata_16[15:0]), -.RADDR({ 4'b0, read_ptr[BITS-1:1] }), -.RCLK(read_clk), -.RCLKE(!reset), -.RE(1), -.WADDR({ 4'b0, write_ptr[BITS-1:1] }), -.WCLK(write_clk), -.WCLKE(!reset), -.WDATA(write_data[15:0]), -.WE(write_strobe), -.MASK(16'h0) -); -`endif - assign data_available = read_ptr != write_ptr; - assign read_data = (!read_ptr[0]) ? rdata_16[15:8] : rdata_16[7:0]; - - always @(posedge read_clk) - begin - if (reset) begin - read_ptr <= 0; - end else - if (read_strobe) begin - read_ptr <= read_ptr + 1; - end - end - - always @(posedge write_clk) - begin - if (reset) begin - write_ptr <= 0; - end else - if (write_strobe) begin -`ifdef BUFFER - buffer[write_ptr[BITS-1:1]] <= write_data; -`endif - write_ptr <= write_ptr + 2; - end - end -endmodule diff --git a/boards/TinyFPGA_BX/uart.v b/boards/TinyFPGA_BX/uart.v deleted file mode 100644 index 39f1e12..0000000 --- a/boards/TinyFPGA_BX/uart.v +++ /dev/null @@ -1,305 +0,0 @@ - /* - * uart.v - High-speed serial support. Includes a baud generator, UART, - * and a simple RFC1662-inspired packet framing protocol. - * - * This module is designed a 3 Mbaud serial port. - * This is the highest data rate supported by - * the popular FT232 USB-to-serial chip. - * - * Copyright (C) 2009 Micah Dowty - * (C) 2018 Trammell Hudson - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -/* - * Byte transmitter, RS-232 8-N-1 - * - * Transmits on 'serial'. When 'ready' goes high, we can accept another byte. - * It should be supplied on 'data' with a pulse on 'data_strobe'. - */ - -module uart_tx( - input clk, - input reset, - input baud_x1, - output serial, - output reg ready, - input [7:0] data, - input data_strobe -); - - /* - * Left-to-right shift register. - * Loaded with data, start bit, and stop bit. - * - * The stop bit doubles as a flag to tell us whether data has been - * loaded; we initialize the whole shift register to zero on reset, - * and when the register goes zero again, it's ready for more data. - */ - reg [7+1+1:0] shiftreg; - - /* - * Serial output register. This is like an extension of the - * shift register, but we never load it separately. This gives - * us one bit period of latency to prepare the next byte. - * - * This register is inverted, so we can give it a reset value - * of zero and still keep the 'serial' output high when idle. - */ - reg serial_r; - assign serial = !serial_r; - - //assign ready = (shiftreg == 0); - - /* - * State machine - */ - - always @(posedge clk) - if (reset) begin - shiftreg <= 0; - serial_r <= 0; - end - else if (data_strobe) begin - shiftreg <= { - 1'b1, // stop bit - data, - 1'b0 // start bit (inverted) - }; - ready <= 0; - end - else if (baud_x1) begin - if (shiftreg == 0) - begin - /* Idle state is idle high, serial_r is inverted */ - serial_r <= 0; - ready <= 1; - end else - serial_r <= !shiftreg[0]; - // shift the output register down - shiftreg <= {1'b0, shiftreg[7+1+1:1]}; - end else - ready <= (shiftreg == 0); - -endmodule - - -/* - * Byte receiver, RS-232 8-N-1 - * - * Receives on 'serial'. When a properly framed byte is - * received, 'data_strobe' pulses while the byte is on 'data'. - * - * Error bytes are ignored. - */ - -module uart_rx(clk, reset, baud_x4, - serial, data, data_strobe); - - input clk, reset, baud_x4, serial; - output [7:0] data; - output data_strobe; - - /* - * Synchronize the serial input to this clock domain - */ - wire serial_sync; - d_flipflop_pair input_dff(clk, reset, serial, serial_sync); - - /* - * State machine: Four clocks per bit, 10 total bits. - */ - reg [8:0] shiftreg; - reg [5:0] state; - reg data_strobe; - wire [3:0] bit_count = state[5:2]; - wire [1:0] bit_phase = state[1:0]; - - wire sampling_phase = (bit_phase == 1); - wire start_bit = (bit_count == 0 && sampling_phase); - wire stop_bit = (bit_count == 9 && sampling_phase); - - wire waiting_for_start = (state == 0 && serial_sync == 1); - - wire error = ( (start_bit && serial_sync == 1) || - (stop_bit && serial_sync == 0) ); - - assign data = shiftreg[7:0]; - - always @(posedge clk or posedge reset) - if (reset) begin - state <= 0; - data_strobe <= 0; - end - else if (baud_x4) begin - - if (waiting_for_start || error || stop_bit) - state <= 0; - else - state <= state + 1; - - if (bit_phase == 1) - shiftreg <= { serial_sync, shiftreg[8:1] }; - - data_strobe <= stop_bit && !error; - - end - else begin - data_strobe <= 0; - end - -endmodule - - -/* - * Output UART with a SPRAM RAM FIFO queue. - * - * Add bytes to the queue and they will be printed when the line is idle. - */ -module uart_tx_fifo( - input clk, - input reset, - input baud_x1, - input [7:0] data, - input data_strobe, - output serial -); - parameter NUM = 32; - - wire uart_txd_ready; // high the UART is ready to take a new byte - reg uart_txd_strobe; // pulse when we have a new byte to transmit - reg [7:0] uart_txd; - - uart_tx txd( - .clk(clk), - .reset(reset), - .baud_x1(baud_x1), - .serial(serial), - .ready(uart_txd_ready), - .data(uart_txd), - .data_strobe(uart_txd_strobe) - ); - - wire fifo_available; - wire fifo_read_strobe; - wire [7:0] fifo_read_data; - - fifo_bram #(.WIDTH(8)) buffer( - .read_clk(clk), - .write_clk(clk), - .reset(reset), - .write_data(data), - .write_strobe(data_strobe), - .data_available(fifo_available), - .read_data(fifo_read_data), - .read_strobe(fifo_read_strobe) - ); - - // drain the fifo into the serial port - reg [3:0] counter; - always @(posedge clk) - begin - uart_txd_strobe <= 0; - fifo_read_strobe <= 0; - counter <= counter + 1; - - if (fifo_available - && uart_txd_ready - && !data_strobe // only single port port RAM - && !uart_txd_strobe // don't TX twice on one byte - && counter == 0 - ) begin - fifo_read_strobe <= 1; - uart_txd_strobe <= 1; - uart_txd <= fifo_read_data; - end - end -endmodule - - -module uart_tx_hexdump( - input clk, - input reset = 0, - input strobe, - input [31:0] data, - input [3:0] len, - input space, - input newline, - output ready, - input uart_txd_ready, - output uart_txd_strobe, - output [7:0] uart_txd -); - reg [3:0] digits; - reg [31:0] bytes; - reg [7:0] uart_txd; - reg in_progress = 0; - reg [8:0] counter; - - assign ready = !in_progress; - - always @(posedge clk) - begin - uart_txd_strobe <= 0; - - if (reset) begin - // nothing to do - in_progress <= 0; - end else - if (strobe) begin - digits <= len; - bytes <= data; - in_progress <= 1; - end else - if (uart_txd_strobe - || !uart_txd_ready - || !in_progress - || counter != 0 - ) begin - // nothing to do until uart is ready - // or we're in progress with an output - counter <= counter + 1; - end else - if (digits != 0) - begin - // time to generate a hex value! - uart_txd_strobe <= 1; - uart_txd <= hexdigit(bytes[31:28]); - - bytes <= { bytes[27:0], 4'b0 }; - digits <= digits - 1; - end else - begin - // after all the digits, output any whitespace - if (space) begin - uart_txd_strobe <= 1; - uart_txd <= " "; - end else - if (newline) begin - uart_txd_strobe <= 1; - uart_txd <= "\n"; - end - - in_progress <= 0; - counter <= 0; - end - end -endmodule diff --git a/boards/TinyFPGA_BX/util.v b/boards/TinyFPGA_BX/util.v deleted file mode 100644 index ec69fc7..0000000 --- a/boards/TinyFPGA_BX/util.v +++ /dev/null @@ -1,220 +0,0 @@ -/** \file - * Utility modules. - */ - -`define CLOG2(x) \ - x <= 2 ? 1 : \ - x <= 4 ? 2 : \ - x <= 8 ? 3 : \ - x <= 16 ? 4 : \ - x <= 32 ? 5 : \ - x <= 64 ? 6 : \ - x <= 128 ? 7 : \ - x <= 256 ? 8 : \ - x <= 512 ? 9 : \ - x <= 1024 ? 10 : \ - x <= 2048 ? 11 : \ - x <= 4096 ? 12 : \ - x <= 8192 ? 13 : \ - x <= 16384 ? 14 : \ - x <= 32768 ? 15 : \ - x <= 65536 ? 16 : \ - -1 - -function [7:0] hexdigit; - input [3:0] x; - begin - hexdigit = - x == 0 ? "0" : - x == 1 ? "1" : - x == 2 ? "2" : - x == 3 ? "3" : - x == 4 ? "4" : - x == 5 ? "5" : - x == 6 ? "6" : - x == 7 ? "7" : - x == 8 ? "8" : - x == 9 ? "9" : - x == 10 ? "a" : - x == 11 ? "b" : - x == 12 ? "c" : - x == 13 ? "d" : - x == 14 ? "e" : - x == 15 ? "f" : - "?"; - end -endfunction - -module divide_by_n( - input clk, - input reset, - output reg out -); - parameter N = 2; - - reg [`CLOG2(N)-1:0] counter; - - always @(posedge clk) - begin - out <= 0; - - if (reset) - counter <= 0; - else - if (counter == 0) - begin - out <= 1; - counter <= N - 1; - end else - counter <= counter - 1; - end -endmodule - - -module fifo( - input clk, - input reset, - output data_available, - input [WIDTH-1:0] write_data, - input write_strobe, - output [WIDTH-1:0] read_data, - input read_strobe -); - parameter WIDTH = 8; - parameter NUM = 256; - - reg [WIDTH-1:0] buffer[0:NUM-1]; - reg [`CLOG2(NUM)-1:0] write_ptr; - reg [`CLOG2(NUM)-1:0] read_ptr; - - assign read_data = buffer[read_ptr]; - assign data_available = read_ptr != write_ptr; - - always @(posedge clk) begin - if (reset) begin - write_ptr <= 0; - read_ptr <= 0; - end else begin - if (write_strobe) begin - buffer[write_ptr] <= write_data; - write_ptr <= write_ptr + 1; - end - if (read_strobe) begin - read_ptr <= read_ptr + 1; - end - end - end -endmodule - - -module pwm( - input clk, - input [BITS-1:0] bright, - output out -); - parameter BITS = 8; - - reg [BITS-1:0] counter; - always @(posedge clk) - begin - counter <= counter + 1; - out <= counter < bright; - end - -endmodule - - -/************************************************************************ - * - * Random utility modules. - * - * Micah Dowty - * - ************************************************************************/ - - -module d_flipflop(clk, reset, d_in, d_out); - input clk, reset, d_in; - output d_out; - - reg d_out; - - always @(posedge clk or posedge reset) - if (reset) begin - d_out <= 0; - end - else begin - d_out <= d_in; - end -endmodule - - -module d_flipflop_pair(clk, reset, d_in, d_out); - input clk, reset, d_in; - output d_out; - wire intermediate; - - d_flipflop dff1(clk, reset, d_in, intermediate); - d_flipflop dff2(clk, reset, intermediate, d_out); -endmodule - - -/* - * A set/reset flipflop which is set on sync_set and reset by sync_reset. - */ -module set_reset_flipflop(clk, reset, sync_set, sync_reset, out); - input clk, reset, sync_set, sync_reset; - output out; - reg out; - - always @(posedge clk or posedge reset) - if (reset) - out <= 0; - else if (sync_set) - out <= 1; - else if (sync_reset) - out <= 0; -endmodule - - -/* - * Pulse stretcher. - * - * When the input goes high, the output goes high - * for as long as the input is high, or as long as - * it takes our timer to roll over- whichever is - * longer. - */ -module pulse_stretcher(clk, reset, in, out); - parameter BITS = 20; - - input clk, reset, in; - output out; - reg out; - - reg [BITS-1:0] counter; - - always @(posedge clk or posedge reset) - if (reset) begin - out <= 0; - counter <= 0; - end - else if (counter == 0) begin - out <= in; - counter <= in ? 1 : 0; - end - else if (&counter) begin - if (in) begin - out <= 1; - end - else begin - out <= 0; - counter <= 0; - end - end - else begin - out <= 1; - counter <= counter + 1; - end -endmodule - From 28a72be0a36fb09b6dd8106fc60fa16f000648d5 Mon Sep 17 00:00:00 2001 From: Trammell hudson Date: Fri, 18 Jan 2019 17:08:30 -0500 Subject: [PATCH 30/31] TinyFPGA_BX: enable all the pins, with -nowarn --- boards/TinyFPGA_BX/pins.pcf | 68 ++++++++++++++++++------------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/boards/TinyFPGA_BX/pins.pcf b/boards/TinyFPGA_BX/pins.pcf index 2736b3a..6fa7e18 100644 --- a/boards/TinyFPGA_BX/pins.pcf +++ b/boards/TinyFPGA_BX/pins.pcf @@ -9,40 +9,40 @@ set_io -nowarn pin_3 B1 set_io -nowarn pin_4 C2 set_io -nowarn pin_5 C1 set_io -nowarn pin_6 D2 -#set_io pin_7 D1 +set_io -nowarn pin_7 D1 set_io -nowarn pin_8 E2 set_io -nowarn pin_9 E1 -#set_io pin_10 G2 -#set_io pin_11 H1 -#set_io pin_12 J1 -#set_io pin_13 H2 -#set_io pin_14 H9 -#set_io pin_15 D9 -#set_io pin_16 D8 -#set_io pin_17 C9 -#set_io pin_18 A9 -#set_io pin_19 B8 -#set_io pin_20 A8 -#set_io pin_21 B7 -#set_io pin_22 A7 -#set_io pin_23 B6 -#set_io pin_24 A6 -#set_io pin_25 G1 -#set_io pin_26 J3 -#set_io pin_27 J4 -#set_io pin_28 H4 -set_io pin_29_miso H7 -set_io pin_30_cs F7 -set_io pin_31_mosi G6 -set_io pin_32_sck G7 -#set_io pin_33 J8 -#set_io pin_34 G9 -#set_io pin_35 J9 -#set_io pin_36 E8 -#set_io pin_37 J2 -set_io pin_led B3 -set_io pin_usbp B4 -set_io pin_usbn A4 -set_io pin_pu A3 -set_io pin_clk B2 +set_io -nowarn pin_10 G2 +set_io -nowarn pin_11 H1 +set_io -nowarn pin_12 J1 +set_io -nowarn pin_13 H2 +set_io -nowarn pin_14 H9 +set_io -nowarn pin_15 D9 +set_io -nowarn pin_16 D8 +set_io -nowarn pin_17 C9 +set_io -nowarn pin_18 A9 +set_io -nowarn pin_19 B8 +set_io -nowarn pin_20 A8 +set_io -nowarn pin_21 B7 +set_io -nowarn pin_22 A7 +set_io -nowarn pin_23 B6 +set_io -nowarn pin_24 A6 +set_io -nowarn pin_25 G1 +set_io -nowarn pin_26 J3 +set_io -nowarn pin_27 J4 +set_io -nowarn pin_28 H4 +set_io -nowarn pin_29_miso H7 +set_io -nowarn pin_30_cs F7 +set_io -nowarn pin_31_mosi G6 +set_io -nowarn pin_32_sck G7 +set_io -nowarn pin_33 J8 +set_io -nowarn pin_34 G9 +set_io -nowarn pin_35 J9 +set_io -nowarn pin_36 E8 +set_io -nowarn pin_37 J2 +set_io -nowarn pin_led B3 +set_io -nowarn pin_usbp B4 +set_io -nowarn pin_usbn A4 +set_io -nowarn pin_pu A3 +set_io -nowarn pin_clk B2 From 84959e7287d2f04c2f7bf3dcf15abb2750b24101 Mon Sep 17 00:00:00 2001 From: Trammell hudson Date: Fri, 18 Jan 2019 17:08:56 -0500 Subject: [PATCH 31/31] TinyFPGA_BX: use nextpnr-ice40 --- boards/TinyFPGA_BX/Makefile | 12 ++++++--- boards/TinyFPGA_BX/bootloader.v | 45 +++++++++++++++++++++++++++------ 2 files changed, 46 insertions(+), 11 deletions(-) diff --git a/boards/TinyFPGA_BX/Makefile b/boards/TinyFPGA_BX/Makefile index b325935..eb006a1 100644 --- a/boards/TinyFPGA_BX/Makefile +++ b/boards/TinyFPGA_BX/Makefile @@ -27,10 +27,16 @@ all: $(PROJ).rpt fw.bin %.blif: %.v ../../common/*.v yosys -q -p 'synth_ice40 -top $(PROJ) -blif $@' $^ -%.asc: $(PIN_DEF) %.blif +NO-%.asc: $(PIN_DEF) %.blif arachne-pnr -d 8k -P $(PKG) -o $@ -p $^ -no-%.asc: $(PIN_DEF) %.json - nextpnr-ice40 -d 8k -P $(PKG) -o $@ -p $^ + +%.asc: $(PIN_DEF) %.json + nextpnr-ice40 \ + --$(DEVICE) \ + --package $(PKG) \ + --asc $@ \ + --pcf $(PIN_DEF) \ + --json $(basename $@).json \ %.bin: %.asc icepack $< $@ diff --git a/boards/TinyFPGA_BX/bootloader.v b/boards/TinyFPGA_BX/bootloader.v index 61917c0..471cbe3 100644 --- a/boards/TinyFPGA_BX/bootloader.v +++ b/boards/TinyFPGA_BX/bootloader.v @@ -10,7 +10,7 @@ module bootloader ( input pin_29_miso, output pin_30_cs, output pin_31_mosi, - output pin_32_sck, + output pin_32_sck ); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// @@ -52,12 +52,11 @@ module bootloader ( ); reg clk_24mhz; - always @(posedge clk_48mhz) clk_24mhz = !clk_24mhz; - reg clk_12mhz; + always @(posedge clk_48mhz) clk_24mhz = !clk_24mhz; always @(posedge clk_24mhz) clk_12mhz = !clk_12mhz; - wire clk = clk_12mhz; // half speed clock + wire clk = clk_12mhz; // quarter speed clock //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// @@ -106,9 +105,39 @@ module bootloader ( ); assign pin_pu = 1'b1; - assign pin_usbp = usb_tx_en ? usb_p_tx : 1'bz; - assign pin_usbn = usb_tx_en ? usb_n_tx : 1'bz; - assign usb_p_rx = usb_tx_en ? 1'b1 : pin_usbp; - assign usb_n_rx = usb_tx_en ? 1'b0 : pin_usbn; + wire usb_p_rx_io; + wire usb_n_rx_io; + assign usb_p_rx = usb_tx_en ? 1'b1 : usb_p_rx_io; + assign usb_n_rx = usb_tx_en ? 1'b0 : usb_n_rx_io; + + tristate usbn_buffer( + .pin(pin_usbn), + .enable(usb_tx_en), + .data_in(usb_n_rx_io), + .data_out(usb_n_tx) + ); + + tristate usbp_buffer( + .pin(pin_usbp), + .enable(usb_tx_en), + .data_in(usb_p_rx_io), + .data_out(usb_p_tx) + ); +endmodule + +module tristate( + inout pin, + input enable, + input data_out, + output data_in +); + SB_IO #( + .PIN_TYPE(6'b1010_01) // tristatable output + ) buffer( + .PACKAGE_PIN(pin), + .OUTPUT_ENABLE(enable), + .D_IN_0(data_in), + .D_OUT_0(data_out) + ); endmodule