├── .gitignore
├── LICENSE
├── Makefile
├── README.md
├── apps
├── README.md
├── blinker
│ ├── blinker.py
│ └── build.sh
├── buzzer
│ ├── build.sh
│ └── buzzer.py
├── hex-uart
│ ├── build.sh
│ └── hex-uart.py
├── mul
│ ├── build.sh
│ └── mul.py
├── off
│ ├── build.sh
│ └── off.py
├── othercase-uart
│ ├── build.sh
│ └── othercase-uart.py
├── pipe-othercase-uart
│ ├── build.sh
│ └── pipe-othercase-uart.py
├── pll-blinker
│ ├── build.sh
│ └── pll-blinker.py
├── receive-uart
│ ├── build.sh
│ └── receive-uart.py
├── seven-seg-counter
│ ├── build.sh
│ └── seven-seg-counter.py
└── seven-seg-fade
│ ├── build.sh
│ └── seven-seg-fade.py
└── nmigen_lib
├── README.md
├── __init__.py
├── blinker.py
├── buzzer.py
├── counter.py
├── i2s.py
├── mul.py
├── oneshot.py
├── pipe
├── __init__.py
├── desc.py
├── endpoint.py
├── pipe.py
├── pipeline.py
├── simple.py
├── spec.py
├── test.py
└── uart.py
├── pll.py
├── seven_segment
├── digit_pattern.py
├── driver.py
└── hex_display.py
├── timer.py
├── uart.py
└── util
├── __init__.py
└── main.py
/.gitignore:
--------------------------------------------------------------------------------
1 | build/
2 | __pycache__/
3 | *.vcd
4 | *.gtkw
5 | *.pyc
6 | *.v
7 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | # Need targets:
2 | # help
3 | # simulate module
4 | # simulate all
5 | # verify module
6 | # simulate all
7 | # program app
8 | # clean
9 |
10 | help:
11 | @echo No help.
12 |
13 | sim-%:
14 | echo $(MAKECMDGOALS)
15 |
16 | foo:
17 | echo $(MAKECMDGOALS)
18 |
19 | clean:
20 | @set -e; \
21 | find * -name \*.gtkw -o -name \*.vcd \
22 | | while read f; \
23 | do \
24 | echo rm -f $$f; \
25 | rm -f "$$f"; \
26 | done
27 | @set -e; \
28 | find * -type d \( -name build -o -name __pycache__ \) \
29 | | while read d; \
30 | do \
31 | echo rm -rf $$d; \
32 | rm -rf "$$d"; \
33 | done
34 |
35 |
36 | .PHONY: help clean
37 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # nmigen-examples
2 |
3 | I want to learn [n]Migen.
4 |
5 | Verilog is awful, as you know. There are a few newer HDLs to explore.
6 | myHDL, Migen and nMigen, and SpinalHDL/Chisel.
7 |
8 | Since I already know Python, it seems like nMigen is a good place to
9 | start. nMigen (new Migen) is a reimplementation of Migen, and I guess
10 | Migen is on its way to deprecation. OTOH, nMigen is far from mature.
11 |
12 | I want to understand whether and how nMigen makes it possible to create
13 | abstractions that Verilog can't.
14 |
15 |
16 | # Extremely basic nMigen
17 |
18 | nMigen is a Python library that implements a hardware description
19 | language (HDL). You describe hardware using nMigen's Python extensions,
20 | then nMigen can simulate your design, emit your design as Verilog, or
21 | synthesize it for an FPGA and optionally load it onto an FPGA dev board.
22 |
23 | More complex arrangements are possible -- nMigen is a Python library, so
24 | it can be embedded into an arbitrary runtime. Check out [the Glasgow
25 | project](https://github.com/GlasgowEmbedded/glasgow) for an example that
26 | uses nMigen to automatically generate and load FPGA functions on the
27 | fly.
28 |
29 |
30 | ## nMigen program structure
31 |
32 | An nMigen design is organized as a tree of modules, just like Verilog.
33 | Each module has:
34 |
35 | * one or more clock domains
36 | * the `comb` pseudo-domain for combinatorial logic
37 | * zero or more submodules.
38 |
39 | Modules are defined in classes derived from `Elaboratable`. Each
40 | `Elaboratable` has a method called `elaborate`, which constructs and
41 | initializes a `Module`. (I don't understand why they're called
42 | "elaboratable". The word does not connote anything useful to me.)
43 |
44 | Within the `elaborate` method, you create the `Module`, attach any clock
45 | domains and submodules, and then add logic statements to the domains,
46 | including the combinatoric pseudo-domain, `comb`. By convention, the
47 | default clock domain is called `sync`. AFAIK there is nothing magical
48 | about `sync` -- you could use any identifier.
49 |
50 | Each domain has a clock signal, an optional reset signal, and a set of
51 | logic statements. The logic statements are implicitly bound to the
52 | clock edge (rising edge by default); Instead of littering your code with
53 | Verilog's `always @(posedge clk) ...`, you litter your code with
54 | `m.d.sync += ...`. nMigen automatically generates code to initialize
55 | signals on reset, and automatically gives signals a default reset value
56 | of zero.
57 |
58 | So that's a higher level than Verilog. Clock and reset are implicit,
59 | and clock domains are explicit.
60 |
61 | TBD: The `Instantiate` class.
62 |
63 | ## nMigen's HDL
64 |
65 | TBD: Start with the `Value` hierarchy, then explain operators,
66 | assignment, and control flow.
67 |
68 | Explain that you need to understand Python operator overloading and
69 | context managers.
70 |
71 |
72 | ## nMigen Simulation
73 |
74 | Building in minimal simulation is trivial. Just drop this at the end of
75 | a source file.
76 |
77 | ```python
78 | from nmigen.cli import main
79 | if __name__ == '__main__':
80 | x = MyModule()
81 | main(x, ports=x.ports)
82 | ```
83 |
84 | Then you simulate that module like this.
85 |
86 | ```sh
87 | $ nmigen mymodule.py simulate -v mymodule.vcd -w mymodule.gtkw -c 1000
88 | ```
89 |
90 | You can also do more complex stuff building in a test bench that sets up
91 | specific conditions and looks for specific outputs. There is also a
92 | unit testing framework that I don't know much about. I think it lets
93 | you run a bunch of simulation runs on the same module.
94 |
95 | nMigen also has `Assert`, `Assume`, and `Cover` keywords. They don't
96 | appear to be fully implemented yet.
97 |
98 | ## nMigen and platforms
99 |
100 | TBD.
101 |
102 |
103 | # Repository Organization
104 |
105 | There are two main subdirectories. `lib` contains reusable modules.
106 | They do not have any platform dependencies. `apps` contains top-level
107 | modules that connect modules from `lib` together and bind them to the
108 | pins of a specific package.
109 |
110 | All of the apps here target the iCEBreaker platform with various PMOD
111 | cards attached.
112 |
113 |
114 | # How to Use
115 |
116 | For reusable modules in the `lib` directory, you can simulate a module
117 | or generate Verilog from it. See the README in that directory.
118 |
119 | The `apps` directory has a subdirectory for each app. Each app creates
120 | a complete FPGA bitstream for one platform and downloads (uploads?) it.
121 | (All my apps are for the iCEBreaker FPGA at present.) There's only one
122 | way to use it -- run `./build.sh`. See `apps/README.md`.
123 |
124 |
125 | ## What's this nmigen command in the READMEs and build scripts?
126 |
127 | That's a shell script I have in my path. It invokes python in the
128 | virtualenv where nmigen is installed. My implementation is complicated
129 | — you don't want to know. It's more or less equivalent to this,
130 | though.
131 |
132 | ```sh
133 | #!/bin/sh
134 | export VIRTUAL_ENV=/path/to/nmigen/virtualenv
135 | export PATH="$VIRTUAL_ENV/bin:$PATH"
136 | unset PYTHONHOME
137 | python ${1+"$@"}
138 | ```
139 |
140 | I recommend putting a script like that in your path.
141 |
142 | # Misc.
143 |
144 | ## Enabling iCE40 DSP inference
145 |
146 | By default, yosys does not infer DSP slices for multiplication.
147 | (*i.e.*, it does not use DSPs to implement multiply ops.)
148 |
149 | You can enable DSP inference by setting the `NMIGEN_synth_opts`
150 | environment variable to `-dsp`.
151 |
152 | ```sh
153 | $ NMIGEN_synth_opts=-dsp nmigen my-app.py
154 | ```
155 |
--------------------------------------------------------------------------------
/apps/README.md:
--------------------------------------------------------------------------------
1 | # Applications
2 |
3 | These are trivial but complete applications ready to be loaded onto an
4 | iCEBreaker FPGA.
5 |
6 | * **blinker** - blink one LED at one Hertz.
7 | Library modules: `Blinker`
8 |
9 | * **pll-blinker** - drive two LEDs from a phase-locked loop.
10 | Library modules: `PLL`, `Blinker`
11 |
12 | One LED blinks at 1 Hz, and the other blinks at 5 Hz. Shows
13 | how to use the iCE40's PLL to create two clock domains.
14 |
15 | * **off** - turn the freq'ing LEDs off.
16 |
17 | They are distracting!
18 |
19 | * **buzzer** - make buzzing sound an I2S interface.
20 | Library modules: `PLL`, `I2SOut`, `Buzzer`
21 |
22 | Makes a simple, continuous buzzer that sounds at 261 Hz (Middle C).
23 |
24 | This demo requires an I2S interface on PMOD 1A. A Digilent [I2S
25 | (retired)](https://store.digilentinc.com/pmod-i2s-stereo-audio-output-retired/)
26 | or
27 | [I2S2](https://store.digilentinc.com/pmod-i2s2-stereo-audio-input-and-output/)
28 | PMOD works. See Digilent's documentation for
29 | [pinout](https://reference.digilentinc.com/reference/pmod/pmodi2s/start).
30 |
31 | * **seven-seg-counter** - count on a seven segment display.
32 | Library modules: `Timer`, `Counter`, `seven_segment.DigitPattern`,
33 | `seven_segment.Driver`
34 |
35 | Display a continuously running two digit counter
36 | on a seven segment display.
37 |
38 | This demo requires a seven segment display in PMOD 1B.
39 | A [1BitSquared PMOD 7 Segment
40 | Display](https://1bitsquared.com/collections/fpga/products/pmod-7-segment-display)
41 | works.
42 |
43 | * **seven-seg-fade** - fade a seven segment display with pwm.
44 | Library modules: `Timer`, `Counter`, `seven_segment.DigitPattern`,
45 | `seven_segment.Driver`, `Mul`
46 |
47 | Display a continuously running counter whose brightness is
48 | proportional to the number displayed.
49 |
50 | As a cheap approximation to perceptual brightness, the PWM
51 | amount is proportional to the square of the counter value.
52 |
53 | This is also the first app that uses a DSP block. The
54 | DSP computes the square of the counter (a simple multiply).
55 | Note that `build.sh` has an environment variable to enable
56 | DSP synthesis.
57 |
58 | * **receive-uart** - receive characters from UART.
59 | Library modules: `UART`, `OneShot`
60 |
61 | Receive characters from the FTDI UART. Flashes the green and
62 | red LEDs to indicate good/bad reception. When a digit 1-5
63 | is received, lights the corresponding LED on the breakaway PMOD.
64 |
65 | Connect to FTDI UART 1 at 9600 baud, 8 data bits, no parity,
66 | one stop bit. To test the error code (red LED), use a faster
67 | baud rate.
68 |
69 | This demo requires the iCEBreaker break-off PMOD on connector
70 | PMOD 2. The iCEBreaker ships with that PMOD attached.
71 |
72 | * **othercase-uart** - echo characters from UART.
73 | Library modules: `UART`
74 |
75 | Receive characters from the FTDI UART and echo them. Uppercase
76 | letters (US ASCII only) are echoed in lowercase, and lowercase
77 | letters are echoed in uppercase.
78 |
79 | The serial setup is the same as `receive_uart` above.
80 |
81 | * **pipe-othercase-uart** - echo characters from UART.
82 | Library modules: `UART`, `PipeSpec`, `Pipeline`
83 |
84 | Same function as `othercase-uart`. But this one uses the
85 | Pipe abstraction.
86 |
87 | * **hex-uart** - display characters' hex values.
88 | Library modules: `seven_segment.digit_pattern`, `seven_segment.driver`,
89 | `UART`, `OneShot`
90 |
91 | Receive characters from the FTDI UART and display their hexadecimal
92 | values on a seven segment display.
93 |
94 | This demo requires a seven-segment display attached to PMOD 1B.
95 | See `seven-seg-counter` above. The serial setup is the same as
96 | `receive_uart` above.
97 |
98 | # How to Use
99 |
100 | ```sh
101 | $ cd $app
102 | $ ./build.sh
103 | $ # app is built and FPGA is flashed.
104 | ```
105 |
--------------------------------------------------------------------------------
/apps/blinker/blinker.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from nmigen import *
4 | from nmigen_boards.icebreaker import ICEBreakerPlatform
5 |
6 | from nmigen_lib.blinker import Blinker
7 |
8 |
9 | class Top(Elaboratable):
10 |
11 | def elaborate(self, platform):
12 | led = platform.request('user_led')
13 | m = Module()
14 | bink = Blinker(period=int(platform.default_clk_frequency))
15 | m.submodules += bink
16 | m.d.comb += led.eq(bink.led)
17 | return m
18 |
19 |
20 | if __name__ == '__main__':
21 | platform = ICEBreakerPlatform()
22 | platform.build(Top(), do_program=True)
23 |
--------------------------------------------------------------------------------
/apps/blinker/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | PYTHONPATH=../.. nmigen blinker.py
4 |
--------------------------------------------------------------------------------
/apps/buzzer/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | PYTHONPATH=../.. nmigen buzzer.py
4 |
--------------------------------------------------------------------------------
/apps/buzzer/buzzer.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from nmigen import *
4 | from nmigen.build import *
5 | from nmigen_boards.icebreaker import ICEBreakerPlatform
6 |
7 | from nmigen_lib.buzzer import Buzzer
8 | from nmigen_lib.i2s import I2SOut
9 | from nmigen_lib.pll import PLL
10 |
11 |
12 | class Top(Elaboratable):
13 |
14 | def elaborate(self, platform):
15 | i2s_pins = platform.request('i2s', 0)
16 | clk_pin = platform.request(platform.default_clk, dir='-')
17 |
18 | freq_in = platform.default_clk_frequency
19 | pll_freq = 24_000_000
20 | freq_in_mhz = freq_in / 1_000_000
21 | pll_freq_mhz = pll_freq / 1_000_000
22 | buzz_freq = 440 * 2**(-9/12) # Middle C
23 |
24 | m = Module()
25 | pll = PLL(freq_in_mhz=freq_in_mhz, freq_out_mhz=pll_freq_mhz)
26 | i2s = I2SOut(pll_freq)
27 | buzzer = Buzzer(buzz_freq, i2s.sample_frequency)
28 | m.domains += pll.domain # override the default 'sync' domain
29 | m.submodules += [pll, buzzer, i2s]
30 | m.d.comb += [
31 | pll.clk_pin.eq(clk_pin),
32 | buzzer.enable.eq(True),
33 | buzzer.ack.eq(i2s.ack),
34 | i2s.samples[0].eq(buzzer.sample),
35 | i2s.samples[1].eq(buzzer.sample),
36 | i2s.stb.eq(buzzer.stb),
37 | i2s_pins.eq(i2s.i2s),
38 | ]
39 | return m
40 |
41 |
42 | if __name__ == '__main__':
43 | platform = ICEBreakerPlatform()
44 | platform.add_resources([
45 | Resource('i2s', 0,
46 | Subsignal('mclk', Pins('1', conn=('pmod', 0), dir='o')),
47 | Subsignal('lrck', Pins('2', conn=('pmod', 0), dir='o')),
48 | Subsignal('sck', Pins('3', conn=('pmod', 0), dir='o')),
49 | Subsignal('sd', Pins('4', conn=('pmod', 0), dir='o')),
50 | ),
51 | ])
52 | platform.build(Top(), do_program=True)
53 |
--------------------------------------------------------------------------------
/apps/hex-uart/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | PYTHONPATH=../.. nmigen hex-uart.py
4 |
--------------------------------------------------------------------------------
/apps/hex-uart/hex-uart.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from nmigen import *
4 | from nmigen.build import *
5 | from nmigen_boards.icebreaker import ICEBreakerPlatform
6 |
7 | from nmigen_lib import UARTRx, HexDisplay, OneShot
8 |
9 |
10 | class Top(Elaboratable):
11 |
12 | def elaborate(self, platform):
13 | clk_freq = platform.default_clk_frequency
14 | uart_baud = 9600
15 | uart_divisor = int(clk_freq // uart_baud)
16 | status_duration = int(0.1 * clk_freq)
17 | uart_pins = platform.request('uart')
18 | bad_led = platform.request('led_r', 0)
19 | good_led = platform.request('led_g', 0)
20 | seg7_pins = platform.request('seg7')
21 |
22 |
23 | m = Module()
24 | uart_rx = UARTRx(divisor=uart_divisor)
25 | recv_status = OneShot(duration=status_duration)
26 | err_status = OneShot(duration=status_duration)
27 | hex_display = HexDisplay(clk_freq, 100, 1)
28 | m.submodules += [uart_rx, recv_status, err_status]
29 | m.submodules.hex_display = hex_display
30 | m.d.comb += [
31 | uart_rx.rx_pin.eq(uart_pins.rx),
32 | recv_status.i_trg.eq(uart_rx.rx_rdy),
33 | good_led.eq(recv_status.o_pulse),
34 | err_status.i_trg.eq(uart_rx.rx_err),
35 | bad_led.eq(err_status.o_pulse),
36 | hex_display.i_data.eq(uart_rx.rx_data),
37 | seg7_pins.eq(hex_display.o_seg7),
38 | ]
39 | m.d.sync += [
40 | hex_display.i_pwm.eq(hex_display.i_pwm | uart_rx.rx_rdy),
41 | ]
42 | return m
43 |
44 |
45 | if __name__ == '__main__':
46 | platform = ICEBreakerPlatform()
47 | conn = ('pmod', 1)
48 | platform.add_resources([
49 | Resource('seg7', 0,
50 | Subsignal('segs', Pins('1 2 3 4 7 8 9', conn=conn, dir='o')),
51 | Subsignal('digit', Pins('10', conn=conn, dir='o')),
52 | ),
53 | ])
54 | top = Top()
55 | platform.build(top, do_program=True)
56 |
--------------------------------------------------------------------------------
/apps/mul/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | PYTHONPATH=../.. nmigen mul.py
4 |
--------------------------------------------------------------------------------
/apps/mul/mul.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | import os
4 |
5 | from nmigen import *
6 | from nmigen.cli import main
7 | from nmigen_boards.icebreaker import ICEBreakerPlatform
8 |
9 | class Mul(Elaboratable):
10 |
11 | def __init__(self):
12 | self.a = Signal(signed(16))
13 | self.b = Signal(signed(16))
14 | self.c = Signal(signed(32))
15 |
16 | def elaborate(self, platform):
17 |
18 | m = Module()
19 | m.d.sync += [
20 | self.c.eq(self.a * self.b)
21 | ]
22 | return m
23 |
24 |
25 | class Top(Elaboratable):
26 |
27 | def elaborate(self, platform):
28 | cnt = Signal(5)
29 | btn0 = platform.request('button', 0)
30 | btn1 = platform.request('button', 1)
31 | led = platform.request('led')
32 | mul = Mul()
33 |
34 | m = Module()
35 | m.submodules += mul
36 | m.d.sync += [
37 | cnt.eq(cnt + 1),
38 | mul.a.eq(mul.a << 1 | btn0),
39 | mul.b.eq(mul.b << 1 | btn1),
40 | led.eq(mul.c.bit_select(cnt, 1)),
41 | ]
42 | return m
43 |
44 |
45 | if __name__ == '__main__':
46 |
47 | # Force Yosys to use DSP slices.
48 | os.environ['NMIGEN_synth_opts'] = '-dsp'
49 |
50 | platform = ICEBreakerPlatform()
51 | platform.add_resources(platform.break_off_pmod)
52 | platform.build(Top(), do_program=True)
53 |
--------------------------------------------------------------------------------
/apps/off/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | PYTHONPATH=../.. nmigen off.py
4 |
--------------------------------------------------------------------------------
/apps/off/off.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | import itertools
4 |
5 | from nmigen import *
6 | from nmigen.build import ResourceError
7 | from nmigen_boards.icebreaker import ICEBreakerPlatform
8 |
9 |
10 | class Top(Elaboratable):
11 |
12 | def elaborate(self, platform):
13 | try:
14 | leds = []
15 | for i in itertools.count():
16 | leds.append(platform.request('user_led', i))
17 |
18 | except ResourceError:
19 | pass
20 | leds = Cat(led.o for led in leds)
21 | m = Module()
22 | m.d.comb += leds.eq(0)
23 | return m
24 |
25 |
26 | if __name__ == '__main__':
27 | platform = ICEBreakerPlatform()
28 | platform.add_resources(platform.break_off_pmod)
29 | platform.build(Top(), do_program=True)
30 |
--------------------------------------------------------------------------------
/apps/othercase-uart/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | PYTHONPATH=../.. nmigen othercase-uart.py
4 |
--------------------------------------------------------------------------------
/apps/othercase-uart/othercase-uart.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from nmigen import *
4 | from nmigen.build import *
5 | from nmigen_boards.icebreaker import ICEBreakerPlatform
6 |
7 | from nmigen_lib.uart import UART
8 |
9 |
10 | class CaseBender(Elaboratable):
11 |
12 | """Translate lowercase to uppercase, uppercase to lower."""
13 |
14 | def __init__(self):
15 | self.char_in = Signal(8)
16 | self.char_out = Signal(8)
17 | self.ports = (self.char_in, self.char_out)
18 |
19 | def elaborate(self, platform):
20 |
21 | m = Module()
22 | is_alpha = (self.char_in & 0xC0) == 0x40
23 | is_alpha &= (self.char_in & 0x1F) >= 1
24 | is_alpha &= (self.char_in & 0x1F) <= 26
25 | with m.If(is_alpha):
26 | m.d.comb += [
27 | self.char_out.eq(self.char_in ^ 0x20),
28 | ]
29 | with m.Else():
30 | m.d.comb += [
31 | self.char_out.eq(self.char_in)
32 | ]
33 | return m
34 |
35 |
36 | class Top(Elaboratable):
37 |
38 | def elaborate(self, platform):
39 | clk_freq = platform.default_clk_frequency
40 | uart_baud = 9600
41 | uart_divisor = int(clk_freq // uart_baud)
42 | status_duration = int(0.1 * clk_freq)
43 | uart_pins = platform.request('uart')
44 |
45 | m = Module()
46 | uart = UART(divisor=uart_divisor)
47 | bender = CaseBender()
48 | m.submodules += [uart, bender]
49 | m.d.comb += [
50 | uart_pins.tx.eq(uart.tx_pin),
51 | bender.char_in.eq(uart.rx_data),
52 | uart.tx_data.eq(bender.char_out),
53 | uart.tx_trg.eq(uart.rx_rdy),
54 | uart.rx_pin.eq(uart_pins.rx),
55 | ]
56 | return m
57 |
58 |
59 | if __name__ == '__main__':
60 | platform = ICEBreakerPlatform()
61 | platform.add_resources(platform.break_off_pmod)
62 | top = Top()
63 | platform.build(top, do_program=True)
64 |
--------------------------------------------------------------------------------
/apps/pipe-othercase-uart/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | PYTHONPATH=../.. nmigen pipe-othercase-uart.py
4 |
--------------------------------------------------------------------------------
/apps/pipe-othercase-uart/pipe-othercase-uart.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from nmigen import *
4 | from nmigen.build import *
5 | from nmigen_boards.icebreaker import ICEBreakerPlatform
6 |
7 | from nmigen_lib.pipe import PipeSpec, Pipeline
8 | from nmigen_lib.pipe.uart import P_UART
9 |
10 |
11 | class CaseBender(Elaboratable):
12 |
13 | """Translate lowercase to uppercase, uppercase to lower."""
14 |
15 | def __init__(self):
16 | spec = PipeSpec(8)
17 | self.char_in = spec.outlet()
18 | self.char_out = spec.inlet()
19 |
20 | def elaborate(self, platform):
21 |
22 | m = Module()
23 | def is_alpha(c):
24 | return ((c & 0xc0) == 0x40) & (1 <= (c & 0x1F)) & ((c & 0x1F) <= 26)
25 | def other_case(c):
26 | return Mux(is_alpha(c), c ^ 0x20, c)
27 | m.d.comb += [
28 | self.char_out.o_valid.eq(self.char_in.i_valid),
29 | self.char_out.o_data.eq(other_case(self.char_in.i_data)),
30 | self.char_in.o_ready.eq(self.char_out.i_ready),
31 | ]
32 | return m
33 |
34 |
35 | class Top(Elaboratable):
36 |
37 | def elaborate(self, platform):
38 | clk_freq = platform.default_clk_frequency
39 | uart_baud = 9600
40 | uart_divisor = int(clk_freq // uart_baud)
41 | uart_pins = platform.request('uart')
42 |
43 | m = Module()
44 | uart = P_UART(divisor=uart_divisor)
45 | bender = CaseBender()
46 | m.submodules.uart = uart
47 | m.submodules.bender = bender
48 | m.submodules.pipeline = Pipeline([uart, bender, uart])
49 | m.d.comb += [
50 | uart_pins.tx.eq(uart.tx_pin),
51 | uart.rx_pin.eq(uart_pins.rx),
52 | ]
53 | return m
54 |
55 |
56 | if __name__ == '__main__':
57 | platform = ICEBreakerPlatform()
58 | platform.add_resources(platform.break_off_pmod)
59 | top = Top()
60 | platform.build(top, do_program=True)
61 |
--------------------------------------------------------------------------------
/apps/pll-blinker/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | PYTHONPATH=../.. nmigen pll-blinker.py
4 |
--------------------------------------------------------------------------------
/apps/pll-blinker/pll-blinker.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from nmigen import *
4 | from nmigen_boards.icebreaker import ICEBreakerPlatform
5 |
6 | from nmigen_lib.blinker import Blinker
7 | from nmigen_lib.pll import PLL
8 |
9 |
10 | class Top(Elaboratable):
11 |
12 | def elaborate(self, platform):
13 | # If you don't specify dir='-', you will experience a world
14 | # of debugging pain.
15 | clk_pin = platform.request(platform.default_clk, dir='-')
16 | led0 = platform.request('user_led', 0)
17 | led1 = platform.request('user_led', 1)
18 | freq_in = platform.default_clk_frequency
19 | pll_freq = 60_000_000
20 | freq_in_mhz = freq_in / 1_000_000
21 | pll_freq_mhz = pll_freq / 1_000_000
22 | bink0_period = int(pll_freq)
23 | bink1_period = pll_freq // 5
24 |
25 | m = Module()
26 | pll = PLL(freq_in_mhz=freq_in_mhz, freq_out_mhz=pll_freq_mhz)
27 | bink0 = Blinker(period=bink0_period)
28 | bink1 = Blinker(period=bink1_period)
29 | m.domains += pll.domain # override the default 'sync' domain
30 | m.submodules += [pll, bink0, bink1]
31 | m.d.comb += [
32 | pll.clk_pin.eq(clk_pin),
33 | led0.eq(bink0.led),
34 | led1.eq(bink1.led),
35 | ]
36 | return m
37 |
38 |
39 | if __name__ == '__main__':
40 | platform = ICEBreakerPlatform()
41 | platform.build(Top(), do_program=True)
42 |
--------------------------------------------------------------------------------
/apps/receive-uart/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | PYTHONPATH=../.. nmigen receive-uart.py
4 |
--------------------------------------------------------------------------------
/apps/receive-uart/receive-uart.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from nmigen import *
4 | from nmigen.build import *
5 | from nmigen_boards.icebreaker import ICEBreakerPlatform
6 |
7 | from nmigen_lib import UARTRx, OneShot
8 |
9 |
10 | class Top(Elaboratable):
11 |
12 | def elaborate(self, platform):
13 | clk_freq = platform.default_clk_frequency
14 | uart_baud = 9600
15 | uart_divisor = int(clk_freq // uart_baud)
16 | status_duration = int(0.1 * clk_freq)
17 | uart_pins = platform.request('uart')
18 | bad_led = platform.request('led', 0)
19 | good_led = platform.request('led', 1)
20 | digit_leds = [platform.request('led', i + 2)
21 | for i in range(5)]
22 |
23 | m = Module()
24 | uart_rx = UARTRx(divisor=uart_divisor)
25 | recv_status = OneShot(duration=status_duration)
26 | err_status = OneShot(duration=status_duration)
27 | m.submodules += [uart_rx, recv_status, err_status]
28 | m.d.comb += [
29 | uart_rx.rx_pin.eq(uart_pins.rx),
30 | recv_status.i_trg.eq(uart_rx.rx_rdy),
31 | good_led.eq(recv_status.o_pulse),
32 | err_status.i_trg.eq(uart_rx.rx_err),
33 | bad_led.eq(err_status.o_pulse),
34 | ]
35 | with m.If(uart_rx.rx_rdy):
36 | m.d.sync += [
37 | digit_leds[i].eq(uart_rx.rx_data == ord('1') + i)
38 | for i in range(5)
39 | ]
40 | return m
41 |
42 |
43 | if __name__ == '__main__':
44 | platform = ICEBreakerPlatform()
45 | platform.add_resources(platform.break_off_pmod)
46 | top = Top()
47 | platform.build(top, do_program=True)
48 |
--------------------------------------------------------------------------------
/apps/seven-seg-counter/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | PYTHONPATH=../.. nmigen seven-seg-counter.py
4 |
--------------------------------------------------------------------------------
/apps/seven-seg-counter/seven-seg-counter.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from nmigen import *
4 | from nmigen.build import *
5 | from nmigen_boards.icebreaker import ICEBreakerPlatform
6 |
7 | from nmigen_lib import Counter, Timer, DigitPattern, SevenSegDriver
8 |
9 |
10 | class Top(Elaboratable):
11 |
12 | def elaborate(self, platform):
13 | seg7_pins = platform.request('seg7', 0)
14 |
15 | clk_freq = platform.default_clk_frequency
16 | min_refresh_freq = 100
17 | count_freq = 4
18 |
19 | m = Module()
20 | ticker = Timer(period=int(clk_freq // count_freq))
21 | counter = Counter(period=16 * 16)
22 | ones_segs = DigitPattern()
23 | tens_segs = DigitPattern()
24 | driver = SevenSegDriver(clk_freq, min_refresh_freq)
25 | m.submodules += [ticker, counter, ones_segs, tens_segs, driver]
26 |
27 | m.d.comb += [
28 | counter.trg.eq(ticker.stb),
29 | ones_segs.digit_in.eq(counter.counter[:4]),
30 | tens_segs.digit_in.eq(counter.counter[4:]),
31 | driver.pwm.eq(~0),
32 | driver.segment_patterns[0].eq(ones_segs.segments_out),
33 | driver.segment_patterns[1].eq(tens_segs.segments_out),
34 | seg7_pins.eq(driver.seg7),
35 | ]
36 | return m
37 |
38 |
39 | if __name__ == '__main__':
40 | platform = ICEBreakerPlatform()
41 | conn = ('pmod', 1)
42 | platform.add_resources([
43 | Resource('seg7', 0,
44 | Subsignal('segs', Pins('1 2 3 4 7 8 9', conn=conn, dir='o')),
45 | Subsignal('digit', Pins('10', conn=conn, dir='o')),
46 | ),
47 | ])
48 | platform.build(Top(), do_program=True)
49 |
--------------------------------------------------------------------------------
/apps/seven-seg-fade/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | NMIGEN_synth_opts=-dsp \
4 | PYTHONPATH=../.. \
5 | nmigen seven-seg-fade.py
6 |
--------------------------------------------------------------------------------
/apps/seven-seg-fade/seven-seg-fade.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from nmigen import *
4 | from nmigen.build import *
5 | from nmigen_boards.icebreaker import ICEBreakerPlatform
6 |
7 | from nmigen_lib.counter import Counter
8 | from nmigen_lib.timer import Timer
9 | from nmigen_lib.mul import Mul
10 | from nmigen_lib.seven_segment.digit_pattern import DigitPattern
11 | from nmigen_lib.seven_segment.driver import SevenSegDriver
12 |
13 |
14 | class Top(Elaboratable):
15 |
16 | def elaborate(self, platform):
17 | seg7_pins = platform.request('seg7', 0)
18 | pwm = Signal(16)
19 |
20 | clk_freq = platform.default_clk_frequency
21 | min_refresh_freq = 100
22 | count_freq = 10
23 | pwm_width = 12
24 |
25 | m = Module()
26 | ticker = Timer(period=int(clk_freq // count_freq))
27 | counter = Counter(period=16 * 16)
28 | ones_segs = DigitPattern()
29 | tens_segs = DigitPattern()
30 | squarer = Mul()
31 | driver = SevenSegDriver(clk_freq, min_refresh_freq, pwm_width)
32 | m.submodules += [ticker, counter, squarer,
33 | ones_segs, tens_segs, driver]
34 |
35 | m.d.comb += [
36 | counter.trg.eq(ticker.stb),
37 | ones_segs.digit_in.eq(counter.counter[:4]),
38 | tens_segs.digit_in.eq(counter.counter[4:]),
39 | squarer.multiplicand.eq(counter.counter),
40 | squarer.multiplier.eq(counter.counter),
41 | driver.pwm.eq(squarer.product[16 - pwm_width:]),
42 | driver.segment_patterns[0].eq(ones_segs.segments_out),
43 | driver.segment_patterns[1].eq(tens_segs.segments_out),
44 | seg7_pins.eq(driver.seg7),
45 | ]
46 | return m
47 |
48 |
49 | if __name__ == '__main__':
50 | platform = ICEBreakerPlatform()
51 | conn = ('pmod', 1)
52 | platform.add_resources([
53 | Resource('seg7', 0,
54 | Subsignal('segs', Pins('1 2 3 4 7 8 9', conn=conn, dir='o')),
55 | Subsignal('digit', Pins('10', conn=conn, dir='o')),
56 | ),
57 | ])
58 | platform.build(Top(), do_program=True)
59 |
--------------------------------------------------------------------------------
/nmigen_lib/README.md:
--------------------------------------------------------------------------------
1 | # Library Modules
2 |
3 | So far, we have one.. blinker. Blinks an LED (or other signal)
4 | with a specified period. Pretty simple.
5 |
6 | ## How to Use
7 |
8 | ```sh
9 | $ # Generate Verilog source.
10 | $ nmigen blinker.py generate > blinker.v
11 | $
12 | $ # Simulate and create .VCD trace. (100 clock periods)
13 | $ nmigen blinker.py simulate -v blinker.vcd -c 100
14 | $ open blinker.vcd
15 | ```
16 |
--------------------------------------------------------------------------------
/nmigen_lib/__init__.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | if sys.argv[:1] == ['-m']:
4 | __all__ = []
5 | else:
6 | from . import pipe, seven_segment
7 | from .blinker import Blinker
8 | from .buzzer import Buzzer
9 | from .counter import Counter
10 | from .i2s import I2SOut
11 | from .mul import Mul
12 | from .oneshot import OneShot
13 | from .pll import PLL
14 | from .timer import Timer
15 | from .uart import UART, UARTTx, UARTRx
16 | from .seven_segment.hex_display import HexDisplay
17 | from .seven_segment.driver import Seg7Record
18 |
19 | __all__ = [
20 | 'Blinker',
21 | 'Buzzer',
22 | 'Counter',
23 | 'HexDisplay',
24 | 'I2SOut',
25 | 'Mul',
26 | 'OneShot',
27 | 'PLL',
28 | 'Seg7Record',
29 | 'Timer',
30 | 'UART',
31 | 'UARTTx',
32 | 'UARTRx',
33 | 'pipe',
34 | 'seven_segment',
35 | ]
36 |
--------------------------------------------------------------------------------
/nmigen_lib/blinker.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from nmigen import *
4 | from nmigen.cli import main
5 |
6 | class Blinker(Elaboratable):
7 |
8 | def __init__(self, period):
9 | assert period % 2 == 0, 'period must be even'
10 | self.period = period
11 | self.led = Signal()
12 | self.counter = Signal((period - 4).bit_length())
13 | self.ports = [self.led]
14 |
15 | def elaborate(self, platform):
16 | m = Module()
17 | with m.If(self.counter[-1]):
18 | m.d.sync += [
19 | self.counter.eq(self.period // 2 - 2),
20 | self.led.eq(~self.led),
21 | ]
22 | with m.Else():
23 | m.d.sync += [
24 | self.counter.eq(self.counter - 1),
25 | ]
26 | return m
27 |
28 | if __name__ == '__main__':
29 | top = Blinker(period=12)
30 | main(top, ports=top.ports)
31 |
--------------------------------------------------------------------------------
/nmigen_lib/buzzer.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | import argparse
4 |
5 | from nmigen import *
6 | from nmigen_lib.util.main import Main
7 |
8 | class Buzzer(Elaboratable):
9 |
10 | def __init__(self, frequency, sample_frequency, depth=16):
11 | self.frequency = frequency
12 | self.sample_frequency = sample_frequency
13 | self.depth = depth
14 | self.sample = Signal(signed(depth))
15 | self.enable = Signal()
16 | self.stb = Signal()
17 | self.ack = Signal()
18 | self.ports = [self.enable, self.stb, self.ack, self.sample]
19 |
20 | def elaborate(self, platform):
21 | inc = round(2**self.depth * self.frequency / self.sample_frequency)
22 | # print(f'Buzzer: frequency = {self.frequency}')
23 | # print(f'Buzzer: sample_frequency = {self.sample_frequency}')
24 | # print(f'Buzzer: inc = {inc}')
25 | # print()
26 | m = Module()
27 | with m.If(self.ack):
28 | m.d.sync += [
29 | self.sample.eq(Mux(self.enable, self.sample + inc, 0)),
30 | self.stb.eq(False),
31 | ]
32 | with m.Else():
33 | m.d.sync += [
34 | self.stb.eq(True),
35 | ]
36 | return m
37 |
38 | if __name__ == '__main__':
39 | buzz_freq = 1_000
40 | samp_freq = 48_000
41 | clk_freq = 1_000_000
42 | sim_duration = 10 / buzz_freq
43 | design = Buzzer(buzz_freq, samp_freq)
44 | with Main(design).sim as sim:
45 | @sim.sync_process
46 | def ack_proc():
47 | strobed = False
48 | delay = round(clk_freq / samp_freq)
49 | yield design.ack.eq(True)
50 | yield design.enable.eq(True)
51 | acked = True
52 | yield
53 | for i in range(round(clk_freq * sim_duration)):
54 | if (yield design.stb):
55 | strobed = True
56 | if strobed and delay == 0:
57 | yield design.ack.eq(True)
58 | delay = round(clk_freq / samp_freq)
59 | strobed = False
60 | acked = True
61 | elif acked:
62 | yield design.ack.eq(False)
63 | acked = False
64 | if delay:
65 | delay -= 1
66 | yield
67 |
--------------------------------------------------------------------------------
/nmigen_lib/counter.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | import argparse
4 |
5 | from nmigen import *
6 | from nmigen_lib.util.main import Main
7 |
8 | class Counter(Elaboratable):
9 |
10 | """Count a fixed number of events. Assert .stb every `period` events."""
11 |
12 | def __init__(self, period):
13 | assert isinstance(period, int)
14 | self.period = period
15 | self.trg = Signal()
16 | self.counter = Signal((period - 1).bit_length())
17 | self.stb = Signal()
18 | self.ports = [self.counter, self.trg, self.stb]
19 |
20 | def elaborate(self, platform):
21 | m = Module()
22 | with m.If(self.trg & (self.counter == self.period - 1)):
23 | m.d.sync += [
24 | self.stb.eq(True),
25 | self.counter.eq(0),
26 | ]
27 | with m.Else():
28 | m.d.sync += [
29 | self.stb.eq(False),
30 | ]
31 | with m.If(self.trg):
32 | m.d.sync += [
33 | self.counter.eq(self.counter + 1),
34 | ]
35 | return m
36 |
37 |
38 | if __name__ == '__main__':
39 | design = Counter(5)
40 | with Main(design).sim as sim:
41 | @sim.sync_process
42 | def sample_gen_proc():
43 | def is_prime(n):
44 | return n >= 2 and all(n % k for k in range(2, n))
45 | for i in range(40):
46 | yield design.trg.eq(not is_prime(i))
47 | yield
48 |
49 |
50 | if __name__ == 'XXX__main__':
51 | def cheap_parser():
52 | parser = argparse.ArgumentParser()
53 | p_action = parser.add_subparsers(dest='action')
54 | p_generate = p_action.add_parser('generate', help='generate Verilog')
55 | p_simulate = p_action.add_parser('simulate', help='simulate the design')
56 | return parser
57 | parser = cheap_parser()
58 | args = parser.parse_args()
59 |
60 | if args.action == 'generate':
61 |
62 | design = Counter(5)
63 | fragment = Fragment.get(design, platform=None)
64 | print(verilog.convert(fragment, name='counter', ports=design.ports))
65 |
66 | elif args.action == 'simulate':
67 |
68 | design = Counter(5)
69 | with pysim.Simulator(design,
70 | vcd_file=open('counter.vcd', 'w'),
71 | gtkw_file=open('counter.gtkw', 'w'),
72 | traces=design.ports) as sim:
73 |
74 | @sim.add_sync_process
75 | def sample_gen_proc():
76 | def is_prime(n):
77 | return n >= 2 and all(n % k for k in range(2, n))
78 | for i in range(40):
79 | yield design.trg.eq(not is_prime(i))
80 | yield
81 |
82 | sim.add_clock(1e-6)
83 | sim.run()
84 | # sim.add_clock(1 / design.clk_freq)
85 | # sim.run_until(0.0005, run_passive=True)
86 |
--------------------------------------------------------------------------------
/nmigen_lib/i2s.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | import argparse
4 |
5 | from nmigen import Array, Cat, Elaboratable, Module, Record, Signal, signed
6 |
7 | from nmigen_lib.util.main import Main
8 |
9 |
10 | class I2SOut(Elaboratable):
11 |
12 | """
13 | Inter-IC Sound (I2S) output. Drives a Cirrus CS4344 converter.
14 |
15 | This module is hardcoded to two channels, 16 bit samples, 256X
16 | master clock. The master clock runs at half the speed of the
17 | module's clock. So the module should be clocked at a speed in
18 | the 16-64 MHz range.
19 |
20 | clock freq sample freq
21 | =========== ===========
22 | 16.3840 MHz 32 KHz
23 | 22.5792 MHz 44.1 KHz
24 | 24.5760 MHz 48 KHz
25 | 45.1584 MHz 88.2 KHz
26 | 49.1520 MHz 96 KHz
27 | 65.5360 MHz 128 KHz
28 |
29 | Intermediate frequencies are possible and are probably necessary
30 | when the hardware doesn't have a clock chosen specifically for I2S.
31 |
32 | Samples are flow controlled by two signals, `stb` and `ack`. The
33 | source should assert `stb` when a stereo sample is available, and
34 | this module asserts `ack` when the sample has been consumed.
35 |
36 | sample[0] is left channel, and sample[1] is right channel.
37 | """
38 |
39 | def __init__(self, clk_freq):
40 | self.clk_freq = clk_freq
41 | self.i2s = Record([
42 | ('mclk', 1),
43 | ('lrck', 1),
44 | ('sck', 1),
45 | ('sd', 1),
46 | ])
47 | self.samples = Array((Signal(signed(16)), Signal(signed(16))))
48 | self.stb = Signal()
49 | self.ack = Signal()
50 | self.ports = [self.i2s.mclk, self.i2s.lrck, self.i2s.sck, self.i2s.sd]
51 | self.ports += [self.samples[0], self.samples[1], self.stb, self.ack]
52 |
53 | @property
54 | def sample_frequency(self):
55 | return self.clk_freq / 2 / 256
56 |
57 | def elaborate(self, platform):
58 | bitstream = Signal(32)
59 | mcnt = Signal(9)
60 | mclk = Signal()
61 | sck = Signal()
62 | sd = Signal()
63 | lrck = Signal()
64 | m = Module()
65 | m.d.sync += [
66 | mcnt.eq(mcnt + 1),
67 | ]
68 | with m.If((mcnt == 0x00F) & (self.stb == True)):
69 | m.d.sync += [
70 | # I2S bitstream is MSB first, so reverse bits here.
71 | bitstream.eq(Cat(self.samples[0][::-1], self.samples[1][::-1])),
72 | self.ack.eq(True),
73 | ]
74 | with m.Elif(mcnt == 0x00F):
75 | m.d.sync += [
76 | bitstream.eq(0),
77 | self.ack.eq(False),
78 | ]
79 | with m.Else():
80 | m.d.sync += [
81 | self.ack.eq(False),
82 | ]
83 | m.d.sync += [
84 | mclk.eq(mcnt[0]),
85 | sck.eq(mcnt[3]),
86 | sd.eq(bitstream.bit_select(mcnt[4:4+5] - 1, 1)),
87 | lrck.eq(mcnt[4 + 4]),
88 | ]
89 | m.d.comb += [
90 | self.i2s.mclk.eq(mclk),
91 | self.i2s.sck.eq(sck),
92 | self.i2s.sd.eq(sd),
93 | self.i2s.lrck.eq(lrck),
94 | ]
95 | return m
96 |
97 |
98 | if __name__ == '__main__':
99 | design = I2SOut(24_000_000)
100 | with Main(design).sim as sim:
101 | @sim.sync_process
102 | def sample_gen_proc():
103 | left = 0; right = 100;
104 | for i in range(24):
105 | yield design.samples[0].eq(left)
106 | yield design.samples[1].eq(right)
107 | yield design.stb.eq(True)
108 | left += 3; right += 5
109 | while (yield design.ack) == False:
110 | yield
111 | yield design.stb.eq(False)
112 | yield
113 |
--------------------------------------------------------------------------------
/nmigen_lib/mul.py:
--------------------------------------------------------------------------------
1 | from nmigen import *
2 | from nmigen.asserts import *
3 |
4 | from nmigen_lib.util.main import Main
5 |
6 | class Mul(Elaboratable):
7 |
8 | def __init__(self, signed=False):
9 | self.multiplicand = Signal(Shape(16, signed))
10 | self.multiplier = Signal(Shape(16, signed))
11 | self.product = Signal(Shape(32, signed))
12 | self.ports = (self.multiplicand, self.multiplier, self.product)
13 |
14 | def elaborate(self, platform):
15 | m = Module()
16 | m.d.sync += [
17 | self.product.eq(self.multiplicand * self.multiplier)
18 | ]
19 | return m
20 |
21 | if __name__ == '__main__':
22 | design = Mul()
23 | with Main(design).sim as sim:
24 | @sim.sync_process
25 | def inputs_proc():
26 | a = b = 0
27 | for i in range(100):
28 | yield design.multiplier.eq(a)
29 | yield design.multiplicand.eq(b)
30 | yield
31 | a += 19
32 | b += 97
33 |
--------------------------------------------------------------------------------
/nmigen_lib/oneshot.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from nmigen import Elaboratable, Module, Signal
4 | from nmigen_lib.util import Main
5 |
6 | class OneShot(Elaboratable):
7 |
8 | def __init__(self, duration):
9 | self.duration = duration
10 | self.i_trg = Signal()
11 | self.o_pulse = Signal()
12 |
13 | def elaborate(self, platform):
14 | counter = Signal(range(-1, self.duration - 1))
15 | m = Module()
16 | with m.If(self.i_trg):
17 | m.d.sync += [
18 | counter.eq(self.duration - 2),
19 | self.o_pulse.eq(True),
20 | ]
21 | with m.Elif(counter[-1]):
22 | m.d.sync += [
23 | self.o_pulse.eq(False),
24 | ]
25 | with m.Else():
26 | m.d.sync += [
27 | counter.eq(counter - 1),
28 | ]
29 | return m
30 |
31 | if __name__ == '__main__':
32 | duration = 3
33 | design = OneShot(duration)
34 |
35 | # work aroun nMigen bug #280
36 | m = Module()
37 | m.submodules.design = design
38 | i_trg = Signal.like(design.i_trg)
39 | m.d.comb += [
40 | design.i_trg.eq(i_trg),
41 | ]
42 | #280 with Main(design).sim as sim:
43 | with Main(m).sim as sim:
44 | @sim.sync_process
45 | def test_proc():
46 |
47 | def set(value):
48 | #280 yield design.i_trg.eq(value)
49 | yield i_trg.eq(value)
50 |
51 | def chk(expected):
52 | actual = yield design.o_pulse
53 | assert actual == expected, f'wanted {expected}, got {actual}'
54 |
55 | def chk_n(expected, n):
56 | for _ in range(n):
57 | yield from chk(expected)
58 | yield
59 |
60 | try:
61 | # single pulse
62 | yield from chk_n(False, 1)
63 | yield from set(True)
64 | yield from chk_n(False, 1)
65 | yield from set(False)
66 | yield from chk_n(False, 1)
67 | yield from chk_n(True, duration)
68 | yield from chk_n(False, 1)
69 |
70 | # two overlapping pulses
71 | yield from set(True)
72 | yield from chk_n(False, 1)
73 | yield from set(False)
74 | yield from chk_n(False, 1)
75 | yield from chk_n(True, 1)
76 | yield from set(True)
77 | yield from chk_n(True, 1)
78 | yield from set(False)
79 | yield from chk_n(True, duration + 1)
80 | yield from chk_n(False, 1)
81 |
82 | except AssertionError:
83 | import traceback
84 | traceback.print_exc()
85 |
--------------------------------------------------------------------------------
/nmigen_lib/pipe/__init__.py:
--------------------------------------------------------------------------------
1 | from .spec import DATA_SIZE, START_STOP, PipeSpec
2 | from .endpoint import UnconnectedPipeEnd
3 | from .pipeline import Pipeline
4 |
5 | __all__ = [
6 | 'PipeSpec',
7 | 'UnconnectedPipeEnd',
8 | 'Pipeline',
9 | 'DATA_SIZE',
10 | 'START_STOP',
11 | ]
12 |
--------------------------------------------------------------------------------
/nmigen_lib/pipe/desc.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from enum import Enum, auto
4 | from typing import NamedTuple, Union
5 |
6 | from nmigen import Shape
7 | from nmigen.hdl.rec import Layout
8 |
9 | class SignalDirection(Enum):
10 | UPSTREAM = auto()
11 | DOWNSTREAM = auto()
12 |
13 |
14 | class SignalDesc(NamedTuple):
15 | name: str
16 | shape: Union[Layout, Shape]
17 | direction: SignalDirection = SignalDirection.DOWNSTREAM
18 |
--------------------------------------------------------------------------------
/nmigen_lib/pipe/endpoint.py:
--------------------------------------------------------------------------------
1 | from warnings import warn_explicit
2 | import sys
3 |
4 | from nmigen import Record, unsigned
5 |
6 | from .desc import SignalDesc, SignalDirection
7 |
8 |
9 | # There is no need to warn about unconnected pipes if the program crashes.
10 | _silence_warnings = False
11 | _old_excepthook = sys.excepthook
12 | def _new_excepthook(type, value, traceback):
13 | global _silence_warnings
14 | _silence_warnings = True
15 | return _old_excepthook(type, value, traceback)
16 | sys.excepthook = _new_excepthook
17 |
18 |
19 | class _PipeEnd(Record):
20 |
21 | def __init__(self, spec, layout, src_loc_at=0, **kwargs):
22 | super().__init__(layout, src_loc_at=src_loc_at + 1, **kwargs)
23 | self._spec = spec
24 | self._connected = False
25 | frame = sys._getframe(1 + src_loc_at)
26 | self._creation_context = {
27 | 'filename': frame.f_code.co_filename,
28 | 'lineno': frame.f_lineno,
29 | 'source': self
30 | }
31 |
32 | def __del__(self):
33 | if not self._connected and not _silence_warnings:
34 | warn_explicit(
35 | f'{self.__class__.__name__} {self!r} was never connected',
36 | UnconnectedPipeEnd,
37 | **self._creation_context,
38 | )
39 |
40 | def leave_unconnected(self):
41 | assert not self._connected, (
42 | f'pipe endpoint {self} is already connected'
43 | )
44 | self._connected = True # suppress warning
45 |
46 | @staticmethod
47 | def connect_ends(source, sink):
48 | assert isinstance(source, PipeInlet), (
49 | f'connection source must be PipeInlet, not {type(source)}'
50 | )
51 | assert isinstance(sink, PipeOutlet), (
52 | f'connection sink must be PipeOutlet, not {type(sink)}'
53 | )
54 | assert not source._connected, (
55 | f'connecting already-connected pipe inlet {source}'
56 | )
57 | assert not sink._connected, (
58 | f'connecting already-connected pipe outlet {sink}'
59 | )
60 | assert _PipeEnd._ends_are_compatible(source, sink), (
61 | f'connecting incompatible pipes {source._spec} and {sink._spec}'
62 | )
63 | source._connected = True
64 | sink._connected = True
65 | spec = source._spec
66 | return [
67 | dst.eq(src)
68 | for (src, dst) in [
69 | (source._get_signal(desc), sink._get_signal(desc))
70 | for desc in spec.downstream_signals
71 | ] + [
72 | (sink._get_signal(desc), source._get_signal(desc))
73 | for desc in spec.upstream_signals
74 | ]
75 | ]
76 |
77 | @staticmethod
78 | def _ends_are_compatible(source, sink):
79 | # Take the easy way out for now.
80 | return source._spec == sink._spec
81 |
82 | def _get_signal(self, desc):
83 | prefix = self.prefices[desc.direction]
84 | sig_name = prefix + desc.name
85 | return getattr(self, sig_name, None)
86 |
87 |
88 | class PipeInlet(_PipeEnd):
89 |
90 | def sent(self):
91 | """True when data is sent on the current clock."""
92 | return self.i_ready & self.o_valid
93 |
94 | def full(self):
95 | """True when receiver hasn't accepted last data."""
96 | return self.o_valid & ~self.i_ready
97 |
98 | def flow_to(self, outlet):
99 | return self.connect_ends(self, outlet)
100 |
101 | def leave_unconnected(self):
102 | super().leave_unconnected()
103 | self.i_ready.reset = 1 # Don't block senders
104 |
105 | prefices = {
106 | SignalDirection.UPSTREAM: 'i_',
107 | SignalDirection.DOWNSTREAM: 'o_',
108 | }
109 |
110 |
111 | class PipeOutlet(_PipeEnd):
112 |
113 | def received(self):
114 | """true when data is received on current clock."""
115 | return self.o_ready & self.i_valid
116 |
117 | def flow_from(self, inlet):
118 | return self.connect_ends(inlet, self)
119 |
120 | prefices = {
121 | SignalDirection.UPSTREAM: 'o_',
122 | SignalDirection.DOWNSTREAM: 'i_',
123 | }
124 |
125 |
126 | class UnconnectedPipeEnd(Warning):
127 | """A pipe end was instantiated but never connected."""
128 |
--------------------------------------------------------------------------------
/nmigen_lib/pipe/pipe.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | """
4 |
5 | # **This module is obsolete. It hasn't been removed because**
6 | # **the doc hasn't been moved to the new API.**
7 |
8 | Pipe -- unidirectional data transfer with handshaking.
9 |
10 | Pipes provide a framework and set of conventions that allows modules
11 | to pass data between them. Using pipes, two modules can be connected
12 | and synchronized without knowing much about each other.
13 |
14 | Pipes are modeled on David Williams' [SpokeFPGA
15 | pipes](https://davidthings.github.io/spokefpga/pipelines). In
16 | principle, they should be binary compatible with a shim to pack and
17 | unpack the signals, though the API is different.
18 |
19 | # The Data
20 |
21 | A pipe transfers one record of data at a time in parallel. The
22 | data format is described by an nMigen `Record` and may contain
23 | several pieces.
24 |
25 | # The Handshake
26 |
27 | The handshake protocol uses two signals,`ready` and `valid`. When the
28 | source is making data available, it stores it in the pipe's `data`
29 | signal and sets `valid`. When the sink can accept new data, it sets
30 | `ready`. Whenever the endpoints see that both `valid` and `ready`
31 | were active at the same time, they know that a transfer is complete.
32 | The sink must either use the data immediately or make a copy of it, as
33 | the source may overwrite it on the next clock.
34 |
35 | # Packets
36 |
37 | A pipe may optionally group data into packets (aka messages or
38 | frames). When a pipe is created with the START_STOP flag, two signals
39 | are created called `start` and `stop`. The pipe implementation itself
40 | does nothing with these signals; it is up to the source and sink to
41 | interpret them as the first and last records in a packet. See the
42 | [the SpokeFPGA
43 | documentation](https://davidthings.github.io/spokefpga/pipelines#start--stop)
44 | for more info.
45 |
46 | # Data Size
47 |
48 | A pipe may optionally pass a `size` signal that describes how many
49 | bits of the `data` field are valid. Again, see [the SpokeFPGA
50 | documentation](https://davidthings.github.io/spokefpga/pipelines#data-size).
51 |
52 | # API
53 |
54 | ## Creating a pipe
55 |
56 | The pipe constructor takes an nMigen Layout, Shape, or integer that
57 | describes the data signal's layout. A Shape or integer is coerced
58 | to a Layout using nMigen's rules.
59 |
60 | The constructor takes an optional `flags` argument. When flags'
61 | `DATA_SIZE` bit is set, the pipe has a `data_size` signal. When the
62 | `START_STOP` bit is set, the pipe has `start` and `stop` signals.
63 |
64 | Here are examples.
65 |
66 | >>> a_layout = Layout( # define a layout with two fields
67 | ... ('command', 4),
68 | ... ('operand', 8),
69 | ... )
70 | >>> my_pipe = Pipe(a_layout) # the payload is two fields.
71 | >>> my_pipe2 = Pipe(signed(16)) # payload is a signed int.
72 | >>> my_pipe3 = Pipe(16) # payload is an unsigned int.
73 | >>> my_pipe4 = Pipe(7, flags=START_STOP | DATA_SIZE)
74 | >>> # enable both options
75 |
76 | # Endpoints
77 |
78 | A pipe has two endpoints, accessible through its `source_end` and
79 | `sink_end` properties. Each endpoint is an nMigen Record subtype,
80 | and the signals can be accessed directly. For clarity, the
81 | signals are prefixed with `i_` for inputs and `o_` for outputs.
82 | Signals that transmit data downstream use the `o_` prefix on
83 | the source end and `i_` on the sink end. Upstream signals
84 | use the opposite convention.
85 |
86 | Currently, the only upstream signal is `ready`. The source
87 | endpoint's signal is called `i_ready`, and the sink endpoint's
88 | signal is called `o_ready`.
89 |
90 | The source endpoint's `sent` method tests whether a transfer has
91 | occurred.
92 |
93 | >>> my_src = my_pipe.source_endpoint
94 | >>> with m.If(my_src.sent()):
95 | ... # transfer happened. `o_data` may be loaded with next data.
96 |
97 | Similarly, the sink endpoint has a `received` method.
98 |
99 | >>> my_sink = my_pipe.sink_endpoint
100 | >>> with m.If(my_sink.received()):
101 | ... # transfer happened. Use or copy `i_data` now.
102 |
103 | # Making the Connection
104 |
105 | A pipe's endpoints must be connected before it works. This is done in
106 | the combinatoric domain. Somewhere, probably close to the pipe's
107 | constructor, connect the pipe with this code.
108 |
109 | >>> m.d.comb += my_pipe.connection()
110 |
111 | If a pipe is not connected, an `UnconnectedPipe` warning is raised
112 | when the pipe is destroyed.
113 |
114 | # TBD
115 |
116 | Create a PipeSpec class analogous to SpokeFPGA's PipeSpec; convert
117 | between PipeSpec and int, and create Pipe from PipeSpec (or int).
118 | Mostly for SpokeFPGA compatibility.
119 |
120 | SpokeFPGA pipes have a bunch of optional features that we don't --
121 | bidirectional data; command, request, and response fields; and
122 | maybe more.
123 | """
124 |
125 |
126 | from enum import Enum, auto
127 | import sys
128 | from typing import NamedTuple, Union
129 | from warnings import warn_explicit
130 |
131 | from nmigen import *
132 | from nmigen import tracer
133 | from nmigen.hdl.rec import *
134 |
135 | from nmigen_lib.util import delay, Main
136 |
137 |
138 | DATA_SIZE = 1 << 8
139 | START_STOP = 1 << 9
140 | REVERSE = 1 << 10
141 |
142 | class UnconnectedPipe(Warning):
143 | pass
144 |
145 |
146 | class SignalDirection(Enum):
147 | UPSTREAM = auto()
148 | DOWNSTREAM = auto()
149 |
150 |
151 | class SignalDesc(NamedTuple):
152 | name: str
153 | shape: Union[Layout, Shape]
154 | direction: SignalDirection = SignalDirection.DOWNSTREAM
155 |
156 |
157 | class PipeSourceEnd(Record):
158 |
159 | def __init__(self, layout, **kwargs):
160 | super().__init__(layout, **kwargs)
161 |
162 | def sent(self):
163 | """True when data is sent on the current clock."""
164 | return self.i_ready & self.o_valid
165 |
166 | def get_signal(self, desc):
167 | prefix = self.prefices[desc.direction]
168 | sig_name = prefix + desc.name
169 | return getattr(self, sig_name, None)
170 |
171 | prefices = {
172 | SignalDirection.UPSTREAM: 'i_',
173 | SignalDirection.DOWNSTREAM: 'o_',
174 | }
175 |
176 |
177 | class PipeSinkEnd(Record):
178 |
179 | def __init__(self, layout, **kwargs):
180 | super().__init__(layout, **kwargs)
181 |
182 | def received(self):
183 | """true when data is received on current clock."""
184 | return self.o_ready & self.i_valid
185 |
186 | def get_signal(self, desc):
187 | prefix = self.prefices[desc.direction]
188 | sig_name = prefix + desc.name
189 | return getattr(self, sig_name, None)
190 |
191 | prefices = {
192 | SignalDirection.UPSTREAM: 'o_',
193 | SignalDirection.DOWNSTREAM: 'i_',
194 | }
195 |
196 |
197 | class Pipe:
198 |
199 | def __init__(self,
200 | shape_or_layout,
201 | *,
202 | name=None,
203 | flags=0,
204 | result_size=0,
205 | command_size=0,
206 | request_size=0,
207 | src_loc_at=0,
208 | ):
209 | if flags & REVERSE:
210 | raise NotImplementedError('reverse pipe not implemented')
211 | if request_size:
212 | raise NotImplementedError('pipe request not implemented')
213 | if result_size:
214 | raise NotImplementedError('pipe result not implemented')
215 | if command_size:
216 | raise NotImplementedError('pipe command not implemented')
217 | if name is None:
218 | name = tracer.get_var_name(depth=2 + src_loc_at, default='$pipe')
219 | self._data_layout = shape_or_layout
220 | self._name = name
221 | self._flags = flags
222 | self._result_size = result_size
223 | self._command_size = command_size
224 | self._request_size = request_size
225 | self._src_loc_at = src_loc_at
226 | self._connected = False
227 | frame = sys._getframe(1 + src_loc_at)
228 | self._creation_context = {
229 | 'filename': frame.f_code.co_filename,
230 | 'lineno': frame.f_lineno,
231 | 'source': self
232 | }
233 | self._src_end = PipeSourceEnd(
234 | Layout(
235 | (PipeSourceEnd.prefices[dir] + name, shape)
236 | for (name, shape, dir) in self._signals()
237 | ),
238 | name='o_' + self._name,
239 | )
240 | self._snk_end = PipeSinkEnd(
241 | Layout(
242 | (PipeSinkEnd.prefices[dir] + name, shape)
243 | for (name, shape, dir) in self._signals()
244 | ),
245 | name='i_' + self._name,
246 | )
247 |
248 | def __del__(self):
249 | if not self._connected:
250 | warn_explicit(
251 | f'{self!r} was never connected',
252 | UnconnectedPipe,
253 | **self._creation_context,
254 | )
255 |
256 | def __repr__(self):
257 | return f'<{self.__class__.__name__} {self._name}>'
258 |
259 | @property
260 | def source_end(self):
261 | return self._src_end
262 |
263 | @property
264 | def sink_end(self):
265 | return self._snk_end
266 |
267 | def connection(self):
268 | self._connected = True
269 | source, sink = self.source_end, self.sink_end
270 | return [
271 | dst.eq(src)
272 | for (src, dst) in [
273 | (source.get_signal(desc), sink.get_signal(desc))
274 | for desc in self.downstream_signals
275 | ] + [
276 | (sink.get_signal(desc), source.get_signal(desc))
277 | for desc in self.upstream_signals
278 | ]
279 | ]
280 |
281 | def _signals(self):
282 | sigs = (
283 | SignalDesc('ready', 1, SignalDirection.UPSTREAM),
284 | SignalDesc('valid', 1),
285 | SignalDesc('data', self._data_layout),
286 | )
287 | if self._flags & DATA_SIZE:
288 | tmp = Record(self._data_layout)
289 | size_bits = (tmp.shape()[0] + 1).bit_length()
290 | sigs += (
291 | SignalDesc('data_size', size_bits),
292 | )
293 | if self._flags & START_STOP:
294 | sigs += (
295 | SignalDesc('start', 1),
296 | SignalDesc('stop', 1),
297 | )
298 | return sigs
299 |
300 | @property
301 | def payload_signals(self):
302 | def is_payload(name, shape, dir):
303 | return name not in {'ready', 'valid'}
304 | return self._filter_signals(is_payload)
305 |
306 | @property
307 | def handshake_signals(self):
308 | def is_handshake(name, shape, dir):
309 | return name in {'ready', 'valid'}
310 | return self._filter_signals(is_handshake)
311 |
312 | @property
313 | def upstream_signals(self):
314 | def is_upstream(name, shape, dir):
315 | return dir == SignalDirection.UPSTREAM
316 | return self._filter_signals(is_upstream)
317 |
318 | @property
319 | def downstream_signals(self):
320 | def is_downstream(name, shape, dir):
321 | return dir == SignalDirection.DOWNSTREAM
322 | return self._filter_signals(is_downstream)
323 |
324 | def _filter_signals(self, predicate):
325 | return tuple(
326 | sig
327 | for sig in self._signals()
328 | if predicate(sig.name, sig.shape, sig.direction)
329 | )
330 |
331 |
332 | if __name__ == '__main__':
333 |
334 | class TestSource(Elaboratable):
335 |
336 | def __init__(self, pipe):
337 | self.trigger = Signal()
338 | self.data_out = pipe.source_end
339 |
340 | def elaborate(self, platform):
341 | counter = Signal.like(self.data_out.o_data, reset=0x10)
342 | m = Module()
343 | m.d.comb += [
344 | self.data_out.o_data.eq(counter),
345 | ]
346 | with m.If(self.trigger):
347 | m.d.sync += [
348 | self.data_out.o_valid.eq(True),
349 | ]
350 | with m.Else():
351 | m.d.sync += [
352 | self.data_out.o_valid.eq(False),
353 | ]
354 | with m.If(self.data_out.sent()):
355 | m.d.sync += [
356 | counter.eq(counter + 1),
357 | ]
358 | return m
359 |
360 |
361 | class TestSink(Elaboratable):
362 |
363 | def __init__(self, pipe):
364 | self.data = Signal.like(pipe.sink_end.i_data)
365 | self.data_in = pipe.sink_end
366 |
367 | def elaborate(self, platform):
368 | m = Module()
369 | with m.If(self.data_in.received()):
370 | m.d.sync += [
371 | self.data.eq(self.data_in.i_data),
372 | self.data_in.o_ready.eq(self.data[1]),
373 | ]
374 | with m.Else():
375 | m.d.sync += [
376 | self.data_in.o_ready.eq(True)
377 | ]
378 | return m
379 |
380 |
381 | class Top(Elaboratable):
382 |
383 | def __init__(self):
384 | self.trigger = Signal()
385 |
386 | def elaborate(self, platform):
387 | my_pipe = Pipe(unsigned(8))
388 | m = Module()
389 | src = TestSource(my_pipe)
390 | snk = TestSink(my_pipe)
391 | m.submodules.source = src
392 | m.submodules.sink = self.sink = snk
393 | m.d.comb += my_pipe.connection()
394 | m.d.comb += src.trigger.eq(self.trigger)
395 | return m
396 |
397 |
398 | top = Top()
399 | with Main(top).sim as sim:
400 | @sim.sync_process
401 | def trigger_proc():
402 | trg = top.trigger
403 | for i in range(10):
404 | yield trg.eq(True)
405 | yield
406 | if i % 3:
407 | yield trg.eq(False)
408 | yield from delay((i + 1) % 3)
409 | yield trg.eq(False)
410 | yield from delay(3)
411 | @sim.sync_process
412 | def result_proc():
413 | expected = (
414 | 0, 0, 0,
415 | 0x10, 0x10, 0x10, 0x10,
416 | 0x11, 0x11,
417 | 0x12, 0x12, 0x12,
418 | 0x13,
419 | 0x14,
420 | 0x15, 0x15, 0x15,
421 | 0x16, 0x16,
422 | )
423 | for (i, e) in enumerate(expected):
424 | a = (yield top.sink.data)
425 | assert (yield top.sink.data) == e, (
426 | f'tick {i}: expected {e:#x}, actual {a:#x}'
427 | )
428 | yield
429 |
--------------------------------------------------------------------------------
/nmigen_lib/pipe/pipeline.py:
--------------------------------------------------------------------------------
1 | from nmigen import Elaboratable, Module
2 |
3 | from .endpoint import PipeInlet, PipeOutlet
4 |
5 | class Pipeline(Elaboratable):
6 |
7 | def __init__(self, seq):
8 | self.seq = seq
9 |
10 | def elaborate(self, platform):
11 | m = Module()
12 | sink = None
13 | for source in self.seq:
14 | if sink is not None:
15 | outlets = find_outlets(source)
16 | if not outlets:
17 | raise ValueError(f'{source} has no PipeOutlet members')
18 | inlets = find_inlets(sink)
19 | if not inlets:
20 | raise ValueError(f'{sink} has no PipeInlet members')
21 | try:
22 | outlet, inlet = best_match(outlets, inlets)
23 | except TypeError:
24 | raise ValueError(
25 | f'{sink} and {source} have no matching pipe endpoints'
26 | )
27 | m.d.comb += outlet.flow_from(inlet)
28 | sink = source
29 | return m
30 |
31 |
32 | def find_outlets(obj):
33 | if isinstance(obj, PipeOutlet):
34 | return [obj]
35 | return [
36 | member
37 | for member in obj.__dict__.values()
38 | if isinstance(member, PipeOutlet)
39 | ]
40 |
41 | def find_inlets(obj):
42 | if isinstance(obj, PipeInlet):
43 | return [obj]
44 | return [
45 | member
46 | for member in obj.__dict__.values()
47 | if isinstance(member, PipeInlet)
48 | ]
49 |
50 | def best_match(outlets, inlets):
51 | for o in outlets:
52 | for i in inlets:
53 | if o._spec == i._spec:
54 | return o, i
55 |
--------------------------------------------------------------------------------
/nmigen_lib/pipe/simple.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from nmigen import Elaboratable, Module
4 |
5 | from nmigen_lib.pipe import PipeSpec, START_STOP
6 |
7 | # This code is an idea. It does not run in current form.
8 | # But boy would it make pipelining easy...
9 | #
10 | # A `SimpleStage` is a pipeline stage that can always compute one
11 | # result from one input in a single clock. It has no state
12 | # or external timing dependencies.
13 | #
14 | # Example:
15 | # into_a = PipeSpec(...)
16 | # a_to_b = PipeSpec(...)
17 | # b_to_c = PipeSpec(...)
18 | # out_of_c = PipeSpec(...)
19 | #
20 | # class A(SimpleStage):
21 | #
22 | # # set output `o` based on input `i`. Handshake
23 | # # and flow control are provided.
24 | # def logic(self, m, i, o):
25 | # m.d.sync += o.eq(...)
26 | # m.d.comb += ...
27 | #
28 | # class B(SimpleStage):
29 | #
30 | # # control both logic and optional handshake signals
31 | # def logic_and_handshake(self, m, i, o):
32 | # m.d.sync += [
33 | # o.data.eq(...),
34 | # o.o_start.eq(...), # or whatever
35 | # ]
36 | #
37 | # m.submodules.a = a = SimpleStage(into_a, a_to_b)
38 | # m.submodules.b = b = SimpleStage(a_to_b, b_to_c)
39 | # m.submodules.c = SimpleStage.sync_expr([o.eq(...), ...])
40 | #
41 | # And that's it. The last one doesn't work, because the input and
42 | # output pipespecs are not passed in, and because `o` is not bound
43 | # in the expression.
44 |
45 | # Here's another idea.
46 | #
47 | # m.pipeline = pipeline = SimplePipeline.assemble(
48 | # PipeSpec(16), # pipe takes unsigned(16) words
49 | # LogicStage(
50 | # lambda i, o: o.eq(some_function(i))
51 | # ),
52 | # PipeSpec(unsigned(12)), # 1st stage passes unsigned(16) to 2nd
53 | # LogicAndHandshakeStage(
54 | # lambda i, o:
55 | # [
56 | # o.o_data_size.eq(whatever),
57 | # o.o_data.flag.eq(some_condition),
58 | # o.o_data.word.eq(other_function(i)),
59 | # ]
60 | # ),
61 | # PipeSpec((('flag': 1), ('word', signed(8)), flags=DATA_SIZE)
62 | # # pipe emits flag + 8-bit word + data_size.
63 | # )
64 |
65 | class Decimator(Elaboratable):
66 |
67 | def __init__(self, cfg):
68 | ...
69 | self.samples_in = mono_sample_spec(cfg.osc_depth).outlet()
70 | self.samples_out = mono_sample_spec(cfg.osc_depth).inlet()
71 |
72 | def elaborate(self, platform):
73 | m = Module()
74 | N = self.M + 2
75 | assert _is_power_of_2(N)
76 | # kernel_RAM = Memory(width=COEFF_WIDTH, depth=N, init=kernel)
77 | m.submodules.kr_port = kr_port = kernel_RAM.read_port()
78 | sample_RAM = Memory(width=self.sample_depth, depth=N, init=[0] * N)
79 | m.submodules.sw_port = sw_port = sample_RAM.write_port()
80 | m.submodules.sr_port = sr_port = sample_RAM.read_port()
81 |
82 | roto_sample_spec = PipeSpec(
83 | (
84 | ('coeff', COEFF_SHAPE),
85 | ('sample', signed(sample_depth)),
86 | ),
87 | flags=START_STOP,
88 | )
89 |
90 | class RotorFIFO(Elaboratable):
91 | def elaborate(self):
92 | m = Module()
93 | # when samples_in and fifo not full: insert sample.
94 | # when samples_readable and out pipe not full:
95 | # out pipe send {}
96 | # o_data.coeff = kernel[c_index],
97 | # o_data.sample = sample[...],
98 | # o_start=c_index == 1,
99 | # o_stop=c_index == ~0,
100 | # }
101 | # when c_index == ~0:
102 | # c_index = 1
103 | # sr_index = start_index + R
104 | # start_index += R
105 | # else:
106 | # c_index += 1
107 | # sr_index += 1
108 | return m
109 |
110 |
111 | m.submodules.rfifo = RotorFifo()
112 | m.submodules.pipe = SimplePipeline.assemble(
113 | roto_sample_spec,
114 | LogicModule(lambda m, i, o: o.eq(i.coeff * i.sample)),
115 | PipeSpec(signed(COEFF_WIDTH + sample_depth)),
116 | LogicAndHandshakeModule(
117 | lambda m, i, o: {
118 | 'sync': acc.eq(Mux(i_start, i_data, acc + i_data)),
119 | 'comb': o.o_data.eq(acc[shift:]),
120 | }
121 | ),
122 | PipeSpec(signed(sample_depth)),
123 | flags=START_STOP,
124 | )
125 | return m
126 |
127 |
128 |
129 | class SimplePipeline(Elaboratable):
130 |
131 | @classmethod
132 | def assemble(cls, *args):
133 | assert len(args) % 2 == 1
134 | assert all(callable(a) for a in args[1::2])
135 | assert all(isinstance(s, PipeSpec) for s in args[::2])
136 | pline = cls()
137 | pline.inlet = args[0]
138 | pline.outlet = args[1]
139 | stages = args[1:-1:2]
140 | sources = args[:-2:2]
141 | sinks = args[2::2]
142 | for (src, stg, snk) in zip(sources, stages, sinks):
143 | # get name for stage
144 | # LogicStg()
145 | ...
146 | return pline
147 |
148 | def __init__(self):
149 | self.stages = []
150 | self.connector_specs = []
151 |
152 | # @property.setter
153 | # def inlet(self, spec):
154 | # self.inlet_spec = spec
155 | # self.data_in = spec.outlet()
156 | # return self
157 | #
158 | # @property.setter
159 | # def outlet(self, spec):
160 | # self.outlet_spec = spec
161 | # self.data_out = spec.inlet()
162 | # return self
163 |
164 | def data(self, data):
165 | self.elements.append(data)
166 | return self
167 |
168 | def logic_stage(self, logic):
169 | """logic may be:
170 | a callable
171 | an assignment (e.g. a.eq(b0))
172 | a list of assignments
173 | a dict that maps domain names to (list of) assignments
174 | """
175 | self.stages.append(logic)
176 | return self
177 |
178 | def logic_and_handshake_stage(self, logic):
179 | """logic may be a callable or a dict"""
180 | self.elements.append(logic)
181 | return self
182 |
183 | def elaborate(self, platform):
184 | ...
185 |
186 |
187 | class SimpleStage(Elaboratable):
188 |
189 | def __init__(self, in_spec, out_spec):
190 | self.in_data = in_spec.outlet()
191 | self.out_data = out_spec.inlet()
192 |
193 | def elaborate(self, platform):
194 | m = Module()
195 | m.d.comb += self.in_data.o_ready.eq(~self.out_data.full())
196 | with m.If(self.in_data.received()):
197 | self.logic_and_handshake(m, self.in_data, self.out_data)
198 | m.d.sync += self.out_data.o_valid.eq(True)
199 | with m.Else():
200 | m.d.sync += self.out_data.o_valid.eq(False)
201 | return
202 |
203 | def logic_and_handshake(self, m, i, o):
204 | """default implementation. Override to access handshake signals."""
205 | ...
206 | return self.logic(m, i.i_data, o.o_data)
207 |
208 | def logic(self, m, i, o):
209 | """Override with code that unconditionally computes o from i."""
210 | raise NotImplementedError()
211 |
212 | def elaborate(self, platform):
213 | m = Module()
214 | logic = self.logic_and_handshake(m, self.in_data, self.out_data)
215 | if isinstance(logic, dict):
216 | ...
217 | elif isinstance(logic, AST):
218 | ...
219 | return m
220 |
221 | # @classmethod
222 | # def sync_expr(cls, m, sync_exprs):
223 | # """create a pipeline stage around one or more nMigen AST expressions"""
224 | # class Anonymous(cls):
225 | # def logic(self, m, i, o):
226 | # m.d.sync += sync_exprs
227 | # return Anonymous()
228 |
229 |
230 | def LogicAndHandshakeStage(SimpleStage):
231 |
232 | def __init__(self, logic):
233 | super().__init__(None, None)
234 | self._logic = logic
235 |
236 | def logic_and_handshake(self, m, i, o):
237 | frag = self._logic
238 | if callable(frag):
239 | frag = frag(m, i, o)
240 | if isinstance(frag, (list, Assign)):
241 | m.d.sync += frag
242 | elif isinstance(frag, dict):
243 | for domain, frags in frag:
244 | m.d[domain] += frag
245 | else:
246 | raise TypeError('unknown logic_and_handshake {frag!r}')
247 |
248 |
249 | if __name__ == '__main__':
250 | spec = PipeSpec(1) # one bit of data
251 | # design = SimpleStage.sync_expr(o.eq(~i))
252 |
--------------------------------------------------------------------------------
/nmigen_lib/pipe/spec.py:
--------------------------------------------------------------------------------
1 | from typing import NamedTuple, Union
2 |
3 | from nmigen import Elaboratable, Module, Record, Shape, Signal, Value
4 | from nmigen import signed, unsigned
5 | from nmigen.hdl.rec import Layout
6 |
7 | from nmigen_lib.util import Main, delay
8 |
9 | from .desc import SignalDesc, SignalDirection
10 | from .endpoint import PipeInlet, PipeOutlet
11 |
12 |
13 | DATA_SIZE = 1 << 8
14 | START_STOP = 1 << 9
15 |
16 |
17 | class PipeSpec(NamedTuple):
18 | flags: int
19 | dsol: Union[Shape, Layout]
20 |
21 | @classmethod
22 | def new(cls, dswol, *, flags=0):
23 | """
24 | Create a PipeSpec.
25 |
26 | The first arg is either the width of the data signal, the `Shape`
27 | of the data signal, a `Layout` describing the data signal, or
28 | a tuple of tuples that nMigen can coerce into a `Layout`.
29 |
30 | The flags arg may include DATA_SIZE or START_STOP flags.
31 | """
32 | # dsol: data shape or layout
33 | # dwsol: data width, shape, or layout
34 | if isinstance(dswol, (Shape, int)):
35 | dsol = Shape.cast(dswol)
36 | else:
37 | dsol = Layout.cast(dswol)
38 | return cls(flags, dsol)
39 |
40 | @classmethod
41 | def from_int(cls, n):
42 | """
43 | Create a PipeSpec from a 32 bit integer for SpokeFPGA compatibility.
44 | """
45 | data_width = n & 0xFF
46 | flags = n & 0x300
47 | if n != data_width | flags:
48 | raise ValueError(f'invalid PipeSpec {n:\#x}')
49 | return cls.new(data_width, flags=flags)
50 |
51 | @property
52 | def as_int(self):
53 | """Convert a PipeSpec to a SpokeFPGA-compatible 32 bit integer."""
54 | return self.data_width | self.flags
55 |
56 | @property
57 | def data_width(self):
58 | return Record((('d', self.dsol), )).shape()[0]
59 |
60 | @property
61 | def data_size(self):
62 | return bool(self.flags & DATA_SIZE)
63 |
64 | @property
65 | def start_stop(self):
66 | return bool(self.flags & START_STOP)
67 |
68 | def inlet(self, **kwargs):
69 | return PipeInlet(
70 | self,
71 | Layout(
72 | (PipeInlet.prefices[dir] + name, shape)
73 | for (name, shape, dir) in self._signals()
74 | ),
75 | src_loc_at=1,
76 | **kwargs,
77 | )
78 |
79 | def outlet(self, **kwargs):
80 | return PipeOutlet(
81 | self,
82 | Layout(
83 | (PipeOutlet.prefices[dir] + name, shape)
84 | for (name, shape, dir) in self._signals()
85 | ),
86 | src_loc_at=1,
87 | **kwargs,
88 | )
89 |
90 | def _signals(self):
91 | # N.B., these need to be in the same order as SpokeFPGA uses.
92 | sigs = (
93 | SignalDesc('data', self.dsol),
94 | )
95 | if self.flags & DATA_SIZE:
96 | size_bits = (self.data_width + 1).bit_length()
97 | sigs += (
98 | SignalDesc('data_size', size_bits),
99 | )
100 | if self.flags & START_STOP:
101 | sigs += (
102 | SignalDesc('stop', 1),
103 | SignalDesc('start', 1),
104 | )
105 | sigs += (
106 | SignalDesc('valid', 1),
107 | SignalDesc('ready', 1, SignalDirection.UPSTREAM),
108 | )
109 | return sigs
110 |
111 | @property
112 | def payload_signals(self):
113 | def is_payload(name, shape, dir):
114 | return name not in {'ready', 'valid'}
115 | return self._filter_signals(is_payload)
116 |
117 | @property
118 | def handshake_signals(self):
119 | def is_handshake(name, shape, dir):
120 | return name in {'ready', 'valid'}
121 | return self._filter_signals(is_handshake)
122 |
123 | @property
124 | def upstream_signals(self):
125 | def is_upstream(name, shape, dir):
126 | return dir == SignalDirection.UPSTREAM
127 | return self._filter_signals(is_upstream)
128 |
129 | @property
130 | def downstream_signals(self):
131 | def is_downstream(name, shape, dir):
132 | return dir == SignalDirection.DOWNSTREAM
133 | return self._filter_signals(is_downstream)
134 |
135 | def _filter_signals(self, predicate):
136 | return tuple(
137 | sig
138 | for sig in self._signals()
139 | if predicate(sig.name, sig.shape, sig.direction)
140 | )
141 |
142 |
143 | # Override the NamedTuple constructor the hard way.
144 | _PipeSpec = PipeSpec
145 | del PipeSpec
146 |
147 | def PipeSpec(data_width_shape_or_layout, *, flags=0):
148 | return _PipeSpec.new(data_width_shape_or_layout, flags=flags)
149 | PipeSpec.__doc__ = _PipeSpec.new.__doc__
150 | PipeSpec.from_int = _PipeSpec.from_int
151 |
--------------------------------------------------------------------------------
/nmigen_lib/pipe/test.py:
--------------------------------------------------------------------------------
1 | from nmigen import Elaboratable, Module, Record, Signal, Value
2 | from nmigen import Shape, signed, unsigned
3 | from nmigen.hdl.rec import Layout
4 |
5 | from nmigen_lib.pipe import *
6 | from nmigen_lib.pipe.endpoint import PipeInlet, PipeOutlet
7 | from nmigen_lib.util import Main, delay
8 |
9 | if __name__ == '__main__':
10 |
11 | def selftest():
12 | ps0 = PipeSpec(8)
13 | assert ps0.data_width == 8
14 | assert ps0.flags == 0
15 | assert type(ps0.dsol) is Shape
16 | assert ps0.dsol == unsigned(8)
17 | assert ps0.start_stop is False
18 | assert ps0.data_size is False
19 | assert ps0.as_int == 8
20 | pi0 = ps0.inlet()
21 | assert isinstance(pi0, PipeInlet)
22 | assert isinstance(pi0, Record)
23 | assert isinstance(pi0, Value)
24 | assert pi0.o_data.shape() == unsigned(8)
25 | c0 = pi0.flow_to(ps0.outlet())
26 | assert len(c0) == 3
27 | assert repr(c0[0]) == '(eq (sig i_data) (sig pi0__o_data))'
28 | assert repr(c0[1]) == '(eq (sig i_valid) (sig pi0__o_valid))'
29 | assert repr(c0[2]) == '(eq (sig pi0__i_ready) (sig o_ready))'
30 |
31 | ps1 = PipeSpec(signed(5), flags=DATA_SIZE)
32 | assert ps1.data_width == 5
33 | assert ps1.flags == DATA_SIZE
34 | assert type(ps1.dsol) is Shape
35 | assert ps1.dsol == signed(5)
36 | assert ps1.start_stop is False
37 | assert ps1.data_size is True
38 | assert ps1.as_int == 256 + 5
39 | pi1 = ps1.inlet()
40 | assert isinstance(pi1, PipeInlet)
41 | assert isinstance(pi1, Record)
42 | assert isinstance(pi1, Value)
43 | assert pi1.o_data.shape() == signed(5)
44 | c1 = ps1.outlet().flow_from(pi1)
45 | assert len(c1) == 4
46 |
47 | ps2 = PipeSpec((('a', signed(4)), ('b', unsigned(2))), flags=START_STOP)
48 | assert ps2.data_width == 6
49 | assert ps2.flags == START_STOP
50 | assert type(ps2.dsol) is Layout
51 | assert ps2.dsol == Layout((('a', signed(4)), ('b', unsigned(2))))
52 | assert ps2.start_stop is True
53 | assert ps2.data_size is False
54 | assert ps2.as_int == 512 + 6
55 | pi2 = ps2.inlet()
56 | assert isinstance(pi2, PipeInlet)
57 | assert isinstance(pi2, Record)
58 | assert isinstance(pi2, Value)
59 | assert pi2.o_data.shape() == unsigned(4 + 2)
60 | po2 = ps2.outlet()
61 | assert isinstance(po2, PipeOutlet)
62 | assert po2.i_data.shape() == unsigned(4 + 2)
63 | c2 = pi2.flow_to(po2)
64 | assert len(c2) == 5
65 |
66 | ps3 = PipeSpec.from_int(START_STOP | DATA_SIZE | 10)
67 | assert ps3.data_width == 10
68 | assert ps3.flags == START_STOP | DATA_SIZE
69 | assert type(ps3.dsol) is Shape
70 | assert ps3.dsol == unsigned(10)
71 | assert ps3.start_stop is True
72 | assert ps3.data_size is True
73 | assert ps3.as_int == 512 + 256 + 10
74 | pi3 = ps3.inlet(name='inlet_3')
75 | assert isinstance(pi3, PipeInlet)
76 | assert isinstance(pi3, Record)
77 | assert isinstance(pi3, Value)
78 | assert pi3.o_data.shape() == unsigned(10)
79 | inlet_3 = ps3.inlet()
80 | po3 = ps3.outlet(name='outlet_3')
81 | outlet_3 = ps3.outlet()
82 | assert repr(pi3) == repr(inlet_3)
83 | assert repr(po3) == repr(outlet_3)
84 | assert repr(pi3.fields) == repr(inlet_3.fields)
85 | assert repr(po3.fields) == repr(outlet_3.fields)
86 | c3 = pi3.flow_to(po3)
87 | c3a = outlet_3.flow_from(inlet_3)
88 | assert len(c3) == 6
89 | assert len(c3a) == 6
90 |
91 | selftest()
92 |
93 | my_spec = PipeSpec(8)
94 |
95 | class TestSource(Elaboratable):
96 |
97 | def __init__(self):
98 | self.trigger = Signal()
99 | self.data_out = my_spec.inlet()
100 |
101 | def elaborate(self, platform):
102 | counter = Signal.like(self.data_out.o_data, reset=0x10)
103 | m = Module()
104 | m.d.comb += [
105 | self.data_out.o_data.eq(counter),
106 | ]
107 | with m.If(self.trigger):
108 | m.d.sync += [
109 | self.data_out.o_valid.eq(True),
110 | ]
111 | with m.Else():
112 | m.d.sync += [
113 | self.data_out.o_valid.eq(False),
114 | ]
115 | with m.If(self.data_out.sent()):
116 | m.d.sync += [
117 | counter.eq(counter + 1),
118 | ]
119 | return m
120 |
121 |
122 | class TestSink(Elaboratable):
123 |
124 | def __init__(self):
125 | self.data_in = my_spec.outlet()
126 | self.data = Signal.like(self.data_in.i_data)
127 |
128 | def elaborate(self, platform):
129 | m = Module()
130 | with m.If(self.data_in.received()):
131 | m.d.sync += [
132 | self.data.eq(self.data_in.i_data),
133 | self.data_in.o_ready.eq(self.data[1]),
134 | ]
135 | with m.Else():
136 | m.d.sync += [
137 | self.data_in.o_ready.eq(True)
138 | ]
139 | return m
140 |
141 |
142 | class Top(Elaboratable):
143 |
144 | def __init__(self):
145 | self.trigger = Signal()
146 |
147 | def elaborate(self, platform):
148 | m = Module()
149 | src = TestSource()
150 | snk = TestSink()
151 | m.submodules.source = src
152 | m.submodules.sink = self.sink = snk
153 | m.d.comb += src.data_out.flow_to(snk.data_in)
154 | m.d.comb += src.trigger.eq(self.trigger)
155 | return m
156 |
157 |
158 | top = Top()
159 | with Main(top).sim as sim:
160 | @sim.sync_process
161 | def trigger_proc():
162 | trg = top.trigger
163 | for i in range(10):
164 | yield trg.eq(True)
165 | yield
166 | if i % 3:
167 | yield trg.eq(False)
168 | yield from delay((i + 1) % 3)
169 | yield trg.eq(False)
170 | yield from delay(3)
171 | @sim.sync_process
172 | def result_proc():
173 | expected = (
174 | 0, 0, 0,
175 | 0x10, 0x10, 0x10, 0x10,
176 | 0x11, 0x11,
177 | 0x12, 0x12, 0x12,
178 | 0x13,
179 | 0x14,
180 | 0x15, 0x15, 0x15,
181 | 0x16, 0x16,
182 | )
183 | for (i, e) in enumerate(expected):
184 | a = (yield top.sink.data)
185 | assert (yield top.sink.data) == e, (
186 | f'tick {i}: expected {e:#x}, actual {a:#x}'
187 | )
188 | yield
189 |
--------------------------------------------------------------------------------
/nmigen_lib/pipe/uart.py:
--------------------------------------------------------------------------------
1 | from nmigen import Elaboratable, Module, Signal
2 | from nmigen.back.pysim import Passive
3 |
4 | from nmigen_lib.uart import UARTTx, UARTRx
5 | from . import *
6 | from nmigen_lib.util import Main, delay
7 |
8 |
9 | class P_UART(Elaboratable):
10 |
11 | def __init__(self, divisor, data_bits=8):
12 | self.divisor = divisor
13 | self.data_bits = data_bits
14 |
15 | data_spec = PipeSpec(data_bits)
16 |
17 | self.tx_in = data_spec.outlet()
18 | self.rx_out = data_spec.inlet()
19 |
20 | self.tx_pin = Signal()
21 | self.rx_pin = Signal()
22 | self.rx_err = Signal()
23 |
24 | def elaborate(self, platform):
25 | m = Module()
26 | tx = P_UARTTx(self.divisor, self.data_bits, self.tx_in)
27 | rx = P_UARTRx(self.divisor, self.data_bits, self.rx_out)
28 | m.submodules.tx = tx
29 | m.submodules.rx = rx
30 | m.d.comb += [
31 | self.tx_pin.eq(tx.tx_pin),
32 | rx.rx_pin.eq(self.rx_pin),
33 | ]
34 | return m
35 |
36 |
37 | class P_UARTTx(Elaboratable):
38 |
39 | def __init__(self, divisor, data_bits, outlet=None):
40 | if outlet is None:
41 | outlet = PipeSpec(data_bits).outlet()
42 | self.divisor = divisor
43 | self.data_bits = data_bits
44 |
45 | self.tx_pin = Signal()
46 | self.tx_in = outlet
47 |
48 | def elaborate(self, platform):
49 | m = Module()
50 | tx = UARTTx(self.divisor, self.data_bits)
51 | m.submodules.tx = tx
52 | m.d.comb += [
53 | self.tx_pin.eq(tx.tx_pin),
54 | self.tx_in.o_ready.eq(tx.tx_rdy),
55 | tx.tx_trg.eq(self.tx_in.i_valid & self.tx_in.o_ready),
56 | tx.tx_data.eq(self.tx_in.i_data),
57 | ]
58 | return m
59 |
60 |
61 | class P_UARTRx(Elaboratable):
62 |
63 | def __init__(self, divisor, data_bits=8, inlet=None):
64 | if inlet is None:
65 | inlet = PipeSpec(data_bits).inlet()
66 | self.divisor = divisor
67 | self.data_bits = data_bits
68 |
69 | self.rx_pin = Signal()
70 | self.rx_out = inlet
71 | self.dbg = Signal(4)
72 |
73 | def elaborate(self, platform):
74 | m = Module()
75 | rx = UARTRx(self.divisor, self.data_bits)
76 | m.submodules.rx = rx
77 | m.d.comb += [
78 | rx.rx_pin.eq(self.rx_pin),
79 | self.dbg.eq(rx.dbg),
80 | ]
81 | with m.If(rx.rx_rdy):
82 | m.d.sync += [
83 | self.rx_out.o_valid.eq(True),
84 | self.rx_out.o_data.eq(rx.rx_data),
85 | ]
86 | with m.If(self.rx_out.sent()):
87 | m.d.sync += self.rx_out.o_valid.eq(False)
88 | m.d.comb += [
89 | ]
90 | return m
91 |
92 |
93 | if __name__ == '__main__':
94 | divisor = 8
95 | design = P_UART(divisor=divisor)
96 | design.tx_in.leave_unconnected()
97 | design.rx_out.leave_unconnected()
98 |
99 | # Workaround nmigen issue #280
100 | m = Module()
101 | m.submodules.design = design
102 | i_ready = Signal()
103 | i_valid = Signal()
104 | i_data = Signal(8)
105 | m.d.comb += design.rx_out.i_ready.eq(i_ready)
106 | m.d.comb += design.tx_in.i_valid.eq(i_valid)
107 | m.d.comb += design.tx_in.i_data.eq(i_data)
108 |
109 | #280 with Main(design).sim as sim:
110 | with Main(m).sim as sim:
111 |
112 | @sim.sync_process
113 | def recv_char():
114 | char = 'Q'
115 | char = chr(0x95) # Test high bit
116 | yield design.rx_pin.eq(1)
117 | yield from delay(3)
118 | for i in range(3):
119 | # Start bit
120 | yield design.rx_pin.eq(0)
121 | yield from delay(divisor)
122 | # Data bits
123 | for i in range(8):
124 | yield design.rx_pin.eq(ord(char) >> i & 1)
125 | yield from delay(divisor)
126 | # Stop bit
127 | yield design.rx_pin.eq(1)
128 | yield from delay(divisor)
129 | yield from delay(2)
130 | char = chr(ord(char) + 1)
131 |
132 | @sim.sync_process
133 | def read_char():
134 | count = 0
135 | yield Passive()
136 | while True:
137 | valid = yield (design.rx_out.o_valid)
138 | if valid:
139 | if not count:
140 | count = 10
141 | if count:
142 | count -= 1
143 | if count == 1:
144 | #280 yield design.rx_out.i_ready.eq(True)
145 | yield i_ready.eq(True)
146 | else:
147 | #280 yield design.rx_out.i_ready.eq(False)
148 | yield i_ready.eq(False)
149 | yield
150 |
151 | @sim.sync_process
152 | def send_char():
153 | yield from delay(2)
154 | yield Passive()
155 | for char in 'QRS':
156 | #280 yield design.tx_in.i_data.eq(ord(char))
157 | #280 yield design.tx_in.i_valid.eq(True)
158 | yield i_data.eq(ord(char))
159 | yield i_valid.eq(True)
160 | yield
161 | while not (yield design.tx_in.o_ready):
162 | yield
163 | #280 yield design.tx_in.i_valid.eq(False)
164 | yield i_valid.eq(False)
165 |
--------------------------------------------------------------------------------
/nmigen_lib/pll.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from collections import namedtuple
4 | import warnings
5 |
6 | from nmigen import *
7 | from nmigen.lib.cdc import ResetSynchronizer
8 | from nmigen.cli import main
9 |
10 |
11 | class PLL(Elaboratable):
12 |
13 | """
14 | Instantiate the iCE40's phase-locked loop (PLL).
15 |
16 | This uses the iCE40's SB_PLL40_PAD primitive in simple feedback
17 | mode.
18 |
19 | The reference clock is directly connected to a package pin. To
20 | allocate that pin, request the pin with dir='-'; otherwise nMigen
21 | inserts an SB_IO on the pin. E.g.,
22 |
23 | clk_pin = platform.request('clk12', dir='-')
24 |
25 | Because the PLL eats the external clock, that clock is not available
26 | for other uses. So you might as well have the PLL generate the
27 | default 'sync' clock domain.
28 |
29 | This module also has a reset synchronizer -- the domain's reset line
30 | is not released until a few clocks after the PLL lock signal is
31 | good.
32 | """
33 |
34 | def __init__(self, freq_in_mhz, freq_out_mhz, domain_name='sync'):
35 | self.freq_in = freq_in_mhz
36 | self.freq_out = freq_out_mhz
37 | self.coeff = self._calc_freq_coefficients()
38 | self.clk_pin = Signal()
39 | self.domain_name = domain_name
40 | self.domain = ClockDomain(domain_name)
41 | self.ports = [
42 | self.clk_pin,
43 | self.domain.clk,
44 | self.domain.rst,
45 | ]
46 |
47 | def _calc_freq_coefficients(self):
48 | # cribbed from Icestorm's icepll.
49 | f_in, f_req = self.freq_in, self.freq_out
50 | assert 10 <= f_in <= 13
51 | assert 16 <= f_req <= 275
52 | coefficients = namedtuple('coefficients', 'divr divf divq')
53 | divf_range = 128 # see comments in icepll.cc
54 | best_fout = float('inf')
55 | for divr in range(16):
56 | pfd = f_in / (divr + 1)
57 | if 10 <= pfd <= 133:
58 | for divf in range(divf_range):
59 | vco = pfd * (divf + 1)
60 | if 533 <= vco <= 1066:
61 | for divq in range(1, 7):
62 | fout = vco * 2**-divq
63 | if abs(fout - f_req) < abs(best_fout - f_req):
64 | best_fout = fout
65 | best = coefficients(divr, divf, divq)
66 | if best_fout != f_req:
67 | warnings.warn(
68 | f'PLL: requested {f_req} MHz, got {best_fout} MHz)',
69 | stacklevel=3)
70 | return best
71 |
72 | def elaborate(self, platform):
73 |
74 | # coeff = self._calc_freq_coefficients()
75 |
76 | pll_lock = Signal()
77 | pll = Instance("SB_PLL40_PAD",
78 | p_FEEDBACK_PATH='SIMPLE',
79 | p_DIVR=self.coeff.divr,
80 | p_DIVF=self.coeff.divf,
81 | p_DIVQ=self.coeff.divq,
82 | p_FILTER_RANGE=0b001,
83 |
84 | i_PACKAGEPIN=self.clk_pin,
85 | i_RESETB=Const(1),
86 | i_BYPASS=Const(0),
87 |
88 | o_PLLOUTGLOBAL=ClockSignal(self.domain_name),
89 | o_LOCK=pll_lock)
90 | rs = ResetSynchronizer(~pll_lock, domain=self.domain_name)
91 |
92 | m = Module()
93 | m.submodules += [pll, rs]
94 | return m
95 |
96 |
97 | # There is no point in simulating this, but you can generate Verilog.
98 |
99 | if __name__ == '__main__':
100 | pll = PLL(12, 30)
101 | main(pll, ports=pll.ports)
102 |
--------------------------------------------------------------------------------
/nmigen_lib/seven_segment/digit_pattern.py:
--------------------------------------------------------------------------------
1 | from nmigen import *
2 | from nmigen.cli import *
3 | from nmigen_lib.util.main import Main
4 |
5 | class DigitPattern(Elaboratable):
6 |
7 | """map four bit binary digit to the pattern representing
8 | that value on a seven segment display."""
9 |
10 | def __init__(self):
11 | self.digit_in = Signal(4)
12 | self.segments_out = Signal(7)
13 | self.ports = [self.digit_in, self.segments_out]
14 |
15 | def elaborate(self, platform):
16 | m = Module()
17 | with m.Switch(self.digit_in):
18 |
19 | with m.Case(0x0):
20 | m.d.comb += self.segments_out.eq(0b0111111)
21 |
22 | with m.Case(0x1):
23 | m.d.comb += self.segments_out.eq(0b0000110)
24 |
25 | with m.Case(0x2):
26 | m.d.comb += self.segments_out.eq(0b1011011)
27 |
28 | with m.Case(0x3):
29 | m.d.comb += self.segments_out.eq(0b1001111)
30 |
31 | with m.Case(0x4):
32 | m.d.comb += self.segments_out.eq(0b1100110)
33 |
34 | with m.Case(0x5):
35 | m.d.comb += self.segments_out.eq(0b1101101)
36 |
37 | with m.Case(0x6):
38 | m.d.comb += self.segments_out.eq(0b1111101)
39 |
40 | with m.Case(0x7):
41 | m.d.comb += self.segments_out.eq(0b0000111)
42 |
43 | with m.Case(0x8):
44 | m.d.comb += self.segments_out.eq(0b1111111)
45 |
46 | with m.Case(0x9):
47 | m.d.comb += self.segments_out.eq(0b1101111)
48 |
49 | with m.Case(0xA):
50 | m.d.comb += self.segments_out.eq(0b1110111)
51 |
52 | with m.Case(0xB):
53 | m.d.comb += self.segments_out.eq(0b1111100)
54 |
55 | with m.Case(0xC):
56 | m.d.comb += self.segments_out.eq(0b0111001)
57 |
58 | with m.Case(0xD):
59 | m.d.comb += self.segments_out.eq(0b1011110)
60 |
61 | with m.Case(0xE):
62 | m.d.comb += self.segments_out.eq(0b1111001)
63 |
64 | with m.Case(0xF):
65 | m.d.comb += self.segments_out.eq(0b1110001)
66 |
67 | return m
68 |
69 | if __name__ == '__main__':
70 | digit_pattern = DigitPattern()
71 |
72 | # Main(digit_pattern).run()
73 | with Main(digit_pattern).sim as sim:
74 | @sim.sync_process
75 | def digits_proc():
76 | for i in range(0x10):
77 | yield digit_pattern.digit_in.eq(i)
78 | yield
79 |
--------------------------------------------------------------------------------
/nmigen_lib/seven_segment/driver.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from nmigen import *
4 | from nmigen_lib.util.main import Main
5 |
6 |
7 | def Seg7Record():
8 | return Record((
9 | ('segs', 7),
10 | ('digit', 1),
11 | ))
12 |
13 |
14 | class SevenSegDriver(Elaboratable):
15 |
16 | def __init__(self, clk_freq, min_refresh_freq=100, pwm_width=8):
17 | self.clk_freq = clk_freq
18 | self.min_refresh_freq = min_refresh_freq
19 | self.pwm_width = pwm_width
20 |
21 | self.segment_patterns = Array((Signal(7), Signal(7)))
22 | self.pwm = Signal(pwm_width)
23 | self.digit_sel = Signal()
24 | self.seg7 = Seg7Record()
25 |
26 | self.ports = (self.pwm, self.digit_sel)
27 | self.ports += tuple(self.segment_patterns)
28 | self.ports += tuple(self.seg7._lhs_signals())
29 |
30 | def elaborate(self, platform):
31 | counter_max0 = int(self.clk_freq / self.min_refresh_freq)
32 | counter_max = (1 << counter_max0.bit_length()) - 1
33 | counter_width = counter_max.bit_length()
34 | assert counter_width > self.pwm_width
35 |
36 | counter = Signal(counter_width)
37 | digit = Signal()
38 | cmp = Signal(self.pwm_width)
39 | on = Signal()
40 |
41 | m = Module()
42 | m.d.sync += [
43 | counter.eq(counter + 1),
44 | ]
45 | m.d.comb += [
46 | digit.eq(counter[-1]),
47 | cmp.eq(counter[-1 - self.pwm_width:-1]),
48 | on.eq(cmp < self.pwm),
49 | self.digit_sel.eq(digit),
50 | self.seg7.digit.eq(~digit),
51 | ]
52 | m.d.sync += [
53 | self.seg7.segs.eq(~Mux(on, self.segment_patterns[digit], 0))
54 | ]
55 | # with m.If(on):
56 | # m.d.sync += [
57 | # self.seg7.segs.eq(~self.segment_patterns[digit]),
58 | # # self.seg7.digit.eq(~digit),
59 | # ]
60 | # with m.Else():
61 | # m.d.sync += [
62 | # self.seg7.segs.eq(~0),
63 | # # self.seg7.digit.eq(~digit),
64 | # ]
65 | return m
66 |
67 |
68 | if __name__ == '__main__':
69 | design = SevenSegDriver(1_000_000, 60_000, pwm_width=2)
70 | with Main(design).sim as sim:
71 | @sim.sync_process
72 | def fade_proc():
73 | yield design.segment_patterns[0].eq(0x0A)
74 | yield design.segment_patterns[1].eq(0x05)
75 | for i in range(4):
76 | yield
77 | yield design.pwm.eq(i)
78 | yield from [None] * 32 # step 32 clocks
79 |
--------------------------------------------------------------------------------
/nmigen_lib/seven_segment/hex_display.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from nmigen import Elaboratable, Module, Signal
4 |
5 | from nmigen_lib.util import Main, delay
6 |
7 | from .digit_pattern import DigitPattern
8 | from .driver import SevenSegDriver, Seg7Record
9 |
10 | class HexDisplay(Elaboratable):
11 |
12 | def __init__(self, clk_freq, min_refresh_freq=100, pwm_width=8):
13 | self.clk_freq = clk_freq
14 | self.min_refresh_freq = min_refresh_freq
15 | self.pwm_width = pwm_width
16 |
17 | self.i_data = Signal(8)
18 | self.i_pwm = Signal(pwm_width)
19 | self.o_seg7 = Seg7Record()
20 | self.o_seg7.segs.reset = ~0
21 | self.o_seg7.digit.reset = ~0
22 |
23 | def elaborate(self, platform):
24 | m = Module()
25 | ones = DigitPattern()
26 | tens = DigitPattern()
27 | drv = SevenSegDriver(
28 | clk_freq=self.clk_freq,
29 | min_refresh_freq=self.min_refresh_freq,
30 | pwm_width=self.pwm_width,
31 | )
32 | m.submodules.ones = ones
33 | m.submodules.tens = tens
34 | m.submodules.drv = drv
35 | m.d.comb += [
36 | ones.digit_in.eq(self.i_data[:4]),
37 | tens.digit_in.eq(self.i_data[4:]),
38 |
39 | drv.pwm.eq(self.i_pwm),
40 | drv.segment_patterns[0].eq(ones.segments_out),
41 | drv.segment_patterns[1].eq(tens.segments_out),
42 |
43 | self.o_seg7.eq(drv.seg7),
44 | ]
45 | oo_seg7 = Signal(8)
46 | m.d.comb += oo_seg7.eq(self.o_seg7)
47 | return m
48 |
49 |
50 | if __name__ == '__main__':
51 | clk_freq = 1e6
52 | clk_per_digit = 4
53 | refresh_freq = clk_freq / clk_per_digit
54 | pwm_width = 2
55 | pwm_count = 2**pwm_width
56 | design = HexDisplay(
57 | clk_freq=clk_freq,
58 | min_refresh_freq=refresh_freq,
59 | pwm_width=pwm_width,
60 | )
61 |
62 | with Main(design).sim as sim:
63 |
64 | @sim.sync_process
65 | def seg_proc():
66 | dig_to_seg = {
67 | 0x0: 0b0111111,
68 | 0x1: 0b0000110,
69 | 0x2: 0b1011011,
70 | 0x3: 0b1001111,
71 | 0x4: 0b1100110,
72 | 0x5: 0b1101101,
73 | 0x6: 0b1111101,
74 | 0x7: 0b0000111,
75 | 0x8: 0b1111111,
76 | 0x9: 0b1101111,
77 | 0xA: 0b1110111,
78 | 0xB: 0b1111100,
79 | 0xC: 0b0111001,
80 | 0xD: 0b1011110,
81 | 0xE: 0b1111001,
82 | 0xF: 0b1110001,
83 | }
84 | expected_segs_z1 = 127
85 | pw_z1 = 0
86 | for i in range(256):
87 | pw = i % pwm_count
88 | pw = 3
89 | yield design.i_data.eq(i)
90 | yield design.i_pwm.eq(pw)
91 | for j in range(clk_per_digit * pwm_count):
92 | seg7 = yield design.o_seg7
93 | actual_digit = (seg7 >> 7) ^ 1
94 | actual_segs = (seg7 & 0x7F) ^ 0x7F
95 | on_off = j % pwm_count < pw_z1
96 | expected_digit = j >> pwm_width & 1
97 | if on_off:
98 | sel = (j >> pwm_width) & 1
99 | assert sel in {0, 1}
100 | dig = [i % 0x10, i // 0x10][sel]
101 | expected_segs = dig_to_seg[dig]
102 | else:
103 | expected_segs = 0
104 | # print(f'i={i} j={j} seg7={seg7:08b}')
105 | # print(f' expected '
106 | # f'digit = {expected_digit} '
107 | # f'segs = {expected_segs:07b}'
108 | # f' (was {expected_segs_z1:07b})')
109 | # print(f' actual '
110 | # f'digit = {actual_digit} '
111 | # f'segs = {actual_segs:07b}')
112 | # print()
113 | assert actual_digit == expected_digit
114 | # XXX This is not right.
115 | # assert actual_segs == expected_segs_z1
116 | yield
117 | pw_z1 = pw
118 | expected_segs_z1 = expected_segs
119 |
--------------------------------------------------------------------------------
/nmigen_lib/timer.py:
--------------------------------------------------------------------------------
1 | from nmigen import *
2 | from nmigen.cli import *
3 |
4 | class Timer(Elaboratable):
5 |
6 | """Count a fixed period. Assert .stb once per period."""
7 |
8 | def __init__(self, period):
9 | assert isinstance(period, int)
10 | self.period = period
11 | self.counter = Signal((period - 1).bit_length())
12 | self.stb = Signal()
13 | self.ports = [self.counter, self.stb]
14 |
15 | def elaborate(self, platform):
16 | m = Module()
17 | with m.If(self.counter == self.period - 1):
18 | m.d.sync += [
19 | self.stb.eq(True),
20 | self.counter.eq(0),
21 | ]
22 | with m.Else():
23 | m.d.sync += [
24 | self.stb.eq(False),
25 | self.counter.eq(self.counter + 1),
26 | ]
27 | return m
28 |
29 |
30 | if __name__ == '__main__':
31 | timer = Timer(period=5)
32 | main(timer, ports=timer.ports)
33 |
--------------------------------------------------------------------------------
/nmigen_lib/uart.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env nmigen
2 |
3 | from nmigen import *
4 |
5 | from nmigen_lib.util import delay
6 | from nmigen_lib.util.main import Main
7 |
8 |
9 | class UART(Elaboratable):
10 |
11 | def __init__(self, divisor, data_bits=8):
12 | self.divisor = divisor
13 | self.data_bits = data_bits
14 |
15 | self.tx_data = Signal(data_bits)
16 | self.tx_pin = Signal()
17 | self.tx_trg = Signal()
18 | self.tx_rdy = Signal()
19 |
20 | self.rx_pin = Signal(reset=1)
21 | self.rx_rdy = Signal()
22 | self.rx_err = Signal()
23 | # self.rx_ovf = Signal() # XXX not used yet
24 | self.rx_data = Signal(data_bits)
25 |
26 | self.ports = (
27 | self.tx_data,
28 | self.tx_trg,
29 | self.tx_rdy,
30 | self.tx_pin,
31 |
32 | self.rx_pin,
33 | self.rx_rdy,
34 | self.rx_err,
35 | # self.rx_ovf,
36 | self.rx_data,
37 | )
38 |
39 | def elaborate(self, platform):
40 | m = Module()
41 | tx = UARTTx(divisor=self.divisor, data_bits=self.data_bits)
42 | rx = UARTRx(divisor=self.divisor, data_bits=self.data_bits)
43 | m.submodules.tx = tx
44 | m.submodules.rx = rx
45 | m.d.comb += [
46 | tx.tx_data.eq(self.tx_data),
47 | tx.tx_trg.eq(self.tx_trg),
48 | self.tx_rdy.eq(tx.tx_rdy),
49 | self.tx_pin.eq(tx.tx_pin),
50 |
51 | rx.rx_pin.eq(self.rx_pin),
52 | self.rx_rdy.eq(rx.rx_rdy),
53 | self.rx_err.eq(rx.rx_err),
54 | # self.rx_ovf.eq(rx.rx_ovf),
55 | self.rx_data.eq(rx.rx_data),
56 | ]
57 | return m
58 |
59 |
60 | class UARTTx(Elaboratable):
61 |
62 | def __init__(self, divisor, data_bits=8):
63 | self.divisor = divisor
64 | self.data_bits = data_bits
65 | self.tx_data = Signal(data_bits)
66 | self.tx_trg = Signal()
67 | self.tx_rdy = Signal()
68 | self.tx_pin = Signal(reset=1)
69 | self.ports = (
70 | self.tx_data,
71 | self.tx_trg,
72 | self.tx_pin,
73 | self.tx_rdy,
74 | )
75 |
76 | def elaborate(self, platform):
77 | tx_data = Signal(self.data_bits)
78 | tx_fast_count = Signal(range(-1, self.divisor - 1), reset=-1)
79 | tx_bit_count = Signal(range(-1, self.data_bits))
80 |
81 | m = Module()
82 |
83 | with m.If(tx_fast_count[-1]):
84 | with m.FSM():
85 | with m.State('IDLE'):
86 | with m.If(self.tx_trg):
87 | m.d.sync += [
88 | tx_data.eq(self.tx_data),
89 | self.tx_rdy.eq(False),
90 | self.tx_pin.eq(0), # start bit
91 | tx_bit_count.eq(self.data_bits - 1),
92 | tx_fast_count.eq(self.divisor - 2),
93 | ]
94 | m.next = 'DATA'
95 | with m.Else():
96 | m.d.sync += [
97 | self.tx_rdy.eq(True),
98 | tx_fast_count.eq(-1),
99 | ]
100 | m.next = 'IDLE'
101 | with m.State('DATA'):
102 | with m.If(tx_bit_count[-1]):
103 | m.d.sync += [
104 | self.tx_rdy.eq(False),
105 | self.tx_pin.eq(1), # stop bit
106 | tx_fast_count.eq(self.divisor - 2),
107 | ]
108 | m.next = 'STOP'
109 | with m.Else():
110 | m.d.sync += [
111 | self.tx_pin.eq(tx_data[0]),
112 | tx_data.eq(tx_data[1:]),
113 | tx_bit_count.eq(tx_bit_count - 1),
114 | tx_fast_count.eq(self.divisor - 2),
115 | ]
116 | m.next = 'DATA'
117 | with m.State('STOP'):
118 | m.d.sync += [
119 | # self.tx_pin.eq(1),
120 | self.tx_rdy.eq(True),
121 | # tx_fast_count.eq(self.divisor - 2),
122 | tx_fast_count.eq(-1),
123 | ]
124 | m.next = 'IDLE'
125 |
126 | with m.Else():
127 | m.d.sync += [
128 | tx_fast_count.eq(tx_fast_count - 1),
129 | ]
130 | return m
131 |
132 |
133 | class UARTRx(Elaboratable):
134 |
135 | def __init__(self, divisor, data_bits=8):
136 | """Assume no parity, 1 stop bit"""
137 | self.divisor = divisor
138 | self.data_bits = data_bits
139 | self.rx_pin = Signal(reset=1)
140 | self.rx_rdy = Signal()
141 | self.rx_err = Signal()
142 | self.dbg = Signal(4) # XXX
143 | # self.rx_ovf = Signal() # XXX not used yet
144 | self.rx_data = Signal(data_bits)
145 | self.ports = (self.rx_pin,
146 | self.rx_rdy,
147 | self.rx_err,
148 | # self.rx_ovf,
149 | self.rx_data,
150 | self.dbg, # XXX
151 | )
152 |
153 | def elaborate(self, platform):
154 | # N.B. both counters (rx_counter, rx_bits) count from n-2 to -1.
155 | rx_max = self.divisor - 2
156 | rx_counter = Signal(range(-1, rx_max + 1), reset=~0)
157 | rx_data = Signal(self.data_bits)
158 | rx_bits = Signal(range(-1, self.data_bits - 1))
159 | rx_resync_max = 10 * self.divisor - 2
160 | rx_resync_counter = Signal(range(-1, rx_resync_max + 1))
161 | rx_pin = Signal(reset=1)
162 | rx_pin1 = Signal(reset=1)
163 |
164 | m = Module()
165 | m.d.comb += self.dbg[0].eq(rx_counter[-1]) # XXX
166 | m.d.sync += [
167 | rx_pin.eq(rx_pin1),
168 | rx_pin1.eq(self.rx_pin),
169 | ]
170 | with m.If(rx_counter[-1]):
171 | with m.FSM():
172 | with m.State('IDLE'):
173 | with m.If(~rx_pin):
174 | m.d.sync += [
175 | rx_data.eq(0),
176 | self.rx_rdy.eq(False),
177 | self.rx_err.eq(False),
178 | rx_counter.eq(self.divisor // 2 - 2),
179 | ]
180 | m.next = 'START'
181 | with m.Else():
182 | m.d.sync += [
183 | self.rx_rdy.eq(False),
184 | self.rx_err.eq(False),
185 | rx_counter.eq(-1),
186 | ]
187 | m.next = 'IDLE'
188 | with m.State('START'):
189 | with m.If(rx_pin):
190 | m.d.sync += [
191 | self.rx_err.eq(True),
192 | rx_counter.eq(-1),
193 | rx_resync_counter.eq(rx_resync_max),
194 | ]
195 | m.next = 'RESYNC'
196 | with m.Else():
197 | m.d.sync += [
198 | rx_bits.eq(self.data_bits - 2),
199 | rx_counter.eq(self.divisor - 2),
200 | ]
201 | m.next = 'DATA'
202 | with m.State('DATA'):
203 | m.d.sync += [
204 | rx_data.eq(Cat(rx_data[1:], rx_pin)),
205 | rx_counter.eq(self.divisor - 2),
206 | ]
207 | with m.If(rx_bits[-1]):
208 | m.next = 'STOP'
209 | with m.Else():
210 | m.d.sync += [
211 | rx_bits.eq(rx_bits - 1),
212 | ]
213 | m.next = 'DATA'
214 | with m.State('STOP'):
215 | with m.If(~rx_pin):
216 | m.d.sync += [
217 | self.rx_err.eq(True),
218 | rx_resync_counter.eq(rx_resync_max),
219 | rx_counter.eq(-1),
220 | ]
221 | m.next = 'RESYNC'
222 | with m.Else():
223 | m.d.sync += [
224 | self.rx_data.eq(rx_data),
225 | self.rx_rdy.eq(True),
226 | ]
227 | m.next = 'IDLE'
228 |
229 | with m.State('RESYNC'):
230 | m.d.sync += [
231 | self.rx_err.eq(False),
232 | rx_counter.eq(-1),
233 | ]
234 | with m.If(rx_pin):
235 | with m.If(rx_resync_counter[-1]):
236 | m.next = 'IDLE'
237 | with m.Else():
238 | m.d.sync += [
239 | rx_resync_counter.eq(rx_resync_counter - 1),
240 | ]
241 | m.next = 'RESYNC'
242 | with m.Else():
243 | m.d.sync += [
244 | rx_resync_counter.eq(rx_resync_max),
245 | ]
246 | m.next = 'RESYNC'
247 | with m.Else():
248 | m.d.sync += [
249 | rx_counter.eq(rx_counter - 1),
250 | self.rx_rdy.eq(False),
251 | self.rx_err.eq(False),
252 | ]
253 | return m
254 |
255 |
256 | if __name__ == '__main__':
257 | divisor = 20
258 | design = UART(divisor=divisor)
259 |
260 | # Workaround nmigen issue #280
261 | m = Module()
262 | m.submodules.design = design
263 | tx_data = Signal(8)
264 | tx_trg = Signal()
265 | m.d.comb += design.tx_data.eq(tx_data)
266 | m.d.comb += design.tx_trg.eq(tx_trg)
267 |
268 | #280 with Main(design).sim as sim:
269 | with Main(m).sim as sim:
270 |
271 | @sim.sync_process
272 | def send_char():
273 | char = 'Q'
274 | yield from delay(2)
275 | #280 yield design.tx_data.eq(ord(char))
276 | #280 yield design.tx_trg.eq(True)
277 | yield tx_data.eq(ord(char))
278 | yield tx_trg.eq(True)
279 | yield
280 | #280 yield design.tx_trg.eq(False)
281 | yield tx_trg.eq(False)
282 | yield from delay(10 * divisor + 4)
283 |
284 | @sim.sync_process
285 | def recv_char():
286 | char = 'Q'
287 | char = chr(0x95) # Test high bit
288 | yield design.rx_pin.eq(1)
289 | yield from delay(3)
290 | for i in range(2):
291 | # Start bit
292 | yield design.rx_pin.eq(0)
293 | yield from delay(divisor)
294 | # Data bits
295 | for i in range(8):
296 | yield design.rx_pin.eq(ord(char) >> i & 1)
297 | yield from delay(divisor)
298 | # Stop bit
299 | yield design.rx_pin.eq(1)
300 | yield from delay(divisor)
301 | yield from delay(2)
302 |
--------------------------------------------------------------------------------
/nmigen_lib/util/__init__.py:
--------------------------------------------------------------------------------
1 | from .main import main, Main
2 |
3 | __all__ = ['delay', 'main', 'Main']
4 |
5 | def delay(n):
6 | """delay n clocks
7 | Use in an async process:
8 |
9 | yield from delay(n)
10 | """
11 | return [None] * n
12 |
--------------------------------------------------------------------------------
/nmigen_lib/util/main.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | from collections import namedtuple
3 | from contextlib import contextmanager
4 | import inspect
5 | import os.path
6 | import warnings
7 |
8 | from nmigen import *
9 | from nmigen.hdl.ir import Fragment
10 | from nmigen.back import rtlil, verilog, pysim
11 |
12 | """
13 | An enhanced main patterned after nmigen.cli.main.
14 |
15 | Has two actions: generate and simulate.
16 |
17 | `generate` generates a Verilog or RTLIL source file from the given
18 | module. It has
19 |
20 | * By default, .ports is used as the list of ports.
21 |
22 | `simulate` runs pysim, but with differences:
23 |
24 | * By default, .ports is used as the list of ports.
25 |
26 | * The `.vcd` and `.gtkw` files have the same basename
27 | as the module's source file by default.
28 |
29 | * The simulator can easily be extended by adding synchronous
30 | and asynchronous processes.
31 |
32 | * The simulator will run for either the number of clocks specified
33 | by the `--clocks=N` argument or until all defined processes
34 | have finished.
35 |
36 | If you want the default simulator, instantiate like this. In this
37 | case, you must specify the `--clocks=N` argument to simulate.
38 |
39 | from nmigen_lib.util.main import main
40 |
41 | if __name__ == '__main__':
42 | design = MyModule()
43 | main(design)
44 |
45 | If you want to add processes to the simulator, instantiate lik this.
46 |
47 | from nmigen_lib.util.main import Main
48 |
49 | if __name__ == '__main__':
50 | design - MyModule()
51 | with Main(design).sim as sim:
52 | @sim.add_sync_process
53 | def my_proc():
54 | ... # your logic here
55 | """
56 |
57 | # default vcd and gtk files
58 | # default run sim until procs exit
59 | # default ports = module.ports
60 | # way to add sim processes
61 |
62 |
63 | class SimClock(namedtuple('SimClock', 'period phase domain if_exists')):
64 | pass
65 |
66 | class SimSyncProc(namedtuple('SimSyncProc', 'process domain')):
67 | pass
68 |
69 | class SimBuilder:
70 |
71 | def __init__(self, design, parse_args):
72 | self.design = design
73 | self.args = parse_args
74 | self.clocks = []
75 | self.procs = []
76 | self.sync_procs = []
77 |
78 | def __enter__(self):
79 | return self
80 |
81 | def __exit__(self, exc_type, exc_val, exc_tb):
82 | return False
83 |
84 | def has_procs(self):
85 | return bool(self.procs or self.sync_procs)
86 |
87 | def has_clocks(self):
88 | return bool(self.clocks)
89 |
90 | def build(self, sim):
91 | for clock in self.clocks:
92 | sim.add_clock(**clock._asdict())
93 | for proc in self.procs:
94 | sim.add_process(proc)
95 | for sync_proc in self.sync_procs:
96 | sim.add_sync_process(sync_proc.process, domain=sync_proc.domain)
97 |
98 | def add_clock(self, period, *,
99 | phase=None, domain='sync', if_exists=False):
100 | self.clocks.append(SimClock(period, phase, domain, if_exists))
101 |
102 | # Use as decorator.
103 | def process(self, proc):
104 | self.procs.append(proc)
105 | return proc
106 |
107 | # Use as decorator.
108 | def sync_process(self, proc, domain='sync'):
109 | if proc is None:
110 | return lambda proc: self.sync_process(proc, domain)
111 | self.sync_procs.append(SimSyncProc(proc, domain))
112 | return proc
113 |
114 |
115 | class Main:
116 |
117 | def __init__(self, design, platform=None, name='top', ports=None):
118 | self.design = design
119 | self.platform = platform
120 | self.name = name
121 | self.ports = ports
122 | self.args = self._arg_parser().parse_args()
123 | self._sim = SimBuilder(design, self.args)
124 |
125 | def run(self):
126 | if self.args.action == 'generate':
127 | self._generate()
128 | elif self.args.action == 'simulate':
129 | self._simulate()
130 | else:
131 | Elaboratable._Elaboratable__silence = True
132 | exit('main: must specify either `generate` or `simulate` action')
133 |
134 | @property
135 | @contextmanager
136 | def sim(self):
137 | ok = True
138 | try:
139 | yield self._sim
140 | except:
141 | ok = False
142 | raise
143 | finally:
144 | if ok:
145 | self.run()
146 |
147 | def _get_ports(self):
148 | ports = self.ports
149 | if ports is None:
150 | ports = getattr(self.design, 'ports', None)
151 | if ports is None:
152 | ports = [sig
153 | for (name, sig) in self.design.__dict__.items()
154 | if isinstance(sig, Signal) and not name.startswith('_')]
155 | return ports
156 |
157 | def _generate(self):
158 | args = self.args
159 | fragment = Fragment.get(self.design, self.platform)
160 | generate_type = args.generate_type
161 | if generate_type is None and args.generate_file:
162 | if args.generate_file.name.endswith(".v"):
163 | generate_type = "v"
164 | if args.generate_file.name.endswith(".il"):
165 | generate_type = "il"
166 | if generate_type is None:
167 | parser.error("specify file type explicitly with -t")
168 | if generate_type == "il":
169 | output = rtlil.convert(fragment,
170 | name=self.name, ports=self._get_ports())
171 | if generate_type == "v":
172 | output = verilog.convert(fragment,
173 | name=self.name, ports=self._get_ports())
174 | if args.generate_file:
175 | args.generate_file.write(output)
176 | else:
177 | print(output)
178 |
179 | def _simulate(self):
180 | if isinstance(self.design, Module):
181 | design_file = self._caller_filename()
182 | elif isinstance(self.design, Elaboratable):
183 | design_file = inspect.getsourcefile(self.design.__class__)
184 | else:
185 | assert TypeError, 'can only simulate Elaboratable or Module'
186 | args = self.args
187 | prefix = os.path.splitext(design_file)[0]
188 | vcd_file = args.vcd_file or prefix + '.vcd'
189 | gtkw_file = args.gtkw_file = prefix + '.gtkw'
190 | traces = self._get_ports()
191 | with pysim.Simulator(self.design,
192 | vcd_file=open(vcd_file, 'w'),
193 | gtkw_file=open(gtkw_file, 'w'),
194 | traces=traces) as sim:
195 | self._sim.build(sim)
196 | if not self._sim.has_clocks():
197 | sim.add_clock(args.sync_period)
198 | if args.sync_clocks:
199 | sim.run_until(args.sync_period * args.sync_clocks,
200 | run_passive=True)
201 | else:
202 | assert self._sim.has_procs(), (
203 | "must provide either a sim process or --clocks"
204 | )
205 | sim.run()
206 |
207 | def _caller_filename(self):
208 | try:
209 | f = None
210 | cur_file = inspect.getsourcefile(inspect.currentframe())
211 | for f in inspect.stack():
212 | if f.filename != cur_file and f.function != '__exit__':
213 | return f.filename
214 | finally:
215 | del f
216 |
217 | def _arg_parser(self, parser=None):
218 | if parser is None:
219 | parser = argparse.ArgumentParser()
220 |
221 | p_action = parser.add_subparsers(dest="action")
222 |
223 | p_generate = p_action.add_parser("generate",
224 | help="generate RTLIL or Verilog from the design")
225 | p_generate.add_argument("-t", "--type", dest="generate_type",
226 | metavar="LANGUAGE", choices=["il", "v"],
227 | default="v",
228 | help="generate LANGUAGE (il for RTLIL, v for Verilog; "
229 | "default: %(default)s)")
230 | p_generate.add_argument("generate_file",
231 | metavar="FILE", type=argparse.FileType("w"), nargs="?",
232 | help="write generated code to FILE")
233 |
234 | p_simulate = p_action.add_parser(
235 | "simulate", help="simulate the design")
236 | p_simulate.add_argument("-v", "--vcd-file",
237 | metavar="VCD-FILE", type=argparse.FileType("w"),
238 | help="write execution trace to VCD-FILE")
239 | p_simulate.add_argument("-w", "--gtkw-file",
240 | metavar="GTKW-FILE", type=argparse.FileType("w"),
241 | help="write GTKWave configuration to GTKW-FILE")
242 | p_simulate.add_argument("-p", "--period", dest="sync_period",
243 | metavar="TIME", type=float, default=1e-6,
244 | help="set 'sync' clock domain period to TIME "
245 | "(default: %(default)s)")
246 | p_simulate.add_argument("-c", "--clocks", dest="sync_clocks",
247 | metavar="COUNT", type=int,
248 | help="simulate for COUNT 'sync' clock periods")
249 |
250 | return parser
251 |
252 | def main(design, platform=None, name='top', ports=()):
253 | Main(design, platform, name, ports).run()
254 |
--------------------------------------------------------------------------------