diff options
121 files changed, 13308 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c8712a5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +*/*.a +*/*.o +*/*.d +*/*.d.* +*/*.hex +*/*.elf +tools/reset_arduino +contrib/LUFA-* +tuer-rfid/update-keys @@ -0,0 +1,3 @@ +Christian Pointner <equinox@spreadspace.org> +Othmar Gsenger <otti@gsenger.com> +Bernhard Tittelbach <xro@realraum.at> @@ -0,0 +1,695 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. @@ -0,0 +1,114 @@ +Dependencies +============ + +make +avr-libc +binutils-avr +gcc-avr +avrdude +dfu-programmer +teensy_loader + + +udev example rules +================== + +DFU programmable Boards: +------------------------ + +SUBSYSTEM=="usb", ACTION=="add", ATTR{idVendor}=="03eb", ATTR{idProduct}=="*", GROUP="plugdev", MODE:="0660" + +Teensy Boards: +-------------- + +SUBSYSTEMS=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="04[789]?", MODE:="0666" +KERNEL=="ttyACM*", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="04[789]?", SYMLINK+="ttyUSB00%n", MODE:="0666", ENV{ID_MM_DEVICE_IGNORE}="1" + +Arduino Boards: +--------------- + +SUBSYSTEMS=="usb", KERNEL=="ttyUSB*", ATTRS{serial}=="A6008hTA", SYMLINK+="arduino", OWNER="equinox", GROUP="equinox" + +Replace "A6008hTA" with the serial of your arduino board. You can obtain it +with the following command: + +udevadm info --name /dev/ttyUSB0 --attribute-walk | grep ATTRs{serial} + +(replace ttyUSB0 with the actual device your arduino uses) + + +Build +===== + +Getting the source via GIT: +--------------------------- + +git clone git://git.spreadspace.org/avr.git +cd avr + + +build and flash blink example +----------------------------- + +# cd blink +adapt Makefile (set BOARD_TYPE) +# make program + + +Some Hints +========== + +The object files for builded libs will be called lib-<name>.o so make sure +not to use files named like this for your own code. i.e. if you want +to use the `led` library it's not possible to have a source file name +lib-led.c inside your project. + +The anyio lib provides a failover between serial and usb-serial (using LUFA) +streams. It's not safe to use any STDIO functions inside interrupts. + +To use LUFA in your project you have to provide the path to the LUFA +source code. You may do this by calling `make` inside the contrib tree. +But any external path is ok. In order to build the lufa object file the +build system has to call `make clean` inside the LUFA_PATH so make sure +there is no lufa build inside which you still need. Also paralell builds +of several projects using the same LUFA_PATH is not possible. + + +License +======= + +The spreadspace AVR utils are licensed under GPLv3. You can find the +full text of the license in the file LICENSE. + +Some examples are based on LUFA which has been licensed under the +following conditions. + +/* + LUFA Library + Copyright (C) Dean Camera, 2012. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaim all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. +*/ diff --git a/any-led/Makefile b/any-led/Makefile new file mode 100644 index 0000000..36eab31 --- /dev/null +++ b/any-led/Makefile @@ -0,0 +1,46 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := any-led
+BOARD_TYPE := teensy2
+OBJ := $(NAME).o
+LIBS := util led lufa-descriptor-usbserial anyio
+EXTERNAL_LIBS := lufa
+RESET_FUNC := ../tools/reset_lufa_cdc
+RESET_PARAM := 'r'
+
+LUFA_PATH := ../contrib/LUFA-120219
+LUFA_OPTS = -D USB_DEVICE_ONLY
+LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0
+LUFA_OPTS += -D ORDERED_EP_CONFIG
+LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1
+LUFA_OPTS += -D USE_FLASH_DESCRIPTORS
+LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
+LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT
+
+LUFA_OPTS += -D USB_MANUFACTURER="L\"equinox\"" -D USB_MANUFACTURER_LEN=7
+LUFA_OPTS += -D USB_PRODUCT="L\"spreadspace any-led example\"" -D USB_PRODUCT_LEN=27
+
+LUFA_COMPONENTS := USB USBCLASS SERIAL
+
+include ../include.mk
diff --git a/any-led/any-led.c b/any-led/any-led.c new file mode 100644 index 0000000..0934ed3 --- /dev/null +++ b/any-led/any-led.c @@ -0,0 +1,68 @@ +/*
+ * spreadspace avr utils
+ *
+ *
+ * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+ *
+ * This file is part of spreadspace avr utils.
+ *
+ * spreadspace avr utils is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * spreadspace avr utils is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+#include <avr/io.h>
+#include <avr/wdt.h>
+#include <avr/interrupt.h>
+#include <avr/power.h>
+#include <stdio.h>
+
+#include "util.h"
+#include "led.h"
+#include "anyio.h"
+
+void handle_cmd(uint8_t cmd)
+{
+ switch(cmd) {
+ case '0': led_off(); break;
+ case '1': led_on(); break;
+ case 't': led_toggle(); break;
+ case 'r': reset2bootloader(); break;
+ default: printf("error\r\n"); return;
+ }
+ printf("ok\r\n");
+}
+
+int main(void)
+{
+ MCUSR &= ~(1 << WDRF);
+ wdt_disable();
+
+ cpu_init();
+ led_init();
+ anyio_init(115200, 0);
+ sei();
+
+ for(;;) {
+ int16_t bytes_received = anyio_bytes_received();
+ while(bytes_received > 0) {
+ int received_byte = fgetc(stdin);
+ if(received_byte != EOF) {
+ handle_cmd(received_byte);
+ }
+ bytes_received--;
+ }
+
+ anyio_task();
+ }
+}
diff --git a/ats-watch/99_ats-watch.rules b/ats-watch/99_ats-watch.rules new file mode 100644 index 0000000..11a67da --- /dev/null +++ b/ats-watch/99_ats-watch.rules @@ -0,0 +1,3 @@ +# /etc/udev/rules.d/99_ats-watch.rules + +SUBSYSTEMS=="usb", KERNEL=="ttyACM*", ATTRS{product}=="ats-watch", SYMLINK+="ats-watch" diff --git a/ats-watch/Makefile b/ats-watch/Makefile new file mode 100644 index 0000000..6047864 --- /dev/null +++ b/ats-watch/Makefile @@ -0,0 +1,44 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := ats-watch
+BOARD_TYPE := teensy2
+OBJ := $(NAME).o
+LIBS := util led lufa-descriptor-usbserial anyio
+EXTERNAL_LIBS := lufa
+
+LUFA_PATH := ../contrib/LUFA-120219
+LUFA_OPTS = -D USB_DEVICE_ONLY
+LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0
+LUFA_OPTS += -D ORDERED_EP_CONFIG
+LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1
+LUFA_OPTS += -D USE_FLASH_DESCRIPTORS
+LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
+LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT
+
+LUFA_OPTS += -D USB_MANUFACTURER="L\"Radio Helsinki\"" -D USB_MANUFACTURER_LEN=14
+LUFA_OPTS += -D USB_PRODUCT="L\"ats-watch\"" -D USB_PRODUCT_LEN=9
+
+LUFA_COMPONENTS := USB USBCLASS SERIAL
+
+include ../include.mk
diff --git a/ats-watch/ats-watch.c b/ats-watch/ats-watch.c new file mode 100644 index 0000000..12a97a2 --- /dev/null +++ b/ats-watch/ats-watch.c @@ -0,0 +1,147 @@ +/*
+ * spreadspace avr utils
+ *
+ *
+ * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+ *
+ * This file is part of spreadspace avr utils.
+ *
+ * spreadspace avr utils is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * spreadspace avr utils is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+#include <avr/io.h>
+#include <avr/wdt.h>
+#include <avr/interrupt.h>
+#include <avr/power.h>
+#include <stdio.h>
+
+#include "util.h"
+#include "led.h"
+#include "anyio.h"
+
+#define ATS_PIN PINB
+#define ATS_PORT PORTB
+#define ATS_DDR DDRB
+#define ATS_IN_A_SELECTED 0
+#define ATS_IN_B_SELECTED 1
+#define ATS_IN_A_OK 2
+#define ATS_IN_B_OK 3
+#define ATS_STATUS 7
+#define ATS_LP_MAX 10000
+
+void ats_init(void)
+{
+ ATS_DDR = 0x00;
+ ATS_PORT = 0xFF;
+}
+
+inline char* ats_get_ats_status(uint8_t stat)
+{
+ return (stat & (1<<ATS_STATUS)) ? "Error" : "Ok";
+}
+
+inline char* ats_get_selected(uint8_t stat)
+{
+ stat &= (1<<ATS_IN_A_SELECTED) | (1<<ATS_IN_B_SELECTED);
+ switch(stat) {
+ case (1<<ATS_IN_A_SELECTED): return "A";
+ case (1<<ATS_IN_B_SELECTED): return "B";
+ default: return "?";
+ }
+}
+
+inline char* ats_get_input_a(uint8_t stat)
+{
+ return (stat & (1<<ATS_IN_A_OK)) ? "Offline" : "Online";
+}
+
+inline char* ats_get_input_b(uint8_t stat)
+{
+ return (stat & (1<<ATS_IN_B_OK)) ? "Offline" : "Online";
+}
+
+void ats_print_status(uint8_t stat)
+{
+ printf("Status: %s, Input %s is selected (A: %s, B: %s)\r\n",
+ ats_get_ats_status(stat), ats_get_selected(stat), ats_get_input_a(stat), ats_get_input_b(stat));
+}
+
+uint8_t ats_get_status(void)
+{
+ static uint8_t last_stat = 0;
+ static uint16_t lp_cnt = 0;
+
+ uint8_t stat = ATS_PIN;
+ if(stat != last_stat)
+ lp_cnt++;
+ else
+ lp_cnt += lp_cnt ? -1 : 0;
+
+ if(lp_cnt >= ATS_LP_MAX) {
+ last_stat = stat;
+ lp_cnt = 0;
+ }
+
+ return last_stat;
+}
+
+void ats_task(void)
+{
+ static uint8_t old_stat = 0;
+
+ uint8_t new_stat = ats_get_status();
+ if(old_stat != new_stat) {
+ ats_print_status(new_stat);
+ old_stat = new_stat;
+ }
+}
+
+void handle_cmd(uint8_t cmd)
+{
+ switch(cmd) {
+ case '0': led_off(); printf("ok\r\n"); break;
+ case '1': led_on(); printf("ok\r\n"); break;
+ case 't': led_toggle(); printf("ok\r\n"); break;
+ case 's': ats_print_status(ATS_PIN); break;
+ /* case 'r': reset2bootloader(); break; */ // for testing only
+ default: printf("error: unknown command\r\n"); return;
+ }
+}
+
+int main(void)
+{
+ MCUSR &= ~(1 << WDRF);
+ wdt_disable();
+
+ cpu_init();
+ led_init();
+ ats_init();
+ anyio_init(115200, 0);
+ sei();
+
+ for(;;) {
+ int16_t bytes_received = anyio_bytes_received();
+ while(bytes_received > 0) {
+ int received_byte = fgetc(stdin);
+ if(received_byte != EOF) {
+ handle_cmd(received_byte);
+ }
+ bytes_received--;
+ }
+
+ anyio_task();
+ ats_task();
+ }
+}
diff --git a/ats-watch/ats-watch.pl b/ats-watch/ats-watch.pl new file mode 100755 index 0000000..f374295 --- /dev/null +++ b/ats-watch/ats-watch.pl @@ -0,0 +1,42 @@ +#!/usr/bin/perl -w + +use strict; +use Device::SerialPort; +use Mail::Sendmail; + +my $port = new Device::SerialPort("/dev/ats-watch"); +$port->baudrate(38400); +$port->parity("none"); +$port->databits(8); +$port->stopbits(1); +$port->handshake("none"); +$port->read_const_time(500); +$port->read_char_time(5); +$port->write_settings; + +$port->lookclear; +$port->write("s"); + +my %mail = ( To => 'logs@helsinki.at', + From => 'noreply@helsinki.at', + ); + +while(1) { + my ($count, $line) = $port->read(100); + if($count > 0) { + if($line =~ /Status: (\w+), Input (\w) is selected \(A: (\w+), B: (\w+)\)/) { + my $state = $1; + if($3 ne 'Online' && $4 ne 'Online') { + $state = 'critical'; + } elsif($3 ne 'Online' || $4 ne 'Online') { + $state = 'degraded'; + } + $mail{Subject} = "[ATS-Watch] PDU0 state $state"; + $mail{Message} = "Current State: $1\n" . "Current Input: $2\n" . "Input A: $3\n" . "Input B: $4\n"; + } else { + $mail{Subject} = '[ATS-Watch] PDU0 state unknown'; + $mail{Message} = $line; + } + sendmail( %mail ) or print $Mail::Sendmail::error . "\n"; + } +} diff --git a/blink/Makefile b/blink/Makefile new file mode 100644 index 0000000..7814de3 --- /dev/null +++ b/blink/Makefile @@ -0,0 +1,28 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := blink
+OBJ := $(NAME).o
+LIBS := util led
+BOARD_TYPE := culV3
+
+include ../include.mk
diff --git a/blink/blink.c b/blink/blink.c new file mode 100644 index 0000000..8021828 --- /dev/null +++ b/blink/blink.c @@ -0,0 +1,42 @@ +/*
+ * spreadspace avr utils
+ *
+ *
+ * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+ *
+ * This file is part of spreadspace avr utils.
+ *
+ * spreadspace avr utils is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * spreadspace avr utils is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <avr/io.h>
+#include <util/delay.h>
+
+#include "util.h"
+#include "led.h"
+
+int main(void)
+{
+ cpu_init();
+ led_init();
+
+ led_off();
+ led2_on();
+ for(;;) {
+ _delay_ms(250);
+ led_toggle();
+ led2_toggle();
+ }
+}
+
diff --git a/contrib/Makefile b/contrib/Makefile new file mode 100644 index 0000000..b5e5f5f --- /dev/null +++ b/contrib/Makefile @@ -0,0 +1,33 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+## Othmar Gsenger <otti@gsenger.com>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+LUFA_VERSION := 120219
+
+all: download-lufa
+
+download-lufa: LUFA-${LUFA_VERSION}.zip
+
+LUFA-${LUFA_VERSION}.zip:
+ wget "http://lufa-lib.googlecode.com/files/$@" -O "$@"
+ unzip $@
+
diff --git a/defines.mk b/defines.mk new file mode 100644 index 0000000..9af0179 --- /dev/null +++ b/defines.mk @@ -0,0 +1,228 @@ +## +## spreadspace avr utils +## +## +## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> +## +## This file is part of spreadspace avr utils. +## +## spreadspace avr utils is free software: you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation, either version 3 of the License, or +## any later version. +## +## spreadspace avr utils is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. +## + +ifeq ($(BOARD_TYPE),teensy1) + MCU := at90usb162 + ARCH = AVR8 + F_CPU := 16000000 + F_USB = $(F_CPU) + PROG := teensy + LUFA_BOARD = TEENSY +endif +ifeq ($(BOARD_TYPE),teensy2) + MCU := atmega32u4 + ARCH = AVR8 + F_CPU := 16000000 + F_USB = $(F_CPU) + PROG := teensy + LUFA_BOARD = TEENSY2 +endif +ifeq ($(BOARD_TYPE),teensy1pp) + MCU := at90usb646 + ARCH = AVR8 + F_CPU := 16000000 + F_USB = $(F_CPU) + PROG := teensy + LUFA_BOARD = TEENSY +endif +ifeq ($(BOARD_TYPE),teensy2pp) + MCU := at90usb1286 + ARCH = AVR8 + F_CPU := 16000000 + F_USB = $(F_CPU) + PROG := teensy + LUFA_BOARD = TEENSY2 +endif +ifeq ($(BOARD_TYPE),minimus) + MCU := at90usb162 + ARCH = AVR8 + F_CPU := 16000000 + F_USB = $(F_CPU) + PROG := DFU + LUFA_BOARD = MINIMUS + RESET_FUNC := ../tools/reset_minimus + RESET_PARAM = "03eb:2ffa" +endif +ifeq ($(BOARD_TYPE),minimus32) + MCU := atmega32u2 + ARCH = AVR8 + F_CPU := 16000000 + F_USB = $(F_CPU) + PROG := DFU + LUFA_BOARD = MINIMUS + RESET_FUNC := ../tools/reset_minimus + RESET_PARAM = "03eb:2ff0" +endif +ifeq ($(BOARD_TYPE),hhd70dongle) + MCU := atmega32u4 + ARCH = AVR8 + F_CPU := 16000000 + F_USB = $(F_CPU) + PROG := DFU + LUFA_BOARD = NONE +endif +ifeq ($(BOARD_TYPE),rda1846dongle) + MCU := atmega32u4 + ARCH = AVR8 + F_CPU := 16000000 + F_USB = $(F_CPU) + PROG := DFU + LUFA_BOARD = NONE +endif +ifeq ($(BOARD_TYPE),culV3) + MCU := atmega32u4 + ARCH = AVR8 + F_CPU := 8000000 + F_USB = $(F_CPU) + PROG := DFU + LUFA_BOARD = CULV3 +endif +ifeq ($(BOARD_TYPE),slowpandongle1) + MCU := at90usb162 + ARCH = AVR8 + F_CPU := 16000000 + F_USB = $(F_CPU) + PROG := DFU + LUFA_BOARD = NONE +endif +ifeq ($(BOARD_TYPE),slowpandongle2) + MCU := atmega32u4 + ARCH = AVR8 + F_CPU := 16000000 + F_USB = $(F_CPU) + PROG := DFU + LUFA_BOARD = NONE +endif +ifeq ($(BOARD_TYPE),teenstep) + MCU := atmega32u4 + ARCH = AVR8 + F_CPU := 16000000 + F_USB = $(F_CPU) + PROG := DFU + LUFA_BOARD = NONE +endif +ifeq ($(BOARD_TYPE),rhmixxx) + MCU := at90usb1286 + ARCH = AVR8 + F_CPU := 16000000 + F_USB = $(F_CPU) + PROG := DFU + LUFA_BOARD = NONE +endif +ifeq ($(BOARD_TYPE),arduinoUno) + MCU := atmega328p + ARCH = AVR8 + F_CPU := 16000000 + PROG := avrdude + UPLOAD_RATE := 57600 + PROG_TYPE := stk500v1 + AVRDUDE_PORT := /dev/ttyUSB0 + RESET_FUNC := ../tools/reset_arduino + RESET_PARAM = $(AVRDUDE_PORT) +endif +ifeq ($(BOARD_TYPE),arduino2009v2) + MCU := atmega328p + ARCH = AVR8 + F_CPU := 16000000 + PROG := avrdude + UPLOAD_RATE := 57600 + PROG_TYPE := stk500v1 + AVRDUDE_PORT := /dev/ttyUSB0 + RESET_FUNC := ../tools/reset_arduino + RESET_PARAM = $(AVRDUDE_PORT) +endif +ifeq ($(BOARD_TYPE),arduino2009) + MCU := atmega168 + ARCH = AVR8 + F_CPU := 16000000 + PROG := avrdude + UPLOAD_RATE := 19200 + PROG_TYPE := stk500v1 + AVRDUDE_PORT := /dev/ttyUSB0 + RESET_FUNC := ../tools/reset_arduino + RESET_PARAM = $(AVRDUDE_PORT) +endif +ifeq ($(BOARD_TYPE),arduino10000) + MCU := atmega168 + ARCH = AVR8 + F_CPU := 16000000 + PROG := avrdude + UPLOAD_RATE := 19200 + PROG_TYPE := stk500v1 + AVRDUDE_PORT := /dev/ttyUSB0 + RESET_FUNC := ../tools/reset_arduino + RESET_PARAM = $(AVRDUDE_PORT) +endif +ifeq ($(BOARD_TYPE),arduinoNG) + MCU := atmega8 + ARCH = AVR8 + F_CPU := 16000000 + PROG := avrdude + UPLOAD_RATE := 19200 + PROG_TYPE := stk500v1 + AVRDUDE_PORT := /dev/ttyUSB0 + RESET_FUNC := ../tools/reset_dummy +endif +ifeq ($(BOARD_TYPE),AvrNetIo) + MCU := atmega32 + ARCH = AVR8 + F_CPU := 16000000 + PROG := avrdude + UPLOAD_RATE := 19200 + PROG_TYPE := stk500v2 + AVRDUDE_PORT := /dev/ttyS0 +endif + +CC = avr-gcc +OBJCOPY = avr-objcopy +AR = avr-ar rcs +SIZE = avr-size + +LIB_DIR = ../lib + +DFU = dfu-programmer +teensy = teensy_loader_cli +avrdude = avrdude + +## Options common to compile, link and assembly rules +COMMON = -mmcu=$(MCU) + +## Compile options common for all C compilation units. +CFLAGS = $(COMMON) +CFLAGS += -O2 +CFLAGS += -funsigned-char +CFLAGS += -funsigned-bitfields +CFLAGS += -ffunction-sections +CFLAGS += -fpack-struct +CFLAGS += -fshort-enums +CFLAGS += -Wall +CFLAGS += -Wstrict-prototypes +CFLAGS += -I$(LIB_DIR) +CFLAGS += -DF_CPU=$(F_CPU)UL +CFLAGS += -D__BOARD_$(BOARD_TYPE)__ +CFLAGS += -DARCH=ARCH_$(ARCH) +CFLAGS += -std=c99 + + +## Linker flags +LDFLAGS = $(COMMON) +LDFLAGS += diff --git a/dolmetsch-ctl/Makefile b/dolmetsch-ctl/Makefile new file mode 100644 index 0000000..331b966 --- /dev/null +++ b/dolmetsch-ctl/Makefile @@ -0,0 +1,44 @@ +## +## spreadspace avr utils +## +## +## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> +## +## This file is part of spreadspace avr utils. +## +## spreadspace avr utils is free software: you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation, either version 3 of the License, or +## any later version. +## +## spreadspace avr utils is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. +## + +NAME := dolmetsch-ctl +BOARD_TYPE := teensy2 +OBJ := $(NAME).o keypad.o eventqueue.o +LIBS := util led lufa-descriptor-midi +EXTERNAL_LIBS := lufa + +LUFA_PATH := ../contrib/LUFA-120219 +LUFA_OPTS = -D USB_DEVICE_ONLY +LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0 +LUFA_OPTS += -D ORDERED_EP_CONFIG +LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8 +LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1 +LUFA_OPTS += -D USE_FLASH_DESCRIPTORS +LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)" +LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT + +LUFA_OPTS += -D USB_MANUFACTURER="L\"equinox\"" -D USB_MANUFACTURER_LEN=7 +LUFA_OPTS += -D USB_PRODUCT="L\"dolmetsch controller\"" -D USB_PRODUCT_LEN=20 + +LUFA_COMPONENTS := USB USBCLASS + +include ../include.mk diff --git a/dolmetsch-ctl/dolmetsch-ctl.c b/dolmetsch-ctl/dolmetsch-ctl.c new file mode 100644 index 0000000..afc74b2 --- /dev/null +++ b/dolmetsch-ctl/dolmetsch-ctl.c @@ -0,0 +1,165 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <avr/io.h> +#include <avr/wdt.h> +#include <avr/interrupt.h> +#include <avr/power.h> +#include <stdio.h> + +/* + LUFA Library + Copyright (C) Dean Camera, 2012. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ +#include <LUFA/Version.h> +#include <LUFA/Drivers/USB/USB.h> +#include "lufa-descriptor-midi.h" + +/** LUFA MIDI Class driver interface configuration and state information. This structure is + * passed to all MIDI Class driver functions, so that multiple instances of the same class + * within a device can be differentiated from one another. + */ +USB_ClassInfo_MIDI_Device_t MIDI_Interface = + { + .Config = + { + .StreamingInterfaceNumber = 1, + + .DataINEndpointNumber = MIDI_STREAM_IN_EPNUM, + .DataINEndpointSize = MIDI_STREAM_EPSIZE, + .DataINEndpointDoubleBank = false, + + .DataOUTEndpointNumber = MIDI_STREAM_OUT_EPNUM, + .DataOUTEndpointSize = MIDI_STREAM_EPSIZE, + .DataOUTEndpointDoubleBank = false, + }, + }; + +/** Event handler for the library USB Configuration Changed event. */ +void EVENT_USB_Device_ConfigurationChanged(void) +{ + MIDI_Device_ConfigureEndpoints(&MIDI_Interface); +} + +/** Event handler for the library USB Control Request reception event. */ +void EVENT_USB_Device_ControlRequest(void) +{ + MIDI_Device_ProcessControlRequest(&MIDI_Interface); +} + +/* end LUFA MIDI Class driver specific definitions*/ + +#include "util.h" +#include "keypad.h" +#include "eventqueue.h" + +#define MIDI_COMMAND_CONTROL_CHANGE 0xB0 +#define MIDI_COMMAND_PROGRAM_CHANGE 0xC0 + +static void process_incoming_midi(void) +{ + MIDI_EventPacket_t ReceivedMIDIEvent; + while(MIDI_Device_ReceiveEventPacket(&MIDI_Interface, &ReceivedMIDIEvent)) { + uint8_t cmd = ReceivedMIDIEvent.Data1 & 0xF0; + uint8_t note = ReceivedMIDIEvent.Data2; + uint8_t value = ReceivedMIDIEvent.Data3 & 0x7F; + if(cmd == MIDI_COMMAND_PROGRAM_CHANGE) { + switch(note) { + case 127: reset2bootloader(); + } + continue; + } + if((note >= KEYPAD_MIDI_NOTE_OFFSET && note < KEYPAD_MIDI_NOTE_OFFSET + KEYPAD_NUM_KEYS) || // KEYPAD + note == KEYPAD_MIDI_NOTE_ALL) { + if(cmd == MIDI_COMMAND_CONTROL_CHANGE) { + switch(value) { + case 0: keypad_led_off(note - KEYPAD_MIDI_NOTE_OFFSET); break; + case 1: keypad_led_on(note - KEYPAD_MIDI_NOTE_OFFSET); break; + case 2: keypad_led_toggle(note - KEYPAD_MIDI_NOTE_OFFSET); break; + default: keypad_led_blink(note, value); break; + } + } + } + } +} + +static void process_outgoing_midi(void) +{ + MIDI_EventPacket_t MIDIEventOn = (MIDI_EventPacket_t) + { + .CableNumber = 0, // TODO: hardcoded value + .Command = (MIDI_COMMAND_NOTE_ON >> 4), + .Data1 = MIDI_COMMAND_NOTE_ON | 0, + .Data2 = 0, + .Data3 = 0x7F, + }; + MIDI_EventPacket_t MIDIEventOff = (MIDI_EventPacket_t) + { + .CableNumber = 0, // TODO: hardcoded value + .Command = (MIDI_COMMAND_NOTE_OFF >> 4), + .Data1 = MIDI_COMMAND_NOTE_OFF | 0, + .Data2 = 0, + .Data3 = 0, + }; + + uint8_t key, state; + while(eventqueue_pop(&key, &state)) { + if (USB_DeviceState == DEVICE_STATE_Configured) { + MIDI_EventPacket_t* MIDIEvent = NULL; + MIDIEvent = state ? &MIDIEventOn : &MIDIEventOff; + MIDIEvent->Data2 = key; + + if(MIDIEvent) + MIDI_Device_SendEventPacket(&MIDI_Interface, MIDIEvent); + } + } + if (USB_DeviceState == DEVICE_STATE_Configured) + MIDI_Device_Flush(&MIDI_Interface); +} + +int main(void) +{ + MCUSR &= ~(1 << WDRF); + wdt_disable(); + + cpu_init(); + jtag_disable(); + eventqueue_init(); + keypad_init(); + + USB_Init(); + sei(); + + for(;;) { + process_incoming_midi(); + + keypad_task(); + + process_outgoing_midi(); + + MIDI_Device_USBTask(&MIDI_Interface); + USB_USBTask(); + } +} diff --git a/dolmetsch-ctl/eventqueue.c b/dolmetsch-ctl/eventqueue.c new file mode 100644 index 0000000..b4637fd --- /dev/null +++ b/dolmetsch-ctl/eventqueue.c @@ -0,0 +1,50 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <LUFA/Drivers/Misc/RingBuffer.h> +#include "eventqueue.h" + +static RingBuffer_t event_queue; +static uint8_t event_queue_data[16]; + +void eventqueue_init(void) +{ + RingBuffer_InitBuffer(&event_queue, event_queue_data, sizeof(event_queue_data)); +} + +uint8_t eventqueue_pop(uint8_t* key, uint8_t* state) +{ + if (RingBuffer_IsEmpty(&event_queue)) + return 0; + + uint8_t event = RingBuffer_Remove(&event_queue); + *state = (event & 0x80) ? 1 : 0; + *key = event & 0x7F; + return 1; +} + +void eventqueue_push(uint8_t key, uint8_t state) +{ + uint8_t event = (state) ? 0x80 : 0; + event |= (key & 0x7F); + RingBuffer_Insert(&event_queue, event); +} diff --git a/dolmetsch-ctl/eventqueue.h b/dolmetsch-ctl/eventqueue.h new file mode 100644 index 0000000..1dc456e --- /dev/null +++ b/dolmetsch-ctl/eventqueue.h @@ -0,0 +1,30 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef DOLMETSCHCTL_eventqueue_h_INCLUDED +#define DOLMETSCHCTL_eventqueue_h_INCLUDED + +void eventqueue_init(void); +uint8_t eventqueue_pop(uint8_t* key, uint8_t* state); +void eventqueue_push(uint8_t key, uint8_t state); + +#endif diff --git a/dolmetsch-ctl/keypad.c b/dolmetsch-ctl/keypad.c new file mode 100644 index 0000000..a4bcabc --- /dev/null +++ b/dolmetsch-ctl/keypad.c @@ -0,0 +1,153 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <avr/io.h> +#include <util/delay.h> + +#include "keypad.h" +#include "eventqueue.h" + +#define KEYPAD_LP_CNT_MAX 200 +static struct { + uint8_t last_sent; + int16_t lp_cnt; +} keypad_state[KEYPAD_NUM_KEYS]; + +static struct { + uint16_t delay; + uint16_t cnt; +} led_blink_state[KEYPAD_NUM_KEYS]; + +void keypad_init(void) +{ + // KEYS are at F4..F7 + DDRF &= 0x0F; + PORTF |= 0xF0; + uint8_t i; + for(i = 0; i < KEYPAD_NUM_KEYS; ++i) { + keypad_state[i].last_sent = 0; + keypad_state[i].lp_cnt = 0; + + led_blink_state[i].delay = 0; + led_blink_state[i].cnt = 0; + } + + // LEDS are at D0..D3 + DDRD |= 0x0F; + PORTD &= 0xFC; + PORTD |= 0x0C; +} + +void keypad_led_on(uint8_t led) +{ + switch(led) { + case 0: PORTD |= 0x01; break; + case 1: PORTD |= 0x02; break; + case 2: PORTD &= 0xFB; break; + case 3: PORTD &= 0xF7; break; + case KEYPAD_MIDI_NOTE_ALL - KEYPAD_MIDI_NOTE_OFFSET: PORTD |= 0x03; PORTD &= 0xF3;; break; + } + keypad_led_blink(led, 0); +} + +void keypad_led_off(uint8_t led) +{ + switch(led) { + case 0: PORTD &= 0xFE; break; + case 1: PORTD &= 0xFD; break; + case 2: PORTD |= 0x04; break; + case 3: PORTD |= 0x08; break; + case KEYPAD_MIDI_NOTE_ALL - KEYPAD_MIDI_NOTE_OFFSET: PORTD &= 0xFC; PORTD |= 0x0C; break; + } + keypad_led_blink(led, 0); +} + +void keypad_led_toggle(uint8_t led) +{ + switch(led) { + case 0: + case 1: + case 2: + case 3: PORTD ^= (1 << led); break; + case KEYPAD_MIDI_NOTE_ALL - KEYPAD_MIDI_NOTE_OFFSET: PORTD ^= 0x0F; break; + } +} + +void keypad_led_blink(uint8_t led, uint8_t value) +{ + if(led < KEYPAD_NUM_KEYS) { + led_blink_state[led].delay = value * 128; + led_blink_state[led].cnt = 0; + } else { + uint8_t i; + for(i = 0; i < KEYPAD_NUM_KEYS; ++i) { + led_blink_state[i].delay = value * 128; + led_blink_state[i].cnt = 0; + } + } +} + +static inline void keypad_key_lowpass(uint8_t key_idx, uint8_t current_state) +{ + keypad_state[key_idx].lp_cnt += current_state ? -1 : +1; + if(keypad_state[key_idx].lp_cnt <= 0 || + keypad_state[key_idx].lp_cnt >= KEYPAD_LP_CNT_MAX) { + + keypad_state[key_idx].lp_cnt = keypad_state[key_idx].lp_cnt <= 0 ? 0 : KEYPAD_LP_CNT_MAX; + + if(current_state != keypad_state[key_idx].last_sent) { + keypad_state[key_idx].last_sent = current_state; + eventqueue_push(KEYPAD_MIDI_NOTE_OFFSET + key_idx, ((current_state) ? 0 : 1)); + } + } +} + +static inline void keypad_led_blinking(uint8_t key_idx) +{ + if(led_blink_state[key_idx].delay > 1) { + if(++led_blink_state[key_idx].cnt >= led_blink_state[key_idx].delay) { + keypad_led_toggle(key_idx); + led_blink_state[key_idx].cnt = 0; + } + } +} + +void keypad_task(void) +{ + uint8_t col, row; + for(col = 0; col < KEYPAD_NUM_COLS; ++col) { + /* KEYPAD_DDR = 1 << (col + 4); */ + /* KEYPAD_PORT = 0x0F; */ + _delay_us(20); + + for(row = 0; row < KEYPAD_NUM_ROWS; ++row) { + uint8_t key_idx = col*KEYPAD_NUM_ROWS + row; + +// uint8_t current_state = KEYPAD_PIN & (1 << row); + uint8_t current_state = PINF & (1 << (row+4)); + keypad_key_lowpass(key_idx, current_state); + + keypad_led_blinking(key_idx); + } + } +// KEYPAD_DDR = 0x00; +} diff --git a/dolmetsch-ctl/keypad.h b/dolmetsch-ctl/keypad.h new file mode 100644 index 0000000..8756458 --- /dev/null +++ b/dolmetsch-ctl/keypad.h @@ -0,0 +1,41 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef DOLMETSCHCTL_keypad_h_INCLUDED +#define DOLMETSCHCTL_keypad_h_INCLUDED + +#define KEYPAD_NUM_COLS 1 +#define KEYPAD_NUM_ROWS 4 +#define KEYPAD_NUM_KEYS KEYPAD_NUM_COLS * KEYPAD_NUM_ROWS +#define KEYPAD_MIDI_NOTE_OFFSET 0 +#define KEYPAD_MIDI_NOTE_ALL KEYPAD_MIDI_NOTE_OFFSET + 31 + +void keypad_init(void); + +void keypad_led_on(uint8_t led); +void keypad_led_off(uint8_t led); +void keypad_led_toggle(uint8_t led); +void keypad_led_blink(uint8_t led, uint8_t value); + +void keypad_task(void); + +#endif diff --git a/include.mk b/include.mk new file mode 100644 index 0000000..c2eb585 --- /dev/null +++ b/include.mk @@ -0,0 +1,162 @@ +## +## spreadspace avr utils +## +## +## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> +## +## This file is part of spreadspace avr utils. +## +## spreadspace avr utils is free software: you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation, either version 3 of the License, or +## any later version. +## +## spreadspace avr utils is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. +## + +include ../defines.mk + +## project-specific objects +SRC := $(OBJ:%.o=%.c) +DEP := $(SRC:%.c=%.d) +OBJ_LIB := $(LIBS:%=lib-%.o) +SRC_LIB := $(LIBS:%=$(LIB_DIR)/%.c) +DEP_LIB := $(LIBS:%=lib-%.d) + +.PHONY: prepare clean clean-external distclean clean-lufa program erase flash reset run + +ELFFILE := $(NAME).elf +HEXFILE := $(NAME).hex + +all: prepare $(HEXFILE) + + +## external Libs +LDFLAGS += -L./ + +ifdef LUFA_PATH +CFLAGS += -I$(LUFA_PATH) +CFLAGS += -DF_USB=$(F_USB)UL +CFLAGS += -DBOARD=BOARD_$(LUFA_BOARD) +CFLAGS += $(LUFA_OPTS) +endif + +prepare: $(EXTERNAL_LIBS:%=build-%) +clean-external: $(EXTERNAL_LIBS:%=clean-%) + +export +build-lufa: liblufa.a + +liblufa.a: Makefile + @echo "building external LUFA lib ($(LUFA_PATH))" + make -f ../lufa.mk liblufa.a + make -f ../lufa.mk clean + +clean-lufa: + @echo "cleaning external LUFA lib ($(LUFA_PATH))" + make -f ../lufa.mk clean + rm -f liblufa.a + + +## project-specific objects +lib-%.d: $(LIB_DIR)/%.c Makefile + @set -e; rm -f $@; \ + $(CC) -MM $(CFLAGS) $< > $@.$$$$; \ + sed 's,\($*\)\.o[ :]*,lib-\1.o $@ : ,g' < $@.$$$$ > $@; \ + rm -f $@.$$$$; echo '(re)building $@' + +%.d: %.c Makefile + @set -e; rm -f $@; \ + $(CC) -MM $(CFLAGS) $< > $@.$$$$; \ + sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \ + rm -f $@.$$$$; echo '(re)building $@' + +ifneq ($(MAKECMDGOALS),distclean) +-include $(DEP) +-include $(DEP_LIB) +endif + +lib-%.o: $(LIB_DIR)/%.c Makefile + $(CC) $(CFLAGS) -c $< -o $@ + +%.o: %.c Makefile + $(CC) $(CFLAGS) -c $< -o $@ + +$(ELFFILE): $(OBJ) $(OBJ_LIB) $(EXTERNAL_LIBS:%=lib%.a) + $(CC) $(LDFLAGS) $(OBJ) $(OBJ_LIB) $(EXTERNAL_LIBS:%=-l%) -o $@ + $(SIZE) $@ + @echo "" + +$(HEXFILE): $(ELFFILE) + $(OBJCOPY) -O ihex -R .eeprom -R .fuse -R .lock -R .signature $< $@ + +clean: $(CLEAN_TARGETS) + rm -f *.o + rm -f *.d + rm -f *.d.* + rm -f $(ELFFILE) + rm -f $(HEXFILE) + +distclean: clean-external clean + +### DFU-Programmer +define DFU/erase + $(DFU) $(MCU) erase || true +endef + +define DFU/flash + $(DFU) $(MCU) flash $1 +endef + +define DFU/run + $(DFU) $(MCU) start +endef + +### teensy-loader +define teensy/erase +endef + +define teensy/flash + $(teensy) -mmcu=$(MCU) -w -v $1 +endef + +define teensy/run +endef + +### avrdude +define avrdude/erase +endef + +define avrdude/flash + $(avrdude) -V -F -p $(MCU) -P $(AVRDUDE_PORT) -c $(PROG_TYPE) -b $(UPLOAD_RATE) -U flash:w:$1 +endef + +define avrdude/run +endef + +### Program Targets +program: reset erase flash run + +erase: + $(call $(PROG)/$@,) + +flash: $(HEXFILE) + $(call $(PROG)/$@,$(HEXFILE)) + +run: + $(call $(PROG)/$@,) + +reset: + @if [ -n "$(RESET_FUNC)" ]; then \ + if [ -x "$(RESET_FUNC)" ]; then \ + eval $(RESET_FUNC) $(RESET_PARAM); \ + else \ + echo "WARNING: ignoring non-existing or non-executable reset script"; \ + fi \ + fi diff --git a/lib/anyio.c b/lib/anyio.c new file mode 100644 index 0000000..2aae54e --- /dev/null +++ b/lib/anyio.c @@ -0,0 +1,116 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <stdio.h> + +#include "anyio.h" + +#include <LUFA/Drivers/USB/USB.h> +#include "lufa-descriptor-usbserial.h" +#include "LUFA/Drivers/Peripheral/Serial.h" + +/* + LUFA Library + Copyright (C) Dean Camera, 2012. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +USB_ClassInfo_CDC_Device_t VirtualSerial_CDC_Interface = + { + .Config = + { + .ControlInterfaceNumber = 0, + + .DataINEndpointNumber = CDC_TX_EPNUM, + .DataINEndpointSize = CDC_TXRX_EPSIZE, + .DataINEndpointDoubleBank = false, + + .DataOUTEndpointNumber = CDC_RX_EPNUM, + .DataOUTEndpointSize = CDC_TXRX_EPSIZE, + .DataOUTEndpointDoubleBank = false, + + .NotificationEndpointNumber = CDC_NOTIFICATION_EPNUM, + .NotificationEndpointSize = CDC_NOTIFICATION_EPSIZE, + .NotificationEndpointDoubleBank = false, + }, + }; + +void EVENT_USB_Device_ConfigurationChanged(void) +{ + CDC_Device_ConfigureEndpoints(&VirtualSerial_CDC_Interface); +} + +void EVENT_USB_Device_ControlRequest(void) +{ + CDC_Device_ProcessControlRequest(&VirtualSerial_CDC_Interface); +} +/* end LUFA CDC-ACM specific definitions*/ + +static FILE usb_stream; +static FILE serial_stream; + +void anyio_init(const uint32_t baudrate, const uint8_t doublespeed) +{ + Serial_Init(baudrate, doublespeed); + Serial_CreateStream(&serial_stream); + stdin = stdout = stderr = &serial_stream; + + USB_Init(); + CDC_Device_CreateStream(&VirtualSerial_CDC_Interface,&usb_stream); +} + +void anyio_task(void) +{ +#if defined(USB_SERIES_4_AVR) || defined(USB_SERIES_6_AVR) || defined(USB_SERIES_7_AVR) + if(USB_DeviceState == DEVICE_STATE_Unattached && USB_VBUS_GetStatus()) { + USB_Disable(); + USB_Init(); + } +#endif + + CDC_Device_USBTask(&VirtualSerial_CDC_Interface); + USB_USBTask(); +} + +int16_t anyio_bytes_received(void) +{ + if(stdin == &usb_stream) + return CDC_Device_BytesReceived(&VirtualSerial_CDC_Interface); + else + return (int16_t)Serial_IsCharReceived(); +} + +void EVENT_CDC_Device_ControLineStateChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo) +{ + if(CDCInterfaceInfo->State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR) + stdin = stdout = stderr = &usb_stream; + else + stdin = stdout = stderr = &serial_stream; +} + +void EVENT_USB_Device_Disconnect(void) +{ + stdin = stdout = stderr = &serial_stream; +} diff --git a/lib/anyio.h b/lib/anyio.h new file mode 100644 index 0000000..2cf4ae1 --- /dev/null +++ b/lib/anyio.h @@ -0,0 +1,33 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef SPREADAVR_anyio_h_INCLUDED +#define SPREADAVR_anyio_h_INCLUDED + +#include <stdint.h> + +void anyio_init(const uint32_t baudrate, const uint8_t doublespeed); +void anyio_task(void); +int16_t anyio_bytes_received(void); + +#endif diff --git a/lib/ds1820.c b/lib/ds1820.c new file mode 100644 index 0000000..4619498 --- /dev/null +++ b/lib/ds1820.c @@ -0,0 +1,167 @@ +/* + * spreadspace avr utils - usb-1wire example + * + * + * Copyright (C) 2013-2014 Bernhard Tittelbach <xro@realraum.at> + * based on code from: + * http://www.pjrc.com/teensy/td_libs_OneWire.html + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "ds1820.h" +#include "onewire.h" +#include "util/delay.h" + +uint8_t owi_ds1820_addr_[MAX_OWI_DEVICES][8]; +uint8_t num_ds1820_found_; + +uint8_t ds1820_discover(void) +{ + uint8_t d=0; + num_ds1820_found_ = 0; + if (! owi_reset()) //if no devices on bus, return now + return 0; + owi_reset_search(); + _delay_ms(250); + + //Search only for DS1820 temp sensors + owi_target_search(DS1820_FAMILY_ID); + + while ( owi_search(owi_ds1820_addr_[ d ])) + { + d++; + if ( d >= MAX_OWI_DEVICES) + break; + } + num_ds1820_found_ = d; + return num_ds1820_found_; +} + +void ds1820_set_resolution(uint8_t d, uint8_t bits) +{ + uint8_t resolution; + if (d >= num_ds1820_found_ || bits < 9 || bits > 12) + return; + + owi_reset(); + owi_select(owi_ds1820_addr_[d]); + + owi_write(DS1820_WRITE_SCRATCHPAD, 0); + owi_write(0xFF, 0); + owi_write(0x7F, 0); + + resolution = (bits - 9) << 5; + owi_write(resolution | 0x1F, 0); +} + +void ds1820_start_measuring(uint8_t d) +{ + owi_reset(); + owi_select(owi_ds1820_addr_[d]); + owi_write(DS1820_START_CONVERSION, 1); +} + +uint16_t ds1820_get_conversion_time_ms(uint8_t bits) +{ + switch (bits) + { + case 9: return DS1820_TCONV_MS_9BITS; + case 10: return DS1820_TCONV_MS_10BITS; + case 11: return DS1820_TCONV_MS_11BITS; + default: return DS1820_TCONV_MS_12BITS; + } +} + +void ds1820_wait_conversion_time(uint8_t bits) +{ + switch (bits) + { + case 9: _delay_ms(DS1820_TCONV_MS_9BITS); break; + case 10: _delay_ms(DS1820_TCONV_MS_10BITS); break; + case 11: _delay_ms(DS1820_TCONV_MS_11BITS); break; + default: _delay_ms(DS1820_TCONV_MS_12BITS); break; + } +} + +int16_t ds1820_read_temperature(uint8_t d) +{ + uint8_t data[9]; + int16_t raw = 0; + uint8_t type_s=0; + uint8_t cfg, i; + + owi_reset(); + owi_select(owi_ds1820_addr_[d]); + owi_write(DS1820_READ_SCRATCHPAD, 0); // Read Scratchpad + for (i = 0; i < 9; i++) { // we need 9 bytes + data[i] = owi_read(); + } + #if (ONEWIRE_CRC == 1) + uint8_t crc_result = owi_crc8(data,8); + if (crc_result != data[8]) + return DS1820_ERROR; + #endif + + // the first ROM byte indicates which chip + switch (owi_ds1820_addr_[d][0]) + { + case 0x10: + type_s = 1; + break; + case 0x28: + case 0x22: + type_s = 0; + break; + default: + break; + } + + // Convert the data to actual temperature + // because the result is a 16 bit signed integer, it should + // be stored to an "int16_t" type, which is always 16 bits + // even when compiled on a 32 bit processor. + raw = (data[1] << 8) | data[0]; + if (type_s) + { + raw = raw << 3; // 9 bit resolution default + if (data[7] == 0x10) { + // "count remain" gives full 12 bit resolution + raw = (raw & 0xFFF0) + 12 - data[6]; + } + } else { + cfg = (data[4] & 0x60); + // at lower res, the low bits are undefined, so let's zero them + if (cfg == DS1820_RESOLUTION_9BITS) + raw = raw & ~7; // 9 bit resolution, 93.75 ms + else if (cfg == DS1820_RESOLUTION_10BITS) + raw = raw & ~3; // 10 bit res, 187.5 ms + else if (cfg == DS1820_RESOLUTION_11BITS) + raw = raw & ~1; // 11 bit res, 375 ms + //// default is 12 bit resolution, 750 ms conversion time + } + + return raw; +} + +float ds1820_raw_temp_to_celsius(int16_t t) +{ + if ( t == DS1820_ERROR ) + return DS1820_ERROR; + else + return ((float) t) / 16.0; +} diff --git a/lib/ds1820.h b/lib/ds1820.h new file mode 100644 index 0000000..64a0089 --- /dev/null +++ b/lib/ds1820.h @@ -0,0 +1,61 @@ +/* + * spreadspace avr utils - usb-1wire example + * + * + * Copyright (C) 2013-2014 Bernhard Tittelbach <xro@realraum.at> + * based on code from: + * http://www.pjrc.com/teensy/td_libs_OneWire.html + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef __DS1820__ +#define __DS1820__ + +#include <stdint.h> + +#define DS1820_FAMILY_ID 0x10 +#define DS1820_START_CONVERSION 0x44 +#define DS1820_READ_SCRATCHPAD 0xbe +#define DS1820_WRITE_SCRATCHPAD 0x4e +#define DS1820_ERROR -1000 // Return code. Outside temperature range. +#define DS1820_RESOLUTION_9BITS 0x00 +#define DS1820_RESOLUTION_10BITS 0x20 +#define DS1820_RESOLUTION_11BITS 0x40 +#define DS1820_RESOLUTION_12BITS 0x60 +#define DS1820_TCONV_MS_9BITS 96 +#define DS1820_TCONV_MS_10BITS 195 +#define DS1820_TCONV_MS_11BITS 390 +#define DS1820_TCONV_MS_12BITS 800 + +#define DS2890_FAMILY_ID 0x2c +#define DS2890_WRITE_CONTROL_REGISTER 0X55 +#define DS2890_RELEASE_CODE 0x96 +#define DS2890_WRITE_POSITION 0x0f + +#ifndef MAX_OWI_DEVICES +#define MAX_OWI_DEVICES 8 +#endif + +uint8_t ds1820_discover(void); +void ds1820_set_resolution(uint8_t d, uint8_t bits); +void ds1820_start_measuring(uint8_t d); +uint16_t ds1820_get_conversion_time_ms(uint8_t bits); +void ds1820_wait_conversion_time(uint8_t bits); +int16_t ds1820_read_temperature(uint8_t d); +float ds1820_raw_temp_to_celsius(int16_t t); + +#endif
\ No newline at end of file diff --git a/lib/led.c b/lib/led.c new file mode 100644 index 0000000..4f3aec2 --- /dev/null +++ b/lib/led.c @@ -0,0 +1,155 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <avr/io.h> + +#include "led.h" + +#if defined(__BOARD_minimus__) || defined(__BOARD_minimus32__) +#define NUM_LEDS 2 +#elif defined(__BOARD_teensy1__) || defined(__BOARD_teensy1pp__) || defined(__BOARD_teensy2__) || defined(__BOARD_teensy2pp__) || \ + defined(__BOARD_arduinoNG__) || defined(__BOARD_arduino2009v2__) || defined(__BOARD_arduino2009__) || defined(__BOARD_arduino10000__) || \ + defined(__BOARD_hhd70dongle__) || defined(__BOARD_rda1846dongle__) || defined(__BOARD_culV3__) || \ + defined(__BOARD_slowpandongle1__) || defined(__BOARD_slowpandongle2__) || defined(__BOARD_teenstep__) || \ + defined(__BOARD_rhmixxx__) +#define NUM_LEDS 1 +#else +#define NUM_LEDS 0 +#endif + +#if defined(__BOARD_teensy1__) || defined(__BOARD_teensy1pp__) || defined(__BOARD_minimus__) || defined(__BOARD_minimus32__) || \ + defined(__BOARD_rhmixxx__) +#define LED_DIR 0 +#else +#define LED_DIR 1 +#endif + +#if defined(__BOARD_teensy1__) || defined(__BOARD_teensy1pp__) || defined(__BOARD_teensy2__) || defined(__BOARD_teensy2pp__) || \ + defined(__BOARD_teenstep__) +#define LED_PORT PORTD +#define LED_DDR DDRD +#define LED_PINNUM 6 +#endif + +#if defined(__BOARD_minimus__) || defined(__BOARD_minimus32__) +#define LED_PORT PORTD +#define LED_DDR DDRD +#define LED_PINNUM 5 + +#define LED2_PORT PORTD +#define LED2_DDR DDRD +#define LED2_PINNUM 6 +#endif + +#if defined(__BOARD_slowpandongle2__) || defined(__BOARD_hhd70dongle__) || defined(__BOARD_rda1846dongle__) || defined(__BOARD_culV3__) +#define LED_PORT PORTE +#define LED_DDR DDRE +#define LED_PINNUM 6 +#endif + +#if defined(__BOARD_slowpandongle1__) +#define LED_PORT PORTC +#define LED_DDR DDRC +#define LED_PINNUM 2 +#endif + +#if defined(__BOARD_arduino2009v2__) || defined(__BOARD_arduino2009__) || defined(__BOARD_arduino10000__) || defined(__BOARD_arduinoNG__) +#define LED_PORT PORTB +#define LED_DDR DDRB +#define LED_PINNUM 5 +#endif + +#if defined(__BOARD_rhmixxx__) +#define LED_PORT PORTE +#define LED_DDR DDRE +#define LED_PINNUM 0 +#endif + +void led_init(void) +{ +#if NUM_LEDS >= 1 + led_off(); + LED_DDR = 1<<LED_PINNUM; +#if NUM_LEDS >= 2 + LED2_DDR |= 1<<LED2_PINNUM; +#endif +#endif +} + +void led_on(void) +{ +#if NUM_LEDS >= 1 +#if LED_DIR == 1 + LED_PORT |= 1<<LED_PINNUM; +#else + LED_PORT &= ~(1<<LED_PINNUM); +#endif +#endif +} + +void led_off(void) +{ +#if NUM_LEDS >= 1 +#if LED_DIR == 1 + LED_PORT &= ~(1<<LED_PINNUM); +#else + LED_PORT |= 1<<LED_PINNUM; +#endif +#endif +} + +void led_toggle(void) +{ +#if NUM_LEDS >= 1 + LED_PORT ^= 1<<LED_PINNUM; +#endif +} + + +void led2_on(void) +{ +#if NUM_LEDS >= 2 +#if LED_DIR == 1 + LED2_PORT |= 1<<LED2_PINNUM; +#else + LED2_PORT &= ~(1<<LED2_PINNUM); +#endif +#endif +} + +void led2_off(void) +{ +#if NUM_LEDS >= 2 +#if LED_DIR == 1 + LED2_PORT &= ~(1<<LED2_PINNUM); +#else + LED2_PORT |= 1<<LED2_PINNUM; +#endif +#endif +} + +void led2_toggle(void) +{ +#if NUM_LEDS >= 2 + LED2_PORT ^= 1<<LED2_PINNUM; +#endif +} diff --git a/lib/led.h b/lib/led.h new file mode 100644 index 0000000..0c78193 --- /dev/null +++ b/lib/led.h @@ -0,0 +1,36 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef SPREADAVR_led_h_INCLUDED +#define SPREADAVR_led_h_INCLUDED + +void led_init(void); + +void led_on(void); +void led_off(void); +void led_toggle(void); + +void led2_on(void); +void led2_off(void); +void led2_toggle(void); + +#endif diff --git a/lib/lufa-descriptor-keyboardmouse.c b/lib/lufa-descriptor-keyboardmouse.c new file mode 100644 index 0000000..acc319b --- /dev/null +++ b/lib/lufa-descriptor-keyboardmouse.c @@ -0,0 +1,310 @@ +/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+/** \file
+ *
+ * USB Device Descriptors, for library use when in USB device mode. Descriptors are special
+ * computer-readable structures which the host requests upon device enumeration, to determine
+ * the device's capabilities and functions.
+ */
+
+#include "lufa-descriptor-keyboardmouse.h"
+
+/** HID class report descriptor. This is a special descriptor constructed with values from the
+ * USBIF HID class specification to describe the reports and capabilities of the HID device. This
+ * descriptor is parsed by the host and its contents used to determine what data (and in what encoding)
+ * the device will send, and what it may be sent back from the host. Refer to the HID specification for
+ * more details on HID report descriptors.
+ *
+ * This descriptor describes the mouse HID interface's report structure.
+ */
+const USB_Descriptor_HIDReport_Datatype_t PROGMEM MouseReport[] =
+{
+ /* Use the HID class driver's standard Mouse report.
+ * Min X/Y Axis values: -1
+ * Max X/Y Axis values: 1
+ * Min physical X/Y Axis values (used to determine resolution): -1
+ * Max physical X/Y Axis values (used to determine resolution): 1
+ * Buttons: 3
+ * Absolute screen coordinates: false
+ */
+ HID_DESCRIPTOR_MOUSE(-1, 1, -1, 1, 3, false)
+};
+
+/** Same as the MouseReport structure, but defines the keyboard HID interface's report structure. */
+const USB_Descriptor_HIDReport_Datatype_t PROGMEM KeyboardReport[] =
+{
+ /* Use the HID class driver's standard Keyboard report.
+ * Max simultaneous keys: 6
+ */
+ HID_DESCRIPTOR_KEYBOARD(6)
+};
+
+/** Device descriptor structure. This descriptor, located in FLASH memory, describes the overall
+ * device characteristics, including the supported USB version, control endpoint size and the
+ * number of device configurations. The descriptor is read out by the USB host when the enumeration
+ * process begins.
+ */
+const USB_Descriptor_Device_t PROGMEM DeviceDescriptor =
+{
+ .Header = {.Size = sizeof(USB_Descriptor_Device_t), .Type = DTYPE_Device},
+
+ .USBSpecification = VERSION_BCD(01.10),
+ .Class = USB_CSCP_NoDeviceClass,
+ .SubClass = USB_CSCP_NoDeviceSubclass,
+ .Protocol = USB_CSCP_NoDeviceProtocol,
+
+ .Endpoint0Size = FIXED_CONTROL_ENDPOINT_SIZE,
+
+ .VendorID = 0x03EB,
+ .ProductID = 0x204D,
+ .ReleaseNumber = VERSION_BCD(00.01),
+
+ .ManufacturerStrIndex = 0x01,
+ .ProductStrIndex = 0x02,
+ .SerialNumStrIndex = NO_DESCRIPTOR,
+
+ .NumberOfConfigurations = FIXED_NUM_CONFIGURATIONS
+};
+
+/** Configuration descriptor structure. This descriptor, located in FLASH memory, describes the usage
+ * of the device in one of its supported configurations, including information about any device interfaces
+ * and endpoints. The descriptor is read out by the USB host during the enumeration process when selecting
+ * a configuration so that the host may correctly communicate with the USB device.
+ */
+const USB_Descriptor_Configuration_t PROGMEM ConfigurationDescriptor =
+{
+ .Config =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Configuration_Header_t), .Type = DTYPE_Configuration},
+
+ .TotalConfigurationSize = sizeof(USB_Descriptor_Configuration_t),
+ .TotalInterfaces = 2,
+
+ .ConfigurationNumber = 1,
+ .ConfigurationStrIndex = NO_DESCRIPTOR,
+
+ .ConfigAttributes = (USB_CONFIG_ATTR_RESERVED | USB_CONFIG_ATTR_SELFPOWERED),
+
+ .MaxPowerConsumption = USB_CONFIG_POWER_MA(100)
+ },
+
+ .HID1_KeyboardInterface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = 0x00,
+ .AlternateSetting = 0x00,
+
+ .TotalEndpoints = 1,
+
+ .Class = HID_CSCP_HIDClass,
+ .SubClass = HID_CSCP_BootSubclass,
+ .Protocol = HID_CSCP_KeyboardBootProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .HID1_KeyboardHID =
+ {
+ .Header = {.Size = sizeof(USB_HID_Descriptor_HID_t), .Type = HID_DTYPE_HID},
+
+ .HIDSpec = VERSION_BCD(01.11),
+ .CountryCode = 0x00,
+ .TotalReportDescriptors = 1,
+ .HIDReportType = HID_DTYPE_Report,
+ .HIDReportLength = sizeof(KeyboardReport)
+ },
+
+ .HID1_ReportINEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | KEYBOARD_IN_EPNUM),
+ .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = HID_EPSIZE,
+ .PollingIntervalMS = 0x01
+ },
+
+ .HID2_MouseInterface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = 0x01,
+ .AlternateSetting = 0x00,
+
+ .TotalEndpoints = 1,
+
+ .Class = HID_CSCP_HIDClass,
+ .SubClass = HID_CSCP_BootSubclass,
+ .Protocol = HID_CSCP_MouseBootProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .HID2_MouseHID =
+ {
+ .Header = {.Size = sizeof(USB_HID_Descriptor_HID_t), .Type = HID_DTYPE_HID},
+
+ .HIDSpec = VERSION_BCD(01.11),
+ .CountryCode = 0x00,
+ .TotalReportDescriptors = 1,
+ .HIDReportType = HID_DTYPE_Report,
+ .HIDReportLength = sizeof(MouseReport)
+ },
+
+ .HID2_ReportINEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | MOUSE_IN_EPNUM),
+ .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = HID_EPSIZE,
+ .PollingIntervalMS = 0x01
+ }
+};
+
+/** Language descriptor structure. This descriptor, located in FLASH memory, is returned when the host requests
+ * the string descriptor with index 0 (the first index). It is actually an array of 16-bit integers, which indicate
+ * via the language ID table available at USB.org what languages the device supports for its string descriptors.
+ */
+const USB_Descriptor_String_t PROGMEM LanguageString =
+{
+ .Header = {.Size = USB_STRING_LEN(1), .Type = DTYPE_String},
+
+ .UnicodeString = {LANGUAGE_ID_ENG}
+};
+
+/** Manufacturer descriptor string. This is a Unicode string containing the manufacturer's details in human readable
+ * form, and is read out upon request by the host when the appropriate string ID is requested, listed in the Device
+ * Descriptor.
+ */
+const USB_Descriptor_String_t PROGMEM ManufacturerString =
+{
+#ifndef USB_MANUFACTURER
+ .Header = {.Size = USB_STRING_LEN(11), .Type = DTYPE_String},
+ .UnicodeString = L"Dean Camera"
+#else
+ .Header = {.Size = USB_STRING_LEN(USB_MANUFACTURER_LEN), .Type = DTYPE_String},
+ .UnicodeString = USB_MANUFACTURER
+#endif
+};
+
+/** Product descriptor string. This is a Unicode string containing the product's details in human readable form,
+ * and is read out upon request by the host when the appropriate string ID is requested, listed in the Device
+ * Descriptor.
+ */
+const USB_Descriptor_String_t PROGMEM ProductString =
+{
+#ifndef USB_PRODUCT
+ .Header = {.Size = USB_STRING_LEN(28), .Type = DTYPE_String},
+ .UnicodeString = L"LUFA Mouse and Keyboard Demo"
+#else
+ .Header = {.Size = USB_STRING_LEN(USB_PRODUCT_LEN), .Type = DTYPE_String},
+ .UnicodeString = USB_PRODUCT
+#endif
+};
+
+/** This function is called by the library when in device mode, and must be overridden (see library "USB Descriptors"
+ * documentation) by the application code so that the address and size of a requested descriptor can be given
+ * to the USB library. When the device receives a Get Descriptor request on the control endpoint, this function
+ * is called so that the descriptor details can be passed back and the appropriate descriptor sent back to the
+ * USB host.
+ */
+uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
+ const uint8_t wIndex,
+ const void** const DescriptorAddress)
+{
+ const uint8_t DescriptorType = (wValue >> 8);
+ const uint8_t DescriptorNumber = (wValue & 0xFF);
+
+ const void* Address = NULL;
+ uint16_t Size = NO_DESCRIPTOR;
+
+ switch (DescriptorType)
+ {
+ case DTYPE_Device:
+ Address = &DeviceDescriptor;
+ Size = sizeof(USB_Descriptor_Device_t);
+ break;
+ case DTYPE_Configuration:
+ Address = &ConfigurationDescriptor;
+ Size = sizeof(USB_Descriptor_Configuration_t);
+ break;
+ case DTYPE_String:
+ switch (DescriptorNumber)
+ {
+ case 0x00:
+ Address = &LanguageString;
+ Size = pgm_read_byte(&LanguageString.Header.Size);
+ break;
+ case 0x01:
+ Address = &ManufacturerString;
+ Size = pgm_read_byte(&ManufacturerString.Header.Size);
+ break;
+ case 0x02:
+ Address = &ProductString;
+ Size = pgm_read_byte(&ProductString.Header.Size);
+ break;
+ }
+
+ break;
+ case HID_DTYPE_HID:
+ if (!(wIndex))
+ {
+ Address = &ConfigurationDescriptor.HID1_KeyboardHID;
+ Size = sizeof(USB_HID_Descriptor_HID_t);
+ }
+ else
+ {
+ Address = &ConfigurationDescriptor.HID2_MouseHID;
+ Size = sizeof(USB_HID_Descriptor_HID_t);
+ }
+
+ break;
+ case HID_DTYPE_Report:
+ if (!(wIndex))
+ {
+ Address = &KeyboardReport;
+ Size = sizeof(KeyboardReport);
+ }
+ else
+ {
+ Address = &MouseReport;
+ Size = sizeof(MouseReport);
+ }
+
+ break;
+ }
+
+ *DescriptorAddress = Address;
+ return Size;
+}
+
diff --git a/lib/lufa-descriptor-keyboardmouse.h b/lib/lufa-descriptor-keyboardmouse.h new file mode 100644 index 0000000..9381602 --- /dev/null +++ b/lib/lufa-descriptor-keyboardmouse.h @@ -0,0 +1,81 @@ +/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+/** \file
+ *
+ * Header file for Descriptors.c.
+ */
+
+#ifndef _DESCRIPTORS_H_
+#define _DESCRIPTORS_H_
+
+ /* Includes: */
+ #include <avr/pgmspace.h>
+
+ #include <LUFA/Drivers/USB/USB.h>
+
+ /* Type Defines: */
+ /** Type define for the device configuration descriptor structure. This must be defined in the
+ * application code, as the configuration descriptor contains several sub-descriptors which
+ * vary between devices, and which describe the device's usage to the host.
+ */
+ typedef struct
+ {
+ USB_Descriptor_Configuration_Header_t Config;
+
+ // Keyboard HID Interface
+ USB_Descriptor_Interface_t HID1_KeyboardInterface;
+ USB_HID_Descriptor_HID_t HID1_KeyboardHID;
+ USB_Descriptor_Endpoint_t HID1_ReportINEndpoint;
+
+ // Mouse HID Interface
+ USB_Descriptor_Interface_t HID2_MouseInterface;
+ USB_HID_Descriptor_HID_t HID2_MouseHID;
+ USB_Descriptor_Endpoint_t HID2_ReportINEndpoint;
+ } USB_Descriptor_Configuration_t;
+
+ /* Macros: */
+ /** Endpoint number of the Keyboard HID reporting IN endpoint. */
+ #define KEYBOARD_IN_EPNUM 1
+
+ /** Endpoint number of the Mouse HID reporting IN endpoint. */
+ #define MOUSE_IN_EPNUM 3
+
+ /** Size in bytes of each of the HID reporting IN endpoints. */
+ #define HID_EPSIZE 8
+
+ /* Function Prototypes: */
+ uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
+ const uint8_t wIndex,
+ const void** const DescriptorAddress)
+ ATTR_WARN_UNUSED_RESULT ATTR_NON_NULL_PTR_ARG(3);
+
+#endif
+
diff --git a/lib/lufa-descriptor-midi.c b/lib/lufa-descriptor-midi.c new file mode 100644 index 0000000..99fab41 --- /dev/null +++ b/lib/lufa-descriptor-midi.c @@ -0,0 +1,337 @@ +/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+/** \file
+ *
+ * USB Device Descriptors, for library use when in USB device mode. Descriptors are special
+ * computer-readable structures which the host requests upon device enumeration, to determine
+ * the device's capabilities and functions.
+ */
+
+#include "lufa-descriptor-midi.h"
+
+/** Device descriptor structure. This descriptor, located in FLASH memory, describes the overall
+ * device characteristics, including the supported USB version, control endpoint size and the
+ * number of device configurations. The descriptor is read out by the USB host when the enumeration
+ * process begins.
+ */
+const USB_Descriptor_Device_t PROGMEM DeviceDescriptor =
+{
+ .Header = {.Size = sizeof(USB_Descriptor_Device_t), .Type = DTYPE_Device},
+
+ .USBSpecification = VERSION_BCD(01.10),
+ .Class = USB_CSCP_NoDeviceClass,
+ .SubClass = USB_CSCP_NoDeviceSubclass,
+ .Protocol = USB_CSCP_NoDeviceProtocol,
+
+ .Endpoint0Size = FIXED_CONTROL_ENDPOINT_SIZE,
+
+ .VendorID = 0x03EB,
+ .ProductID = 0x2048,
+ .ReleaseNumber = VERSION_BCD(00.01),
+
+ .ManufacturerStrIndex = 0x01,
+ .ProductStrIndex = 0x02,
+ .SerialNumStrIndex = NO_DESCRIPTOR,
+
+ .NumberOfConfigurations = FIXED_NUM_CONFIGURATIONS
+};
+
+/** Configuration descriptor structure. This descriptor, located in FLASH memory, describes the usage
+ * of the device in one of its supported configurations, including information about any device interfaces
+ * and endpoints. The descriptor is read out by the USB host during the enumeration process when selecting
+ * a configuration so that the host may correctly communicate with the USB device.
+ */
+const USB_Descriptor_Configuration_t PROGMEM ConfigurationDescriptor =
+{
+ .Config =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Configuration_Header_t), .Type = DTYPE_Configuration},
+
+ .TotalConfigurationSize = sizeof(USB_Descriptor_Configuration_t),
+ .TotalInterfaces = 2,
+
+ .ConfigurationNumber = 1,
+ .ConfigurationStrIndex = NO_DESCRIPTOR,
+
+ .ConfigAttributes = (USB_CONFIG_ATTR_RESERVED | USB_CONFIG_ATTR_SELFPOWERED),
+
+ .MaxPowerConsumption = USB_CONFIG_POWER_MA(100)
+ },
+
+ .Audio_ControlInterface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = 0,
+ .AlternateSetting = 0,
+
+ .TotalEndpoints = 0,
+
+ .Class = AUDIO_CSCP_AudioClass,
+ .SubClass = AUDIO_CSCP_ControlSubclass,
+ .Protocol = AUDIO_CSCP_ControlProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .Audio_ControlInterface_SPC =
+ {
+ .Header = {.Size = sizeof(USB_Audio_Descriptor_Interface_AC_t), .Type = DTYPE_CSInterface},
+ .Subtype = AUDIO_DSUBTYPE_CSInterface_Header,
+
+ .ACSpecification = VERSION_BCD(01.00),
+ .TotalLength = sizeof(USB_Audio_Descriptor_Interface_AC_t),
+
+ .InCollection = 1,
+ .InterfaceNumber = 1,
+ },
+
+ .Audio_StreamInterface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = 1,
+ .AlternateSetting = 0,
+
+ .TotalEndpoints = 2,
+
+ .Class = AUDIO_CSCP_AudioClass,
+ .SubClass = AUDIO_CSCP_MIDIStreamingSubclass,
+ .Protocol = AUDIO_CSCP_StreamingProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .Audio_StreamInterface_SPC =
+ {
+ .Header = {.Size = sizeof(USB_MIDI_Descriptor_AudioInterface_AS_t), .Type = DTYPE_CSInterface},
+ .Subtype = AUDIO_DSUBTYPE_CSInterface_General,
+
+ .AudioSpecification = VERSION_BCD(01.00),
+
+ .TotalLength = (sizeof(USB_Descriptor_Configuration_t) -
+ offsetof(USB_Descriptor_Configuration_t, Audio_StreamInterface_SPC))
+ },
+
+ .MIDI_In_Jack_Emb =
+ {
+ .Header = {.Size = sizeof(USB_MIDI_Descriptor_InputJack_t), .Type = DTYPE_CSInterface},
+ .Subtype = AUDIO_DSUBTYPE_CSInterface_InputTerminal,
+
+ .JackType = MIDI_JACKTYPE_Embedded,
+ .JackID = 0x01,
+
+ .JackStrIndex = NO_DESCRIPTOR
+ },
+
+ .MIDI_In_Jack_Ext =
+ {
+ .Header = {.Size = sizeof(USB_MIDI_Descriptor_InputJack_t), .Type = DTYPE_CSInterface},
+ .Subtype = AUDIO_DSUBTYPE_CSInterface_InputTerminal,
+
+ .JackType = MIDI_JACKTYPE_External,
+ .JackID = 0x02,
+
+ .JackStrIndex = NO_DESCRIPTOR
+ },
+
+ .MIDI_Out_Jack_Emb =
+ {
+ .Header = {.Size = sizeof(USB_MIDI_Descriptor_OutputJack_t), .Type = DTYPE_CSInterface},
+ .Subtype = AUDIO_DSUBTYPE_CSInterface_OutputTerminal,
+
+ .JackType = MIDI_JACKTYPE_Embedded,
+ .JackID = 0x03,
+
+ .NumberOfPins = 1,
+ .SourceJackID = {0x02},
+ .SourcePinID = {0x01},
+
+ .JackStrIndex = NO_DESCRIPTOR
+ },
+
+ .MIDI_Out_Jack_Ext =
+ {
+ .Header = {.Size = sizeof(USB_MIDI_Descriptor_OutputJack_t), .Type = DTYPE_CSInterface},
+ .Subtype = AUDIO_DSUBTYPE_CSInterface_OutputTerminal,
+
+ .JackType = MIDI_JACKTYPE_External,
+ .JackID = 0x04,
+
+ .NumberOfPins = 1,
+ .SourceJackID = {0x01},
+ .SourcePinID = {0x01},
+
+ .JackStrIndex = NO_DESCRIPTOR
+ },
+
+ .MIDI_In_Jack_Endpoint =
+ {
+ .Endpoint =
+ {
+ .Header = {.Size = sizeof(USB_Audio_Descriptor_StreamEndpoint_Std_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_OUT | MIDI_STREAM_OUT_EPNUM),
+ .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = MIDI_STREAM_EPSIZE,
+ .PollingIntervalMS = 0x01
+ },
+
+ .Refresh = 0,
+ .SyncEndpointNumber = 0
+ },
+
+ .MIDI_In_Jack_Endpoint_SPC =
+ {
+ .Header = {.Size = sizeof(USB_MIDI_Descriptor_Jack_Endpoint_t), .Type = DTYPE_CSEndpoint},
+ .Subtype = AUDIO_DSUBTYPE_CSEndpoint_General,
+
+ .TotalEmbeddedJacks = 0x01,
+ .AssociatedJackID = {0x01}
+ },
+
+ .MIDI_Out_Jack_Endpoint =
+ {
+ .Endpoint =
+ {
+ .Header = {.Size = sizeof(USB_Audio_Descriptor_StreamEndpoint_Std_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | MIDI_STREAM_IN_EPNUM),
+ .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = MIDI_STREAM_EPSIZE,
+ .PollingIntervalMS = 0x01
+ },
+
+ .Refresh = 0,
+ .SyncEndpointNumber = 0
+ },
+
+ .MIDI_Out_Jack_Endpoint_SPC =
+ {
+ .Header = {.Size = sizeof(USB_MIDI_Descriptor_Jack_Endpoint_t), .Type = DTYPE_CSEndpoint},
+ .Subtype = AUDIO_DSUBTYPE_CSEndpoint_General,
+
+ .TotalEmbeddedJacks = 0x01,
+ .AssociatedJackID = {0x03}
+ }
+};
+
+/** Language descriptor structure. This descriptor, located in FLASH memory, is returned when the host requests
+ * the string descriptor with index 0 (the first index). It is actually an array of 16-bit integers, which indicate
+ * via the language ID table available at USB.org what languages the device supports for its string descriptors.
+ */
+const USB_Descriptor_String_t PROGMEM LanguageString =
+{
+ .Header = {.Size = USB_STRING_LEN(1), .Type = DTYPE_String},
+
+ .UnicodeString = {LANGUAGE_ID_ENG}
+};
+
+/** Manufacturer descriptor string. This is a Unicode string containing the manufacturer's details in human readable
+ * form, and is read out upon request by the host when the appropriate string ID is requested, listed in the Device
+ * Descriptor.
+ */
+const USB_Descriptor_String_t PROGMEM ManufacturerString =
+{
+#ifndef USB_MANUFACTURER
+ .Header = {.Size = USB_STRING_LEN(11), .Type = DTYPE_String},
+ .UnicodeString = L"Dean Camera"
+#else
+ .Header = {.Size = USB_STRING_LEN(USB_MANUFACTURER_LEN), .Type = DTYPE_String},
+ .UnicodeString = USB_MANUFACTURER
+#endif
+};
+
+/** Product descriptor string. This is a Unicode string containing the product's details in human readable form,
+ * and is read out upon request by the host when the appropriate string ID is requested, listed in the Device
+ * Descriptor.
+ */
+const USB_Descriptor_String_t PROGMEM ProductString =
+{
+#ifndef USB_PRODUCT
+ .Header = {.Size = USB_STRING_LEN(14), .Type = DTYPE_String},
+ .UnicodeString = L"LUFA MIDI Demo"
+#else
+ .Header = {.Size = USB_STRING_LEN(USB_PRODUCT_LEN), .Type = DTYPE_String},
+ .UnicodeString = USB_PRODUCT
+#endif
+};
+
+/** This function is called by the library when in device mode, and must be overridden (see library "USB Descriptors"
+ * documentation) by the application code so that the address and size of a requested descriptor can be given
+ * to the USB library. When the device receives a Get Descriptor request on the control endpoint, this function
+ * is called so that the descriptor details can be passed back and the appropriate descriptor sent back to the
+ * USB host.
+ */
+uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
+ const uint8_t wIndex,
+ const void** const DescriptorAddress)
+{
+ const uint8_t DescriptorType = (wValue >> 8);
+ const uint8_t DescriptorNumber = (wValue & 0xFF);
+
+ const void* Address = NULL;
+ uint16_t Size = NO_DESCRIPTOR;
+
+ switch (DescriptorType)
+ {
+ case DTYPE_Device:
+ Address = &DeviceDescriptor;
+ Size = sizeof(USB_Descriptor_Device_t);
+ break;
+ case DTYPE_Configuration:
+ Address = &ConfigurationDescriptor;
+ Size = sizeof(USB_Descriptor_Configuration_t);
+ break;
+ case DTYPE_String:
+ switch (DescriptorNumber)
+ {
+ case 0x00:
+ Address = &LanguageString;
+ Size = pgm_read_byte(&LanguageString.Header.Size);
+ break;
+ case 0x01:
+ Address = &ManufacturerString;
+ Size = pgm_read_byte(&ManufacturerString.Header.Size);
+ break;
+ case 0x02:
+ Address = &ProductString;
+ Size = pgm_read_byte(&ProductString.Header.Size);
+ break;
+ }
+
+ break;
+ }
+
+ *DescriptorAddress = Address;
+ return Size;
+}
+
diff --git a/lib/lufa-descriptor-midi.h b/lib/lufa-descriptor-midi.h new file mode 100644 index 0000000..592ac9f --- /dev/null +++ b/lib/lufa-descriptor-midi.h @@ -0,0 +1,87 @@ +/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+/** \file
+ *
+ * Header file for Descriptors.c.
+ */
+
+#ifndef _DESCRIPTORS_H_
+#define _DESCRIPTORS_H_
+
+ /* Includes: */
+ #include <LUFA/Drivers/USB/USB.h>
+
+ #include <avr/pgmspace.h>
+
+ /* Macros: */
+ /** Endpoint number of the MIDI streaming data IN endpoint, for device-to-host data transfers. */
+ #define MIDI_STREAM_IN_EPNUM 2
+
+ /** Endpoint number of the MIDI streaming data OUT endpoint, for host-to-device data transfers. */
+ #define MIDI_STREAM_OUT_EPNUM 1
+
+ /** Endpoint size in bytes of the Audio isochronous streaming data IN and OUT endpoints. */
+ #define MIDI_STREAM_EPSIZE 64
+
+ /* Type Defines: */
+ /** Type define for the device configuration descriptor structure. This must be defined in the
+ * application code, as the configuration descriptor contains several sub-descriptors which
+ * vary between devices, and which describe the device's usage to the host.
+ */
+ typedef struct
+ {
+ USB_Descriptor_Configuration_Header_t Config;
+
+ // MIDI Audio Control Interface
+ USB_Descriptor_Interface_t Audio_ControlInterface;
+ USB_Audio_Descriptor_Interface_AC_t Audio_ControlInterface_SPC;
+
+ // MIDI Audio Streaming Interface
+ USB_Descriptor_Interface_t Audio_StreamInterface;
+ USB_MIDI_Descriptor_AudioInterface_AS_t Audio_StreamInterface_SPC;
+ USB_MIDI_Descriptor_InputJack_t MIDI_In_Jack_Emb;
+ USB_MIDI_Descriptor_InputJack_t MIDI_In_Jack_Ext;
+ USB_MIDI_Descriptor_OutputJack_t MIDI_Out_Jack_Emb;
+ USB_MIDI_Descriptor_OutputJack_t MIDI_Out_Jack_Ext;
+ USB_Audio_Descriptor_StreamEndpoint_Std_t MIDI_In_Jack_Endpoint;
+ USB_MIDI_Descriptor_Jack_Endpoint_t MIDI_In_Jack_Endpoint_SPC;
+ USB_Audio_Descriptor_StreamEndpoint_Std_t MIDI_Out_Jack_Endpoint;
+ USB_MIDI_Descriptor_Jack_Endpoint_t MIDI_Out_Jack_Endpoint_SPC;
+ } USB_Descriptor_Configuration_t;
+
+ /* Function Prototypes: */
+ uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
+ const uint8_t wIndex,
+ const void** const DescriptorAddress)
+ ATTR_WARN_UNUSED_RESULT ATTR_NON_NULL_PTR_ARG(3);
+
+#endif
+
diff --git a/lib/lufa-descriptor-rndis.c b/lib/lufa-descriptor-rndis.c new file mode 100644 index 0000000..ba29037 --- /dev/null +++ b/lib/lufa-descriptor-rndis.c @@ -0,0 +1,267 @@ +/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+/** \file
+ *
+ * USB Device Descriptors, for library use when in USB device mode. Descriptors are special
+ * computer-readable structures which the host requests upon device enumeration, to determine
+ * the device's capabilities and functions.
+ */
+
+#include "lufa-descriptor-rndis.h"
+
+/** Device descriptor structure. This descriptor, located in FLASH memory, describes the overall
+ * device characteristics, including the supported USB version, control endpoint size and the
+ * number of device configurations. The descriptor is read out by the USB host when the enumeration
+ * process begins.
+ */
+const USB_Descriptor_Device_t PROGMEM DeviceDescriptor =
+{
+ .Header = {.Size = sizeof(USB_Descriptor_Device_t), .Type = DTYPE_Device},
+
+ .USBSpecification = VERSION_BCD(01.10),
+ .Class = CDC_CSCP_CDCClass,
+ .SubClass = CDC_CSCP_NoSpecificSubclass,
+ .Protocol = CDC_CSCP_NoSpecificProtocol,
+
+ .Endpoint0Size = FIXED_CONTROL_ENDPOINT_SIZE,
+
+ .VendorID = 0x03EB,
+ .ProductID = 0x204C,
+ .ReleaseNumber = VERSION_BCD(00.01),
+
+ .ManufacturerStrIndex = 0x01,
+ .ProductStrIndex = 0x02,
+ .SerialNumStrIndex = NO_DESCRIPTOR,
+
+ .NumberOfConfigurations = FIXED_NUM_CONFIGURATIONS
+};
+
+/** Configuration descriptor structure. This descriptor, located in FLASH memory, describes the usage
+ * of the device in one of its supported configurations, including information about any device interfaces
+ * and endpoints. The descriptor is read out by the USB host during the enumeration process when selecting
+ * a configuration so that the host may correctly communicate with the USB device.
+ */
+const USB_Descriptor_Configuration_t PROGMEM ConfigurationDescriptor =
+{
+ .Config =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Configuration_Header_t), .Type = DTYPE_Configuration},
+
+ .TotalConfigurationSize = sizeof(USB_Descriptor_Configuration_t),
+ .TotalInterfaces = 2,
+
+ .ConfigurationNumber = 1,
+ .ConfigurationStrIndex = NO_DESCRIPTOR,
+
+ .ConfigAttributes = (USB_CONFIG_ATTR_RESERVED | USB_CONFIG_ATTR_SELFPOWERED),
+
+ .MaxPowerConsumption = USB_CONFIG_POWER_MA(100)
+ },
+
+ .CDC_CCI_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = 0,
+ .AlternateSetting = 0,
+
+ .TotalEndpoints = 1,
+
+ .Class = CDC_CSCP_CDCClass,
+ .SubClass = CDC_CSCP_ACMSubclass,
+ .Protocol = CDC_CSCP_VendorSpecificProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .CDC_Functional_Header =
+ {
+ .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalHeader_t), .Type = DTYPE_CSInterface},
+ .Subtype = CDC_DSUBTYPE_CSInterface_Header,
+
+ .CDCSpecification = VERSION_BCD(01.10),
+ },
+
+ .CDC_Functional_ACM =
+ {
+ .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalACM_t), .Type = DTYPE_CSInterface},
+ .Subtype = CDC_DSUBTYPE_CSInterface_ACM,
+
+ .Capabilities = 0x00,
+ },
+
+ .CDC_Functional_Union =
+ {
+ .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalUnion_t), .Type = DTYPE_CSInterface},
+ .Subtype = CDC_DSUBTYPE_CSInterface_Union,
+
+ .MasterInterfaceNumber = 0,
+ .SlaveInterfaceNumber = 1,
+ },
+
+ .CDC_NotificationEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | CDC_NOTIFICATION_EPNUM),
+ .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CDC_NOTIFICATION_EPSIZE,
+ .PollingIntervalMS = 0xFF
+ },
+
+ .CDC_DCI_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = 1,
+ .AlternateSetting = 0,
+
+ .TotalEndpoints = 2,
+
+ .Class = CDC_CSCP_CDCDataClass,
+ .SubClass = CDC_CSCP_NoDataSubclass,
+ .Protocol = CDC_CSCP_NoDataProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .RNDIS_DataOutEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_OUT | CDC_RX_EPNUM),
+ .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CDC_TXRX_EPSIZE,
+ .PollingIntervalMS = 0x01
+ },
+
+ .RNDIS_DataInEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | CDC_TX_EPNUM),
+ .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CDC_TXRX_EPSIZE,
+ .PollingIntervalMS = 0x01
+ }
+};
+
+/** Language descriptor structure. This descriptor, located in FLASH memory, is returned when the host requests
+ * the string descriptor with index 0 (the first index). It is actually an array of 16-bit integers, which indicate
+ * via the language ID table available at USB.org what languages the device supports for its string descriptors.
+ */
+const USB_Descriptor_String_t PROGMEM LanguageString =
+{
+ .Header = {.Size = USB_STRING_LEN(1), .Type = DTYPE_String},
+
+ .UnicodeString = {LANGUAGE_ID_ENG}
+};
+
+/** Manufacturer descriptor string. This is a Unicode string containing the manufacturer's details in human readable
+ * form, and is read out upon request by the host when the appropriate string ID is requested, listed in the Device
+ * Descriptor.
+ */
+const USB_Descriptor_String_t PROGMEM ManufacturerString =
+{
+#ifndef USB_MANUFACTURER
+ .Header = {.Size = USB_STRING_LEN(11), .Type = DTYPE_String},
+ .UnicodeString = L"Dean Camera"
+#else
+ .Header = {.Size = USB_STRING_LEN(USB_MANUFACTURER_LEN), .Type = DTYPE_String},
+ .UnicodeString = USB_MANUFACTURER
+#endif
+};
+
+/** Product descriptor string. This is a Unicode string containing the product's details in human readable form,
+ * and is read out upon request by the host when the appropriate string ID is requested, listed in the Device
+ * Descriptor.
+ */
+const USB_Descriptor_String_t PROGMEM ProductString =
+{
+#ifndef USB_PRODUCT
+ .Header = {.Size = USB_STRING_LEN(23), .Type = DTYPE_String},
+ .UnicodeString = L"LUFA USB-RS232 Adapter"
+#else
+ .Header = {.Size = USB_STRING_LEN(USB_PRODUCT_LEN), .Type = DTYPE_String},
+ .UnicodeString = USB_PRODUCT
+#endif
+};
+
+/** This function is called by the library when in device mode, and must be overridden (see library "USB Descriptors"
+ * documentation) by the application code so that the address and size of a requested descriptor can be given
+ * to the USB library. When the device receives a Get Descriptor request on the control endpoint, this function
+ * is called so that the descriptor details can be passed back and the appropriate descriptor sent back to the
+ * USB host.
+ */
+uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
+ const uint8_t wIndex,
+ const void** const DescriptorAddress)
+{
+ const uint8_t DescriptorType = (wValue >> 8);
+ const uint8_t DescriptorNumber = (wValue & 0xFF);
+
+ const void* Address = NULL;
+ uint16_t Size = NO_DESCRIPTOR;
+
+ switch (DescriptorType)
+ {
+ case DTYPE_Device:
+ Address = &DeviceDescriptor;
+ Size = sizeof(USB_Descriptor_Device_t);
+ break;
+ case DTYPE_Configuration:
+ Address = &ConfigurationDescriptor;
+ Size = sizeof(USB_Descriptor_Configuration_t);
+ break;
+ case DTYPE_String:
+ switch (DescriptorNumber)
+ {
+ case 0x00:
+ Address = &LanguageString;
+ Size = pgm_read_byte(&LanguageString.Header.Size);
+ break;
+ case 0x01:
+ Address = &ManufacturerString;
+ Size = pgm_read_byte(&ManufacturerString.Header.Size);
+ break;
+ case 0x02:
+ Address = &ProductString;
+ Size = pgm_read_byte(&ProductString.Header.Size);
+ break;
+ }
+
+ break;
+ }
+
+ *DescriptorAddress = Address;
+ return Size;
+}
+
diff --git a/lib/lufa-descriptor-rndis.h b/lib/lufa-descriptor-rndis.h new file mode 100644 index 0000000..508ac2f --- /dev/null +++ b/lib/lufa-descriptor-rndis.h @@ -0,0 +1,89 @@ +/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+/** \file
+ *
+ * Header file for Descriptors.c.
+ */
+
+#ifndef _DESCRIPTORS_H_
+#define _DESCRIPTORS_H_
+
+ /* Includes: */
+ #include <LUFA/Drivers/USB/USB.h>
+
+ #include <avr/pgmspace.h>
+
+ /* Macros: */
+ /** Endpoint number of the CDC device-to-host notification IN endpoint. */
+ #define CDC_NOTIFICATION_EPNUM 3
+
+ /** Endpoint number of the CDC device-to-host data IN endpoint. */
+ #define CDC_TX_EPNUM 1
+
+ /** Endpoint number of the CDC host-to-device data OUT endpoint. */
+ #define CDC_RX_EPNUM 2
+
+ /** Size in bytes of the CDC device-to-host notification IN endpoint. */
+ #define CDC_NOTIFICATION_EPSIZE 8
+
+ /** Size in bytes of the CDC data IN and OUT endpoints. */
+ #define CDC_TXRX_EPSIZE 64
+
+ /* Type Defines: */
+ /** Type define for the device configuration descriptor structure. This must be defined in the
+ * application code, as the configuration descriptor contains several sub-descriptors which
+ * vary between devices, and which describe the device's usage to the host.
+ */
+ typedef struct
+ {
+ USB_Descriptor_Configuration_Header_t Config;
+
+ // RNDIS CDC Control Interface
+ USB_Descriptor_Interface_t CDC_CCI_Interface;
+ USB_CDC_Descriptor_FunctionalHeader_t CDC_Functional_Header;
+ USB_CDC_Descriptor_FunctionalACM_t CDC_Functional_ACM;
+ USB_CDC_Descriptor_FunctionalUnion_t CDC_Functional_Union;
+ USB_Descriptor_Endpoint_t CDC_NotificationEndpoint;
+
+ // RNDIS CDC Data Interface
+ USB_Descriptor_Interface_t CDC_DCI_Interface;
+ USB_Descriptor_Endpoint_t RNDIS_DataOutEndpoint;
+ USB_Descriptor_Endpoint_t RNDIS_DataInEndpoint;
+ } USB_Descriptor_Configuration_t;
+
+ /* Function Prototypes: */
+ uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
+ const uint8_t wIndex,
+ const void** const DescriptorAddress)
+ ATTR_WARN_UNUSED_RESULT ATTR_NON_NULL_PTR_ARG(3);
+
+#endif
+
diff --git a/lib/lufa-descriptor-usbdualserial.c b/lib/lufa-descriptor-usbdualserial.c new file mode 100644 index 0000000..639391c --- /dev/null +++ b/lib/lufa-descriptor-usbdualserial.c @@ -0,0 +1,394 @@ +/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+/** \file
+ *
+ * USB Device Descriptors, for library use when in USB device mode. Descriptors are special
+ * computer-readable structures which the host requests upon device enumeration, to determine
+ * the device's capabilities and functions.
+ */
+
+#include "lufa-descriptor-usbdualserial.h"
+
+/* On some devices, there is a factory set internal serial number which can be automatically sent to the host as
+ * the device's serial number when the Device Descriptor's .SerialNumStrIndex entry is set to USE_INTERNAL_SERIAL.
+ * This allows the host to track a device across insertions on different ports, allowing them to retain allocated
+ * resources like COM port numbers and drivers. On demos using this feature, give a warning on unsupported devices
+ * so that the user can supply their own serial number descriptor instead or remove the USE_INTERNAL_SERIAL value
+ * from the Device Descriptor (forcing the host to generate a serial number for each device from the VID, PID and
+ * port location).
+ */
+#if (USE_INTERNAL_SERIAL == NO_DESCRIPTOR)
+ #warning USE_INTERNAL_SERIAL is not available on this AVR - please manually construct a device serial descriptor.
+#endif
+
+/** Device descriptor structure. This descriptor, located in FLASH memory, describes the overall
+ * device characteristics, including the supported USB version, control endpoint size and the
+ * number of device configurations. The descriptor is read out by the USB host when the enumeration
+ * process begins.
+ */
+const USB_Descriptor_Device_t PROGMEM DeviceDescriptor =
+{
+ .Header = {.Size = sizeof(USB_Descriptor_Device_t), .Type = DTYPE_Device},
+
+ .USBSpecification = VERSION_BCD(01.10),
+ .Class = USB_CSCP_IADDeviceClass,
+ .SubClass = USB_CSCP_IADDeviceSubclass,
+ .Protocol = USB_CSCP_IADDeviceProtocol,
+
+ .Endpoint0Size = FIXED_CONTROL_ENDPOINT_SIZE,
+
+ .VendorID = 0x03EB,
+ .ProductID = 0x204E,
+ .ReleaseNumber = VERSION_BCD(00.01),
+
+ .ManufacturerStrIndex = 0x01,
+ .ProductStrIndex = 0x02,
+ .SerialNumStrIndex = USE_INTERNAL_SERIAL,
+
+ .NumberOfConfigurations = FIXED_NUM_CONFIGURATIONS
+};
+
+/** Configuration descriptor structure. This descriptor, located in FLASH memory, describes the usage
+ * of the device in one of its supported configurations, including information about any device interfaces
+ * and endpoints. The descriptor is read out by the USB host during the enumeration process when selecting
+ * a configuration so that the host may correctly communicate with the USB device.
+ */
+const USB_Descriptor_Configuration_t PROGMEM ConfigurationDescriptor =
+{
+ .Config =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Configuration_Header_t), .Type = DTYPE_Configuration},
+
+ .TotalConfigurationSize = sizeof(USB_Descriptor_Configuration_t),
+ .TotalInterfaces = 4,
+
+ .ConfigurationNumber = 1,
+ .ConfigurationStrIndex = NO_DESCRIPTOR,
+
+ .ConfigAttributes = (USB_CONFIG_ATTR_RESERVED | USB_CONFIG_ATTR_SELFPOWERED),
+
+ .MaxPowerConsumption = USB_CONFIG_POWER_MA(100)
+ },
+
+ .CDC1_IAD =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_Association_t), .Type = DTYPE_InterfaceAssociation},
+
+ .FirstInterfaceIndex = 0,
+ .TotalInterfaces = 2,
+
+ .Class = CDC_CSCP_CDCClass,
+ .SubClass = CDC_CSCP_ACMSubclass,
+ .Protocol = CDC_CSCP_ATCommandProtocol,
+
+ .IADStrIndex = NO_DESCRIPTOR
+ },
+
+ .CDC1_CCI_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = 0,
+ .AlternateSetting = 0,
+
+ .TotalEndpoints = 1,
+
+ .Class = CDC_CSCP_CDCClass,
+ .SubClass = CDC_CSCP_ACMSubclass,
+ .Protocol = CDC_CSCP_ATCommandProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .CDC1_Functional_Header =
+ {
+ .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalHeader_t), .Type = DTYPE_CSInterface},
+ .Subtype = CDC_DSUBTYPE_CSInterface_Header,
+
+ .CDCSpecification = VERSION_BCD(01.10),
+ },
+
+ .CDC1_Functional_ACM =
+ {
+ .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalACM_t), .Type = DTYPE_CSInterface},
+ .Subtype = CDC_DSUBTYPE_CSInterface_ACM,
+
+ .Capabilities = 0x06,
+ },
+
+ .CDC1_Functional_Union =
+ {
+ .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalUnion_t), .Type = DTYPE_CSInterface},
+ .Subtype = CDC_DSUBTYPE_CSInterface_Union,
+
+ .MasterInterfaceNumber = 0,
+ .SlaveInterfaceNumber = 1,
+ },
+
+ .CDC1_ManagementEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | CDC1_NOTIFICATION_EPNUM),
+ .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CDC_NOTIFICATION_EPSIZE,
+ .PollingIntervalMS = 0xFF
+ },
+
+ .CDC1_DCI_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = 1,
+ .AlternateSetting = 0,
+
+ .TotalEndpoints = 2,
+
+ .Class = CDC_CSCP_CDCDataClass,
+ .SubClass = CDC_CSCP_NoDataSubclass,
+ .Protocol = CDC_CSCP_NoDataProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .CDC1_DataOutEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_OUT | CDC1_RX_EPNUM),
+ .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CDC_TXRX_EPSIZE,
+ .PollingIntervalMS = 0x01
+ },
+
+ .CDC1_DataInEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | CDC1_TX_EPNUM),
+ .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CDC_TXRX_EPSIZE,
+ .PollingIntervalMS = 0x01
+ },
+
+ .CDC2_IAD =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_Association_t), .Type = DTYPE_InterfaceAssociation},
+
+ .FirstInterfaceIndex = 2,
+ .TotalInterfaces = 2,
+
+ .Class = CDC_CSCP_CDCClass,
+ .SubClass = CDC_CSCP_ACMSubclass,
+ .Protocol = CDC_CSCP_ATCommandProtocol,
+
+ .IADStrIndex = NO_DESCRIPTOR
+ },
+
+ .CDC2_CCI_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = 2,
+ .AlternateSetting = 0,
+
+ .TotalEndpoints = 1,
+
+ .Class = CDC_CSCP_CDCClass,
+ .SubClass = CDC_CSCP_ACMSubclass,
+ .Protocol = CDC_CSCP_ATCommandProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .CDC2_Functional_Header =
+ {
+ .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalHeader_t), .Type = DTYPE_CSInterface},
+ .Subtype = CDC_DSUBTYPE_CSInterface_Header,
+
+ .CDCSpecification = VERSION_BCD(01.10),
+ },
+
+ .CDC2_Functional_ACM =
+ {
+ .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalACM_t), .Type = DTYPE_CSInterface},
+ .Subtype = CDC_DSUBTYPE_CSInterface_ACM,
+
+ .Capabilities = 0x06,
+ },
+
+ .CDC2_Functional_Union =
+ {
+ .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalUnion_t), .Type = DTYPE_CSInterface},
+ .Subtype = CDC_DSUBTYPE_CSInterface_Union,
+
+ .MasterInterfaceNumber = 2,
+ .SlaveInterfaceNumber = 3,
+ },
+
+ .CDC2_ManagementEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | CDC2_NOTIFICATION_EPNUM),
+ .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CDC_NOTIFICATION_EPSIZE,
+ .PollingIntervalMS = 0xFF
+ },
+
+ .CDC2_DCI_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = 3,
+ .AlternateSetting = 0,
+
+ .TotalEndpoints = 2,
+
+ .Class = CDC_CSCP_CDCDataClass,
+ .SubClass = CDC_CSCP_NoDataSubclass,
+ .Protocol = CDC_CSCP_NoDataProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .CDC2_DataOutEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_OUT | CDC2_RX_EPNUM),
+ .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CDC_TXRX_EPSIZE,
+ .PollingIntervalMS = 0x01
+ },
+
+ .CDC2_DataInEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | CDC2_TX_EPNUM),
+ .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CDC_TXRX_EPSIZE,
+ .PollingIntervalMS = 0x01
+ }
+};
+
+/** Language descriptor structure. This descriptor, located in FLASH memory, is returned when the host requests
+ * the string descriptor with index 0 (the first index). It is actually an array of 16-bit integers, which indicate
+ * via the language ID table available at USB.org what languages the device supports for its string descriptors.
+ */
+const USB_Descriptor_String_t PROGMEM LanguageString =
+{
+ .Header = {.Size = USB_STRING_LEN(1), .Type = DTYPE_String},
+
+ .UnicodeString = {LANGUAGE_ID_ENG}
+};
+
+/** Manufacturer descriptor string. This is a Unicode string containing the manufacturer's details in human readable
+ * form, and is read out upon request by the host when the appropriate string ID is requested, listed in the Device
+ * Descriptor.
+ */
+const USB_Descriptor_String_t PROGMEM ManufacturerString =
+{
+#ifndef USB_MANUFACTURER
+ .Header = {.Size = USB_STRING_LEN(11), .Type = DTYPE_String},
+ .UnicodeString = L"Dean Camera"
+#else
+ .Header = {.Size = USB_STRING_LEN(USB_MANUFACTURER_LEN), .Type = DTYPE_String},
+ .UnicodeString = USB_MANUFACTURER
+#endif
+};
+
+/** Product descriptor string. This is a Unicode string containing the product's details in human readable form,
+ * and is read out upon request by the host when the appropriate string ID is requested, listed in the Device
+ * Descriptor.
+ */
+const USB_Descriptor_String_t PROGMEM ProductString =
+{
+#ifndef USB_PRODUCT
+ .Header = {.Size = USB_STRING_LEN(13), .Type = DTYPE_String},
+ .UnicodeString = L"LUFA Dual CDC Demo"
+#else
+ .Header = {.Size = USB_STRING_LEN(USB_PRODUCT_LEN), .Type = DTYPE_String},
+ .UnicodeString = USB_PRODUCT
+#endif
+};
+
+/** This function is called by the library when in device mode, and must be overridden (see library "USB Descriptors"
+ * documentation) by the application code so that the address and size of a requested descriptor can be given
+ * to the USB library. When the device receives a Get Descriptor request on the control endpoint, this function
+ * is called so that the descriptor details can be passed back and the appropriate descriptor sent back to the
+ * USB host.
+ */
+uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
+ const uint8_t wIndex,
+ const void** const DescriptorAddress)
+{
+ const uint8_t DescriptorType = (wValue >> 8);
+ const uint8_t DescriptorNumber = (wValue & 0xFF);
+
+ const void* Address = NULL;
+ uint16_t Size = NO_DESCRIPTOR;
+
+ switch (DescriptorType)
+ {
+ case DTYPE_Device:
+ Address = &DeviceDescriptor;
+ Size = sizeof(USB_Descriptor_Device_t);
+ break;
+ case DTYPE_Configuration:
+ Address = &ConfigurationDescriptor;
+ Size = sizeof(USB_Descriptor_Configuration_t);
+ break;
+ case DTYPE_String:
+ switch (DescriptorNumber)
+ {
+ case 0x00:
+ Address = &LanguageString;
+ Size = pgm_read_byte(&LanguageString.Header.Size);
+ break;
+ case 0x01:
+ Address = &ManufacturerString;
+ Size = pgm_read_byte(&ManufacturerString.Header.Size);
+ break;
+ case 0x02:
+ Address = &ProductString;
+ Size = pgm_read_byte(&ProductString.Header.Size);
+ break;
+ }
+
+ break;
+ }
+
+ *DescriptorAddress = Address;
+ return Size;
+}
+
diff --git a/lib/lufa-descriptor-usbdualserial.h b/lib/lufa-descriptor-usbdualserial.h new file mode 100644 index 0000000..d1e6ca6 --- /dev/null +++ b/lib/lufa-descriptor-usbdualserial.h @@ -0,0 +1,112 @@ +/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+/** \file
+ *
+ * Header file for Descriptors.c.
+ */
+
+#ifndef _DESCRIPTORS_H_
+#define _DESCRIPTORS_H_
+
+ /* Includes: */
+ #include <avr/pgmspace.h>
+
+ #include <LUFA/Drivers/USB/USB.h>
+
+ /* Macros: */
+ /** Endpoint number of the first CDC interface's device-to-host data IN endpoint. */
+ #define CDC1_TX_EPNUM 1
+
+ /** Endpoint number of the first CDC interface's host-to-device data OUT endpoint. */
+ #define CDC1_RX_EPNUM 2
+
+ /** Endpoint number of the first CDC interface's device-to-host notification IN endpoint. */
+ #define CDC1_NOTIFICATION_EPNUM 3
+
+ /** Endpoint number of the second CDC interface's device-to-host data IN endpoint. */
+ #define CDC2_TX_EPNUM 4
+
+ /** Endpoint number of the second CDC interface's host-to-device data OUT endpoint. */
+ #define CDC2_RX_EPNUM 5
+
+ /** Endpoint number of the second CDC interface's device-to-host notification IN endpoint. */
+ #define CDC2_NOTIFICATION_EPNUM 6
+
+ /** Size in bytes of the CDC device-to-host notification IN endpoints. */
+ #define CDC_NOTIFICATION_EPSIZE 8
+
+ /** Size in bytes of the CDC data IN and OUT endpoints. */
+ #define CDC_TXRX_EPSIZE 16
+
+ /* Type Defines: */
+ /** Type define for the device configuration descriptor structure. This must be defined in the
+ * application code, as the configuration descriptor contains several sub-descriptors which
+ * vary between devices, and which describe the device's usage to the host.
+ */
+ typedef struct
+ {
+ USB_Descriptor_Configuration_Header_t Config;
+
+ // First CDC Control Interface
+ USB_Descriptor_Interface_Association_t CDC1_IAD;
+ USB_Descriptor_Interface_t CDC1_CCI_Interface;
+ USB_CDC_Descriptor_FunctionalHeader_t CDC1_Functional_Header;
+ USB_CDC_Descriptor_FunctionalACM_t CDC1_Functional_ACM;
+ USB_CDC_Descriptor_FunctionalUnion_t CDC1_Functional_Union;
+ USB_Descriptor_Endpoint_t CDC1_ManagementEndpoint;
+
+ // First CDC Data Interface
+ USB_Descriptor_Interface_t CDC1_DCI_Interface;
+ USB_Descriptor_Endpoint_t CDC1_DataOutEndpoint;
+ USB_Descriptor_Endpoint_t CDC1_DataInEndpoint;
+
+ // Second CDC Control Interface
+ USB_Descriptor_Interface_Association_t CDC2_IAD;
+ USB_Descriptor_Interface_t CDC2_CCI_Interface;
+ USB_CDC_Descriptor_FunctionalHeader_t CDC2_Functional_Header;
+ USB_CDC_Descriptor_FunctionalACM_t CDC2_Functional_ACM;
+ USB_CDC_Descriptor_FunctionalUnion_t CDC2_Functional_Union;
+ USB_Descriptor_Endpoint_t CDC2_ManagementEndpoint;
+
+ // Second CDC Data Interface
+ USB_Descriptor_Interface_t CDC2_DCI_Interface;
+ USB_Descriptor_Endpoint_t CDC2_DataOutEndpoint;
+ USB_Descriptor_Endpoint_t CDC2_DataInEndpoint;
+ } USB_Descriptor_Configuration_t;
+
+ /* Function Prototypes: */
+ uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
+ const uint8_t wIndex,
+ const void** const DescriptorAddress)
+ ATTR_WARN_UNUSED_RESULT ATTR_NON_NULL_PTR_ARG(3);
+
+#endif
+
diff --git a/lib/lufa-descriptor-usbserial.c b/lib/lufa-descriptor-usbserial.c new file mode 100644 index 0000000..fa2ef25 --- /dev/null +++ b/lib/lufa-descriptor-usbserial.c @@ -0,0 +1,280 @@ +/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+/** \file
+ *
+ * USB Device Descriptors, for library use when in USB device mode. Descriptors are special
+ * computer-readable structures which the host requests upon device enumeration, to determine
+ * the device's capabilities and functions.
+ */
+
+#include "lufa-descriptor-usbserial.h"
+
+/* On some devices, there is a factory set internal serial number which can be automatically sent to the host as
+ * the device's serial number when the Device Descriptor's .SerialNumStrIndex entry is set to USE_INTERNAL_SERIAL.
+ * This allows the host to track a device across insertions on different ports, allowing them to retain allocated
+ * resources like COM port numbers and drivers. On demos using this feature, give a warning on unsupported devices
+ * so that the user can supply their own serial number descriptor instead or remove the USE_INTERNAL_SERIAL value
+ * from the Device Descriptor (forcing the host to generate a serial number for each device from the VID, PID and
+ * port location).
+ */
+#if (USE_INTERNAL_SERIAL == NO_DESCRIPTOR)
+ #warning USE_INTERNAL_SERIAL is not available on this AVR - please manually construct a device serial descriptor.
+#endif
+
+/** Device descriptor structure. This descriptor, located in FLASH memory, describes the overall
+ * device characteristics, including the supported USB version, control endpoint size and the
+ * number of device configurations. The descriptor is read out by the USB host when the enumeration
+ * process begins.
+ */
+const USB_Descriptor_Device_t PROGMEM DeviceDescriptor =
+{
+ .Header = {.Size = sizeof(USB_Descriptor_Device_t), .Type = DTYPE_Device},
+
+ .USBSpecification = VERSION_BCD(01.10),
+ .Class = CDC_CSCP_CDCClass,
+ .SubClass = CDC_CSCP_NoSpecificSubclass,
+ .Protocol = CDC_CSCP_NoSpecificProtocol,
+
+ .Endpoint0Size = FIXED_CONTROL_ENDPOINT_SIZE,
+
+ .VendorID = 0x03EB,
+ .ProductID = 0x204B,
+ .ReleaseNumber = VERSION_BCD(00.01),
+
+ .ManufacturerStrIndex = 0x01,
+ .ProductStrIndex = 0x02,
+ .SerialNumStrIndex = USE_INTERNAL_SERIAL,
+
+ .NumberOfConfigurations = FIXED_NUM_CONFIGURATIONS
+};
+
+/** Configuration descriptor structure. This descriptor, located in FLASH memory, describes the usage
+ * of the device in one of its supported configurations, including information about any device interfaces
+ * and endpoints. The descriptor is read out by the USB host during the enumeration process when selecting
+ * a configuration so that the host may correctly communicate with the USB device.
+ */
+const USB_Descriptor_Configuration_t PROGMEM ConfigurationDescriptor =
+{
+ .Config =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Configuration_Header_t), .Type = DTYPE_Configuration},
+
+ .TotalConfigurationSize = sizeof(USB_Descriptor_Configuration_t),
+ .TotalInterfaces = 2,
+
+ .ConfigurationNumber = 1,
+ .ConfigurationStrIndex = NO_DESCRIPTOR,
+
+ .ConfigAttributes = (USB_CONFIG_ATTR_RESERVED | USB_CONFIG_ATTR_SELFPOWERED),
+
+ .MaxPowerConsumption = USB_CONFIG_POWER_MA(100)
+ },
+
+ .CDC_CCI_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = 0,
+ .AlternateSetting = 0,
+
+ .TotalEndpoints = 1,
+
+ .Class = CDC_CSCP_CDCClass,
+ .SubClass = CDC_CSCP_ACMSubclass,
+ .Protocol = CDC_CSCP_ATCommandProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .CDC_Functional_Header =
+ {
+ .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalHeader_t), .Type = DTYPE_CSInterface},
+ .Subtype = CDC_DSUBTYPE_CSInterface_Header,
+
+ .CDCSpecification = VERSION_BCD(01.10),
+ },
+
+ .CDC_Functional_ACM =
+ {
+ .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalACM_t), .Type = DTYPE_CSInterface},
+ .Subtype = CDC_DSUBTYPE_CSInterface_ACM,
+
+ .Capabilities = 0x06,
+ },
+
+ .CDC_Functional_Union =
+ {
+ .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalUnion_t), .Type = DTYPE_CSInterface},
+ .Subtype = CDC_DSUBTYPE_CSInterface_Union,
+
+ .MasterInterfaceNumber = 0,
+ .SlaveInterfaceNumber = 1,
+ },
+
+ .CDC_NotificationEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | CDC_NOTIFICATION_EPNUM),
+ .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CDC_NOTIFICATION_EPSIZE,
+ .PollingIntervalMS = 0xFF
+ },
+
+ .CDC_DCI_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = 1,
+ .AlternateSetting = 0,
+
+ .TotalEndpoints = 2,
+
+ .Class = CDC_CSCP_CDCDataClass,
+ .SubClass = CDC_CSCP_NoDataSubclass,
+ .Protocol = CDC_CSCP_NoDataProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .CDC_DataOutEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_OUT | CDC_RX_EPNUM),
+ .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CDC_TXRX_EPSIZE,
+ .PollingIntervalMS = 0x01
+ },
+
+ .CDC_DataInEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | CDC_TX_EPNUM),
+ .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CDC_TXRX_EPSIZE,
+ .PollingIntervalMS = 0x01
+ }
+};
+
+/** Language descriptor structure. This descriptor, located in FLASH memory, is returned when the host requests
+ * the string descriptor with index 0 (the first index). It is actually an array of 16-bit integers, which indicate
+ * via the language ID table available at USB.org what languages the device supports for its string descriptors.
+ */
+const USB_Descriptor_String_t PROGMEM LanguageString =
+{
+ .Header = {.Size = USB_STRING_LEN(1), .Type = DTYPE_String},
+
+ .UnicodeString = {LANGUAGE_ID_ENG}
+};
+
+
+/** Manufacturer descriptor string. This is a Unicode string containing the manufacturer's details in human readable
+ * form, and is read out upon request by the host when the appropriate string ID is requested, listed in the Device
+ * Descriptor.
+ */
+const USB_Descriptor_String_t PROGMEM ManufacturerString =
+{
+#ifndef USB_MANUFACTURER
+ .Header = {.Size = USB_STRING_LEN(11), .Type = DTYPE_String},
+ .UnicodeString = L"Dean Camera"
+#else
+ .Header = {.Size = USB_STRING_LEN(USB_MANUFACTURER_LEN), .Type = DTYPE_String},
+ .UnicodeString = USB_MANUFACTURER
+#endif
+};
+
+/** Product descriptor string. This is a Unicode string containing the product's details in human readable form,
+ * and is read out upon request by the host when the appropriate string ID is requested, listed in the Device
+ * Descriptor.
+ */
+const USB_Descriptor_String_t PROGMEM ProductString =
+{
+#ifndef USB_PRODUCT
+ .Header = {.Size = USB_STRING_LEN(23), .Type = DTYPE_String},
+ .UnicodeString = L"LUFA USB-RS232 Adapter"
+#else
+ .Header = {.Size = USB_STRING_LEN(USB_PRODUCT_LEN), .Type = DTYPE_String},
+ .UnicodeString = USB_PRODUCT
+#endif
+};
+
+/** This function is called by the library when in device mode, and must be overridden (see library "USB Descriptors"
+ * documentation) by the application code so that the address and size of a requested descriptor can be given
+ * to the USB library. When the device receives a Get Descriptor request on the control endpoint, this function
+ * is called so that the descriptor details can be passed back and the appropriate descriptor sent back to the
+ * USB host.
+ */
+uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
+ const uint8_t wIndex,
+ const void** const DescriptorAddress)
+{
+ const uint8_t DescriptorType = (wValue >> 8);
+ const uint8_t DescriptorNumber = (wValue & 0xFF);
+
+ const void* Address = NULL;
+ uint16_t Size = NO_DESCRIPTOR;
+
+ switch (DescriptorType)
+ {
+ case DTYPE_Device:
+ Address = &DeviceDescriptor;
+ Size = sizeof(USB_Descriptor_Device_t);
+ break;
+ case DTYPE_Configuration:
+ Address = &ConfigurationDescriptor;
+ Size = sizeof(USB_Descriptor_Configuration_t);
+ break;
+ case DTYPE_String:
+ switch (DescriptorNumber)
+ {
+ case 0x00:
+ Address = &LanguageString;
+ Size = pgm_read_byte(&LanguageString.Header.Size);
+ break;
+ case 0x01:
+ Address = &ManufacturerString;
+ Size = pgm_read_byte(&ManufacturerString.Header.Size);
+ break;
+ case 0x02:
+ Address = &ProductString;
+ Size = pgm_read_byte(&ProductString.Header.Size);
+ break;
+ }
+
+ break;
+ }
+
+ *DescriptorAddress = Address;
+ return Size;
+}
+
diff --git a/lib/lufa-descriptor-usbserial.h b/lib/lufa-descriptor-usbserial.h new file mode 100644 index 0000000..97afd41 --- /dev/null +++ b/lib/lufa-descriptor-usbserial.h @@ -0,0 +1,89 @@ +/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+/** \file
+ *
+ * Header file for Descriptors.c.
+ */
+
+#ifndef _DESCRIPTORS_H_
+#define _DESCRIPTORS_H_
+
+ /* Includes: */
+ #include <avr/pgmspace.h>
+
+ #include <LUFA/Drivers/USB/USB.h>
+
+ /* Macros: */
+ /** Endpoint number of the CDC device-to-host notification IN endpoint. */
+ #define CDC_NOTIFICATION_EPNUM 2
+
+ /** Endpoint number of the CDC device-to-host data IN endpoint. */
+ #define CDC_TX_EPNUM 3
+
+ /** Endpoint number of the CDC host-to-device data OUT endpoint. */
+ #define CDC_RX_EPNUM 4
+
+ /** Size in bytes of the CDC device-to-host notification IN endpoint. */
+ #define CDC_NOTIFICATION_EPSIZE 8
+
+ /** Size in bytes of the CDC data IN and OUT endpoints. */
+ #define CDC_TXRX_EPSIZE 16
+
+ /* Type Defines: */
+ /** Type define for the device configuration descriptor structure. This must be defined in the
+ * application code, as the configuration descriptor contains several sub-descriptors which
+ * vary between devices, and which describe the device's usage to the host.
+ */
+ typedef struct
+ {
+ USB_Descriptor_Configuration_Header_t Config;
+
+ // CDC Command Interface
+ USB_Descriptor_Interface_t CDC_CCI_Interface;
+ USB_CDC_Descriptor_FunctionalHeader_t CDC_Functional_Header;
+ USB_CDC_Descriptor_FunctionalACM_t CDC_Functional_ACM;
+ USB_CDC_Descriptor_FunctionalUnion_t CDC_Functional_Union;
+ USB_Descriptor_Endpoint_t CDC_NotificationEndpoint;
+
+ // CDC Data Interface
+ USB_Descriptor_Interface_t CDC_DCI_Interface;
+ USB_Descriptor_Endpoint_t CDC_DataOutEndpoint;
+ USB_Descriptor_Endpoint_t CDC_DataInEndpoint;
+ } USB_Descriptor_Configuration_t;
+
+ /* Function Prototypes: */
+ uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
+ const uint8_t wIndex,
+ const void** const DescriptorAddress)
+ ATTR_WARN_UNUSED_RESULT ATTR_NON_NULL_PTR_ARG(3);
+
+#endif
+
diff --git a/lib/onewire.c b/lib/onewire.c new file mode 100644 index 0000000..f28ef41 --- /dev/null +++ b/lib/onewire.c @@ -0,0 +1,571 @@ +/* +Copyright (c) 2007, Jim Studt (original old version - many contributors since) +refactored from C++ to C by Bernhard Tittelbach + +The latest version of this library may be found at: + http://www.pjrc.com/teensy/td_libs_OneWire.html + +OneWire has been maintained by Paul Stoffregen (paul@pjrc.com) since +January 2010. At the time, it was in need of many bug fixes, but had +been abandoned the original author (Jim Studt). None of the known +contributors were interested in maintaining OneWire. Paul typically +works on OneWire every 6 to 12 months. Patches usually wait that +long. If anyone is interested in more actively maintaining OneWire, +please contact Paul. + +Version 2.2: + Teensy 3.0 compatibility, Paul Stoffregen, paul@pjrc.com + Arduino Due compatibility, http://arduino.cc/forum/index.php?topic=141030 + Fix DS18B20 example negative temperature + Fix DS18B20 example's low res modes, Ken Butcher + Improve reset timing, Mark Tillotson + Add const qualifiers, Bertrik Sikken + Add initial value input to crc16, Bertrik Sikken + Add target_search() function, Scott Roberts + +Version 2.1: + Arduino 1.0 compatibility, Paul Stoffregen + Improve temperature example, Paul Stoffregen + DS250x_PROM example, Guillermo Lovato + PIC32 (chipKit) compatibility, Jason Dangel, dangel.jason AT gmail.com + Improvements from Glenn Trewitt: + - crc16() now works + - check_crc16() does all of calculation/checking work. + - Added read_bytes() and write_bytes(), to reduce tedious loops. + - Added ds2408 example. + Delete very old, out-of-date readme file (info is here) + +Version 2.0: Modifications by Paul Stoffregen, January 2010: +http://www.pjrc.com/teensy/td_libs_OneWire.html + Search fix from Robin James + http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295/27#27 + Use direct optimized I/O in all cases + Disable interrupts during timing critical sections + (this solves many random communication errors) + Disable interrupts during read-modify-write I/O + Reduce RAM consumption by eliminating unnecessary + variables and trimming many to 8 bits + Optimize both crc8 - table version moved to flash + +Modified to work with larger numbers of devices - avoids loop. +Tested in Arduino 11 alpha with 12 sensors. +26 Sept 2008 -- Robin James +http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295/27#27 + +Updated to work with arduino-0008 and to include skip() as of +2007/07/06. --RJL20 + +Modified to calculate the 8-bit CRC directly, avoiding the need for +the 256-byte lookup table to be loaded in RAM. Tested in arduino-0010 +-- Tom Pollard, Jan 23, 2008 + +Jim Studt's original library was modified by Josh Larios. + +Tom Pollard, pollard@alum.mit.edu, contributed around May 20, 2008 + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Much of the code was inspired by Derek Yerger's code, though I don't +think much of that remains. In any event that was.. + (copyleft) 2006 by Derek Yerger - Free to distribute freely. + +The CRC code was excerpted and inspired by the Dallas Semiconductor +sample code bearing this copyright. +//--------------------------------------------------------------------------- +// Copyright (C) 2000 Dallas Semiconductor Corporation, All Rights Reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL DALLAS SEMICONDUCTOR BE LIABLE FOR ANY CLAIM, DAMAGES +// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// +// Except as contained in this notice, the name of Dallas Semiconductor +// shall not be used except as stated in the Dallas Semiconductor +// Branding Policy. +//-------------------------------------------------------------------------- +*/ + +#include "onewire.h" +#include <util/delay.h> +#include <avr/interrupt.h> + + +IO_REG_TYPE owi_bitmask; +volatile IO_REG_TYPE *owi_baseReg; +#if ONEWIRE_SEARCH +// global search state +unsigned char ROM_NO[8]; +uint8_t owi_LastDiscrepancy; +uint8_t owi_LastFamilyDiscrepancy; +uint8_t owi_LastDeviceFlag; +#endif + + +void owi_init(uint8_t pin, volatile IO_REG_TYPE *pin_read_port) +{ + owi_bitmask = _BV(pin); + owi_baseReg = pin_read_port; + DIRECT_MODE_INPUT(owi_baseReg, owi_bitmask); +#if ONEWIRE_SEARCH + owi_reset_search(); +#endif +} + + +// Perform the onewire reset function. We will wait up to 250uS for +// the bus to come high, if it doesn't then it is broken or shorted +// and we return a 0; +// +// Returns 1 if a device asserted a presence pulse, 0 otherwise. +// +uint8_t owi_reset(void) +{ + IO_REG_TYPE mask = owi_bitmask; + register volatile IO_REG_TYPE *reg IO_REG_ASM = owi_baseReg; + uint8_t r; + uint8_t retries = 125; + + cli(); + DIRECT_MODE_INPUT(reg, mask); + sei(); + // wait until the wire is high... just in case + do { + if (--retries == 0) return 0; + _delay_us(2); + } while ( !DIRECT_READ(reg, mask)); + + cli(); + DIRECT_WRITE_LOW(reg, mask); + DIRECT_MODE_OUTPUT(reg, mask); // drive output low + sei(); + _delay_us(480); + cli(); + DIRECT_MODE_INPUT(reg, mask); // allow it to float + _delay_us(70); + r = !DIRECT_READ(reg, mask); + sei(); + _delay_us(410); + return r; +} + +// +// Write a bit. Port and bit is used to cut lookup time and provide +// more certain timing. +// +void owi_write_bit(uint8_t v) +{ + IO_REG_TYPE mask=owi_bitmask; + register volatile IO_REG_TYPE *reg IO_REG_ASM = owi_baseReg; + + if (v & 1) { + cli(); + DIRECT_WRITE_LOW(reg, mask); + DIRECT_MODE_OUTPUT(reg, mask); // drive output low + _delay_us(10); + DIRECT_WRITE_HIGH(reg, mask); // drive output high + sei(); + _delay_us(55); + } else { + cli(); + DIRECT_WRITE_LOW(reg, mask); + DIRECT_MODE_OUTPUT(reg, mask); // drive output low + _delay_us(65); + DIRECT_WRITE_HIGH(reg, mask); // drive output high + sei(); + _delay_us(5); + } +} + +// +// Read a bit. Port and bit is used to cut lookup time and provide +// more certain timing. +// +uint8_t owi_read_bit(void) +{ + IO_REG_TYPE mask=owi_bitmask; + register volatile IO_REG_TYPE *reg IO_REG_ASM = owi_baseReg; + uint8_t r; + + cli(); + DIRECT_MODE_OUTPUT(reg, mask); + DIRECT_WRITE_LOW(reg, mask); + _delay_us(3); + DIRECT_MODE_INPUT(reg, mask); // let pin float, pull up will raise + _delay_us(10); + r = DIRECT_READ(reg, mask); + sei(); + _delay_us(53); + return r; +} + +// +// Write a byte. The writing code uses the active drivers to raise the +// pin high, if you need power after the write (e.g. DS18S20 in +// parasite power mode) then set 'power' to 1, otherwise the pin will +// go tri-state at the end of the write to avoid heating in a short or +// other mishap. +// +void owi_write(uint8_t v, uint8_t power /* = 0 */) { + uint8_t bitMask; + + for (bitMask = 0x01; bitMask; bitMask <<= 1) { + owi_write_bit( (bitMask & v)?1:0); + } + if ( !power) { + cli(); + DIRECT_MODE_INPUT(owi_baseReg, owi_bitmask); + DIRECT_WRITE_LOW(owi_baseReg, owi_bitmask); + sei(); + } +} + +void owi_write_bytes(const uint8_t *buf, uint16_t count, bool power /* = 0 */) { + for (uint16_t i = 0 ; i < count ; i++) + owi_write(buf[i],0); + if (!power) { + cli(); + DIRECT_MODE_INPUT(owi_baseReg, owi_bitmask); + DIRECT_WRITE_LOW(owi_baseReg, owi_bitmask); + sei(); + } +} + +// +// Read a byte +// +uint8_t owi_read() { + uint8_t bitMask; + uint8_t r = 0; + + for (bitMask = 0x01; bitMask; bitMask <<= 1) { + if ( owi_read_bit()) r |= bitMask; + } + return r; +} + +void owi_read_bytes(uint8_t *buf, uint16_t count) { + for (uint16_t i = 0 ; i < count ; i++) + buf[i] = owi_read(); +} + +// +// Do a ROM select +// +void owi_select(const uint8_t rom[8]) +{ + uint8_t i; + + owi_write(0x55,0); // Choose ROM + + for (i = 0; i < 8; i++) owi_write(rom[i],0); +} + +// +// Do a ROM skip +// +void owi_skip() +{ + owi_write(0xCC,0); // Skip ROM +} + +void owi_depower() +{ + cli(); + DIRECT_MODE_INPUT(owi_baseReg, owi_bitmask); + sei(); +} + +#if ONEWIRE_SEARCH + +// +// You need to use this function to start a search again from the beginning. +// You do not need to do it for the first search, though you could. +// +void owi_reset_search() +{ + // reset the search state + owi_LastDiscrepancy = 0; + owi_LastDeviceFlag = FALSE; + owi_LastFamilyDiscrepancy = 0; + for(int i = 7; ; i--) { + ROM_NO[i] = 0; + if ( i == 0) break; + } +} + +// Setup the search to find the device type 'family_code' on the next call +// to search(*newAddr) if it is present. +// +void owi_target_search(uint8_t family_code) +{ + // set the search state to find SearchFamily type devices + ROM_NO[0] = family_code; + for (uint8_t i = 1; i < 8; i++) + ROM_NO[i] = 0; + owi_LastDiscrepancy = 64; + owi_LastFamilyDiscrepancy = 0; + owi_LastDeviceFlag = FALSE; +} + +// +// Perform a search. If this function returns a '1' then it has +// enumerated the next device and you may retrieve the ROM from the +// owi_address variable. If there are no devices, no further +// devices, or something horrible happens in the middle of the +// enumeration then a 0 is returned. If a new device is found then +// its address is copied to newAddr. Use owi_reset_search() to +// start over. +// +// --- Replaced by the one from the Dallas Semiconductor web site --- +//-------------------------------------------------------------------------- +// Perform the 1-Wire Search Algorithm on the 1-Wire bus using the existing +// search state. +// Return TRUE : device found, ROM number in ROM_NO buffer +// FALSE : device not found, end of search +// +uint8_t owi_search(uint8_t *newAddr) +{ + uint8_t id_bit_number; + uint8_t last_zero, rom_byte_number, search_result; + uint8_t id_bit, cmp_id_bit; + + unsigned char rom_byte_mask, search_direction; + + // initialize for search + id_bit_number = 1; + last_zero = 0; + rom_byte_number = 0; + rom_byte_mask = 1; + search_result = 0; + + // if the last call was not the last one + if (!owi_LastDeviceFlag) + { + // 1-Wire reset + if (!owi_reset()) + { + // reset the search + owi_LastDiscrepancy = 0; + owi_LastDeviceFlag = FALSE; + owi_LastFamilyDiscrepancy = 0; + return FALSE; + } + + // issue the search command + owi_write(0xF0,0); + + // loop to do the search + do + { + // read a bit and its complement + id_bit = owi_read_bit(); + cmp_id_bit = owi_read_bit(); + + // check for no devices on 1-wire + if ((id_bit == 1) && (cmp_id_bit == 1)) + break; + else + { + // all devices coupled have 0 or 1 + if (id_bit != cmp_id_bit) + search_direction = id_bit; // bit write value for search + else + { + // if this discrepancy if before the Last Discrepancy + // on a previous next then pick the same as last time + if (id_bit_number < owi_LastDiscrepancy) + search_direction = ((ROM_NO[rom_byte_number] & rom_byte_mask) > 0); + else + // if equal to last pick 1, if not then pick 0 + search_direction = (id_bit_number == owi_LastDiscrepancy); + + // if 0 was picked then record its position in LastZero + if (search_direction == 0) + { + last_zero = id_bit_number; + + // check for Last discrepancy in family + if (last_zero < 9) + owi_LastFamilyDiscrepancy = last_zero; + } + } + + // set or clear the bit in the ROM byte rom_byte_number + // with mask rom_byte_mask + if (search_direction == 1) + ROM_NO[rom_byte_number] |= rom_byte_mask; + else + ROM_NO[rom_byte_number] &= ~rom_byte_mask; + + // serial number search direction write bit + owi_write_bit(search_direction); + + // increment the byte counter id_bit_number + // and shift the mask rom_byte_mask + id_bit_number++; + rom_byte_mask <<= 1; + + // if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask + if (rom_byte_mask == 0) + { + rom_byte_number++; + rom_byte_mask = 1; + } + } + } + while(rom_byte_number < 8); // loop until through all ROM bytes 0-7 + + // if the search was successful then + if (!(id_bit_number < 65)) + { + // search successful so set owi_LastDiscrepancy,owi_LastDeviceFlag,search_result + owi_LastDiscrepancy = last_zero; + + // check for last device + if (owi_LastDiscrepancy == 0) + owi_LastDeviceFlag = TRUE; + + search_result = TRUE; + } + } + + // if no device found then reset counters so next 'search' will be like a first + if (!search_result || !ROM_NO[0]) + { + owi_LastDiscrepancy = 0; + owi_LastDeviceFlag = FALSE; + owi_LastFamilyDiscrepancy = 0; + search_result = FALSE; + } + for (int i = 0; i < 8; i++) newAddr[i] = ROM_NO[i]; + return search_result; + } + +#endif + +#if ONEWIRE_CRC +// The 1-Wire CRC scheme is described in Maxim Application Note 27: +// "Understanding and Using Cyclic Redundancy Checks with Maxim iButton Products" +// + +#if ONEWIRE_CRC8_TABLE +// This table comes from Dallas sample code where it is freely reusable, +// though Copyright (C) 2000 Dallas Semiconductor Corporation +const uint8_t PROGMEM dscrc_table[] = { + 0, 94,188,226, 97, 63,221,131,194,156,126, 32,163,253, 31, 65, + 157,195, 33,127,252,162, 64, 30, 95, 1,227,189, 62, 96,130,220, + 35,125,159,193, 66, 28,254,160,225,191, 93, 3,128,222, 60, 98, + 190,224, 2, 92,223,129, 99, 61,124, 34,192,158, 29, 67,161,255, + 70, 24,250,164, 39,121,155,197,132,218, 56,102,229,187, 89, 7, + 219,133,103, 57,186,228, 6, 88, 25, 71,165,251,120, 38,196,154, + 101, 59,217,135, 4, 90,184,230,167,249, 27, 69,198,152,122, 36, + 248,166, 68, 26,153,199, 37,123, 58,100,134,216, 91, 5,231,185, + 140,210, 48,110,237,179, 81, 15, 78, 16,242,172, 47,113,147,205, + 17, 79,173,243,112, 46,204,146,211,141,111, 49,178,236, 14, 80, + 175,241, 19, 77,206,144,114, 44,109, 51,209,143, 12, 82,176,238, + 50,108,142,208, 83, 13,239,177,240,174, 76, 18,145,207, 45,115, + 202,148,118, 40,171,245, 23, 73, 8, 86,180,234,105, 55,213,139, + 87, 9,235,181, 54,104,138,212,149,203, 41,119,244,170, 72, 22, + 233,183, 85, 11,136,214, 52,106, 43,117,151,201, 74, 20,246,168, + 116, 42,200,150, 21, 75,169,247,182,232, 10, 84,215,137,107, 53}; + +// +// Compute a Dallas Semiconductor 8 bit CRC. These show up in the ROM +// and the registers. (note: this might better be done without to +// table, it would probably be smaller and certainly fast enough +// compared to all those delayMicrosecond() calls. But I got +// confused, so I use this table from the examples.) +// +uint8_t owi_crc8(const uint8_t *addr, uint8_t len) +{ + uint8_t crc = 0; + + while (len--) { + crc = pgm_read_byte(dscrc_table + (crc ^ *addr++)); + } + return crc; +} +#else +// +// Compute a Dallas Semiconductor 8 bit CRC directly. +// this is much slower, but much smaller, than the lookup table. +// +uint8_t owi_crc8(const uint8_t *addr, uint8_t len) +{ + uint8_t crc = 0; + + while (len--) { + uint8_t inbyte = *addr++; + for (uint8_t i = 8; i; i--) { + uint8_t mix = (crc ^ inbyte) & 0x01; + crc >>= 1; + if (mix) crc ^= 0x8C; + inbyte >>= 1; + } + } + return crc; +} +#endif + +#if ONEWIRE_CRC16 +bool owi_check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc) +{ + crc = ~owi_crc16(input, len, crc); + return (crc & 0xFF) == inverted_crc[0] && (crc >> 8) == inverted_crc[1]; +} + +uint16_t owi_crc16(const uint8_t* input, uint16_t len, uint16_t crc) +{ + static const uint8_t oddparity[16] = + { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 }; + + for (uint16_t i = 0 ; i < len ; i++) { + // Even though we're just copying a byte from the input, + // we'll be doing 16-bit computation with it. + uint16_t cdata = input[i]; + cdata = (cdata ^ crc) & 0xff; + crc >>= 8; + + if (oddparity[cdata & 0x0F] ^ oddparity[cdata >> 4]) + crc ^= 0xC001; + + cdata <<= 6; + crc ^= cdata; + cdata <<= 1; + crc ^= cdata; + } + return crc; +} +#endif + +#endif diff --git a/lib/onewire.h b/lib/onewire.h new file mode 100644 index 0000000..1410fde --- /dev/null +++ b/lib/onewire.h @@ -0,0 +1,206 @@ +#ifndef OneWire_h +#define OneWire_h + +#include <inttypes.h> +#include <stdbool.h> +#include <avr/pgmspace.h> + +// You can exclude certain features from OneWire. In theory, this +// might save some space. In practice, the compiler automatically +// removes unused code (technically, the linker, using -fdata-sections +// and -ffunction-sections when compiling, and Wl,--gc-sections +// when linking), so most of these will not result in any code size +// reduction. Well, unless you try to use the missing features +// and redesign your program to not need them! ONEWIRE_CRC8_TABLE +// is the exception, because it selects a fast but large algorithm +// or a small but slow algorithm. + +// you can exclude onewire_search by defining that to 0 +#ifndef ONEWIRE_SEARCH +#define ONEWIRE_SEARCH 1 +#endif + +// You can exclude CRC checks altogether by defining this to 0 +#ifndef ONEWIRE_CRC +#define ONEWIRE_CRC 1 +#endif + +// Select the table-lookup method of computing the 8-bit CRC +// by setting this to 1. The lookup table enlarges code size by +// about 250 bytes. It does NOT consume RAM (but did in very +// old versions of OneWire). If you disable this, a slower +// but very compact algorithm is used. +#ifndef ONEWIRE_CRC8_TABLE +#define ONEWIRE_CRC8_TABLE 1 +#endif + +// You can allow 16-bit CRC checks by defining this to 1 +// (Note that ONEWIRE_CRC must also be 1.) +#ifndef ONEWIRE_CRC16 +#define ONEWIRE_CRC16 1 +#endif + +#define FALSE 0 +#define TRUE 1 + +// Platform specific I/O definitions + +#if defined(__AVR__) +#define PIN_TO_BASEREG(pin) (portInputRegister(digitalPinToPort(pin))) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint8_t +#define IO_REG_ASM __asm__("r30") +#define DIRECT_READ(base, mask) (((*(base)) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) ((*((base)+1)) &= ~(mask)) +#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+1)) |= (mask)) +#define DIRECT_WRITE_LOW(base, mask) ((*((base)+2)) &= ~(mask)) +#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+2)) |= (mask)) + +#elif defined(__MK20DX128__) +#define PIN_TO_BASEREG(pin) (portOutputRegister(pin)) +#define PIN_TO_BITMASK(pin) (1) +#define IO_REG_TYPE uint8_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) (*((base)+512)) +#define DIRECT_MODE_INPUT(base, mask) (*((base)+640) = 0) +#define DIRECT_MODE_OUTPUT(base, mask) (*((base)+640) = 1) +#define DIRECT_WRITE_LOW(base, mask) (*((base)+256) = 1) +#define DIRECT_WRITE_HIGH(base, mask) (*((base)+128) = 1) + +#elif defined(__SAM3X8E__) +// Arduino 1.5.1 may have a bug in delayMicroseconds() on Arduino Due. +// http://arduino.cc/forum/index.php/topic,141030.msg1076268.html#msg1076268 +// If you have trouble with OneWire on Arduino Due, please check the +// status of delayMicroseconds() before reporting a bug in OneWire! +#define PIN_TO_BASEREG(pin) (&(digitalPinToPort(pin)->PIO_PER)) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint32_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) (((*((base)+15)) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) ((*((base)+5)) = (mask)) +#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+4)) = (mask)) +#define DIRECT_WRITE_LOW(base, mask) ((*((base)+13)) = (mask)) +#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+12)) = (mask)) +#ifndef PROGMEM +#define PROGMEM +#endif +#ifndef pgm_read_byte +#define pgm_read_byte(addr) (*(const uint8_t *)(addr)) +#endif + +#elif defined(__PIC32MX__) +#define PIN_TO_BASEREG(pin) (portModeRegister(digitalPinToPort(pin))) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint32_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) (((*(base+4)) & (mask)) ? 1 : 0) //PORTX + 0x10 +#define DIRECT_MODE_INPUT(base, mask) ((*(base+2)) = (mask)) //TRISXSET + 0x08 +#define DIRECT_MODE_OUTPUT(base, mask) ((*(base+1)) = (mask)) //TRISXCLR + 0x04 +#define DIRECT_WRITE_LOW(base, mask) ((*(base+8+1)) = (mask)) //LATXCLR + 0x24 +#define DIRECT_WRITE_HIGH(base, mask) ((*(base+8+2)) = (mask)) //LATXSET + 0x28 + +#else +#error "Please define I/O register types here" +#endif + +#ifndef _BV +#define _BV(bit) (1 << (bit)) +#endif + +void owi_init(uint8_t pin, volatile IO_REG_TYPE *pin_read_port); + +uint8_t owi_reset(void); +void owi_select(const uint8_t rom[8]); + +// Issue a 1-Wire rom skip command, to address all on bus. +void owi_skip(void); + +// Write a byte. If 'power' is one then the wire is held high at +// the end for parasitically powered devices. You are responsible +// for eventually depowering it by calling depower() or doing +// another read or write. +void owi_write(uint8_t v, uint8_t power); + +void owi_write_bytes(const uint8_t *buf, uint16_t count, bool power); + +// Read a byte. +uint8_t owi_read(void); + +void owi_read_bytes(uint8_t *buf, uint16_t count); + +// Write a bit. The bus is always left powered at the end, see +// note in write() about that. +void owi_write_bit(uint8_t v); + +// Read a bit. +uint8_t owi_read_bit(void); + +// Stop forcing power onto the bus. You only need to do this if +// you used the 'power' flag to write() or used a write_bit() call +// and aren't about to do another read or write. You would rather +// not leave this powered if you don't have to, just in case +// someone shorts your bus. +void owi_depower(void); + +#if ONEWIRE_SEARCH +// Clear the search state so that if will start from the beginning again. +void owi_reset_search(void); + +// Setup the search to find the device type 'family_code' on the next call +// to search(*newAddr) if it is present. +void owi_target_search(uint8_t family_code); + +// Look for the next device. Returns 1 if a new address has been +// returned. A zero might mean that the bus is shorted, there are +// no devices, or you have already retrieved all of them. It +// might be a good idea to check the CRC to make sure you didn't +// get garbage. The order is deterministic. You will always get +// the same devices in the same order. +uint8_t owi_search(uint8_t *newAddr); +#endif + +#if ONEWIRE_CRC +// Compute a Dallas Semiconductor 8 bit CRC, these are used in the +// ROM and scratchpad registers. +uint8_t owi_crc8(const uint8_t *addr, uint8_t len); + +#if ONEWIRE_CRC16 +// Compute the 1-Wire CRC16 and compare it against the received CRC. +// Example usage (reading a DS2408): +// // Put everything in a buffer so we can compute the CRC easily. +// uint8_t buf[13]; +// buf[0] = 0xF0; // Read PIO Registers +// buf[1] = 0x88; // LSB address +// buf[2] = 0x00; // MSB address +// WriteBytes(net, buf, 3); // Write 3 cmd bytes +// ReadBytes(net, buf+3, 10); // Read 6 data bytes, 2 0xFF, 2 CRC16 +// if (!CheckCRC16(buf, 11, &buf[11])) { +// // Handle error. +// } +// +// @param input - Array of bytes to checksum. +// @param len - How many bytes to use. +// @param inverted_crc - The two CRC16 bytes in the received data. +// This should just point into the received data, +// *not* at a 16-bit integer. +// @param crc - The crc starting value (optional) +// @return True, iff the CRC matches. +bool owi_check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc); + +// Compute a Dallas Semiconductor 16 bit CRC. This is required to check +// the integrity of data received from many 1-Wire devices. Note that the +// CRC computed here is *not* what you'll get from the 1-Wire network, +// for two reasons: +// 1) The CRC is transmitted bitwise inverted. +// 2) Depending on the endian-ness of your processor, the binary +// representation of the two-byte return value may have a different +// byte order than the two bytes you get from 1-Wire. +// @param input - Array of bytes to checksum. +// @param len - How many bytes to use. +// @param crc - The crc starting value (optional) +// @return The CRC16, as defined by Dallas Semiconductor. +uint16_t owi_crc16(const uint8_t* input, uint16_t len, uint16_t crc); +#endif +#endif + +#endif diff --git a/lib/rda1846.c b/lib/rda1846.c new file mode 100644 index 0000000..83cc270 --- /dev/null +++ b/lib/rda1846.c @@ -0,0 +1,485 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2015 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "LUFA/Drivers/Peripheral/TWI.h" +#include <stdio.h> + +#include "rda1846.h" +#include "rda1846_defines.h" + +static uint8_t rda1846_write_register_raw(const uint8_t addr, const uint16_t data) +{ + if(TWI_StartTransmission(RDA1846_CHIP_ADDR | TWI_ADDRESS_WRITE,10) != TWI_ERROR_NoError) + return 1; + + if(!TWI_SendByte(addr | RDA1846_ADDR_W)) + goto i2c_error; + if(!TWI_SendByte((uint8_t)(data>>8))) + goto i2c_error; + if(!TWI_SendByte((uint8_t)data)) + goto i2c_error; + + TWI_StopTransmission(); + return 0; + +i2c_error: + TWI_StopTransmission(); + printf("I2C error (write_register_raw)\r\n"); + return 1; +} + +static uint8_t rda1846_read_register_raw(const uint8_t addr, uint16_t* data) +{ + if(TWI_StartTransmission(RDA1846_CHIP_ADDR | TWI_ADDRESS_WRITE,10) != TWI_ERROR_NoError) + return 1; + if(!TWI_SendByte(addr | RDA1846_ADDR_R)) + goto i2c_error; + + if(TWI_StartTransmission(RDA1846_CHIP_ADDR | TWI_ADDRESS_READ,10) != TWI_ERROR_NoError) + goto i2c_error; + uint8_t tmp; + if(!TWI_ReceiveByte(&tmp, 0)) + goto i2c_error; + *data = tmp << 8; + if(!TWI_ReceiveByte(&tmp, 1)) + goto i2c_error; + *data |= tmp; + + TWI_StopTransmission(); + return 0; + +i2c_error: + TWI_StopTransmission(); + printf("I2C error (read_register_raw)\r\n"); + return 1; +} + +static uint8_t rda1846_write_register(const uint8_t addr, const uint16_t data) +{ + if(addr < RDA1846_ADDR_LIMIT) + return rda1846_write_register_raw(addr, data); + + if(addr > RDA1846_ADDR_LIMIT) { + uint8_t ret = rda1846_write_register_raw(RDA1846_ADDR_LIMIT, 1); + if(ret) return ret; + + ret = rda1846_write_register_raw(addr, data); + if(ret) return ret; + + return rda1846_write_register_raw(RDA1846_ADDR_LIMIT, 0); + } + return 1; +} + +static uint8_t rda1846_read_register(const uint8_t addr, uint16_t* data) +{ + if(addr < RDA1846_ADDR_LIMIT) + return rda1846_read_register_raw(addr, data); + + if(addr > RDA1846_ADDR_LIMIT) { + uint8_t ret = rda1846_write_register_raw(RDA1846_ADDR_LIMIT, 1); + if(ret) return ret; + + ret = rda1846_read_register_raw(addr - RDA1846_ADDR_LIMIT + 1, data); + if(ret) return ret; + + return rda1846_write_register_raw(RDA1846_ADDR_LIMIT, 0); + } + return 1; +} + +static rf_band_t rf_band_; +static channel_bw_t channel_bw_; +static rda1846_state_t state_; + +/* + * EXTERNAL INTERFACE + */ + +char* rda1846_rf_band_to_string(rf_band_t b) +{ + switch(b) + { + case b_2m: return "2m (134-174 MHz)"; + case b_1m5: return "1.5m (200-260 MHz)"; + case b_70cm: return "70cm (400-520 MHz)"; + } + return ""; +} + +char* rda1846_channel_bw_to_string(channel_bw_t bw) +{ + switch(bw) + { + case bw_12k5: return "12,5 kHz"; + case bw_25k: return "25 kHz"; + } + return ""; +} + +char* rda1846_state_to_string(rda1846_state_t s) +{ + switch(s) + { + case powerdown: return "powerdown"; + case idle: return "idle"; + case receive: return "receiving"; + case transmit: return "transmitting"; + } + return ""; +} + +void rda1846_init(void) +{ + TWI_Init(TWI_BIT_PRESCALE_1, TWI_BITLENGTH_FROM_FREQ(1, 200000)); +} + +void rda1846_reg_init(void) +{ + rda1846_write_register(RDA1846_REG_CTL, RDA1846_CTL_SOFT_RST); + rda1846_write_register(RDA1846_REG_CTL, RDA1846_CTL_PDN); + + rda1846_write_register(RDA1846_REG_XTAL, RDA1846_XTAL_FREQ); + rda1846_write_register(RDA1846_REG_ADCLK, RDA1846_ADCLK_FREQ); + rda1846_write_register(RDA1846_REG_CLK_MODE, RDA1846_CLK_MODE); + + rda1846_write_register(RDA1846_REG_RF_BAND, RDA1846_RF_BAND_2M); + rf_band_ = b_2m; + + rda1846_write_register(RDA1846_REG_CTL, RDA1846_CTL_CH_12K5 | RDA1846_CTL_RX_M_TX_M | RDA1846_CTL_PDN); + channel_bw_ = bw_12k5; + state_ = idle; + + rda1846_write_register(RDA1846_REG_TX_VOICE, RDA1846_TX_VOICE_NONE); +// rda1846_write_register(RDA1846_REG_TX_VOICE, RDA1846_TX_VOICE_MIC); +// rda1846_write_register(RDA1846_REG_TX_VOICE, RDA1846_TX_VOICE_TONE2); +// rda1846_write_register(RDA1846_REG_DTMF_T2, 6689); + + rda1846_write_register(RDA1846_REG_DTMF_C01, (RDA1846_DTMF_C0 << 8) | RDA1846_DTMF_C1); + rda1846_write_register(RDA1846_REG_DTMF_C23, (RDA1846_DTMF_C1 << 8) | RDA1846_DTMF_C3); + rda1846_write_register(RDA1846_REG_DTMF_C45, (RDA1846_DTMF_C3 << 8) | RDA1846_DTMF_C5); + rda1846_write_register(RDA1846_REG_DTMF_C67, (RDA1846_DTMF_C6 << 8) | RDA1846_DTMF_C7); + rda1846_write_register(RDA1846_REG_DTMF_CTL, RDA1846_DTMF_DUAL | RDA1846_DTMF_EN); + rda1846_write_register(RDA1846_REG_INT, RDA1846_INT_DTMF_IDLE); + + rda1846_gpio_default(); +} + +void rda1846_soft_reset(void) +{ + rda1846_write_register(RDA1846_REG_CTL, RDA1846_CTL_SOFT_RST); +} + + + +void rda1846_set_band(rf_band_t b) +{ + uint16_t data = RDA1846_RF_BAND_2M; + if(b == b_1m5) data = RDA1846_RF_BAND_1M5; + if(b == b_70cm) data = RDA1846_RF_BAND_70CM; + if(!rda1846_write_register(RDA1846_REG_RF_BAND, data)) + rf_band_ = b; +} + +rf_band_t rda1846_get_band(void) +{ + return rf_band_; +} + +void rda1846_set_bw(channel_bw_t bw) +{ + uint16_t data; + if(rda1846_read_register(RDA1846_REG_CTL, &data)) + return; + + data &= RDA1846_CTL_CH_RESET; + data |= bw == bw_12k5 ? RDA1846_CTL_CH_12K5 : RDA1846_CTL_CH_25K; + if(!rda1846_write_register(RDA1846_REG_CTL, data)) + channel_bw_ = bw; +} + +channel_bw_t rda1846_get_bw(void) +{ + return channel_bw_; +} + +uint8_t rda1846_set_freq_kHz(int32_t freq) +{ + if((rf_band_ == b_2m && (freq < RDA1846_BAND_2M_LOW || freq > RDA1846_BAND_2M_HIGH)) || + (rf_band_ == b_1m5 && (freq < RDA1846_BAND_1M5_LOW || freq > RDA1846_BAND_1M5_HIGH)) || + (rf_band_ == b_70cm && (freq < RDA1846_BAND_70CM_LOW || freq > RDA1846_BAND_70CM_HIGH)) ) + return 1; + + freq = freq<<3; + uint8_t ret = rda1846_write_register(RDA1846_REG_FREQH, ((freq>>16) & 0x00003FFF)); + if(ret) + return 1; + + return rda1846_write_register(RDA1846_REG_FREQL, (freq & 0x0000FFFF)); +} + +static int32_t corr_freq(int32_t f) +{ + float corr = RDA1846_FREQ_CORR_2M; + if(rf_band_ == b_1m5) corr = RDA1846_FREQ_CORR_1M5; + if(rf_band_ == b_70cm) corr = RDA1846_FREQ_CORR_70CM; + return (int32_t)(((float)f)/corr); +} + +int32_t rda1846_get_freq_kHz(void) +{ + if(state_ == powerdown || state_ == idle) + return -1; + + uint16_t data; + uint8_t ret = rda1846_read_register(RDA1846_REG_FREQH, &data); + if(ret) + return -1; + + int32_t freq = (((uint32_t)(data & 0x3FFF))<<16); + ret = rda1846_read_register(RDA1846_REG_FREQL, &data); + if(ret) + return -1; + + freq = corr_freq((freq+data)>>3); + return (freq / 8) + ((freq % 8) < 4 ? 0 : 1); +} + + + +void rda1846_powerdown(void) +{ + uint16_t data; + if(rda1846_read_register(RDA1846_REG_CTL, &data)) + return; + + data &= ~(RDA1846_CTL_TX | RDA1846_CTL_RX | RDA1846_CTL_CHIP_CAL | RDA1846_CTL_PDN); + if(!rda1846_write_register(RDA1846_REG_CTL, data)) + state_ = powerdown; +} + +void rda1846_idle(void) +{ + uint16_t data; + if(rda1846_read_register(RDA1846_REG_CTL, &data)) + return; + + data &= ~(RDA1846_CTL_TX | RDA1846_CTL_RX | RDA1846_CTL_CHIP_CAL); + data |= RDA1846_CTL_PDN; + if(!rda1846_write_register(RDA1846_REG_CTL, data)) + state_ = idle; +} + +void rda1846_receive(void) +{ + uint16_t data; + if(rda1846_read_register(RDA1846_REG_CTL, &data)) + return; + + data &= ~(RDA1846_CTL_TX); + data |= RDA1846_CTL_RX | RDA1846_CTL_CHIP_CAL | RDA1846_CTL_PDN; + if(!rda1846_write_register(RDA1846_REG_CTL, data)) + state_ = receive; +} + +void rda1846_transmit(void) +{ + uint16_t data; + if(rda1846_read_register(RDA1846_REG_CTL, &data)) + return; + + data &= ~(RDA1846_CTL_RX); + data |= RDA1846_CTL_TX | RDA1846_CTL_CHIP_CAL | RDA1846_CTL_PDN; + if(!rda1846_write_register(RDA1846_REG_CTL, data)) + state_ = transmit; +} + +rda1846_state_t rda1846_get_state(void) +{ + return state_; +} + + + +uint16_t rda1846_get_dtmf(uint8_t* idx1, uint8_t* idx2, uint8_t* code, uint8_t* valid) +{ + uint16_t data; + if(rda1846_read_register(RDA1846_REG_DTMF_OUT, &data)) + return 0xFFFF; + + if(idx1) *idx1 = (uint8_t)((data & 0x0700)>>8); + if(idx2) *idx2 = (uint8_t)((data & 0x00E0)>>5); + if(code) *code = (uint8_t)(data & 0x000F); + if(valid) *valid = data & 0x0010 ? 0 : 1; + + return data; +} + +void rda1846_clear_int(void) +{ + rda1846_write_register(0x00, 0x1846); +} + + + +void rda1846_set_volume(int8_t vol) +{ + uint16_t data; + if(vol < -30 || vol > 0) + return; + + if(vol >= -15) + data = 0x000F | (((vol + 15)<<4) & 0xF0); + else + data = (vol + 30) & 0x0F; + + rda1846_write_register(RDA1846_REG_RX_VOICE, data); +} + +int8_t rda1846_get_volume(void) +{ + uint16_t data; + if(rda1846_read_register(RDA1846_REG_RX_VOICE, &data)) + return 1; + + return (int8_t)(((data & 0x00F0)>>4) + (data & 0x000F)) - 30; +} + + + +void rda1846_gpio_default(void) +{ + rda1846_write_register(RDA1846_REG_GPIO, RDA1846_GPIO_7_VOX | RDA1846_GPIO_6_SQ | + RDA1846_GPIO_5_TXON_RF | RDA1846_GPIO_4_RXON_RF | + RDA1846_GPIO_2_INT); +} + +void rda1846_gpio_AA(void) +{ + rda1846_write_register(RDA1846_REG_GPIO, RDA1846_GPIO_7_HIGH | RDA1846_GPIO_6_LOW | + RDA1846_GPIO_5_HIGH | RDA1846_GPIO_4_LOW | + RDA1846_GPIO_3_HIGH | RDA1846_GPIO_2_LOW | + RDA1846_GPIO_1_HIGH | RDA1846_GPIO_0_LOW); +} + +void rda1846_gpio_55(void) +{ + rda1846_write_register(RDA1846_REG_GPIO, RDA1846_GPIO_7_LOW | RDA1846_GPIO_6_HIGH | + RDA1846_GPIO_5_LOW | RDA1846_GPIO_4_HIGH | + RDA1846_GPIO_3_LOW | RDA1846_GPIO_2_HIGH | + RDA1846_GPIO_1_LOW | RDA1846_GPIO_0_HIGH); +} + +void rda1846_gpio_off(void) +{ + rda1846_write_register(RDA1846_REG_GPIO, RDA1846_GPIO_7_HI_Z | RDA1846_GPIO_6_HI_Z | + RDA1846_GPIO_5_HI_Z | RDA1846_GPIO_4_HI_Z | + RDA1846_GPIO_3_HI_Z | RDA1846_GPIO_2_HI_Z | + RDA1846_GPIO_1_HI_Z | RDA1846_GPIO_0_HI_Z); +} + + + +int16_t rda1846_get_rssi(void) +{ + uint16_t data; + if(rda1846_read_register(RDA1846_REG_RSSI, &data)) + return -1; + + return ((int16_t)(data & 0x03FF) - 135*8); +} + +int16_t rda1846_get_vssi(void) +{ + uint16_t data; + if(rda1846_read_register(RDA1846_REG_VSSI, &data)) + return -1; + + return (int16_t)data; +} + +uint16_t rda1846_get_flags(void) +{ + uint16_t data; + if(rda1846_read_register(RDA1846_REG_FLAG, &data)) + return 0xFFFF; + + return data & RDA1846_FLAGS_MASK; +} + + + +static char* rda1846_regaddr_to_string(uint8_t addr) +{ + switch(addr) { + case RDA1846_REG_CTL: return "CTL"; + case RDA1846_REG_GPIO: return "GPIO"; + case RDA1846_REG_INT: return "INT"; + case RDA1846_REG_FLAG: return "FLAG"; + case RDA1846_REG_RSSI: return "RSSI"; + case RDA1846_REG_VSSI: return "VSSI"; + case RDA1846_REG_CLK_MODE: return "CLK_MODE"; + case RDA1846_REG_XTAL: return "XTAL"; + case RDA1846_REG_ADCLK: return "ADCLK"; + case RDA1846_REG_RF_BAND: return "RF_BAND"; + case RDA1846_REG_FREQH: return "FREQH"; + case RDA1846_REG_FREQL: return "FREQL"; + case RDA1846_REG_PA_BIAS: return "PA_BIAS"; + case RDA1846_REG_TX_VOICE: return "TX_VOICE"; + case RDA1846_REG_VOX_OPEN: return "VOX_OPEN"; + case RDA1846_REG_VOX_SHUT: return "VOX_SHUT"; + case RDA1846_REG_SUBAUDIO: return "SUBAUDIO"; + case RDA1846_REG_RX_VOICE: return "RX_VOICE"; + case RDA1846_REG_SQ_OPEN: return "SQ_OPEN"; + case RDA1846_REG_SQ_SHUT: return "SQ_SHUT"; + case RDA1846_REG_DTMF_CTL: return "DTMF_CTL"; + case RDA1846_REG_DTMF_T1: return "DTMF_T1"; + case RDA1846_REG_DTMF_T2: return "DTMF_T2"; + case RDA1846_REG_DTMF_C01: return "DTMF_C01"; + case RDA1846_REG_DTMF_C23: return "DTMF_C23"; + case RDA1846_REG_DTMF_C45: return "DTMF_C45"; + case RDA1846_REG_DTMF_C67: return "DTMF_C67"; + case RDA1846_REG_DTMF_OUT: return "DTMF_OUT"; + default: return "unknown"; + } +} + +void rda1846_dump_register(void) +{ + printf("RDA1846: register dump\r\n"); + + const uint8_t regs[] = { RDA1846_REG_CLK_MODE, RDA1846_REG_XTAL, RDA1846_REG_ADCLK, + RDA1846_REG_RF_BAND, RDA1846_REG_FREQH, RDA1846_REG_FREQL, + RDA1846_REG_CTL, RDA1846_REG_INT, RDA1846_REG_GPIO, + RDA1846_REG_PA_BIAS, RDA1846_REG_TX_VOICE, RDA1846_REG_VOX_OPEN, RDA1846_REG_VOX_SHUT, + RDA1846_REG_SUBAUDIO, RDA1846_REG_RX_VOICE, RDA1846_REG_SQ_OPEN, RDA1846_REG_SQ_SHUT, + RDA1846_REG_DTMF_CTL, RDA1846_REG_DTMF_OUT, RDA1846_REG_DTMF_T1, RDA1846_REG_DTMF_T2, + RDA1846_REG_RSSI, RDA1846_REG_VSSI, RDA1846_REG_FLAG }; + + int i; + for(i=0; i<sizeof(regs); ++i) { + uint16_t data; + if(rda1846_read_register(regs[i], &data)) + data = 0xFFFF; + printf(" 0x%02X (%s): 0x%04X\r\n", regs[i], rda1846_regaddr_to_string(regs[i]), data); + } +} diff --git a/lib/rda1846.h b/lib/rda1846.h new file mode 100644 index 0000000..d043f00 --- /dev/null +++ b/lib/rda1846.h @@ -0,0 +1,67 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2015 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef SPREADAVR_rda1846_h_INCLUDED +#define SPREADAVR_rda1846_h_INCLUDED + +typedef enum { b_2m, b_1m5, b_70cm } rf_band_t; +char* rda1846_rf_band_to_string(rf_band_t); +typedef enum { bw_12k5, bw_25k } channel_bw_t; +char* rda1846_channel_bw_to_string(channel_bw_t); +typedef enum { powerdown, idle, receive, transmit } rda1846_state_t; +char* rda1846_state_to_string(rda1846_state_t); + +void rda1846_init(void); +void rda1846_reg_init(void); +void rda1846_soft_reset(void); + +void rda1846_powerdown(void); +void rda1846_idle(void); +void rda1846_receive(void); +void rda1846_transmit(void); +rda1846_state_t rda1846_get_state(void); + +void rda1846_set_band(rf_band_t); +rf_band_t rda1846_get_band(void); +void rda1846_set_bw(channel_bw_t); +channel_bw_t rda1846_get_bw(void); +uint8_t rda1846_set_freq_kHz(int32_t freq); +int32_t rda1846_get_freq_kHz(void); + +uint16_t rda1846_get_dtmf(uint8_t*, uint8_t*, uint8_t*, uint8_t*); +void rda1846_clear_int(void); + +void rda1846_set_volume(int8_t); +int8_t rda1846_get_volume(void); + +void rda1846_gpio_default(void); +void rda1846_gpio_55(void); +void rda1846_gpio_AA(void); +void rda1846_gpio_off(void); + +int16_t rda1846_get_rssi(void); +int16_t rda1846_get_vssi(void); +uint16_t rda1846_get_flags(void); + +void rda1846_dump_register(void); + +#endif diff --git a/lib/rda1846_defines.h b/lib/rda1846_defines.h new file mode 100644 index 0000000..37f1fba --- /dev/null +++ b/lib/rda1846_defines.h @@ -0,0 +1,238 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2015 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef SPREADAVR_rda1846_defines_h_INCLUDED +#define SPREADAVR_rda1846_defines_h_INCLUDED + +// TWI +#define RDA1846_CHIP_ADDR 0xE2 +#define RDA1846_ADDR_W (0<<7) +#define RDA1846_ADDR_R (1<<7) +#define RDA1846_ADDR_LIMIT 0x7F + + +// registers +#define RDA1846_REG_CTL 0x30 +#define RDA1846_REG_GPIO 0x1F +#define RDA1846_REG_INT 0x2D +#define RDA1846_REG_FLAG 0x5C +#define RDA1846_REG_RSSI 0x5F +#define RDA1846_REG_VSSI 0x60 + +#define RDA1846_REG_CLK_MODE 0x04 +#define RDA1846_REG_XTAL 0x2B +#define RDA1846_REG_ADCLK 0x2C + +#define RDA1846_REG_RF_BAND 0x0F +#define RDA1846_REG_FREQH 0x29 +#define RDA1846_REG_FREQL 0x2A + +#define RDA1846_REG_PA_BIAS 0x0A +#define RDA1846_REG_TX_VOICE 0x3C +#define RDA1846_REG_VOX_OPEN 0x41 +#define RDA1846_REG_VOX_SHUT 0x42 + +#define RDA1846_REG_RX_VOICE 0x44 +#define RDA1846_REG_SUBAUDIO 0x45 +#define RDA1846_REG_SQ_OPEN 0x48 +#define RDA1846_REG_SQ_SHUT 0x49 + +#define RDA1846_REG_DTMF_CTL 0x63 +#define RDA1846_REG_DTMF_T1 0x35 +#define RDA1846_REG_DTMF_T2 0x36 +#define RDA1846_REG_DTMF_C01 0x66 +#define RDA1846_REG_DTMF_C23 0x67 +#define RDA1846_REG_DTMF_C45 0x68 +#define RDA1846_REG_DTMF_C67 0x69 +#define RDA1846_REG_DTMF_OUT 0x6C + +//freq +#ifdef RDA_QUARTZ_12M288 +#define RDA1846_FREQ_CORR_2M 73.1428567759 +#endif // RDA_QUARTZ_12M288 +#ifdef RDA_QUARTZ_13M +#define RDA1846_FREQ_CORR_2M 69.136878448 +#endif // RDA_QUARTZ_13M + +#define RDA1846_FREQ_CORR_1M5 RDA1846_FREQ_CORR_2M/1.5 +#define RDA1846_FREQ_CORR_70CM RDA1846_FREQ_CORR_2M/3.0 + + +// init values +#define RDA1846_RF_BAND_2M 0x00E4 // select 2m Band +#define RDA1846_BAND_2M_LOW 134000 // kHz +#define RDA1846_BAND_2M_HIGH 174000 // kHZ + +#define RDA1846_RF_BAND_1M5 0x00A4 // select 1.5m Band +#define RDA1846_BAND_1M5_LOW 200000 // kHz +#define RDA1846_BAND_1M5_HIGH 260000 // kHZ + +#define RDA1846_RF_BAND_70CM 0x0024 // select 70cm Band +#define RDA1846_BAND_70CM_LOW 400000 // kHz +#define RDA1846_BAND_70CM_HIGH 520000 // kHZ + +#ifdef RDA_QUARTZ_12M288 +#define RDA1846_XTAL_FREQ 12288 // 12.288 MHz +#define RDA1846_ADCLK_FREQ 6144 // 12.288/2 MHz +#define RDA1846_CLK_MODE 0x0F11 // 12-14 MHz +#endif // RDA_QUARTZ_12M288 + +#ifdef RDA_QUARTZ_13M +#define RDA1846_XTAL_FREQ 13000 // 13.000 MHz +#define RDA1846_ADCLK_FREQ 6500 // 13.000/2 MHz +#define RDA1846_CLK_MODE 0x0F11 // 12-14 MHz +#endif // RDA_QUARTZ_13M + + + + +// ctl +#define RDA1846_CTL_CH_25K 0x3000 +#define RDA1846_CTL_CH_12K5 0x0000 +#define RDA1846_CTL_CH_RESET 0xCFFF + +#define RDA1846_CTL_TAIL_ELIM 0x0800 + +#define RDA1846_CTL_RX_A_TX_A 0x0200 +#define RDA1846_CTL_RX_A_TX_M 0x0100 +#define RDA1846_CTL_RX_M_TX_M 0x0000 + +#define RDA1846_CTL_MUTE 0x0080 +#define RDA1846_CTL_TX 0x0040 +#define RDA1846_CTL_RX 0x0020 +#define RDA1846_CTL_VOX 0x0010 +#define RDA1846_CTL_SQ 0x0008 +#define RDA1846_CTL_PDN 0x0004 +#define RDA1846_CTL_CHIP_CAL 0x0002 +#define RDA1846_CTL_SOFT_RST 0x0001 + + +// flag +#define RDA1846_FLAG_DTMF_IDLE 0x1000 +#define RDA1846_FLAG_RXON_RF 0x0400 +#define RDA1846_FLAG_TXON_RF 0x0200 +#define RDA1846_FLAG_INVERT_DET 0x0080 +#define RDA1846_FLAG_CSS_CMP 0x0004 +#define RDA1846_FLAG_SQ 0x0002 +#define RDA1846_FLAG_VOX 0x0001 + +#define RDA1846_FLAGS_MASK 0x1687 + + +// gpio +#define RDA1846_GPIO_7_HI_Z 0x0000 +#define RDA1846_GPIO_7_VOX 0x4000 +#define RDA1846_GPIO_7_LOW 0x8000 +#define RDA1846_GPIO_7_HIGH 0xC000 + +#define RDA1846_GPIO_6_HI_Z 0x0000 +#define RDA1846_GPIO_6_SQ 0x1000 +#define RDA1846_GPIO_6_LOW 0x2000 +#define RDA1846_GPIO_6_HIGH 0x3000 + +#define RDA1846_GPIO_5_HI_Z 0x0000 +#define RDA1846_GPIO_5_TXON_RF 0x0400 +#define RDA1846_GPIO_5_LOW 0x0800 +#define RDA1846_GPIO_5_HIGH 0x0C00 + +#define RDA1846_GPIO_4_HI_Z 0x0000 +#define RDA1846_GPIO_4_RXON_RF 0x0100 +#define RDA1846_GPIO_4_LOW 0x0200 +#define RDA1846_GPIO_4_HIGH 0x0300 + +#define RDA1846_GPIO_3_HI_Z 0x0000 +#define RDA1846_GPIO_3_SDO 0x0040 +#define RDA1846_GPIO_3_LOW 0x0080 +#define RDA1846_GPIO_3_HIGH 0x00C0 + +#define RDA1846_GPIO_2_HI_Z 0x0000 +#define RDA1846_GPIO_2_INT 0x0010 +#define RDA1846_GPIO_2_LOW 0x0020 +#define RDA1846_GPIO_2_HIGH 0x0030 + +#define RDA1846_GPIO_1_HI_Z 0x0000 +#define RDA1846_GPIO_1_CODE 0x0004 +#define RDA1846_GPIO_1_LOW 0x0008 +#define RDA1846_GPIO_1_HIGH 0x000C + +#define RDA1846_GPIO_0_HI_Z 0x0000 +#define RDA1846_GPIO_0_CSS 0x0001 +#define RDA1846_GPIO_0_LOW 0x0002 +#define RDA1846_GPIO_0_HIGH 0x0003 + + +// int +#define RDA1846_INT_CSS_CMP 0x0200 +#define RDA1846_INT_RXON_RF 0x0100 +#define RDA1846_INT_TXON_RF 0x0080 +#define RDA1846_INT_DTMF_IDLE 0x0040 +#define RDA1846_INT_INVERT_DET 0x0020 +#define RDA1846_INT_IDLE_TO 0x0010 +#define RDA1846_INT_RXON_RF_TO 0x0008 +#define RDA1846_INT_SQ 0x0004 +#define RDA1846_INT_TXON_RF_TO 0x0002 +#define RDA1846_INT_VOX 0x0001 + + +// tx voice channel +#define RDA1846_TX_VOICE_MIC 0x0958 +#define RDA1846_TX_VOICE_TONE2 0x4958 +#define RDA1846_TX_VOICE_GPIO1 0x8958 +#define RDA1846_TX_VOICE_NONE 0xC958 + + +// DTMF ctl +#define RDA1846_DTMF_SINGLE 0x0200 +#define RDA1846_DTMF_DUAL 0x0000 +#define RDA1846_DTMF_EN 0x0100 + +// DTMF tone freq +#include <math.h> + +#define dtmf_tone_freq_hz(value) (uint16_t)round(value/4.096) +#define dtmf_tone_freq_value(hz) (uint16_t)round(hz*4.096) + +#ifdef RDA_QUARTZ_12M288 +// DTMF frequencies @ 12.288 MHz - these are the defaults... are they? +#define RDA1846_DTMF_C0 0x61 // 697 Hz +#define RDA1846_DTMF_C1 0x5B // 770 Hz +#define RDA1846_DTMF_C2 0x53 // 852 Hz +#define RDA1846_DTMF_C3 0x4B // 941 Hz +#define RDA1846_DTMF_C4 0x2C // 1209 Hz +#define RDA1846_DTMF_C5 0x1E // 1336 Hz +#define RDA1846_DTMF_C6 0x0A // 1477 Hz +#define RDA1846_DTMF_C7 0xF6 // 1633 Hz +#endif // RDA_QUARTZ_12M8 + +#ifdef RDA_QUARTZ_13M +// DTMF frequencies @ 13 MHz - these are the defaults... +#define RDA1846_DTMF_C0 0x61 // 697 Hz +#define RDA1846_DTMF_C1 0x5E // 770 Hz +#define RDA1846_DTMF_C2 0x57 // 852 Hz +#define RDA1846_DTMF_C3 0x4B // 941 Hz +#define RDA1846_DTMF_C4 0x31 // 1209 Hz +#define RDA1846_DTMF_C5 0x1E // 1336 Hz +#define RDA1846_DTMF_C6 0x0F // 1477 Hz +#define RDA1846_DTMF_C7 0xFB // 1633 Hz +#endif // RDA_QUARTZ_13M + +#endif diff --git a/lib/serialio.c b/lib/serialio.c new file mode 100644 index 0000000..fde2935 --- /dev/null +++ b/lib/serialio.c @@ -0,0 +1,44 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <stdio.h> + +#include "serialio.h" +#include "LUFA/Drivers/Peripheral/Serial.h" + +static FILE serial_stream; + +void serialio_init(const uint32_t baudrate, const uint8_t doublespeed) +{ + Serial_Init(baudrate, doublespeed); + Serial_CreateStream(&serial_stream); + stdin = stdout = stderr = &serial_stream; +} + +void serialio_task(void) +{ +} + +int16_t serialio_bytes_received(void) +{ + return (int16_t)Serial_IsCharReceived(); +} diff --git a/lib/serialio.h b/lib/serialio.h new file mode 100644 index 0000000..3b0781e --- /dev/null +++ b/lib/serialio.h @@ -0,0 +1,32 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef SPREADAVR_serialio_h_INCLUDED +#define SPREADAVR_serialio_h_INCLUDED + +#include <stdint.h> + +void serialio_init(const uint32_t baudrate, const uint8_t doublespeed); +void serialio_task(void); +int16_t serialio_bytes_received(void); + +#endif diff --git a/lib/usbio.c b/lib/usbio.c new file mode 100644 index 0000000..fbdd5a3 --- /dev/null +++ b/lib/usbio.c @@ -0,0 +1,116 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <stdio.h> + +#include "usbio.h" + +#include <LUFA/Drivers/USB/USB.h> +#include "lufa-descriptor-usbserial.h" +#include "LUFA/Drivers/Peripheral/Serial.h" + +/* + LUFA Library + Copyright (C) Dean Camera, 2012. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +USB_ClassInfo_CDC_Device_t VirtualSerial_CDC_Interface = + { + .Config = + { + .ControlInterfaceNumber = 0, + + .DataINEndpointNumber = CDC_TX_EPNUM, + .DataINEndpointSize = CDC_TXRX_EPSIZE, + .DataINEndpointDoubleBank = false, + + .DataOUTEndpointNumber = CDC_RX_EPNUM, + .DataOUTEndpointSize = CDC_TXRX_EPSIZE, + .DataOUTEndpointDoubleBank = false, + + .NotificationEndpointNumber = CDC_NOTIFICATION_EPNUM, + .NotificationEndpointSize = CDC_NOTIFICATION_EPSIZE, + .NotificationEndpointDoubleBank = false, + }, + }; + +void EVENT_USB_Device_ConfigurationChanged(void) +{ + CDC_Device_ConfigureEndpoints(&VirtualSerial_CDC_Interface); +} + +void EVENT_USB_Device_ControlRequest(void) +{ + CDC_Device_ProcessControlRequest(&VirtualSerial_CDC_Interface); +} +/* end LUFA CDC-ACM specific definitions*/ + +static int dummy_putchar(char DataByte, FILE *Stream) { return 0; } +static int dummy_getchar(FILE *Stream) { return 0; } +static FILE dummy_stream = FDEV_SETUP_STREAM(dummy_putchar, dummy_getchar, _FDEV_SETUP_RW); +static FILE usb_stream; + +void usbio_init(void) +{ + stdin = stdout = stderr = &dummy_stream; + + USB_Init(); + CDC_Device_CreateStream(&VirtualSerial_CDC_Interface,&usb_stream); +} + +void usbio_task(void) +{ +#if defined(USB_SERIES_4_AVR) || defined(USB_SERIES_6_AVR) || defined(USB_SERIES_7_AVR) + if(USB_DeviceState == DEVICE_STATE_Unattached && USB_VBUS_GetStatus()) { + USB_Disable(); + USB_Init(); + } +#endif + + CDC_Device_USBTask(&VirtualSerial_CDC_Interface); + USB_USBTask(); +} + +int16_t usbio_bytes_received(void) +{ + if(stdin == &usb_stream) + return CDC_Device_BytesReceived(&VirtualSerial_CDC_Interface); + else + return 0; +} + +void EVENT_CDC_Device_ControLineStateChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo) +{ + if(CDCInterfaceInfo->State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR) + stdin = stdout = stderr = &usb_stream; + else + stdin = stdout = stderr = &dummy_stream; +} + +void EVENT_USB_Device_Disconnect(void) +{ + stdin = stdout = stderr = &dummy_stream; +} diff --git a/lib/usbio.h b/lib/usbio.h new file mode 100644 index 0000000..1237f37 --- /dev/null +++ b/lib/usbio.h @@ -0,0 +1,33 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef SPREADAVR_usbio_h_INCLUDED +#define SPREADAVR_usbio_h_INCLUDED + +#include <stdint.h> + +void usbio_init(void); +void usbio_task(void); +int16_t usbio_bytes_received(void); + +#endif diff --git a/lib/util.c b/lib/util.c new file mode 100644 index 0000000..7f15bfe --- /dev/null +++ b/lib/util.c @@ -0,0 +1,135 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <avr/interrupt.h> +#include <avr/io.h> +#include <util/delay.h> + +#include "util.h" + +#if defined(CLKPR) +#define CPU_PRESCALE(n) do { CLKPR = 0x80; CLKPR = (n); } while(0) +#else +#define CPU_PRESCALE(n) +#endif + +void cpu_init(void) +{ + CPU_PRESCALE(0); +} + +#if defined JTD +void jtag_disable(void) +{ + uint8_t tempreg; + __asm __volatile("in %[tempreg], %[mcucr]" "\n\t" + "ori %[tempreg], %[jtd]" "\n\t" + "out %[mcucr], %[tempreg]" "\n\t" + "out %[mcucr], %[tempreg]" + : [tempreg] "=d" (tempreg) + : [mcucr] "I" (_SFR_IO_ADDR(MCUCR)), [jtd] "M" (_BV(JTD))); +} +#endif + +#if defined(__BOARD_teensy1__) + #define BOOTLOADER_VEC 0x3E00 +#elif defined(__BOARD_teensy2__) + #define BOOTLOADER_VEC 0x7E00 +#elif defined(__BOARD_teensy1pp__) + #define BOOTLOADER_VEC 0xFC00 +#elif defined(__BOARD_teensy2pp__) + #define BOOTLOADER_VEC 0x1FC00 +#elif defined(__BOARD_minimus__) + #define BOOTLOADER_VEC 0x3000 +#elif defined(__BOARD_minimus32__) + #define BOOTLOADER_VEC 0x3800 +#elif defined(__BOARD_hhd70dongle__) || defined(__BOARD_rda1846dongle__) || defined(__BOARD_culV3__) + #define BOOTLOADER_VEC 0x3800 +#elif defined(__BOARD_slowpandongle1__) || defined(__BOARD_slowpandongle2__) || defined(__BOARD_teenstep__) + #define BOOTLOADER_VEC 0x3800 +#elif defined(__BOARD_rhmixxx__) + #define BOOTLOADER_VEC 0xF000 +#else + #define BOOTLOADER_VEC 0x0000 +#endif + +typedef void (*f_ptr_type)(void); +f_ptr_type start_bootloader = (f_ptr_type)BOOTLOADER_VEC; + +void reset2bootloader(void) +{ +#if defined(__BOARD_teensy1__) || defined(__BOARD_teensy1pp__) || defined(__BOARD_teensy2__) || defined(__BOARD_teensy2pp__) || \ + defined(__BOARD_hhd70dongle__) || defined(__BOARD_rda1846dongle__) || defined(__BOARD_culV3__) || \ + defined(__BOARD_slowpandongle1__) || defined(__BOARD_slowpandongle2__) || defined(__BOARD_teenstep__) || \ + defined(__BOARD_rhmixxx__) || defined(__BOARD_minimus__) || defined(__BOARD_minimus32__) + cli(); + // disable watchdog, if enabled + // disable all peripherals + UDCON = 1; + USBCON = (1<<FRZCLK); // disable USB + UCSR1B = 0; + _delay_ms(5); + #if defined(__BOARD_teensy1__) + EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; + TIMSK0 = 0; TIMSK1 = 0; UCSR1B = 0; + DDRB = 0; DDRC = 0; DDRD = 0; + PORTB = 0; PORTC = 0; PORTD = 0; + #elif defined(__BOARD_teensy2__) + EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0; + TIMSK0 = 0; TIMSK1 = 0; TIMSK3 = 0; TIMSK4 = 0; UCSR1B = 0; TWCR = 0; + DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0; TWCR = 0; + PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0; + #elif defined(__BOARD_teensy1pp__) + EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0; + TIMSK0 = 0; TIMSK1 = 0; TIMSK2 = 0; TIMSK3 = 0; UCSR1B = 0; TWCR = 0; + DDRA = 0; DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0; + PORTA = 0; PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0; + #elif defined(__BOARD_teensy2pp__) + EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0; + TIMSK0 = 0; TIMSK1 = 0; TIMSK2 = 0; TIMSK3 = 0; UCSR1B = 0; TWCR = 0; + DDRA = 0; DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0; + PORTA = 0; PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0; + #elif defined(__BOARD_minimus__) || defined(__BOARD_slowpandongle1__) + EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; + TIMSK0 = 0; TIMSK1 = 0; UCSR1B = 0; + DDRB = 0; DDRC = 0; DDRD = 0; + PORTB = 0; PORTC = 0; PORTD = 0; + #elif defined(__BOARD_minimus32__) + EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; + TIMSK0 = 0; TIMSK1 = 0; UCSR1B = 0; + DDRB = 0; DDRC = 0; DDRD = 0; + PORTB = 0; PORTC = 0; PORTD = 0; + #elif defined(__BOARD_hhd70dongle2__) || defined(__BOARD_hhd70dongle__) || defined(__BOARD_rda1846dongle__) || defined(__BOARD_culV3__) || \ + defined(__BOARD_slowpandongle2__) || defined(__BOARD_teenstep__) + EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0; + TIMSK0 = 0; TIMSK1 = 0; TIMSK3 = 0; TIMSK4 = 0; UCSR1B = 0; TWCR = 0; + DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0; TWCR = 0; + PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0; + #elif defined(__BOARD_rhmixxx__) + EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0; + TIMSK0 = 0; TIMSK1 = 0; TIMSK2 = 0; TIMSK3 = 0; UCSR1B = 0; TWCR = 0; + DDRA = 0; DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0; + PORTA = 0; PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0; + #endif + start_bootloader(); +#endif +} diff --git a/lib/util.h b/lib/util.h new file mode 100644 index 0000000..51c946d --- /dev/null +++ b/lib/util.h @@ -0,0 +1,32 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef SPREADAVR_util_h_INCLUDED +#define SPREADAVR_util_h_INCLUDED + +void cpu_init(void); +#if defined JTD +void jtag_disable(void); +#endif +void reset2bootloader(void); + +#endif @@ -0,0 +1,41 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+include ../defines.mk
+
+include $(LUFA_PATH)/LUFA/makefile
+SRC:=$(foreach COMP,$(LUFA_COMPONENTS),$(LUFA_SRC_$(COMP)))
+
+CFLAGS += -DF_USB=$(F_USB)UL
+CFLAGS += -DBOARD=BOARD_$(LUFA_BOARD)
+CFLAGS += $(LUFA_OPTS)
+
+OBJ = $(SRC:%.c=%.o)
+
+liblufa.a: $(OBJ)
+ $(AR) $@ $(OBJ)
+
+%.o: %.c
+ $(CC) -c $(CFLAGS) $< -o $@
+
+clean:
+ rm -f $(SRC:%.c=%.o)
diff --git a/pcr-controller/Makefile b/pcr-controller/Makefile new file mode 100644 index 0000000..399294e --- /dev/null +++ b/pcr-controller/Makefile @@ -0,0 +1,46 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := pcr-controller
+BOARD_TYPE := teensy2
+OBJ := $(NAME).o pwm.o pid_control.o temp_curve.o cmd_queue.o
+LIBS := util led lufa-descriptor-usbserial anyio onewire ds1820
+EXTERNAL_LIBS := lufa
+RESET_FUNC := ../tools/reset_lufa_cdc
+RESET_PARAM := 'R'
+
+LUFA_PATH := ../contrib/LUFA-120219
+LUFA_OPTS = -D USB_DEVICE_ONLY
+LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0
+LUFA_OPTS += -D ORDERED_EP_CONFIG
+LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1
+LUFA_OPTS += -D USE_FLASH_DESCRIPTORS
+LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
+LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT
+
+LUFA_OPTS += -D USB_MANUFACTURER="L\"xro\"" -D USB_MANUFACTURER_LEN=3
+LUFA_OPTS += -D USB_PRODUCT="L\"OLGA pcr-controller\"" -D USB_PRODUCT_LEN=19
+
+LUFA_COMPONENTS := USB USBCLASS SERIAL
+
+include ../include.mk
diff --git a/pcr-controller/cmd_queue.c b/pcr-controller/cmd_queue.c new file mode 100644 index 0000000..b17235a --- /dev/null +++ b/pcr-controller/cmd_queue.c @@ -0,0 +1,131 @@ +/* + * r3PCR Teensy Controller Code + * + * + * Copyright (C) 2013-2014 Bernhard Tittelbach <xro@realraum.at> + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This code is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include <stdlib.h> +#include <stdio.h> +#include "cmd_queue.h" + +//static assert: +//~ static int SDFLKJ[sizeof(int) == sizeof(int16_t)] = { 0 }; + +#define CMDQ_INPUT_LIST_LEN 2 + +typedef struct { + uint8_t num_args; + uint8_t cmd; + void* function_ptr; + int16_t input_list[CMDQ_INPUT_LIST_LEN]; + uint8_t num_args_read; +} cmd_queue_item; + +#define CMQ_QUEUE_LENGTH 4 +cmd_queue_item cmd_queue_[CMQ_QUEUE_LENGTH]; +uint8_t cmd_queue_todo_pos_ = 0; +uint8_t cmd_queue_fillargs_pos_ = 0; +uint8_t cmd_queue_next_here_ = 0; + + + +#define CMDQ_READBUFFER_LEN 20 +char cmdq_readbuffer_[CMDQ_READBUFFER_LEN]; +uint8_t cmdq_readbuffer_pos_ = 0; + +inline void cmdq_finishReadingArgument(void) +{ + cmdq_readbuffer_[cmdq_readbuffer_pos_] = '\0'; + cmdq_readbuffer_pos_ = 0; + cmd_queue_[cmd_queue_fillargs_pos_].input_list[cmd_queue_[cmd_queue_fillargs_pos_].num_args_read++] = atoi(cmdq_readbuffer_); +} + +//call regularily if in state CQ_READING +uint8_t cmdq_addCharToArgumentBuffer(uint8_t c) +{ + if ( cmd_queue_todo_pos_ == cmd_queue_next_here_ ) + return 1; //nothing to do with us, since no cmd's queued + if (cmd_queue_[cmd_queue_fillargs_pos_].num_args_read >= CMDQ_INPUT_LIST_LEN) + return 1; //nothing to do with us + if (cmd_queue_[cmd_queue_fillargs_pos_].num_args_read >= cmd_queue_[cmd_queue_fillargs_pos_].num_args ) + return 1; //nothing to do with us + //if input terminated by \n or \r then addArgument + if (c == '\n' || c == '\r' || c == ',' || c == 0x1B) + { + cmdq_finishReadingArgument(); + return 0; + } else { //continue reading + cmdq_readbuffer_[cmdq_readbuffer_pos_++] = (char) c; + } + //if numlen +1 of readbuffer reached, addArgument as well (leave one char free to terminate with \0) + if (cmdq_readbuffer_pos_ +1 >= CMDQ_READBUFFER_LEN) + { + cmdq_finishReadingArgument(); + } + return 0; +} + +void cmdq_queueCmdWithNumArgs(void* fptr, uint8_t num_args, uint8_t cmd) +{ + if (num_args > CMDQ_INPUT_LIST_LEN) + { + printf("{\"cmd\":\"%c\",\"cmd_ok\":false,\"error\":\"max args == %d\"}\r\n", cmd, CMDQ_INPUT_LIST_LEN); + return; //to continue would hang cmdq, so we don't + } + if ((cmd_queue_next_here_ +1) % CMQ_QUEUE_LENGTH == cmd_queue_todo_pos_) //for this check REQUIRED: CMQ_QUEUE_LENGTH > 2 + cmdq_doWork(); //no more space in queue -> execute now ! + cmd_queue_[cmd_queue_next_here_].num_args = num_args; + cmd_queue_[cmd_queue_next_here_].cmd = cmd; + cmd_queue_[cmd_queue_next_here_].function_ptr = fptr; + cmd_queue_[cmd_queue_next_here_].num_args_read = 0; + cmd_queue_fillargs_pos_ = cmd_queue_next_here_; + cmd_queue_next_here_++; + cmd_queue_next_here_ %= CMQ_QUEUE_LENGTH; +} + +void cmdq_doWork(void) +{ + while ( cmd_queue_todo_pos_ != cmd_queue_next_here_ ) + { + // is num_args_read_ now equal to num args we expect ? + if (cmd_queue_[cmd_queue_todo_pos_].num_args_read != cmd_queue_[cmd_queue_todo_pos_].num_args ) + break; + if (cmd_queue_[cmd_queue_todo_pos_].function_ptr == 0 ) + break; + + switch (cmd_queue_[cmd_queue_todo_pos_].num_args) + { + case 0: + ((void(*)(void)) cmd_queue_[cmd_queue_todo_pos_].function_ptr)(); + break; + case 1: + ((void(*)(int16_t)) cmd_queue_[cmd_queue_todo_pos_].function_ptr)(cmd_queue_[cmd_queue_todo_pos_].input_list[0]); + break; + case 2: + ((void(*)(int16_t,int16_t)) cmd_queue_[cmd_queue_todo_pos_].function_ptr)(cmd_queue_[cmd_queue_todo_pos_].input_list[0], cmd_queue_[cmd_queue_todo_pos_].input_list[1]); + break; + } + char cmd = cmd_queue_[cmd_queue_todo_pos_].cmd; + cmd_queue_[cmd_queue_todo_pos_].num_args_read = 0; + cmd_queue_[cmd_queue_todo_pos_].num_args = 0; + cmd_queue_[cmd_queue_todo_pos_].function_ptr = 0; + cmd_queue_[cmd_queue_todo_pos_].cmd = 0; + cmd_queue_todo_pos_++; + cmd_queue_todo_pos_ %= CMQ_QUEUE_LENGTH; + printf("{\"cmd\":\"%c\",\"cmd_ok\":true}\r\n",cmd); + } +} diff --git a/pcr-controller/cmd_queue.h b/pcr-controller/cmd_queue.h new file mode 100644 index 0000000..9bd29db --- /dev/null +++ b/pcr-controller/cmd_queue.h @@ -0,0 +1,37 @@ +/* + * r3PCR Teensy Controller Code + * + * + * Copyright (C) 2013-2014 Bernhard Tittelbach <xro@realraum.at> + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This code is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef CMD_QUEUE_INCLUDE_H_ +#define CMD_QUEUE_INCLUDE_H_ + +#include <avr/io.h> + +/* The only actual reason for this queue is to enable non-blocking reads. +* I.e. we want to avoid blocking the main loop while waiting on a user-input terminating '\n', '\r' or ',' . +* As we could (and DO if the queue is full) execute a command right away once all arguments have been read, +* the queue really does not need to be 4 long and the whole handling could me much much simpler. +* I.e. only ever remember ONE command and execute it as soon as all args are present! +*/ + +uint8_t cmdq_addCharToArgumentBuffer(uint8_t c); +void cmdq_queueCmdWithNumArgs(void* fptr, uint8_t num_args, uint8_t cmd); +void cmdq_doWork(void); + +#endif diff --git a/pcr-controller/pcr-controller.c b/pcr-controller/pcr-controller.c new file mode 100644 index 0000000..d3b0ea6 --- /dev/null +++ b/pcr-controller/pcr-controller.c @@ -0,0 +1,385 @@ +/* + * r3PCR Teensy Controller Code + * + * + * Copyright (C) 2013-2014 Bernhard Tittelbach <xro@realraum.at> +* uses avr-utils, anyio & co by Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include <avr/io.h> +#include <avr/wdt.h> +#include <avr/interrupt.h> +#include <avr/power.h> +#include <stdio.h> + +#include "util.h" +#include "led.h" +#include "anyio.h" + +#include "onewire.h" +#include "ds1820.h" + +#include "pwm.h" +#include "pid_control.h" +#include "temp_curve.h" +#include "cmd_queue.h" + +#define PIN_HIGH(PORT, PIN) PORT |= (1 << PIN) +#define PIN_LOW(PORT, PIN) PORT &= ~(1 << PIN) +#define PINMODE_OUTPUT PIN_HIGH //just use DDR instead of PORT +#define PINMODE_INPUT PIN_LOW //just use DDR instead of PORT + +#define OP_SETBIT |= +#define OP_CLEARBIT &= ~ +#define OP_CHECK & +#define PIN_SW(PORTDDRREG, PIN, OP) PORTDDRREG OP (1 << PIN) + +#define HIGHv OP_SETBIT +#define LOWv OP_CLEARBIT + +#define PELTIER_INA_PIN PINF7 +#define PELTIER_INA_PORT PORTF +#define PELTIER_INA_DDR DDRF + +#define PELTIER_INB_PIN PINB6 +#define PELTIER_INB_PORT PORTB +#define PELTIER_INB_DDR DDRB + +//OC1A +#define PELETIER_PWM_EN_PIN PINB5 +#define PELETIER_PWM_EN_PORT PORTB +#define PELETIER_PWM_EN_DDR DDRB + +//OC4D +#define TOPHEAT_PIN PIND7 +#define TOPHEAT_PORT PORTD +#define TOPHEAT_DDR DDRD + +#define PUMP_PIN PINC6 +#define PUMP_PORT PORTC +#define PUMP_DDR DDRC + +#define ONEWIRE_PIN PINC7 +#define ONEWIRE_PINBASE PINC + +uint8_t num_temp_sensors_ = 0; +int16_t raw_temp_ = 0; +uint8_t temp_is_fresh_ = 0; +uint8_t debug_ = 0; +uint8_t monitor_temp_ = 0; +uint8_t pump_autoon_ = 0; +// at f_system_clk = 10Hz, system_clk_ will not overrun for at least 13 years. PCR won't run that long +volatile uint32_t system_clk_ = 0; + +//with F_CPU = 16MHz and TIMER3 Prescaler set to /1024, TIMER3 increments with f = 16KHz. Thus if TIMER3 reaches 16, 1ms has passed. +#define T3_MS *16 +//set TICK_TIME to 1/10 of a second +#define SYSCLKTICK_DURATION_IN_MS 100 +#define TICK_TIME (SYSCLKTICK_DURATION_IN_MS T3_MS) + +ISR(TIMER3_COMPA_vect) +{ + //increment system_clk every TIME_TICK (aka 100ms) + system_clk_++; + //set up "clock" comparator for next tick + OCR3A = (OCR3A + TICK_TIME) & 0xFFFF; + if (debug_) + led_toggle(); +} + +void initSysClkTimer3(void) +{ + system_clk_ = 0; + // set counter to 0 + TCNT3 = 0x0000; + // no outputs + TCCR3A = 0; + // Prescaler for Timer3: F_CPU / 1024 -> counts with f= 16KHz ms + TCCR3B = _BV(CS32) | _BV(CS30); + // set up "clock" comparator for first tick + OCR3A = TICK_TIME & 0xFFFF; + // enable interrupt + TIMSK3 = _BV(OCIE3A); +} + +void queryAndSaveTemperature(uint8_t bit_resolution) +{ + static uint32_t conversion_start_time = 0; + uint8_t sensor_index = 0; + + if (num_temp_sensors_ == 0) + { + num_temp_sensors_ = ds1820_discover(); + } + + if (conversion_start_time == 0) + { + // -- trigger temperatur conversion in sensor + for (sensor_index=0; sensor_index < num_temp_sensors_; sensor_index++) + { + ds1820_set_resolution(sensor_index, bit_resolution); + ds1820_start_measuring(sensor_index); + } + conversion_start_time = system_clk_; + // -- end trigger + } else + if ( (system_clk_ - conversion_start_time)*SYSCLKTICK_DURATION_IN_MS > ds1820_get_conversion_time_ms(bit_resolution)) + { + // -- receive temperatur after conversion time has passed + for (sensor_index=0; sensor_index < num_temp_sensors_; sensor_index++) + { + raw_temp_ = ds1820_read_temperature(sensor_index); + if (raw_temp_ != DS1820_ERROR) + { + temp_is_fresh_ = 1; + break; //we need only one successfully read value + } + } + conversion_start_time = 0; + // -- end receive + } +} + +void printRawTemp(int16_t raw_temp) +{ + int16_t decimals = 100 * (raw_temp % 16) / 16; + if (decimals < 0) + decimals *= -1; + printf("%d.%02d", raw_temp / 16, decimals); +} + +void printStatus(void) +{ + if (num_temp_sensors_ == 0) + { + printf("{\"cmd\":\"s\",\"cmd_ok\":false,\"error\": \"No DS1820 sensors on 1wire bus, thus no temperature\"}\r\n"); + return; + } + if (raw_temp_ == DS1820_ERROR) + { + printf("{\"cmd\":\"s\",\"cmd_ok\":false,\"error\":\"talking to DS18b20, no valid temperature!\"}\r\n"); + } else { + printf("{\"cmd\":\"s\",\"t\":%lu, \"currtemp\":", system_clk_); + printRawTemp(raw_temp_); + printf(", \"targettemp\":"); + printRawTemp(pid_getTargetValue()); + printf(", \"curve\":%s", (tcurve_isSet()?"true":"false")); + printf(", \"curve_t_elapsed\":%u", tcurve_getTimeElapsed()); + printf(", \"cycles_left\":%u}\r\n", tcurve_getRepeatsLeft()); + } +} + +//~ void readIntoBuffer(char *buffer, uint8_t buflen) +//~ { + //~ while (anyio_bytes_received() == 0); + //~ int ReceivedByte=0; + //~ do { + //~ ReceivedByte = fgetc(stdin); + //~ if (ReceivedByte != EOF) + //~ { + //~ *buffer = (char) ReceivedByte; + //~ buffer++; + //~ buflen --; + //~ } + //~ } while (ReceivedByte != '\n' && ReceivedByte != '\r' && buflen > 1); + //~ *buffer = 0; +//~ } + +//~ int16_t readNumber(void) +//~ { + //~ char buffer[20]; + //~ readIntoBuffer(buffer, 20); + //~ return atoi(buffer); +//~ } + +void setPeltierCoolingDirectionPower(int16_t value) +{ + if (value > 255) + value = 255; + if (value < -255) + value = -255; + + if (value >= 0) + { + PIN_LOW(PELTIER_INA_PORT, PELTIER_INA_PIN); + PIN_HIGH(PELTIER_INB_PORT, PELTIER_INB_PIN); + pwm_b5_set((uint8_t) value); + } else { + PIN_HIGH(PELTIER_INA_PORT, PELTIER_INA_PIN); + PIN_LOW(PELTIER_INB_PORT, PELTIER_INB_PIN); + pwm_b5_set((uint8_t) (-1 * value)); + } + if (debug_) + printf("Peltier value: %d, INA: %d, INB: %d, OCR1AH: %d, OCR1AL: %d\r\n", value, (PELTIER_INA_PORT & _BV(PELTIER_INA_PIN)) > 0, (PELTIER_INB_PORT & _BV(PELTIER_INB_PIN)) > 0, OCR1AH, OCR1AL); +} + +void setTopHeaderValue(int16_t value) +{ + pwm_d7_set((uint8_t) (value & 0xFF)); +} + +void handle_cmd(uint8_t cmd) +{ + switch(cmd) { + case ' ': + case '\n': + case '\r': + return; + case 'R': + case 'r': reset2bootloader(); break; + case '?': debug_ = ~debug_; break; + case 'M': monitor_temp_ = 1; break; + case 'm': monitor_temp_ = 0; break; + case '=': pid_setTargetValue(raw_temp_); break; + case '#': pid_setTargetValue(PID_DISABLED); break; + case 't': + case 's': printStatus(); return; + case 'L': led_toggle(); break; + case 'l': cmdq_queueCmdWithNumArgs((void*) led_toggle, 0, cmd); return; + case 'p': + case 'i': + case 'd': + pid_printVars(); + return; + case 'T': cmdq_queueCmdWithNumArgs((void*) pid_setTargetValue, 1, cmd); return; + case 'P': cmdq_queueCmdWithNumArgs((void*) pid_setP, 1, cmd); return; + case 'I': cmdq_queueCmdWithNumArgs((void*) pid_setI, 1, cmd); return; + case 'D': cmdq_queueCmdWithNumArgs((void*) pid_setD, 1, cmd); return; + case 'A': + PIN_HIGH(PUMP_PORT, PUMP_PIN); + pump_autoon_ = 0; + break; + case 'a': + PIN_LOW(PUMP_PORT, PUMP_PIN); + pump_autoon_ = 0; + break; + case 'B': cmdq_queueCmdWithNumArgs((void*) setTopHeaderValue, 1, cmd); return; + case 'b': setTopHeaderValue(0); break; + //~ case 'B': PIN_HIGH(TOPHEAT_PORT,TOPHEAT_PIN); break; + //~ case 'b': PIN_LOW(TOPHEAT_PORT,TOPHEAT_PIN); break; + case '@': pump_autoon_ = 1; break; + case '.': tcurve_printCurve(cmd); return; + case '-': //reset temp curve + tcurve_reset(); + break; + case '+': //add temp curve entry + //~ tcurve_add(readNumber(), readNumber()); + cmdq_queueCmdWithNumArgs((void*) tcurve_add, 2, cmd); + return; + case '>': cmdq_queueCmdWithNumArgs((void*) tcurve_setRepeatStartPosToLatestEntry, 0, cmd); return; + case '<': cmdq_queueCmdWithNumArgs((void*) tcurve_setRepeatEndPosToLatestEntry, 0, cmd); return; + case 'Z': cmdq_queueCmdWithNumArgs((void*) tcurve_setRepeats, 1, cmd); return; + default: printf("{\"cmd\":\"%c\",\"cmd_ok\":false,\"error\":\"unknown cmd\"}\r\n",cmd); return; + } + printf("{\"cmd\":\"%c\",\"cmd_ok\":true}\r\n",cmd); +} + +int main(void) +{ + /* Disable watchdog if enabled by bootloader/fuses */ + MCUSR &= ~(1 << WDRF); + wdt_disable(); + + cpu_init(); + led_init(); + anyio_init(115200, 0); + sei(); + + led_off(); + owi_init(ONEWIRE_PIN, &ONEWIRE_PINBASE); + PINMODE_OUTPUT(PUMP_DDR, PUMP_PIN); + PIN_LOW(PUMP_PORT, PUMP_PIN); + PINMODE_OUTPUT(PELETIER_PWM_EN_DDR, PELETIER_PWM_EN_PIN); + PINMODE_OUTPUT(PELTIER_INB_DDR, PELTIER_INB_PIN); + PINMODE_OUTPUT(PELTIER_INA_DDR, PELTIER_INA_PIN); + PINMODE_OUTPUT(TOPHEAT_DDR, TOPHEAT_PIN); + PIN_LOW(TOPHEAT_PORT, TOPHEAT_PIN); + + pwm_init(); + pwm_b5_set(0); + + pid_loadFromEEPROM(); + + num_temp_sensors_ = ds1820_discover(); + + uint32_t last_time = 0; + uint32_t last_time2 = 0; + initSysClkTimer3(); //start system clock + + for(;;) + { + int16_t BytesReceived = anyio_bytes_received(); + while(BytesReceived > 0) + { + int ReceivedByte = fgetc(stdin); + if (ReceivedByte != EOF) + { + // Ask cmdq_addCharToArgumentBuffer if it wants the current char, otherwise let handle_cmd() have it + if (cmdq_addCharToArgumentBuffer(ReceivedByte)) + handle_cmd(ReceivedByte); + } + BytesReceived--; + } + + cmdq_doWork(); //may call queued functions + + queryAndSaveTemperature(11); //at 11bit resolution + + if (temp_is_fresh_) + { + temp_is_fresh_ = 0; //once used, temp is used up ;-> + + if (monitor_temp_) + printStatus(); + + if (tcurve_isSet()) + { + uint16_t time_elapsed = (uint16_t) (system_clk_ - last_time); + last_time = system_clk_; + //PID_DISABLED == TCURVE_ERROR so this works out fine and we disable heating and PID in this case + pid_setTargetValue(tcurve_getTempToSet(raw_temp_, time_elapsed)); + } + + // PID control + // make sure this is called at exact periodic intervals (i.e. make sure there are no large variable delays in for loop) + // e.g. enable periodic temp monitoring 'm' rather than querying temp at some intervall 's' + if (pid_isEnabled()) + { + if (pump_autoon_) + PIN_HIGH(PUMP_PORT, PUMP_PIN); + if (debug_) + printf("pid_calc.."); + while (system_clk_ - last_time2 < 5); //wait until at least 500ms have passed since last time. Should be enough time for everything else to finish. (after 13 years, code will hang here) + if (debug_) + printf(" clk: %lu, elaps: %lu\r\n",system_clk_ , system_clk_ - last_time2); + last_time2 = system_clk_; + temp_is_fresh_ = 0; + setPeltierCoolingDirectionPower(pid_calc(raw_temp_)); + } + else + { + setPeltierCoolingDirectionPower(0); + if (pump_autoon_) + PIN_LOW(PUMP_PORT, PUMP_PIN); + } + } + + anyio_task(); + } +} diff --git a/pcr-controller/pid_control.c b/pcr-controller/pid_control.c new file mode 100644 index 0000000..6ab275b --- /dev/null +++ b/pcr-controller/pid_control.c @@ -0,0 +1,137 @@ +/* + * r3PCR Teensy Controller Code + * + * + * Copyright (C) 2013-2014 Bernhard Tittelbach <xro@realraum.at> + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This code is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "pid_control.h" + +#include <avr/eeprom.h> + +EEMEM int32_t pid_p_eeprom_; +EEMEM int32_t pid_i_eeprom_; +EEMEM int32_t pid_d_eeprom_; +EEMEM int32_t crc_eeprom_; + +#define PID_SCALE 1024L + +int32_t pid_outlimit_min_ = -255 * PID_SCALE; +int32_t pid_outlimit_max_ = 255 * PID_SCALE; + +int32_t pid_p_ = 8192; +int32_t pid_i_ = 512; +int32_t pid_d_ = 24576; + +int32_t pid_i_integralsum_ = 0; +int32_t pid_last_input_ = 0; + +int16_t pid_target_value_ = PID_DISABLED; + +void pid_setP(int16_t p) +{ + pid_p_ = (int32_t) p; + pid_saveToEEPROM(); +} + +void pid_setI(int16_t i) +{ + pid_i_ = (int32_t) i; + pid_saveToEEPROM(); +} + +void pid_setD(int16_t d) +{ + pid_d_ = (int32_t) d; + pid_saveToEEPROM(); +} + +void pid_printVars(void) +{ + printf("{\"PID_P\":%d, \"PID_I\":%d, \"PID_D\":%d, \"PID_SCALE\":%d}\r\n", (int16_t) (pid_p_), (int16_t) (pid_i_), (int16_t) (pid_d_), (int16_t) PID_SCALE); +} + +void pid_setTargetValue(int16_t v) +{ + pid_target_value_ = v; +} + +int16_t pid_getTargetValue(void) +{ + return pid_target_value_; +} + +int pid_isEnabled(void) +{ + return pid_target_value_ != PID_DISABLED; +} + +// PRE-CONDITION: call pid_calc at exactly regular intervals !! +int16_t pid_calc(int16_t current_value) +{ + if (pid_target_value_ == PID_DISABLED) + return PID_DISABLED; + + int32_t error = (int32_t) pid_target_value_ - (int32_t) current_value; + // derivative + // instead of derivative of error we take derivative on measurement + // since dError/dt = - dInput/dt (note the - ) + int32_t d_measure = (int32_t) current_value - pid_last_input_; + pid_last_input_ = (int32_t) current_value; + + // integral (bring pid_i_ into integral, so we get smooth transfer if pid_i_ suddenly changes) + pid_i_integralsum_ += pid_i_ * error; + + // prevent integrator wind-up + if (pid_i_integralsum_ > pid_outlimit_max_) + pid_i_integralsum_ = pid_outlimit_max_; + else if (pid_i_integralsum_ < pid_outlimit_min_) + pid_i_integralsum_ = pid_outlimit_min_; + + // combine factors (insofar as we did not already do it above) + int32_t pid_output_preclamp = ( + (error * pid_p_) + (pid_i_integralsum_) - (d_measure * pid_d_) + ); + + // limit output + if (pid_output_preclamp > pid_outlimit_max_) + return (int16_t) (pid_outlimit_max_ / PID_SCALE); + else if (pid_output_preclamp < pid_outlimit_min_) + return (int16_t) (pid_outlimit_min_ / PID_SCALE); + else + return (int16_t) (pid_output_preclamp / PID_SCALE); +} + +void pid_loadFromEEPROM(void) +{ + int32_t p = eeprom_read_dword((uint32_t *) &pid_p_eeprom_); + int32_t i = eeprom_read_dword((uint32_t *) &pid_i_eeprom_); + int32_t d = eeprom_read_dword((uint32_t *) &pid_d_eeprom_); + int32_t crc = eeprom_read_dword((uint32_t *) &crc_eeprom_); + if (crc == (p ^ i ^ d)) { + pid_p_ = p; + pid_i_ = i; + pid_d_ = d; + } +} + +void pid_saveToEEPROM(void) +{ + eeprom_write_dword((uint32_t *) &pid_p_eeprom_, pid_p_); + eeprom_write_dword((uint32_t *) &pid_i_eeprom_, pid_i_); + eeprom_write_dword((uint32_t *) &pid_d_eeprom_, pid_d_); + eeprom_write_word((uint16_t *) &crc_eeprom_, pid_p_ ^ pid_i_ ^ pid_d_); +} diff --git a/pcr-controller/pid_control.h b/pcr-controller/pid_control.h new file mode 100644 index 0000000..1d45925 --- /dev/null +++ b/pcr-controller/pid_control.h @@ -0,0 +1,39 @@ +/* + * r3PCR Teensy Controller Code + * + * + * Copyright (C) 2013-2014 Bernhard Tittelbach <xro@realraum.at> + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This code is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef PID_CONTROLLER_INCLUDE_H_ +#define PID_CONTROLLER_INCLUDE_H_ + +#include <stdio.h> + +#define PID_DISABLED (1<<15) + +void pid_setP(int16_t p); +void pid_setI(int16_t i); +void pid_setD(int16_t d); +void pid_printVars(void); +void pid_setTargetValue(int16_t v); +int pid_isEnabled(void); +int16_t pid_getTargetValue(void); +int16_t pid_calc(int16_t current_value); +void pid_loadFromEEPROM(void); +void pid_saveToEEPROM(void); + +#endif diff --git a/pcr-controller/protocol_uc.txt b/pcr-controller/protocol_uc.txt new file mode 100644 index 0000000..6326454 --- /dev/null +++ b/pcr-controller/protocol_uc.txt @@ -0,0 +1,117 @@ +==== Command bytes ==== +'s' Temperatursensor lesen -> parse_float(string("%3.2f")) + \r\n +'t' Same as above +'T' Set PID target temperature. <-TempValue + (Only works if no temperature curve is set.) +'P' Set PID value P <-PIDValue +'I' Set PID value I <-PIDValue +'D' Set PID value D <-PIDValue +'p' Print all PID values as JSON string +'i' Same as above +'d' Same as above +'A' Switch on pump. +'a' Switch pump off. +'@' Switch pump on automatically if temp goes higher than 30°C or lower than 19°C +'B' Set top heater PWM to value between 0 and 255 (in future pwm value may be fixed and 'B' may return to simple on switch) <-IntValue +'b' Switch top heater off. +'L' Toggle LED (Debug) +'l' Toggle LED by using queuing system (Debug) +'R' Reset microcontroller +'r' Same as above +'=' Set PID target temperature to current temperature. +'-' Clear temperature curve. +'.' Print out currently programmed temperature curve as JSON string. +'+' Add a temperature curve point. <-TempValue <-Duration + Excpects 2 arguments: Targettemperature and duration for which that temperature is to be held after it has been reached. +'>' Set the last added (with '+') temperature curve point to be the cycle start point. + E.g. if >0 curve repetitions are set (with 'Z') the repetitions will start here, instead of at the first added curve point. +'<' Set the last added (with '+') temperature curve point to be the cycle end point. + E.g. this and any temperature points added after this marker will not be repeated, but programmed after the main loop +'Z' Set number of cycle repetitions <-IntValue + E.g: 0 == default == no repetitions == 1 cycle + 1 == 1 repetitions == 2 cycles) + .... +'M' Enable periodic status output as JSON string. +'m' Disable periodic status output as JSON string. +'?' Toggle Debug Output. +'#' Disable PID (i.e. set PID target temperature to -2048.00) + (Only works if no temperature curve is set. If needed use '-' first.) + + +==== Command arguments ==== +If arguments are required they are to be given as numeric string. + +Temperature is given in degrees celcsius multiplied by 16, thus allowing us to set decimal degrees by storing and transmitting integer values. +Negative temperatures are prepended by '-'. +E.g. a temperature of -20 °C would be input as -320. + +PID parpameters are multiplied by 1024 (or whatever PID_SCALE is set to). +E.g. an I value of 0.5 would be input as 512. + +Duration or time values are input as 100ms (1/10th second) integer values. +E.g. a duration of 2 seconds would be input as 20. + +If multiple arguments are required, they are to be separated by the comma character ','. + +<-IntValue ...means: string(uint16_t x) +<-TempValue ...means: string(int16_t(float temp * 16)) +<-PIDValue ...means: string(uint16_t x * 1024) +<-Duration ...means: string(uint16_t s * 10) + + +==== Command responses ==== +are formated as JSON values. +PID Values are output just like they are expected to be input. +Temperatures are output as formated float values in °C, expect when printing the current temperature curve when temperatures are printed as internal integer values (see TempValue) + +A value of -2048.00 or -32768 generally means something is DISABLED or inapplicable in the current state. + + +==== Example uc Answers ==== +Responses to "s": +{"cmd":"s","t":503, "currtemp":20.34, "targettemp":-2048.00, "curve":false, "curve_t_elapsed":0, "cycles_left":0} //curve and pid disabled (pid disabel when targettemp == -2048.00 +{"cmd":"s","t":97000, "currtemp":40.34, "targettemp":70.00, "curve":true, "curve_t_elapsed":14, "cycles_left":11} +{"cmd":"s","t":97200, "currtemp":69.72, "targettemp":70.00, "curve":true, "curve_t_elapsed":214, "cycles_left":11} +{"cmd":"s","t":110123, "currtemp":30.14, "targettemp":30.00, "curve":true, "curve_t_elapsed":10, "cycles_left":9} +{"cmd":"s","t":9999999, "currtemp":5.02, "targettemp":5.00, "curve":true, "curve_t_elapsed":65535, "cycles_left":0} //we know all is finished because targettemp is hold-temp + +Response to "." +{"cmd":".","curve":[{"temp":1520,"duration":9000,"is_curr":1,"is_loop_start":0,"is_loop_end":0},{"temp":1040,"duration":10,"is_curr":0,"is_loop_start":1,"is_loop_end":0},{"temp":960,"duration":300,"is_curr":0,"is_loop_start":0,"is_loop_end":0},{"temp":1120,"duration":300,"is_curr":0,"is_loop_start":0,"is_loop_end":0},{"temp":1120,"duration":1000,"is_curr":0,"is_loop_start":0,"is_loop_end":1},0],"end_temp":80,"loop_repeats":30} + +Response to other commands: +{"cmd":"s","cmd_ok":false,"error": "No DS1820 sensors on 1wire bus, thus no temperature"} +{"cmd":"s","cmd_ok":false,"error":"talking to DS18b20, no valid temperature!"} +{"cmd":"A","cmd_ok":true} +{"cmd":"a","cmd_ok":true} +{"cmd":"#","cmd_ok":true} + + +==== Example Program ==== +s +- += +@ +b ++1536,300 +> ++448,300 ++1152,300 +< +Z30 ++64,9999 +M + +The sequence of above commands +- prints current temperature +- deletes any currenlty set temperature curve +- instructs the PID controller to hold the current temperature +- set the pump to auto +- switch off top heater +- programms the following temperature curve: [ 96°C (30s) -> 28°C (30s) -> 72°C (30s) ] +- sets the curve to repeat the items in >< brackets 30 times +- programms final holding temperature of 4°C (note that duration of last entry does not really matter since it will always be held indefinately). +- activates periodic status output. + + +(c) Bernhard Tittelbach, 2013 + diff --git a/pcr-controller/pwm.c b/pcr-controller/pwm.c new file mode 100644 index 0000000..3ca5bbe --- /dev/null +++ b/pcr-controller/pwm.c @@ -0,0 +1,87 @@ + +#include "pwm.h" + +//OutputCompareRegister for Timer1 and pin OC1A/B5 +#define PWMB5_VAL OCR1AL +//for FastPWM in Timer4 OCR4C is TOP for all OC4x pins, all other PWM Modes use OCR4A,OCR4B or OCR4D +#define PWMD7_VAL OCR4D + +void pwm_init(void) +{ + //for OC1A on pin B5 + DDRB |= (1<<PB5); + TCCR1A = 0; + TCNT1 = 0; + OCR1A = 0; + TCCR1A = (1<<WGM10); //Fast PWM, 8-bit + TCCR1B = (1<<WGM12); //Fast PWM, 8-bit + //TCCR1A |= (1<<COM1A1) // Clear OCnA/OCnB/OCnC on compare match when up-counting. Set OCnA/OCnB/OCnC on compare match when downcounting. (for FastPWM) + + //for OC4D on pin D7 + DDRD |= (1<<PD7); + TCCR4A = 0; + TCCR4B = 0; + TCCR4C = _BV(PWM4D); //Fast PWM: PWM4x == 0x1 && WGM41..40 ==0x00 + TCCR4D = 0; //Fast PWM: PWM4x == 0x1 && WGM41..40 ==0x00 + TCNT4 = 0; + OCR4C = 0xFF; //TOP value + OCR4D = 0; +} + +inline void pwm_b5_on(void) +{ + TCCR1A |= (1<<COM1A1); // Clear OCnA/OCnB/OCnC on compare match when up-counting. Set OCnA/OCnB/OCnC on compare match when downcounting. + TCCR1B = (TCCR1B & 0xF8) | (1<<CS10); // enable timer clock, no prescaling +} + +inline void pwm_d7_on(void) +{ + TCCR4B = (TCCR4B & 0xF0) | (1<<CS40); // enable timer clock, no prescaling + TCCR4C |= (1<<COM4D1); // Clear OC4D on compare match when up-counting. Set when when TCNT4 == 0x000 (for FastPWM) +} + +inline void pwm_b5_off(void) +{ + TCCR1A &= ~((1<<COM1A1) | (1<<COM1A0)); //normal port operation + TCCR1B = (TCCR1B & 0xF8); //no clock source, timer stopped + TCNT1 = 0; + PORTB &= ~(1 << PB5); //set pin to LOW (otherwise it will remain in state since last pwm toggle) +} + +inline void pwm_d7_off(void) +{ + TCCR4B = (TCCR4B & 0xF0); //no clock source, timer stopped + TCCR4C &= ~(_BV(COM4D1) | _BV(COM4D0)); //normal port operation + TCNT4 = 0; + PORTD &= ~(1 << PD7); //set pin to LOW (otherwise it will remain in state since last pwm toggle) +} + +void pwm_b5_set(uint8_t val) +{ + if (val > 0) + pwm_b5_on(); + else + pwm_b5_off(); + PWMB5_VAL = val; +} + +void pwm_d7_set(uint8_t val) +{ + if (val > 0) + pwm_d7_on(); + else + pwm_d7_off(); + PWMD7_VAL = val; +} + +inline void pwm_b5_inc(void) +{ + if(PWMB5_VAL < 255) + PWMB5_VAL++; +} + +inline void pwm_b5_dec(void) +{ + if(PWMB5_VAL > 0) + PWMB5_VAL--; +} diff --git a/pcr-controller/pwm.h b/pcr-controller/pwm.h new file mode 100644 index 0000000..2459cd3 --- /dev/null +++ b/pcr-controller/pwm.h @@ -0,0 +1,11 @@ +#ifndef PWM_H_INCLUDED_ +#define PWM_H_INCLUDED_ + +#include <avr/io.h> + +void pwm_init(void); +void pwm_b5_set(uint8_t val); +void pwm_d7_set(uint8_t val); + + +#endif diff --git a/pcr-controller/temp_curve.c b/pcr-controller/temp_curve.c new file mode 100644 index 0000000..29db29e --- /dev/null +++ b/pcr-controller/temp_curve.c @@ -0,0 +1,177 @@ +/* + * r3PCR Teensy Controller Code + * + * + * Copyright (C) 2013-2014 Bernhard Tittelbach <xro@realraum.at> + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This code is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "temp_curve.h" +#include <stdlib.h> +#include <stdio.h> + +extern uint8_t debug_; + +const int16_t temp_margin_ = 16; // 1 °C + +typedef struct tc_entry tc_entry; +struct tc_entry { + int16_t target_temp; + uint16_t hold_for_timeticks; + tc_entry *next; +}; + +tc_entry *temp_curve_ = 0; //pointer to start of curve (so we can free it by going through the list) +tc_entry *temp_curve_end_ = 0; //pointer to last added entry in curve (so we know can quickly append new entries) +tc_entry *temp_curve_current_ = 0; //pointer to currently active entry (temp we currently hold) +tc_entry *temp_curve_loop_first_ = 0; //pointer to start of loop (loop is a subset of curve list) +tc_entry *temp_curve_loop_last_ = 0; //pointer to end of loop (loop is a subset of curve list) + +uint16_t temp_stable_time_ = 0; + +uint8_t temp_curve_original_num_repeats_ = 0; +uint8_t curve_loop_num_repeats_ = 0; // number of times the loop still needs to be reapeated before finishing the rest of the curve + +void tcurve_reset(void) +{ + tc_entry *curr = temp_curve_; + tc_entry *next = 0; + while (curr != 0) { + next = curr->next; + if (debug_) + printf("tcreset: curr: 0x%x, next: 0x%x, end: 0x%x\r\n",(uint16_t)curr,(uint16_t)next,(uint16_t)temp_curve_end_); + free(curr); + if (curr == temp_curve_end_) + break; //just to be sure + curr = next; + } + temp_curve_ = 0; + temp_curve_end_ = 0; + temp_curve_current_ = 0; + temp_curve_original_num_repeats_ = 0; + curve_loop_num_repeats_ = 0; + temp_curve_loop_first_ = temp_curve_; + temp_curve_loop_last_ = 0; + if (debug_) + printf("tcreset: done\n\n"); +} + +uint16_t tcurve_getTimeElapsed(void) +{ + return temp_stable_time_; +} + +uint8_t tcurve_getRepeatsLeft(void) +{ + return curve_loop_num_repeats_; +} + +uint8_t tcurve_isSet(void) +{ + return temp_curve_ != 0; +} + +void tcurve_setRepeats(uint8_t r) +{ + curve_loop_num_repeats_ = r; + temp_curve_original_num_repeats_ = r; +} + +void tcurve_add(int16_t temp, uint16_t hold_for_ticks) +{ + tc_entry *new_entry = malloc(sizeof(tc_entry)); + new_entry->target_temp = temp; + new_entry->hold_for_timeticks = hold_for_ticks; + new_entry->next = 0; + + if (temp_curve_end_ == 0) + { + temp_curve_end_ = new_entry; + temp_curve_ = new_entry; + temp_curve_current_ = new_entry; + temp_curve_loop_first_ = new_entry; + } else { + temp_curve_end_->next = new_entry; + temp_curve_end_ = new_entry; + } +} + +void tcurve_setRepeatStartPosToLatestEntry(void) +{ + //calling this again, overwrites last set loop start entry + temp_curve_loop_first_= temp_curve_end_; + //no loop_last_ before loop_first_ + temp_curve_loop_last_ = 0; +} + +void tcurve_setRepeatEndPosToLatestEntry(void) +{ + //calling this again, overwrites last set loop stop entry + temp_curve_loop_last_ = temp_curve_end_; +} + +void tcurve_printCurve(uint8_t cmd) +{ + if (temp_curve_ == 0) + { + printf("{\"cmd\":\"%c\",\"cmd_ok\":false,\"error\":\"No curve set\"}\r\n",cmd); + return; + } + printf("{\"cmd\":\"%c\",\"curve\":[",cmd); + for (tc_entry *ce = temp_curve_; ; ce=ce->next) + { + printf("{\"temp\":%d,\"duration\":%u,\"is_curr\":%d,\"is_loop_start\":%d,\"is_loop_end\":%d},", + ce->target_temp, + ce->hold_for_timeticks, + ce == temp_curve_current_, + ce == temp_curve_loop_first_, + ce == temp_curve_loop_last_); + + if (ce == temp_curve_end_) + break; + } + printf("0],\"loop_repeats\":%d}\r\n", temp_curve_original_num_repeats_); +} + +int16_t tcurve_getTempToSet(int16_t current_temp, uint16_t ticks_elapsed) +{ + if (temp_curve_current_ == 0) + return TCURVE_ERROR; + + if (current_temp > temp_curve_current_->target_temp - temp_margin_ && current_temp < temp_curve_current_->target_temp + temp_margin_) + { + temp_stable_time_ += ticks_elapsed; + } // else: ignore the case of temp falling temporarily outside of temp_margin_ + + //if temp has been stable for the set amount of timeticks in current curve element + if (temp_stable_time_ >= temp_curve_current_->hold_for_timeticks) + { + temp_stable_time_ = 0; + + if (curve_loop_num_repeats_ && //if repetitions left + ( (temp_curve_loop_last_ != 0 && temp_curve_current_ == temp_curve_loop_last_) //and we have reached a set loop endpoint + || temp_curve_current_->next == 0 //or the end of the list + )) + { //go back to first point in loop + curve_loop_num_repeats_--; + temp_curve_current_ = temp_curve_loop_first_; + } else if (temp_curve_current_->next != 0) //else if elements left in curve list + { // go to next element + temp_curve_current_ = temp_curve_current_->next; + } + //else stay on temperature of last element forever (until reset is called or new elements are added) + } + return temp_curve_current_->target_temp; +} diff --git a/pcr-controller/temp_curve.h b/pcr-controller/temp_curve.h new file mode 100644 index 0000000..46bb57e --- /dev/null +++ b/pcr-controller/temp_curve.h @@ -0,0 +1,40 @@ +/* + * rPCR Teensy Controller Code + * + * + * Copyright (C) 2013-2014 Bernhard Tittelbach <xro@realraum.at> + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This code is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef TEMP_CURVE_INCLUDE_H_ +#define TEMP_CURVE_INCLUDE_H_ + +#define TCURVE_ERROR (1<<15) + +#include <avr/io.h> + +void tcurve_reset(void); +void tcurve_setRepeats(uint8_t r); +void tcurve_setRepeatStartPosToLatestEntry(void); +void tcurve_setRepeatEndPosToLatestEntry(void); +uint8_t tcurve_isSet(void); +uint8_t tcurve_hasFinished(void); +uint16_t tcurve_getTimeElapsed(void); +uint8_t tcurve_getRepeatsLeft(void); +void tcurve_add(int16_t temp, uint16_t hold_for_s); +int16_t tcurve_getTempToSet(int16_t current_temp, uint16_t time_elapsed); +void tcurve_printCurve(uint8_t cmd); + +#endif diff --git a/rf433send/Makefile b/rf433send/Makefile new file mode 100644 index 0000000..d9ec7c6 --- /dev/null +++ b/rf433send/Makefile @@ -0,0 +1,47 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+## Othmar Gsenger <otti@gsenger.com>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := rf433send
+BOARD_TYPE := teensy2
+OBJ := $(NAME).o
+LIBS := util led lufa-descriptor-usbserial usbio
+EXTERNAL_LIBS := lufa
+RESET_FUNC := ../tools/reset_lufa_cdc
+RESET_PARAM := 'r'
+
+LUFA_PATH := ../contrib/LUFA-120219
+LUFA_OPTS = -D USB_DEVICE_ONLY
+LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0
+LUFA_OPTS += -D ORDERED_EP_CONFIG
+LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1
+LUFA_OPTS += -D USE_FLASH_DESCRIPTORS
+LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
+LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT
+
+LUFA_OPTS += -D USB_MANUFACTURER="L\"otti\"" -D USB_MANUFACTURER_LEN=4
+LUFA_OPTS += -D USB_PRODUCT="L\"realraum RF433 controller\"" -D USB_PRODUCT_LEN=25
+
+LUFA_COMPONENTS := USB USBCLASS
+
+include ../include.mk
diff --git a/rf433send/rf433send.c b/rf433send/rf433send.c new file mode 100644 index 0000000..f83027f --- /dev/null +++ b/rf433send/rf433send.c @@ -0,0 +1,232 @@ +/*
+ * spreadspace avr utils
+ *
+ *
+ * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+ * Othmar Gsenger <otti@gsenger.com>
+ *
+ * This file is part of spreadspace avr utils.
+ *
+ * spreadspace avr utils is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * spreadspace avr utils is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+#include <avr/io.h>
+#include <avr/wdt.h>
+#include <avr/interrupt.h>
+#include <avr/power.h>
+#include <stdio.h>
+
+#include "util.h"
+#include "led.h"
+#include "usbio.h"
+
+/*
+ this program listens on a usb serial/acm interface. When the send command ('s')
+ is received the send buffer gets filled with the next 3 bytes. These bites are
+ sent out serialized to a specified port using PWM. Before the data is sent, a
+ sync bit is sent. The data is repeated multiple times.
+
+ This version of the program is optimized for 433MHz radio controlled power plugs.
+ To control them you need to add a ASK modulator to the output pin (default F0).
+*/
+
+// RF433 Sender is Connected to PF0
+#define SEND_PORT PORTF
+#define SEND_DDR DDRF
+#define SEND_SERIAL 0
+// Logical Zero (Sender turned off) is when output is low
+#define SEND_ZERO 1
+// rf433 command length is 3 bytes
+#define SEND_CMD_LENGTH 3
+// pwm is SEND_PWM_BASE timers high and SEND_PWN_LONG_MULT * SEND_PWM_BASE timers low for a low bit (low bit = low is longer)
+#define SEND_PWM_BASE 1
+#define SEND_PWN_LONG_MULT 3
+#define SEND_PWN_SYNC_MULT 31
+
+//bits are read LSB from first byte first
+#define SEND_CURRENT_BIT (send_cmd_buffer[send_cmd_buffer_bit_pos/8] & (1<< (send_cmd_buffer_bit_pos % 8 )))
+
+static char send_cmd_buffer[SEND_CMD_LENGTH];
+static int8_t send_cmd_buffer_bit_pos=0;
+static uint8_t send_pwm_remain=0;
+static uint8_t send_pwm_output=0;
+static uint8_t send_repeat=0;
+static uint8_t send_sync=0;
+
+
+
+static inline void sender_on(void)
+{
+ if(SEND_ZERO)
+ SEND_PORT |= (1 << SEND_SERIAL);
+ else
+ SEND_PORT &= ~(1 << SEND_SERIAL);
+ send_pwm_output=1;
+}
+
+static inline void sender_off(void)
+{
+ if(SEND_ZERO)
+ SEND_PORT &= ~(1 << SEND_SERIAL);
+ else
+ SEND_PORT |= (1 << SEND_SERIAL);
+ send_pwm_output=0;
+}
+
+inline void sender_toggle(void)
+{
+ SEND_PORT ^= (1 << SEND_SERIAL);
+}
+
+void sender_timer_enable(void)
+{
+ TCCR0A = 1<<WGM01;
+ OCR0A = 22; // (1+17)*16us = 352us
+ TCCR0B = 1<<CS02 | 0<<CS01| 0<<CS00; //Teiler 256
+ TCNT0 = 0;
+ TIMSK0 |= (1<<OCIE0A);
+}
+
+inline void sender_timer_disable(void)
+{
+ TCCR0B =0;
+ TIMSK0 &= ~(1<<OCIE0A);
+}
+
+inline uint8_t sender_timer_status(void)
+{
+ return (TIMSK0 & (1<<OCIE0A))>>OCIE0A;
+}
+
+ISR(TIMER0_COMPA_vect)
+{
+ PORTF^=2; //debug;
+ if(send_cmd_buffer_bit_pos < SEND_CMD_LENGTH * 8) {
+ if(send_pwm_remain)
+ {
+ //NOTHING
+ } else if (send_sync) {
+ sender_off();
+ send_pwm_remain=SEND_PWM_BASE*SEND_PWN_SYNC_MULT;
+ send_sync=0;
+ send_cmd_buffer_bit_pos=-1;
+ } else if (send_pwm_output) {
+ sender_off();
+ if(SEND_CURRENT_BIT)
+ {
+ send_pwm_remain=SEND_PWM_BASE;
+ } else {
+ send_pwm_remain=SEND_PWM_BASE*SEND_PWN_LONG_MULT;
+ }
+ } else {
+ send_cmd_buffer_bit_pos++;
+ sender_on();
+ if(SEND_CURRENT_BIT)
+ {
+ send_pwm_remain=SEND_PWM_BASE*SEND_PWN_LONG_MULT;
+ } else {
+ send_pwm_remain=SEND_PWM_BASE;
+ }
+ }
+ send_pwm_remain--;
+ } else {
+ send_cmd_buffer_bit_pos=0;
+ send_pwm_remain=0;
+ if(send_repeat)
+ {
+ send_repeat--;
+ send_sync=1;
+ send_pwm_remain=SEND_PWM_BASE;
+ sender_on();
+ } else {
+ sender_timer_disable();
+ sender_off();
+ }
+ }
+}
+
+void pins_init(void)
+{
+ sender_off();
+ SEND_DDR |= 1 << SEND_SERIAL;
+ DDRF |= 2; //DEBUG
+}
+
+void timer_init(void)
+{
+}
+
+static uint8_t command_pos=0;
+
+void handle_cmd(uint8_t cmd)
+{
+ if (!command_pos)
+ {
+ switch(cmd) {
+ case '0': led_off(); break;
+ case '1': led_on(); break;
+ case 't': led_toggle(); break;
+ case 'r': reset2bootloader(); break;
+ case 's':
+ printf("Expecting multibyte command now\n\r");
+ command_pos=1;
+ break;
+ default: printf("error\n\r"); return;
+ }
+ printf("ok\n\r");
+ } else {
+ send_cmd_buffer[command_pos-1]=cmd;
+ if (command_pos==SEND_CMD_LENGTH)
+ {
+ printf("Enabling Timer\n\r");
+ command_pos=0;
+ send_sync=1;
+ send_pwm_remain=SEND_PWM_BASE;
+ send_repeat=15;
+ sender_on();
+ sender_timer_enable();
+ }
+ else
+ command_pos++;
+ }
+}
+
+
+
+int main(void)
+{
+ MCUSR &= ~(1 << WDRF);
+ wdt_disable();
+
+ cpu_init();
+ led_init();
+ usbio_init();
+ pins_init();
+ timer_init();
+ sei();
+
+ for(;;) {
+ int16_t BytesReceived = usbio_bytes_received();
+ while(BytesReceived > 0) {
+ int16_t ReceivedByte = fgetc(stdin);
+ if(ReceivedByte != EOF) {
+ handle_cmd(ReceivedByte);
+ }
+ BytesReceived--;
+ }
+
+ usbio_task();
+ }
+}
diff --git a/serial-led/Makefile b/serial-led/Makefile new file mode 100644 index 0000000..cd73ecc --- /dev/null +++ b/serial-led/Makefile @@ -0,0 +1,32 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := serial-led
+BOARD_TYPE := slowpandongle1
+OBJ := $(NAME).o
+LIBS := util led serialio
+EXTERNAL_LIBS := lufa
+
+LUFA_PATH := ../contrib/LUFA-120219
+LUFA_COMPONENTS := SERIAL
+
+include ../include.mk
diff --git a/serial-led/serial-led.c b/serial-led/serial-led.c new file mode 100644 index 0000000..76dd03a --- /dev/null +++ b/serial-led/serial-led.c @@ -0,0 +1,67 @@ +/*
+ * spreadspace avr utils
+ *
+ *
+ * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+ *
+ * This file is part of spreadspace avr utils.
+ *
+ * spreadspace avr utils is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * spreadspace avr utils is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+#include <avr/io.h>
+#include <avr/wdt.h>
+#include <avr/interrupt.h>
+#include <avr/power.h>
+#include <stdio.h>
+
+#include "util.h"
+#include "led.h"
+#include "serialio.h"
+
+void handle_cmd(uint8_t cmd)
+{
+ switch(cmd) {
+ case '0': led_off(); break;
+ case '1': led_on(); break;
+ case 't': led_toggle(); break;
+ case 'r': reset2bootloader(); break;
+ default: printf("error\r\n"); return;
+ }
+ printf("ok\r\n");
+}
+
+int main(void)
+{
+ MCUSR &= ~(1 << WDRF);
+ wdt_disable();
+
+ cpu_init();
+ led_init();
+ serialio_init(9600, 0);
+ sei();
+
+ for(;;) {
+ int16_t BytesReceived = serialio_bytes_received();
+ while(BytesReceived > 0) {
+ int ReceivedByte = fgetc(stdin);
+ if(ReceivedByte != EOF) {
+ handle_cmd(ReceivedByte);
+ }
+ BytesReceived--;
+ }
+ serialio_task();
+ }
+}
diff --git a/tools/Makefile b/tools/Makefile new file mode 100644 index 0000000..26c4f8c --- /dev/null +++ b/tools/Makefile @@ -0,0 +1,36 @@ +## +## spreadspace avr utils +## +## +## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> +## +## This file is part of spreadspace avr utils. +## +## spreadspace avr utils is free software: you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation, either version 3 of the License, or +## any later version. +## +## spreadspace avr utils is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. +## + +TARGETS=reset_arduino + +all: $(TARGETS) + +reset_arduino: reset_arduino.c + $(CC) -o $@ $< + +.PHONY: clean + +clean: + rm -f *.o + rm -f *.d + rm -f *.d.* + rm -f $(TARGETS) diff --git a/tools/reset_arduino.c b/tools/reset_arduino.c new file mode 100644 index 0000000..4eb22bb --- /dev/null +++ b/tools/reset_arduino.c @@ -0,0 +1,67 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <stdlib.h> +#include <termios.h> +#include <fcntl.h> +#include <sys/ioctl.h> +#include <time.h> +#include <stdio.h> +#include <sys/select.h> +#include <errno.h> +#include <string.h> + +#define STATE_OFF 0 +#define STATE_ON 1 + +void setDTRState (int fd, int state) { + int flags; + + ioctl(fd, TIOCMGET, &flags); + flags = (state == STATE_ON ? flags | TIOCM_DTR : flags & ~TIOCM_DTR); + ioctl(fd, TIOCMSET, &flags); +} + +int +main(int argc, char* argv[]) +{ + char* device = argc < 2 ? "/dev/ttyUSB0" : argv[1]; + int fd = open(device, O_RDWR); + if (fd < 0) { + fprintf(stderr, "Could not open %s (%s)\n", device, strerror(errno)); + return EXIT_FAILURE; + } + + printf("reseting arduino at %s\n", device); + + setDTRState(fd, STATE_ON); + struct timeval sleeptime = {0, 100000}; // 100ms + select(0, NULL, NULL, NULL, &sleeptime); + setDTRState(fd, STATE_OFF); + sleeptime.tv_sec = 0; + sleeptime.tv_usec = 100000; + select(0, NULL, NULL, NULL, &sleeptime); + setDTRState(fd, STATE_ON); + close(fd); + + return EXIT_SUCCESS; +} diff --git a/tools/reset_dummy b/tools/reset_dummy new file mode 100755 index 0000000..36db140 --- /dev/null +++ b/tools/reset_dummy @@ -0,0 +1,19 @@ +#!/bin/sh + +if [ -n "$1" ]; then + DELAY="$1" +else + DELAY=5 +fi + +echo -n "Please press the reset button " +i=$DELAY +while (test $i -gt 0); do + sleep 1 + i=$(($i-1)) + echo -n "." +done + +echo "" + +exit 0 diff --git a/tools/reset_lufa_cdc b/tools/reset_lufa_cdc new file mode 100755 index 0000000..d1f4a80 --- /dev/null +++ b/tools/reset_lufa_cdc @@ -0,0 +1,9 @@ +#!/bin/bash + +echo "resetting device .." +echo $1 > /dev/ttyACM0 + +echo "waiting for device to enumerate .." +sleep 4 + +exit 0 diff --git a/tools/reset_minimus b/tools/reset_minimus new file mode 100755 index 0000000..38ba7b8 --- /dev/null +++ b/tools/reset_minimus @@ -0,0 +1,36 @@ +#!/bin/sh + +if [ -z "$1" ]; then + IDS="03eb:2ff0 03eb:2ffa" +else + IDS=$1 +fi + +WAIT_MAX=15 + +FOUND=0 +echo -n "Please press and hold 'H' button and reset the device using the 'R' button " +i=$WAIT_MAX +while (test $i -gt 0); do + echo -n "." + for id in $IDS; do + lsusb -d $id > /dev/null 2>&1 + if [ $? -eq 0 ]; then + FOUND=1 + break; + fi + done + if [ $FOUND -eq 1 ]; then + break; + fi + sleep 1 + i=$(($i-1)) +done + +if [ $FOUND -eq 1 ]; then + echo " device found!" +else + echo " timout - trying anyway" +fi + +exit 0 diff --git a/tube-rotator/Makefile b/tube-rotator/Makefile new file mode 100644 index 0000000..c75c022 --- /dev/null +++ b/tube-rotator/Makefile @@ -0,0 +1,46 @@ +## +## spreadspace avr utils +## +## +## Copyright (C) 2014 Christian Pointner <equinox@spreadspace.org> +## +## This file is part of spreadspace avr utils. +## +## spreadspace avr utils is free software: you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation, either version 3 of the License, or +## any later version. +## +## spreadspace avr utils is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. +## + +NAME := tube-rotator +BOARD_TYPE := teenstep +OBJ := $(NAME).o stepper.o +LIBS := util led lufa-descriptor-usbserial anyio +EXTERNAL_LIBS := lufa +RESET_FUNC := ../tools/reset_lufa_cdc +RESET_PARAM := '!' + +LUFA_PATH := ../contrib/LUFA-120219 +LUFA_OPTS = -D USB_DEVICE_ONLY +LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0 +LUFA_OPTS += -D ORDERED_EP_CONFIG +LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8 +LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1 +LUFA_OPTS += -D USE_FLASH_DESCRIPTORS +LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)" +LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT + +LUFA_OPTS += -D USB_MANUFACTURER="L\"equinox\"" -D USB_MANUFACTURER_LEN=7 +LUFA_OPTS += -D USB_PRODUCT="L\"realraum tube rotator\"" -D USB_PRODUCT_LEN=21 + +LUFA_COMPONENTS := USB USBCLASS SERIAL + +include ../include.mk diff --git a/tube-rotator/stepper.c b/tube-rotator/stepper.c new file mode 100644 index 0000000..8b718ae --- /dev/null +++ b/tube-rotator/stepper.c @@ -0,0 +1,169 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <avr/sfr_defs.h> +#include <avr/interrupt.h> +#include <util/atomic.h> +#include <math.h> + +#include "stepper.h" + +uint8_t step_table [] = +{ + 2, // 0010 + 6, // 0110 + 4, // 0100 + 5, // 0101 + 1, // 0001 + 9, // 1001 + 8, // 1000 + 10, // 1010 +}; + +#define STEPPER_PORT PORTF +#define STEPPER_DDR DDRF +#define STEPPER_FIRST_BIT 4 +#define STEPPER_ENABLE_A_BIT 0 +#define STEPPER_ENABLE_B_BIT 1 +#define LENGTH_STEP_TABLE (sizeof(step_table)/sizeof(uint8_t)) +#define STEPPER_OUTPUT_BITMASK (~(0xF << STEPPER_FIRST_BIT )) + +volatile uint16_t target_speed; +uint16_t current_speed; +stepper_state_t current_state; + +void stepper_init(void) +{ + target_speed = STEPPER_SPEED_DEFAULT; + STEPPER_PORT &= ~(0xF << STEPPER_FIRST_BIT | 1<<STEPPER_ENABLE_A_BIT | 1<<STEPPER_ENABLE_B_BIT); + STEPPER_DDR |= (0xF << STEPPER_FIRST_BIT) | (1<<STEPPER_ENABLE_A_BIT) | (1<<STEPPER_ENABLE_B_BIT); + stepper_stop(); +} + +void stepper_start(void) +{ + if(current_state == stepper_running) return; + + current_speed = STEPPER_SPEED_MIN; + STEPPER_PORT |= (1<<STEPPER_ENABLE_A_BIT) | (1<<STEPPER_ENABLE_B_BIT); + TCNT1 = 0; + OCR1A = current_speed; + TCCR1A = 0; // prescaler 1:64, WGM = 4 (CTC) + TCCR1B = 1<<WGM12 | 1<<CS11 | 1<<CS10; // + TIMSK1 = 1<<OCIE1A; + current_state = stepper_running; +} + +void stepper_stop(void) +{ + STEPPER_PORT &= ~(0xF << STEPPER_FIRST_BIT | 1<<STEPPER_ENABLE_A_BIT | 1<<STEPPER_ENABLE_B_BIT); + TCCR1B = 0; // no clock source + TIMSK1 = 0; // disable timer interrupt + current_state = stepper_stopped; +} + +static inline void stepper_handle(void) +{ + static uint8_t step_idx = 0; + + uint8_t stepper_output = step_table[step_idx]; + stepper_output <<= STEPPER_FIRST_BIT; + STEPPER_PORT = (STEPPER_PORT & STEPPER_OUTPUT_BITMASK ) | stepper_output; + step_idx++; + step_idx %= LENGTH_STEP_TABLE; + + if(step_idx != 0 && step_idx % 8) { + if(current_speed > target_speed) + OCR1A = (uint16_t)((STEPPER_SPEED_CONVERT_VALUE/(--current_speed)) - 1); + else if(current_speed < target_speed) + OCR1A = (uint16_t)((STEPPER_SPEED_CONVERT_VALUE/(++current_speed)) - 1); + } +} + +ISR(TIMER1_COMPA_vect) +{ + stepper_handle(); +} + +stepper_state_t stepper_get_state(void) +{ + return current_state; +} + +const char* stepper_state_to_string(stepper_state_t state) +{ + switch(state) { + case stepper_running: return "running"; + case stepper_stopped: return "stopped"; + } + return "?"; +} + +void stepper_set_speed(uint16_t new_speed) +{ + if(new_speed >= STEPPER_SPEED_MIN && new_speed <= STEPPER_SPEED_MAX) { + ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { + target_speed = new_speed; + } + } +} + +void stepper_inc_speed(void) +{ + ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { + target_speed = (target_speed >= STEPPER_SPEED_MAX) ? STEPPER_SPEED_MAX : target_speed + 1; + } +} + +void stepper_dec_speed(void) +{ + ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { + target_speed = (target_speed <= STEPPER_SPEED_MIN) ? STEPPER_SPEED_MIN : target_speed - 1; + } +} + +uint16_t stepper_get_speed(void) +{ + return target_speed; +} + +void stepper_set_speed_rpm(uint8_t new_rpm) +{ + stepper_set_speed( (uint16_t)lround( ( (double)(64.0 * 800.0 * (double)STEPPER_SPEED_CONVERT_VALUE) / (double)(60.0 * (double)F_CPU) ) * (double)new_rpm) ); +} + +uint8_t stepper_get_speed_rpm(void) +{ + return (uint8_t)lround( ( (double)(60.0 * (double)F_CPU) / (double)(64.0 * 800.0 * (double)STEPPER_SPEED_CONVERT_VALUE) ) * (double)(target_speed) ); +} + +void stepper_inc_speed_rpm(void) +{ + uint8_t rpm = stepper_get_speed_rpm(); + stepper_set_speed_rpm((rpm >= 255) ? 255 : rpm+1); +} + +void stepper_dec_speed_rpm(void) +{ + uint8_t rpm = stepper_get_speed_rpm(); + stepper_set_speed_rpm((rpm <= 1) ? 1 : rpm-1); +} diff --git a/tube-rotator/stepper.h b/tube-rotator/stepper.h new file mode 100644 index 0000000..5b5a315 --- /dev/null +++ b/tube-rotator/stepper.h @@ -0,0 +1,59 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef R3TUBE_stepper_h_INCLUDED +#define R3TUBE_stepper_h_INCLUDED + +#define STEPPER_SPEED_MIN 150 +#define STEPPER_SPEED_MAX 700 +#define STEPPER_SPEED_CONVERT_VALUE (uint32_t)(105000) + +#define STEPPER_SPEED_30RPM 168 +#define STEPPER_SPEED_40RPM 224 +#define STEPPER_SPEED_50RPM 281 +#define STEPPER_SPEED_60RPM 336 +#define STEPPER_SPEED_70RPM 393 +#define STEPPER_SPEED_80RPM 451 +#define STEPPER_SPEED_90RPM 507 +#define STEPPER_SPEED_100RPM 561 + +#define STEPPER_SPEED_DEFAULT STEPPER_SPEED_60RPM + +typedef enum { stepper_stopped = 0, stepper_running = 1 } stepper_state_t; + +void stepper_init(void); +void stepper_start(void); +void stepper_stop(void); +stepper_state_t stepper_get_state(void); +const char* stepper_state_to_string(stepper_state_t state); + +void stepper_set_speed(uint16_t new_speed); +void stepper_inc_speed(void); +void stepper_dec_speed(void); +uint16_t stepper_get_speed(void); + +void stepper_set_speed_rpm(uint8_t new_rpm); +uint8_t stepper_get_speed_rpm(void); +void stepper_inc_speed_rpm(void); +void stepper_dec_speed_rpm(void); + +#endif diff --git a/tube-rotator/tube-rotator.c b/tube-rotator/tube-rotator.c new file mode 100644 index 0000000..065dd2f --- /dev/null +++ b/tube-rotator/tube-rotator.c @@ -0,0 +1,81 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <avr/io.h> +#include <avr/wdt.h> +#include <avr/interrupt.h> +#include <avr/power.h> + +#include <stdio.h> +#include <string.h> + +#include "util.h" +#include "led.h" +#include "anyio.h" + +#include "stepper.h" + +void handle_cmd(uint8_t cmd) +{ + switch(cmd) { + case '!': reset2bootloader(); break; + case 'r': led_on(); stepper_start(); break; + case 's': stepper_stop(); led_off(); break; + case '*': stepper_inc_speed(); break; + case '+': stepper_inc_speed_rpm(); break; + case '-': stepper_dec_speed_rpm(); break; + case '_': stepper_dec_speed(); break; + case '3': stepper_set_speed_rpm(30); break; + case '4': stepper_set_speed_rpm(40); break; + case '5': stepper_set_speed_rpm(50); break; + case '6': stepper_set_speed_rpm(60); break; + case '7': stepper_set_speed_rpm(70); break; + case '8': stepper_set_speed_rpm(80); break; + case '9': stepper_set_speed_rpm(90); break; + case '0': stepper_set_speed_rpm(100); break; + case '1': stepper_set_speed_rpm(110); break; + case '2': stepper_set_speed_rpm(120); break; + } + printf("state: %s, %3d rpm\r", stepper_state_to_string(stepper_get_state()), stepper_get_speed_rpm()); +} + +int main(void) +{ + MCUSR &= ~(1 << WDRF); + wdt_disable(); + + cpu_init(); + jtag_disable(); + led_init(); + anyio_init(115200, 0); + + stepper_init(); + sei(); + + for(;;) { + anyio_task(); + + int16_t bytes_received = anyio_bytes_received(); + if(bytes_received > 0) + handle_cmd(fgetc(stdin)); + } +} diff --git a/tuer-rfid/Makefile b/tuer-rfid/Makefile new file mode 100644 index 0000000..ae4bbba --- /dev/null +++ b/tuer-rfid/Makefile @@ -0,0 +1,61 @@ +## +## spreadspace avr utils +## +## +## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> +## Othmar Gsenger <otti@wirdorange.org> +## +## This file is part of spreadspace avr utils. +## +## spreadspace avr utils is free software: you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation, either version 3 of the License, or +## any later version. +## +## spreadspace avr utils is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. +## + +NAME := tuer-rfid +BOARD_TYPE := teenstep +OBJ := $(NAME).o heartbeat.o stepper.o ledmatrix.o sl018.o keystore.o statemachine.o eventqueue.o limits.o manual.o ajar.o +LIBS := util led lufa-descriptor-usbserial anyio +EXTERNAL_LIBS := lufa +RESET_FUNC := ../tools/reset_lufa_cdc +RESET_PARAM := 'r' + +LUFA_PATH := ../contrib/LUFA-120219 +LUFA_OPTS = -D USB_DEVICE_ONLY +LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0 +LUFA_OPTS += -D ORDERED_EP_CONFIG +LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8 +LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1 +LUFA_OPTS += -D USE_FLASH_DESCRIPTORS +LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)" +LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT + +LUFA_OPTS += -D USB_MANUFACTURER="L\"equinox\"" -D USB_MANUFACTURER_LEN=7 +LUFA_OPTS += -D USB_PRODUCT="L\"realraum door firmware\"" -D USB_PRODUCT_LEN=22 + +LUFA_COMPONENTS := USB USBCLASS TWI SERIAL + +CLEAN_TARGETS += clean-pdf clean-update-keys + +include ../include.mk + +update-keys: update-keys.c + gcc -o $@ $< + +clean-update-keys: + rm -f update-keys + +pdf: statemachine.dot + dot -Tpdf statemachine.dot -o statemachine.pdf + +clean-pdf: + rm -f statemachine.pdf diff --git a/tuer-rfid/ajar.c b/tuer-rfid/ajar.c new file mode 100644 index 0000000..271aeb9 --- /dev/null +++ b/tuer-rfid/ajar.c @@ -0,0 +1,76 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <avr/io.h> +#include <stdio.h> +#include "ajar.h" + +#define AJAR_PIN PINC +#define AJAR_PORT PORTC +#define AJAR_DDR DDRC +#define AJAR_BIT 7 + +#define AJAR_LP_MAX 20000 + +void ajar_init(void) +{ + AJAR_DDR = AJAR_DDR & ~(1<<AJAR_BIT); + AJAR_PORT |= (1<<AJAR_BIT); +} + +ajar_t ajar_get(void) +{ + static uint8_t last_state = (1<<AJAR_BIT); + static uint16_t lp_cnt = 0; + + uint8_t state = AJAR_PIN & (1<<AJAR_BIT); + if(state != last_state) + lp_cnt++; + else + lp_cnt += lp_cnt ? -1 : 0; + + if(lp_cnt >= AJAR_LP_MAX) { + last_state = state; + lp_cnt = 0; + } + + if(last_state) + return ajar; + return shut; +} + +const char* ajar_to_string(ajar_t a) +{ + return a == ajar ? "ajar" : "shut"; +} + +void ajar_task(void) +{ + static ajar_t last_state = shut; + + ajar_t state = ajar_get(); + if(last_state != state) + printf("Info(ajar): door is now %s\r\n", ajar_to_string(state)); + + last_state = state; +} diff --git a/tuer-rfid/ajar.h b/tuer-rfid/ajar.h new file mode 100644 index 0000000..e4b2d06 --- /dev/null +++ b/tuer-rfid/ajar.h @@ -0,0 +1,34 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef R3TUER_ajar_h_INCLUDED +#define R3TUER_ajar_h_INCLUDED + +typedef enum { ajar, shut } ajar_t; + +void ajar_init(void); +ajar_t ajar_get(void); +const char* ajar_to_string(ajar_t a); +void ajar_task(void); + +#endif diff --git a/tuer-rfid/eventqueue.c b/tuer-rfid/eventqueue.c new file mode 100644 index 0000000..5841d63 --- /dev/null +++ b/tuer-rfid/eventqueue.c @@ -0,0 +1,61 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "eventqueue.h" +#include <LUFA/Drivers/Misc/RingBuffer.h> + +static RingBuffer_t event_queue; +static uint8_t event_queue_data[16]; + +void eventqueue_init(void) +{ + RingBuffer_InitBuffer(&event_queue, event_queue_data, sizeof(event_queue_data)); +} + +event_t eventqueue_pop(void) +{ + if (RingBuffer_IsEmpty(&event_queue)) + return none; + return RingBuffer_Remove(&event_queue); +} + +void eventqueue_push(event_t event) +{ + RingBuffer_Insert(&event_queue,event); +} + +const char* event_to_string(event_t event) +{ + switch(event) { + case none: return "none"; + case cmd_open: return "cmd_open"; + case cmd_close: return "cmd_close"; + case cmd_toggle: return "cmd_toggle"; + case btn_toggle: return "btn_toggle"; + case card: return "card"; + case open_fin: return "open_fin"; + case close_fin: return "close_fin"; + case move_timeout: return "move_timeout"; + } + return "invalid"; // gcc - shut the fuck up!!! +} diff --git a/tuer-rfid/eventqueue.h b/tuer-rfid/eventqueue.h new file mode 100644 index 0000000..3397e63 --- /dev/null +++ b/tuer-rfid/eventqueue.h @@ -0,0 +1,34 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef R3TUER_eventqueue_h_INCLUDED +#define R3TUER_eventqueue_h_INCLUDED + +typedef enum { none, cmd_open, cmd_close, cmd_toggle, btn_toggle, card, close_fin, open_fin, move_timeout } event_t; + +void eventqueue_init(void); +event_t eventqueue_pop(void); +void eventqueue_push(event_t); +const char* event_to_string(event_t event); + +#endif diff --git a/tuer-rfid/heartbeat.c b/tuer-rfid/heartbeat.c new file mode 100644 index 0000000..b656521 --- /dev/null +++ b/tuer-rfid/heartbeat.c @@ -0,0 +1,74 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <avr/sfr_defs.h> +#include <avr/interrupt.h> + +#include "led.h" +#include "heartbeat.h" + +#define HEARTBEAT_DURATION 10 // *10 ms, duration of heartbeat pulse +#define HEARTBEAT_DELAY 200 // *10 ms, 1/heartbeat-frequency +uint8_t heartbeat_cnt = 0; +uint8_t heartbeat_flag; + +#define FASTBEAT_PORT PORTD +#define FASTBEAT_DDR DDRD +#define FASTBEAT_BIT 5 + +// while running this gets called every ~10ms +ISR(TIMER0_COMPA_vect) +{ + heartbeat_cnt++; + if(heartbeat_cnt == HEARTBEAT_DURATION) + heartbeat_flag = 0; + else if(heartbeat_cnt >= HEARTBEAT_DELAY) { + heartbeat_flag = 1; + heartbeat_cnt = 0; + } +} + +void heartbeat_init(void) +{ + led_off(); + heartbeat_cnt = 0; + heartbeat_flag = 1; + + TCCR0A = 1<<WGM01; // OC0A and OC0B as normal output, WGM = 2 (CTC) + TCCR0B = 1<<CS02 | 1<<CS00; // Prescaler 1:1024 + OCR0A = 155; // (1+155)*1024 = 159744 -> ~10 ms @ 16 MHz + TCNT0 = 0; + TIMSK0 = 1<<OCIE0A; + + FASTBEAT_DDR |= 1<<FASTBEAT_BIT; +} + +void heartbeat_task(void) +{ + FASTBEAT_PORT ^= 1<<FASTBEAT_BIT; + + if(heartbeat_flag) + led_on(); + else + led_off(); +} diff --git a/tuer-rfid/heartbeat.h b/tuer-rfid/heartbeat.h new file mode 100644 index 0000000..692d932 --- /dev/null +++ b/tuer-rfid/heartbeat.h @@ -0,0 +1,30 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef R3TUER_heatbeat_h_INCLUDED +#define R3TUER_heatbeat_h_INCLUDED + +void heartbeat_init(void); +void heartbeat_task(void); + +#endif diff --git a/tuer-rfid/keystore.c b/tuer-rfid/keystore.c new file mode 100644 index 0000000..f02f9a2 --- /dev/null +++ b/tuer-rfid/keystore.c @@ -0,0 +1,110 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "keystore.h" +#include <avr/eeprom.h> +#include <stdio.h> +#include <string.h> + +#include "led.h" +#include "anyio.h" + +#define EEPROM_SIZE 1024 +typedef uint8_t keyslot_t[8]; +keyslot_t EEMEM keystore[EEPROM_SIZE/sizeof(keyslot_t)]; + + +void keystore_flash_from_stdio(void) +{ + keyslot_t ks; + uint8_t byte_pos=0; + printf("Info(keystore): flashing\r\n"); + fflush(stdout); + for(uint8_t ks_pos=0;ks_pos<EEPROM_SIZE/sizeof(ks);) { + anyio_task(); + + int16_t bytes_received = anyio_bytes_received(); + while(bytes_received > 0) { + ks[byte_pos++]=fgetc(stdin); + bytes_received--; + if (byte_pos == sizeof(ks)) { + byte_pos=0; + eeprom_update_block(&ks,&keystore[ks_pos],sizeof(ks)); + ks_pos++; + fputc('.', stdout); + fflush(stdout); + led_toggle(); + } + } + } + printf("\r\n"); + fputc(0, stdout); + led_off(); +} + +void keystore_dump_to_stdio(void) +{ + keyslot_t ks; + for(uint8_t ks_pos=0;ks_pos<EEPROM_SIZE/sizeof(ks);ks_pos++) { + eeprom_read_block(&ks,&keystore[ks_pos],sizeof(ks)); + for (uint8_t i=0; i< sizeof(ks); i++) + printf("%02X",ks[i]); + printf("\r\n"); + } +} + +/* this generates a Fletcher8 checksum */ +/* code from: http://stackoverflow.com/questions/13491700/8-bit-fletcher-checksum-of-16-byte-data */ +uint8_t generate_csum(uint8_t* data) +{ + uint16_t sum1 = 0xf, sum2 = 0xf, len = sizeof(keyslot_t) - 1; + do { sum2 += ( sum1 += *data++ ); } while (--len); + return sum2<<4 | sum1; +} + +uint8_t compare_keyslots(const keyslot_t a, const keyslot_t b) +{ + uint8_t tmp=0; + // constant time compare + for(uint8_t i=0; i<sizeof(keyslot_t); ++i) + tmp |= a[i] ^ b[i]; + return tmp; +} + +uint8_t keystore_check_card(const uint8_t * uid, uint8_t uid_len) +{ + keyslot_t card, ks; + memset(card, 0, sizeof(card)); + for (uint8_t pos=0; pos<uid_len; pos++) + card[pos]=uid[uid_len-pos-1]; + card[sizeof(keyslot_t)-1]=generate_csum(card); + uint8_t valid=0; + for(uint8_t ks_pos=0;ks_pos<(EEPROM_SIZE/sizeof(ks));ks_pos++) { + eeprom_read_block(&ks,&keystore[ks_pos],sizeof(ks)); + if(!compare_keyslots(card, ks)) { + valid=1; + // break; // this would break security (not constant time) + } + } + return valid; +} diff --git a/tuer-rfid/keystore.h b/tuer-rfid/keystore.h new file mode 100644 index 0000000..22499dc --- /dev/null +++ b/tuer-rfid/keystore.h @@ -0,0 +1,33 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef R3TUER_keystore_h_INCLUDED +#define R3TUER_keystore_h_INCLUDED + +#include <stdint.h> + +void keystore_flash_from_stdio(void); +void keystore_dump_to_stdio(void); +uint8_t keystore_check_card(const uint8_t * uid, uint8_t uid_len); + +#endif diff --git a/tuer-rfid/ledmatrix.c b/tuer-rfid/ledmatrix.c new file mode 100644 index 0000000..4cfbcc8 --- /dev/null +++ b/tuer-rfid/ledmatrix.c @@ -0,0 +1,218 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <avr/sfr_defs.h> +#include <avr/interrupt.h> + +#include "ledmatrix.h" + +#define LEDMATRIX_PORT PORTB +#define LEDMATRIX_DDR DDRB +#define LEDMATRIX_RED 6 +#define LEDMATRIX_GREEN 7 +#define LEDMATRIX_NUM_LEDS 6 +#define LEDMATRIX_MASK 0x3F +#define BLINK_DELAY 3 + +ledmatrix_mode_t mode = off; +uint8_t moving_cnt = 0; +uint8_t wait_cnt = 0; + +void ledmatrix_start_timer(void) +{ + TCCR3A = 0; // prescaler 1:1024, WGM = 4 (CTC) + TCCR3B = 1<<WGM32 | 1<<CS32 | 1<<CS30; // + OCR3A = 1561; // (1+1561)*1024 = 1599488 -> ~100 ms @ 16 MHz + TCNT3 = 0; + TIMSK3 = 1<<OCIE3A; +} + +void ledmatrix_stop_timer(void) +{ + TCCR3B = 0; + TIMSK3 = 0; +} + +void ledmatrix_off_init(void) +{ + LEDMATRIX_PORT = LEDMATRIX_MASK; + LEDMATRIX_PORT |= 1<<LEDMATRIX_RED | 1<<LEDMATRIX_GREEN; +} + + +void ledmatrix_red_init(void) +{ + LEDMATRIX_PORT = LEDMATRIX_MASK | 1<<LEDMATRIX_GREEN; + LEDMATRIX_PORT &= ~(1<<LEDMATRIX_RED); +} + + +void ledmatrix_red_moving_init(void) +{ + moving_cnt = 0; + LEDMATRIX_PORT = (1<<LEDMATRIX_GREEN) | (LEDMATRIX_MASK & (1<<moving_cnt)); + ledmatrix_start_timer(); +} + +void ledmatrix_red_moving_handle(void) +{ + moving_cnt++; + if(moving_cnt >= LEDMATRIX_NUM_LEDS) + moving_cnt = 0; + LEDMATRIX_PORT = (1<<LEDMATRIX_GREEN) | (LEDMATRIX_MASK & (1<<moving_cnt)); +} + + +void ledmatrix_red_blink_init(void) +{ + wait_cnt = 0; + ledmatrix_red_init(); + ledmatrix_start_timer(); +} + +void ledmatrix_red_blink_handle(void) +{ + if(++wait_cnt >= BLINK_DELAY) { + LEDMATRIX_PORT ^= 1<<LEDMATRIX_RED; + wait_cnt = 0; + } +} + + +void ledmatrix_green_init(void) +{ + LEDMATRIX_PORT = LEDMATRIX_MASK | 1<<LEDMATRIX_RED; + LEDMATRIX_PORT &= ~(1<<LEDMATRIX_GREEN); +} + + +void ledmatrix_green_moving_init(void) +{ + moving_cnt = 0; + LEDMATRIX_PORT = (1<<LEDMATRIX_RED) | (LEDMATRIX_MASK & (1<<(LEDMATRIX_NUM_LEDS - moving_cnt - 1))); + ledmatrix_start_timer(); +} + +void ledmatrix_green_moving_handle(void) +{ + moving_cnt++; + if(moving_cnt >= LEDMATRIX_NUM_LEDS) + moving_cnt = 0; + LEDMATRIX_PORT = (1<<LEDMATRIX_RED) | (LEDMATRIX_MASK & (1<<(LEDMATRIX_NUM_LEDS - moving_cnt - 1))); +} + + +void ledmatrix_green_blink_init(void) +{ + wait_cnt = 0; + ledmatrix_green_init(); + ledmatrix_start_timer(); +} + +void ledmatrix_green_blink_handle(void) +{ + if(++wait_cnt >= BLINK_DELAY) { + LEDMATRIX_PORT ^= 1<<LEDMATRIX_GREEN; + wait_cnt = 0; + } +} + + +void ledmatrix_rg_moving_init(void) +{ + moving_cnt = 0; + LEDMATRIX_PORT = (1<<LEDMATRIX_GREEN) | (LEDMATRIX_MASK & (1<<moving_cnt)); + ledmatrix_start_timer(); +} + +void ledmatrix_rg_moving_handle(void) +{ + moving_cnt++; + if(moving_cnt >= 2*LEDMATRIX_NUM_LEDS) + moving_cnt = 0; + + if(moving_cnt >= LEDMATRIX_NUM_LEDS) { + uint8_t offset = moving_cnt - LEDMATRIX_NUM_LEDS; + LEDMATRIX_PORT = (1<<LEDMATRIX_RED) | (LEDMATRIX_MASK & (1<<(LEDMATRIX_NUM_LEDS - offset - 1))); + } else { + LEDMATRIX_PORT = (1<<LEDMATRIX_GREEN) | (LEDMATRIX_MASK & (1<<moving_cnt)); + } +} + + +void ledmatrix_rg_blink_init(void) +{ + wait_cnt = 0; + ledmatrix_red_init(); + ledmatrix_start_timer(); +} + +void ledmatrix_rg_blink_handle(void) +{ + if(++wait_cnt >= BLINK_DELAY) { + LEDMATRIX_PORT ^= ~(LEDMATRIX_MASK); + wait_cnt = 0; + } +} + + +void ledmatrix_init(void) +{ + LEDMATRIX_DDR = 0xFF; + LEDMATRIX_PORT = 0xFF; +} + +void ledmatrix_set(ledmatrix_mode_t m) +{ + if(m == mode) + return; + + mode = m; + ledmatrix_stop_timer(); + switch(mode) + { + case off: ledmatrix_off_init(); break; + case red: ledmatrix_red_init(); break; + case red_moving: ledmatrix_red_moving_init(); break; + case red_blink: ledmatrix_red_blink_init(); break; + case green: ledmatrix_green_init(); break; + case green_moving: ledmatrix_green_moving_init(); break; + case green_blink: ledmatrix_green_blink_init(); break; + case rg_moving: ledmatrix_rg_moving_init(); break; + case rg_blink: ledmatrix_rg_blink_init(); break; + } +} + +ISR(TIMER3_COMPA_vect) +{ + switch(mode) + { + case red_moving: ledmatrix_red_moving_handle(); break; + case red_blink: ledmatrix_red_blink_handle(); break; + case green_moving: ledmatrix_green_moving_handle(); break; + case green_blink: ledmatrix_green_blink_handle(); break; + case rg_moving: ledmatrix_rg_moving_handle(); break; + case rg_blink: ledmatrix_rg_blink_handle(); break; + default: break; + } +} diff --git a/tuer-rfid/ledmatrix.h b/tuer-rfid/ledmatrix.h new file mode 100644 index 0000000..3be7f0f --- /dev/null +++ b/tuer-rfid/ledmatrix.h @@ -0,0 +1,34 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef R3TUER_ledmatrix_h_INCLUDED +#define R3TUER_ledmatrix_h_INCLUDED + +typedef enum { off, red, red_moving, red_blink, + green, green_moving, green_blink, + rg_moving, rg_blink } ledmatrix_mode_t; + +void ledmatrix_init(void); +void ledmatrix_set(ledmatrix_mode_t mode); + +#endif diff --git a/tuer-rfid/limits.c b/tuer-rfid/limits.c new file mode 100644 index 0000000..28c30ca --- /dev/null +++ b/tuer-rfid/limits.c @@ -0,0 +1,81 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <avr/io.h> +#include "limits.h" +#include <LUFA/Drivers/Peripheral/ADC.h> + +#define LIMITS_ADC_CHAN_NUM 8 +#define LIMITS_ADC_CHAN ADC_CHANNEL8 + +#define LIMITS_RINGBUF_SIZE 5 +/* HINT: this is compared to a sliding sum not an average! */ +#define LIMITS_TH_CLOSE 800 +#define LIMITS_TH_OPEN 2700 + +void limits_init(void) +{ + ADC_Init(ADC_FREE_RUNNING | ADC_PRESCALE_128); + ADC_SetupChannel(LIMITS_ADC_CHAN_NUM); + ADC_StartReading(ADC_REFERENCE_AVCC | ADC_RIGHT_ADJUSTED | LIMITS_ADC_CHAN); +} + +static uint16_t sum = 0; + +void limits_task(void) +{ + static uint16_t r[LIMITS_RINGBUF_SIZE] = { 0 }; + static uint8_t idx = 0; + + if(ADC_IsReadingComplete()) { + r[idx] = ADC_GetResult(); + idx = (idx + 1) % LIMITS_RINGBUF_SIZE; + cli(); + sum = 0; + uint8_t i; + for(i=0; i<LIMITS_RINGBUF_SIZE; ++i) sum += r[i]; + sei(); + } +} + +limits_t limits_get(void) +{ + if(sum < LIMITS_TH_CLOSE) + return close; + + if(sum < LIMITS_TH_OPEN) + return moving; + + return open; +} + +const char* limits_to_string(limits_t limits) +{ + switch(limits) { + case moving: return "..."; + case open: return "opened"; + case close: return "closed"; + case both: return "error"; + } + return "invalid"; // gcc - shut the fuck up!!! +} diff --git a/tuer-rfid/limits.h b/tuer-rfid/limits.h new file mode 100644 index 0000000..9ea11f9 --- /dev/null +++ b/tuer-rfid/limits.h @@ -0,0 +1,34 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef R3TUER_limits_h_INCLUDED +#define R3TUER_limits_h_INCLUDED + +typedef enum { moving, open, close, both } limits_t; + +void limits_init(void); +void limits_task(void); +limits_t limits_get(void); +const char* limits_to_string(limits_t limits); + +#endif diff --git a/tuer-rfid/manual.c b/tuer-rfid/manual.c new file mode 100644 index 0000000..6d338ba --- /dev/null +++ b/tuer-rfid/manual.c @@ -0,0 +1,61 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <avr/io.h> +#include <stdio.h> +#include "manual.h" +#include "eventqueue.h" + +#define MANUAL_PIN PIND +#define MANUAL_PORT PORTD +#define MANUAL_DDR DDRD +#define MANUAL_BIT 7 + +#define MANUAL_LP_MAX 255 + +void manual_init(void) +{ + MANUAL_DDR = MANUAL_DDR & ~(1<<MANUAL_BIT); + MANUAL_PORT |= (1<<MANUAL_BIT); +} + +void manual_task(void) +{ + static uint8_t last_state = (1<<MANUAL_BIT); + static uint8_t lp_cnt = 0; + + uint8_t state = MANUAL_PIN & (1<<MANUAL_BIT); + if(state != last_state) + lp_cnt++; + else + lp_cnt += lp_cnt ? -1 : 0; + + if(lp_cnt >= MANUAL_LP_MAX) { + if(!state) { + eventqueue_push(btn_toggle); + printf("Info(manual): manual button has been pressed\r\n"); + } + last_state = state; + lp_cnt = 0; + } +} diff --git a/tuer-rfid/manual.h b/tuer-rfid/manual.h new file mode 100644 index 0000000..13cf2be --- /dev/null +++ b/tuer-rfid/manual.h @@ -0,0 +1,30 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef R3TUER_manual_h_INCLUDED +#define R3TUER_manual_h_INCLUDED + +void manual_init(void); +void manual_task(void); + +#endif diff --git a/tuer-rfid/sl018.c b/tuer-rfid/sl018.c new file mode 100644 index 0000000..9ef90f5 --- /dev/null +++ b/tuer-rfid/sl018.c @@ -0,0 +1,245 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "sl018.h" +#include "LUFA/Drivers/Peripheral/TWI.h" +#include <stdio.h> +#include <util/delay.h> + +#define SL018_TWI_ADDR 0xA0 +#define SL018_TAG_STA_PIN PINE +#define SL018_TAG_STA_BIT 6 +#define CARD_PRESENT (!((SL018_TAG_STA_PIN >> SL018_TAG_STA_BIT) & 1)) +#define MAX_UID_LEN 7 + + +const char* SL018_cmd_tostring(const uint8_t cmd) +{ + switch(cmd) { + case 0x01: return "Select Mifare card"; + case 0x02: return "Login to a sector"; + case 0x03: return "Read a data block"; + case 0x04: return "Write a data block"; + case 0x05: return "Read a value block"; + case 0x06: return "Initialize a value block"; + case 0x07: return "Write master key"; + case 0x08: return "Increment value"; + case 0x09: return "Decrement value"; + case 0x0A: return "Copy value"; + case 0x10: return "Read a data page"; + case 0x11: return "Write a data page"; + case 0x40: return "Control the red led"; + case 0xF0: return "Get firmware version"; + case 0xFF: return "Reset"; + default: return "unknown"; + } +} + +const char* SL018_status_tostring(const uint8_t status) +{ + switch(status) { + case 0x0: return "Operation succeed"; + case 0x1: return "No tag"; + case 0x2: return "Login succeed"; + case 0x3: return "Login fail"; + case 0x4: return "Read fail"; + case 0x5: return "Write fail"; + case 0x6: return "Unable to read after write"; + case 0xA: return "Collision occur"; + case 0xC: return "Load key fail"; + case 0xD: return "Not authenticate"; + case 0xE: return "Not a value block"; + default: return "unknown"; + } +} + +const char* SL018_tagtype_tostring(const uint8_t type) +{ + switch(type) { + case 0x1: return "Mifare 1k, 4 byte UID"; + case 0x2: return "Mifare 1k, 7 byte UID"; + case 0x3: return "Mifare Ultralight or NATG203, 7 byte UID"; + case 0x4: return "Mifare 4k, 4 byte UID"; + case 0x5: return "Mifare 4k, 7 byte UID"; + case 0x6: return "Mifare DesFire, 7 byte UID"; + default: return "unknown"; + } +} + +uint8_t SL018_tagtype_to_uidlen(const uint8_t type) +{ + switch(type) { + case 0x1: + case 0x4: return 4; + case 0x2: + case 0x3: + case 0x5: + case 0x6: return 7; + default: return 0; + } +} + +const uint8_t SL018_CMD_ComSelectCard[] = {1,0x01}; +const uint8_t SL018_CMD_ComRedLedOn[] = {2,0x40,1}; +const uint8_t SL018_CMD_ComRedLedOff[] = {2,0x40,0}; +const uint8_t SL018_CMD_ComGetFirmwareVersion[] = {1,0xF0}; +const uint8_t SL018_CMD_ComReset[] = {1,0xFF}; + +uint8_t twi_recv_buf[256]; +typedef struct __attribute__((__packed__)) +{ + uint8_t len; + uint8_t command; + uint8_t status; + uint8_t data[sizeof(twi_recv_buf)-3]; +} sl018_message_t; + +sl018_message_t* twi_recv_msg = (sl018_message_t *)&twi_recv_buf; + + +uint8_t sl018_cmd_raw(const uint8_t* twi_send_buf, bool wait_for_answer) +{ + uint8_t pos = 0; + + if (TWI_StartTransmission(SL018_TWI_ADDR | TWI_ADDRESS_WRITE,10) == TWI_ERROR_NoError) { + for(pos=0; pos<=twi_send_buf[0]; pos++) { + if( ! TWI_SendByte(twi_send_buf[pos])) { + TWI_StopTransmission(); + return 1; + } + } + TWI_StopTransmission(); + } else + return 1; + + if(!wait_for_answer) return 0; + + memset(twi_recv_buf, 0, sizeof(twi_recv_buf)); + _delay_ms(50); + + if (TWI_StartTransmission(SL018_TWI_ADDR | TWI_ADDRESS_READ,10) == TWI_ERROR_NoError) { + TWI_ReceiveByte(twi_recv_buf, 0); + for(pos=1; pos<=twi_recv_buf[0]; pos++) { + if (! TWI_ReceiveByte(&twi_recv_buf[pos], (pos == twi_recv_buf[0]) ? 1:0 ) ) { + TWI_StopTransmission(); + return 1; + } + } + TWI_StopTransmission(); + } else + return 1; + + return 0; +} + +uint8_t sl018_reset(void) +{ + if(sl018_cmd_raw(SL018_CMD_ComReset, 0)) { + printf("Error(i2c): bus error\r\n"); + return 1; + } + return 0; +} + +uint8_t sl018_cmd(const uint8_t* twi_send_buf) +{ + if(sl018_cmd_raw(twi_send_buf, 1)) { + printf("Error(i2c): bus error\r\n"); + return 1; + } else { + if(twi_recv_msg->len < 2) { + printf("Error(SL018): short message received\r\n"); + return 1; + } + if(twi_recv_msg->status) { + printf("Error(SL018): '%s','%s'\r\n",SL018_cmd_tostring(twi_recv_msg->command),SL018_status_tostring(twi_recv_msg->status)); + return 1; + } + sl018_message_t * twi_send_msg = (sl018_message_t *)twi_send_buf; + if(twi_send_msg->command != twi_recv_msg->command) { + printf("Error(SL018): mismatch of sent and received command code: %02X,%02X\r\n",twi_send_msg->command,twi_recv_msg->command); + } + } + return 0; +} + +void sl018_read_card_uid(uid_t * uid) +{ + uid->length=0; + uid->buffer=NULL; + printf( "Info(card): "); + if(!sl018_cmd(SL018_CMD_ComSelectCard)) + { + uint8_t uid_len = twi_recv_msg->len - sizeof(twi_recv_msg->command) - sizeof(twi_recv_msg->status) - 1; + if(uid_len == 255 || uid_len > MAX_UID_LEN) { + printf(" received UID length (%d) is to big for keystore \r\n", uid_len); + return; + } + uint8_t type = twi_recv_msg->data[uid_len]; + uint8_t expected_uid_len = SL018_tagtype_to_uidlen(type); + if(expected_uid_len != uid_len) { + printf(" Invalid uid length (%d) for tag type: %s\r\n", uid_len, SL018_tagtype_tostring(type)); + return; + } + + for (uint8_t pos=0; pos<uid_len; pos++) + printf("%02X",twi_recv_msg->data[uid_len-pos-1]); + printf( ", %s\r\n", SL018_tagtype_tostring(type)); + + if (0 < type && type < 7) { + uid->length= uid_len; + uid->buffer=twi_recv_msg->data; + } else { + printf("Info(card): Ignoring unknown card type %02x\r\n",type); + } + } +} + +void sl018_set_led(uint8_t on) +{ + if(on) + sl018_cmd(SL018_CMD_ComRedLedOn); + else + sl018_cmd(SL018_CMD_ComRedLedOff); +} + +uint8_t sl018_check_for_new_card(void) +{ + static uint8_t card_status = 0; + if(CARD_PRESENT != card_status) { + card_status = CARD_PRESENT; + if(card_status) + return 1; + } + return 0; +} + +unsigned char * sl018_get_firmware_version(void) +{ + if(!sl018_cmd(SL018_CMD_ComGetFirmwareVersion)) { + twi_recv_msg->data[sizeof(twi_recv_msg->data) - 1] = 0; + return twi_recv_msg->data; + } else { + return NULL; + } +} diff --git a/tuer-rfid/sl018.h b/tuer-rfid/sl018.h new file mode 100644 index 0000000..ca7df4b --- /dev/null +++ b/tuer-rfid/sl018.h @@ -0,0 +1,40 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef R3TUER_sl018_h_INCLUDED +#define R3TUER_sl018_h_INCLUDED + +#include <stdint.h> + +typedef struct { + uint8_t length; + unsigned char * buffer; +} uid_t; + +void sl018_set_led(uint8_t on); +uint8_t sl018_check_for_new_card(void); +void sl018_read_card_uid(uid_t * uid); +uint8_t sl018_reset(void); +unsigned char * sl018_get_firmware_version(void); + +#endif diff --git a/tuer-rfid/statemachine.c b/tuer-rfid/statemachine.c new file mode 100644 index 0000000..ce54cc0 --- /dev/null +++ b/tuer-rfid/statemachine.c @@ -0,0 +1,185 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "statemachine.h" +#include "stepper.h" +#include "eventqueue.h" +#include "limits.h" +#include "ledmatrix.h" +#include <stdio.h> + +typedef enum {reset, closed, closing, opened, opening, timeout_after_open, timeout_after_close, error, manual_movement} state_t; +state_t state = reset; + +const char* state_to_string(state_t s) +{ + switch(s) { + case reset: return "reset"; + case error: return "error"; + case closing: return "closing"; + case opening: return "opening"; + case manual_movement: return "manual_movement"; + case timeout_after_open: return "timeout_after_open"; + case timeout_after_close: return "timeout_after_close"; + case closed: return "closed"; + case opened: return "opened"; + } + return "invalid"; // gcc - shut the fuck up!!! +} + +void change_state(state_t new_state) +{ + if (new_state == state) + return; + printf("State: %s\r\n", state_to_string(new_state)); + switch(new_state) { + case reset: + break; + case closed: ledmatrix_set(red); break; + case closing: + ledmatrix_set(red_moving); + stepper_start(dir_close); + break; + case opened: ledmatrix_set(green); break; + case opening: + ledmatrix_set(green_moving); + stepper_start(dir_open); + break; + case timeout_after_open: ledmatrix_set(green_blink); break; + case timeout_after_close: ledmatrix_set(red_blink); break; + case error: ledmatrix_set(rg_blink); break; + case manual_movement: ledmatrix_set(rg_moving); break; + break; + } + state = new_state; +} + +void statemachine_task_limits(void) +{ + limits_t limits = limits_get(); + if (limits == both) + return change_state(error); + + switch(state) { + case reset: + switch(limits) { + case open: + return change_state(opened); + case close: + return change_state(closed); + default: + return change_state(closing); + } + case error: + case closed: + case opened: + switch(limits) { + case open: + return change_state(opened); + case close: + return change_state(closed); + default: + return change_state(manual_movement); + } + case manual_movement: + case timeout_after_open: + case timeout_after_close: + switch(limits) { + case open: + return change_state(opened); + case close: + return change_state(closed); + default: + return; + } + case closing: + break; + case opening: + break; + } +} + +void statemachine_task_event(void) +{ + event_t event = eventqueue_pop(); + if(event == none) + return; + + switch(state) { + case closing: + case opening: + switch(event) { + case open_fin: + return change_state(opened); + case close_fin: + return change_state(closed); + case move_timeout: + return change_state(state==opening?timeout_after_open:timeout_after_close); + default: + printf("Error(state): event %s not allowed in state %s\r\n", event_to_string(event), state_to_string(state)); + return; + } + case reset: + case error: + printf("Error(state): Not accepting commands in state %s\r\n", state_to_string(state)); + break; // Not accepting commands + case manual_movement: + case timeout_after_open: + case timeout_after_close: + case closed: + case opened: + switch(event) { + case none: + return; + case cmd_open: + return change_state(opening); + case cmd_close: + return change_state(closing); + case cmd_toggle: + case btn_toggle: + case card: + return change_state( + (state==closed || state == timeout_after_close) ? + opening: + closing); + case open_fin: + case close_fin: + case move_timeout: + printf("Error(state): event %s not allowed in state %s\r\n", event_to_string(event), state_to_string(state)); + return; + } + } + +} + +void statemachine_task(void) +{ + statemachine_task_limits(); + statemachine_task_event(); +} + +const char* statemachine_get_state_as_string(void) +{ + return state_to_string(state); +} diff --git a/tuer-rfid/statemachine.dot b/tuer-rfid/statemachine.dot new file mode 100644 index 0000000..d581de8 --- /dev/null +++ b/tuer-rfid/statemachine.dot @@ -0,0 +1,45 @@ +digraph G { + reset [shape=box]; + toggle [shape=diamond]; + btn_toggle [shape=diamond]; + cmd_toggle [shape=diamond]; + card [shape=diamond]; + card ->toggle; + btn_toggle ->toggle; + cmd_toggle ->toggle; + all_states [shape=box]; + opened [shape=box]; + closed [shape=box]; + opening [shape=box]; + closing [shape=box]; + timeout_after_open [shape=box]; + timeout_after_close [shape=box]; + manual_movement [shape=box]; + error [shape=box]; + reset -> closed [label="limit_closed"]; + reset -> closing [label="limit_none"]; + reset -> opened [label="limit_opened"]; + error -> closed [label="limit_closed"]; + error -> opened [label="limit_opened"]; + error -> manual_movement [label="limit_none"]; + manual_movement -> opening [label="cmd_open"]; + manual_movement -> closing [label="cmd_close"]; + manual_movement -> closing [label="toggle"]; + opened -> closing [label="cmd_close"]; + opened -> closing [label="toggle"]; + closed -> opening [label="cmd_open"]; + closed -> opening [label="toggle"]; + opening -> opened [label="open_fin"]; + closing -> closed [label="close_fin"]; + closing -> timeout_after_close [label="timeout"]; + opening -> timeout_after_open [label="timeout"]; + timeout_after_open -> closing [label="cmd_close"]; + timeout_after_open -> closing [label="toggle"]; + timeout_after_open -> opened [label="limit_open"]; + timeout_after_open -> closed [label="limit_close"]; + timeout_after_close -> opening [label="cmd_open"]; + timeout_after_close -> opening [label="toggle"]; + timeout_after_close -> opened [label="limit_open"]; + timeout_after_close -> closed [label="limit_close"]; + all_states -> error [label="limit_both"]; +} diff --git a/tuer-rfid/statemachine.h b/tuer-rfid/statemachine.h new file mode 100644 index 0000000..c02a6d4 --- /dev/null +++ b/tuer-rfid/statemachine.h @@ -0,0 +1,30 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef R3TUER_statemachine_h_INCLUDED +#define R3TUER_statemachine_h_INCLUDED + +void statemachine_task(void); +const char* statemachine_get_state_as_string(void); + +#endif diff --git a/tuer-rfid/stepper.c b/tuer-rfid/stepper.c new file mode 100644 index 0000000..b477419 --- /dev/null +++ b/tuer-rfid/stepper.c @@ -0,0 +1,127 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <avr/sfr_defs.h> +#include <avr/interrupt.h> + +#include "stepper.h" +#include "limits.h" +#include "eventqueue.h" + +uint8_t step_table [] = +{ + /* full steps */ + /* 6, // 0110 */ + /* 5, // 0101 */ + /* 9, // 1001 */ + /* 10, // 1010 */ + + /* half steps */ + 2, // 0010 + 6, // 0110 + 4, // 0100 + 5, // 0101 + 1, // 0001 + 9, // 1001 + 8, // 1000 + 10, // 1010 +}; + +#define STEPPER_PORT PORTF +#define STEPPER_DDR DDRF +#define STEPPER_FIRST_BIT 4 +#define STEPPER_ENABLE_A_BIT 0 +#define STEPPER_ENABLE_B_BIT 1 +#define LENGTH_STEP_TABLE (sizeof(step_table)/sizeof(uint8_t)) +#define STEPPER_OUTPUT_BITMASK (~(0xF << STEPPER_FIRST_BIT )) + +volatile uint16_t step_cnt = 0; +#define STEP_CNT_STOP (LENGTH_STEP_TABLE*172) +#define STEP_CNT_STOP_PLUS_EXTRA (STEP_CNT_STOP + (LENGTH_STEP_TABLE*20)) +stepper_direction_t step_direction = dir_open; + +inline void stepper_stop(void) +{ + STEPPER_PORT &= ~(0xF << STEPPER_FIRST_BIT | 1<<STEPPER_ENABLE_A_BIT | 1<<STEPPER_ENABLE_B_BIT); + TCCR1B = 0; // no clock source + TIMSK1 = 0; // disable timer interrupt + + if(step_direction == dir_open) + eventqueue_push(open_fin); + else + eventqueue_push(close_fin); +} + +static inline uint8_t stepper_handle(void) +{ + static uint8_t step_idx = 0; + + uint8_t stepper_output = step_table[step_idx]; + stepper_output <<= STEPPER_FIRST_BIT; + STEPPER_PORT = (STEPPER_PORT & STEPPER_OUTPUT_BITMASK ) | stepper_output; + step_idx += (step_direction == dir_open) ? 1 : -1; + step_idx %= LENGTH_STEP_TABLE; + + if(step_cnt < STEP_CNT_STOP) { + limits_t l = limits_get(); + if((step_direction == dir_open && l == open) || + (step_direction == dir_close && l == close) || l == both) + step_cnt = STEP_CNT_STOP + 1; + + } else if(step_cnt == STEP_CNT_STOP) { + eventqueue_push(move_timeout); + return 0; //stop + } + + step_cnt++; + if(step_cnt >= STEP_CNT_STOP_PLUS_EXTRA) + return 0; //stop + + return 1; // continue running +} + +void stepper_init(void) +{ + STEPPER_PORT &= ~(0xF << STEPPER_FIRST_BIT | 1<<STEPPER_ENABLE_A_BIT | 1<<STEPPER_ENABLE_B_BIT); + STEPPER_DDR |= (0xF << STEPPER_FIRST_BIT) | (1<<STEPPER_ENABLE_A_BIT) | (1<<STEPPER_ENABLE_B_BIT); +} + +uint8_t stepper_start(stepper_direction_t direction) +{ + step_cnt = 0; + step_direction = direction; + STEPPER_PORT |= (1<<STEPPER_ENABLE_A_BIT) | (1<<STEPPER_ENABLE_B_BIT); + TCCR1A = 0; // prescaler 1:256, WGM = 4 (CTC) + TCCR1B = 1<<WGM12 | 1<<CS12; // + OCR1A = 150; + TCNT1 = 0; + TIMSK1 = 1<<OCIE1A; + + return 1; +} + +ISR(TIMER1_COMPA_vect) +{ + if(!stepper_handle()) + stepper_stop(); +} diff --git a/tuer-rfid/stepper.h b/tuer-rfid/stepper.h new file mode 100644 index 0000000..33fe27a --- /dev/null +++ b/tuer-rfid/stepper.h @@ -0,0 +1,32 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef R3TUER_stepper_h_INCLUDED +#define R3TUER_stepper_h_INCLUDED +#include <stdint.h> +typedef enum { dir_open = 0, dir_close = 1 } stepper_direction_t; + +void stepper_init(void); +uint8_t stepper_start(stepper_direction_t direction); + +#endif diff --git a/tuer-rfid/tuer-rfid.c b/tuer-rfid/tuer-rfid.c new file mode 100644 index 0000000..1c540cd --- /dev/null +++ b/tuer-rfid/tuer-rfid.c @@ -0,0 +1,155 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * Othmar Gsenger <otti@wirdorange.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <avr/io.h> +#include <avr/wdt.h> +#include <avr/interrupt.h> +#include <avr/power.h> +#include "LUFA/Drivers/Peripheral/TWI.h" + +#include <stdio.h> +#include <string.h> + +#include "util.h" +#include "led.h" +#include "anyio.h" + +#include "heartbeat.h" +#include "stepper.h" +#include "ledmatrix.h" +#include "sl018.h" +#include "keystore.h" +#include "statemachine.h" +#include "eventqueue.h" +#include "limits.h" +#include "manual.h" +#include "ajar.h" + +void handle_cmd(uint8_t cmd) +{ + switch(cmd) { + case 'r': + reset2bootloader(); + break; + case 'R': + if(!sl018_reset()) + printf("ok\r\n"); + break; + case 'f': { + unsigned char * firmware_str = sl018_get_firmware_version(); + if(firmware_str) + printf("%s\r\n",firmware_str); + + break; + } + case 'e': //flash eeprom + keystore_flash_from_stdio(); + break; + case 'd': //dump eeprom - this breaks security! + keystore_dump_to_stdio(); + break; + case 'o': + eventqueue_push(cmd_open); + break; + case 'c': + eventqueue_push(cmd_close); + break; + case 't': + eventqueue_push(cmd_toggle); + break; + case 's': + printf("Status: %s %s %s\r\n", limits_to_string(limits_get()), statemachine_get_state_as_string(), ajar_to_string(ajar_get())); + break; + /* case '0': ledmatrix_set(off); break; */ + /* case '1': ledmatrix_set(red); break; */ + /* case '2': ledmatrix_set(red_moving); break; */ + /* case '3': ledmatrix_set(red_blink); break; */ + /* case '4': ledmatrix_set(green); break; */ + /* case '5': ledmatrix_set(green_moving); break; */ + /* case '6': ledmatrix_set(green_blink); break; */ + /* case '7': ledmatrix_set(rg_moving); break; */ + /* case '8': ledmatrix_set(rg_blink); break; */ + default: printf("Error(cmd): unknown command %02X '%c'\r\n", cmd, cmd); return; + } +} + +void handle_card(void) +{ + uid_t uid; + sl018_read_card_uid(&uid); + if (uid.length) + { + printf("Info(card): card("); + for (uint8_t pos=0; pos<uid.length; pos++) + printf("%02X",uid.buffer[uid.length-pos-1]); + printf(") "); + + if(keystore_check_card(uid.buffer,uid.length)) { + printf("found - opening/closing door\r\n"); + eventqueue_push(card); + } else { + printf("not found - ignoring\r\n"); + } + } +} + +int main(void) +{ + MCUSR &= ~(1 << WDRF); + wdt_disable(); + + cpu_init(); + jtag_disable(); + led_init(); + anyio_init(115200, false); + TWI_Init(TWI_BIT_PRESCALE_1, TWI_BITLENGTH_FROM_FREQ(1, 200000)); + + heartbeat_init(); + stepper_init(); + ledmatrix_init(); + eventqueue_init(); + limits_init(); + manual_init(); + ajar_init(); + sei(); + + sl018_reset(); + + for(;;) { + statemachine_task(); + + anyio_task(); + manual_task(); + ajar_task(); + limits_task(); + + int16_t bytes_received = anyio_bytes_received(); + if(bytes_received > 0) + handle_cmd(fgetc(stdin)); + + if (sl018_check_for_new_card()) + handle_card(); + + heartbeat_task(); + } +} diff --git a/tuer-rfid/update-keys.c b/tuer-rfid/update-keys.c new file mode 100644 index 0000000..a47e075 --- /dev/null +++ b/tuer-rfid/update-keys.c @@ -0,0 +1,138 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <stdint.h> +#include <ctype.h> +#include <stdio.h> +#include <termios.h> + +#define EEPROM_SIZE 1024 +typedef uint8_t keyslot_t[8]; + +/* this generates a Fletcher8 checksum */ +/* code from: http://stackoverflow.com/questions/13491700/8-bit-fletcher-checksum-of-16-byte-data */ +uint8_t generate_csum(keyslot_t data) +{ + uint16_t sum1 = 0xf, sum2 = 0xf, len = sizeof(keyslot_t)-1; + do { sum2 += ( sum1 += *data++ ); } while (--len); + return sum2<<4 | sum1; +} + +int send_key(keyslot_t key, FILE* dev) +{ + fwrite(key, sizeof(keyslot_t), 1, dev); + fflush(dev); + char tmp; + while(fread(&tmp, 1, 1, dev)) { + fwrite(&tmp, 1, 1, stdout); + if(tmp == 0) return 1; + if(tmp == '.') return 0; + } + return 0; +} + +int main(int argc, char* argv[]) +{ + if(argc<2) { + fprintf(stderr, "Usage: update-keys <device>\n"); + return -1; + } + + FILE* dev; + dev = fopen(argv[1], "r+"); + if(!dev) { + fprintf(stderr, "fopen failed!\n"); + return -2; + } + + int fd = fileno(dev); + struct termios t; + tcgetattr(fd, &t); + t.c_lflag &= ~(ICANON | ECHO); + t.c_iflag &= ~(ICRNL | INLCR | IXON | IXOFF); + cfmakeraw(&t); + tcflush(fd, TCIOFLUSH); + tcsetattr(fd, TCSANOW, &t); + + fprintf(dev, "e"); + + char* line = NULL; + size_t len = 0; + int line_num = 0; + keyslot_t key; + int key_num = 0; + + for(;;) { + ssize_t ret = getline(&line, &len, stdin); + if(ret <= 0) break; + line_num++; + + int i; + for(i=0; i<len; ++i) { + if(!isxdigit(line[i])) { + line[i] = 0; + break; + } + } + if(i & 1 || i == 0 || i > (sizeof(keyslot_t)-1)*2) { + fprintf(stderr, "ignoring invalid key (odd number of digits or empty string or too long) at line %d\n", line_num); + continue; + } + uint8_t tmp[3]; + int j; + tmp[2] = 0; + for(j = 0; j<(i/2); ++j) { + tmp[0] = line[j*2]; + tmp[1] = line[j*2 + 1]; + key[j] = (char)strtoul(tmp, NULL, 16); + } + for(j=i/2; j < sizeof(keyslot_t)-1; ++j) { + key[j] = 0; + } + key[sizeof(keyslot_t)-1] = generate_csum(key); + if(send_key(key, dev)) { + fprintf(stderr, "send_key failed at keyslot %d\n", key_num); + return 1; + } + + key_num++; + if(key_num > EEPROM_SIZE/sizeof(keyslot_t)) { + fprintf(stderr, "reached maximum number of key slots (%d), will ignore remaining keys\n", (int)(EEPROM_SIZE/sizeof(keyslot_t))); + break; + } + } + printf("\nread %d keys from STDIN - filling rest of keystore with invalid keys\n", key_num); + + int i; + for(i=0; i<=sizeof(keyslot_t)-1; ++i) key[i] = 0xFF; + for(i=key_num; i < EEPROM_SIZE/sizeof(keyslot_t); ++i) { + if(send_key(key, dev)) { + fprintf(stderr, "send_key failed at keyslot %d\n", key_num); + return 1; + } + key_num++; + } + + printf("\nwrite of %d keys finished\n", key_num); + + return 0; +} diff --git a/usb-1wire/Makefile b/usb-1wire/Makefile new file mode 100644 index 0000000..44219b4 --- /dev/null +++ b/usb-1wire/Makefile @@ -0,0 +1,46 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := usb-1wire
+BOARD_TYPE := teensy2
+OBJ := $(NAME).o
+LIBS := util led lufa-descriptor-usbserial usbio onewire ds1820
+EXTERNAL_LIBS := lufa
+RESET_FUNC := ../tools/reset_lufa_cdc
+RESET_PARAM := 'r'
+
+LUFA_PATH := ../contrib/LUFA-120219
+LUFA_OPTS = -D USB_DEVICE_ONLY
+LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0
+LUFA_OPTS += -D ORDERED_EP_CONFIG
+LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1
+LUFA_OPTS += -D USE_FLASH_DESCRIPTORS
+LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
+LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT
+
+LUFA_OPTS += -D USB_MANUFACTURER="L\"xro\"" -D USB_MANUFACTURER_LEN=3
+LUFA_OPTS += -D USB_PRODUCT="L\"spreadspace usb-1wire example\"" -D USB_PRODUCT_LEN=29
+
+LUFA_COMPONENTS := USB USBCLASS
+
+include ../include.mk
diff --git a/usb-1wire/usb-1wire.c b/usb-1wire/usb-1wire.c new file mode 100644 index 0000000..a94067c --- /dev/null +++ b/usb-1wire/usb-1wire.c @@ -0,0 +1,168 @@ +/*
+ * spreadspace avr utils - usb-1wire example
+ *
+ *
+ * Copyright (C) 2013-2014 Bernhard Tittelbach <xro@realraum.at>
+ * basically this is refactored and enhanced code from:
+ * http://www.pjrc.com/teensy/td_libs_OneWire.html
+ *
+ * This file is part of spreadspace avr utils.
+ *
+ * spreadspace avr utils is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * spreadspace avr utils is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+#include <avr/io.h>
+#include <avr/wdt.h>
+#include <avr/interrupt.h>
+#include <util/delay.h>
+#include <stdio.h>
+
+#include "util.h"
+#include "led.h"
+#include "usbio.h"
+
+#define MAX_OWI_DEVICES 8
+
+#include "onewire.h"
+#include "ds1820.h"
+
+
+uint8_t owi_addr_[MAX_OWI_DEVICES][8];
+uint8_t num_owi_dev_found_ = 0;
+uint8_t num_temp_sensors_ = 0;
+
+void discoverOWIBus(void)
+{
+ uint8_t d=0;
+ led_on();
+
+ printf("Searching 1W Bus ");
+ num_owi_dev_found_ = 0;
+ if (owi_reset())
+ printf(" !something is there! ");
+ owi_reset_search();
+ _delay_ms(250);
+
+ while ( owi_search(owi_addr_[ d ]))
+ {
+ d++;
+ printf("%d. found, ", d);
+ led_toggle();
+ if ( d >= MAX_OWI_DEVICES)
+ break;
+ }
+ num_owi_dev_found_ = d;
+ printf(" done \r\n");
+ printf("%d devices found\r\n", d);
+
+ for (d=0; d<num_owi_dev_found_; d++)
+ {
+ printf("OW Dev #%d: addr = ", d);
+ for (uint8_t a=0; a<8; a++)
+ printf("%02x ", owi_addr_[d][a]);
+ if (owi_crc8(owi_addr_[d], 7) == owi_addr_[d][7])
+ printf(" CRC OK");
+ else
+ printf(" CRC ERROR");
+ printf("\r\n");
+ }
+ led_off();
+}
+
+void tempToUSB(uint8_t bit_resolution)
+{
+ uint8_t sensor_index = 0;
+ uint16_t raw_temp = 0;
+ double temp=0.0;
+
+ led_on();
+
+ if (num_temp_sensors_ == 0)
+ {
+ printf("No DS1820 sensors ?? running bus discovery... \r\n");
+ num_temp_sensors_ = ds1820_discover();
+ }
+ printf("%d DS18x20 sensors on the bus\r\n", num_temp_sensors_);
+
+ for (sensor_index=0; sensor_index < num_temp_sensors_; sensor_index++)
+ {
+ ds1820_set_resolution(sensor_index, bit_resolution);
+ ds1820_start_measuring(sensor_index);
+ }
+
+ ds1820_wait_conversion_time(bit_resolution);
+
+ for (sensor_index=0; sensor_index < num_temp_sensors_; sensor_index++)
+ {
+ raw_temp = ds1820_read_temperature(sensor_index);
+ printf("DS1820 #%d: ", sensor_index);
+ if (raw_temp == DS1820_ERROR)
+ {
+ printf("CRC comm error\r\n");
+ } else {
+ temp = ds1820_raw_temp_to_celsius( raw_temp );
+ printf("raw: %d, celsius (float): %f, celsius (int): %d.%02d, %d bit resolution\r\n",
+ raw_temp,
+ temp ,
+ raw_temp / 16, (raw_temp <0 ? -1 : 1) * 100 * (raw_temp % 16) / 16,
+ bit_resolution
+ );
+ }
+ }
+ led_off();
+}
+
+
+void handle_cmd(uint8_t cmd)
+{
+ switch(cmd) {
+ case '0': discoverOWIBus(); break;
+ case '1': num_temp_sensors_ = ds1820_discover(); break;
+ case '2': tempToUSB(9); break;
+ case '3': tempToUSB(10); break;
+ case '4': tempToUSB(11); break;
+ case '5': tempToUSB(12); break;
+ case 'r': reset2bootloader(); break;
+ default: printf("error\r\n"); return;
+ }
+ printf("ok\r\n");
+}
+
+int main(void)
+{
+ MCUSR &= ~(1 << WDRF);
+ wdt_disable();
+
+ cpu_init();
+ led_init();
+ usbio_init();
+ sei();
+ owi_init(7, &PINC);
+
+ for(;;)
+ {
+ int16_t BytesReceived = usbio_bytes_received();
+ while(BytesReceived > 0)
+ {
+ int ReceivedByte = fgetc(stdin);
+ if(ReceivedByte != EOF) {
+ handle_cmd(ReceivedByte);
+ }
+ BytesReceived--;
+ }
+
+ usbio_task();
+ }
+}
diff --git a/usb-adc-dustsensor/Makefile b/usb-adc-dustsensor/Makefile new file mode 100644 index 0000000..71133e8 --- /dev/null +++ b/usb-adc-dustsensor/Makefile @@ -0,0 +1,46 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := usb-adc-dustsensor
+BOARD_TYPE := teensy2
+OBJ := $(NAME).o
+LIBS := util led lufa-descriptor-usbserial usbio
+EXTERNAL_LIBS := lufa
+RESET_FUNC := ../tools/reset_lufa_cdc
+RESET_PARAM := 'r'
+
+LUFA_PATH := ../contrib/LUFA-120219
+LUFA_OPTS = -D USB_DEVICE_ONLY
+LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0
+LUFA_OPTS += -D ORDERED_EP_CONFIG
+LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1
+LUFA_OPTS += -D USE_FLASH_DESCRIPTORS
+LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
+LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT
+
+LUFA_OPTS += -D USB_MANUFACTURER="L\"xro\"" -D USB_MANUFACTURER_LEN=3
+LUFA_OPTS += -D USB_PRODUCT="L\"spreadspace usb-adc-dustsensor example\"" -D USB_PRODUCT_LEN=38
+
+LUFA_COMPONENTS := USB USBCLASS
+
+include ../include.mk
diff --git a/usb-adc-dustsensor/usb-adc-dustsensor.c b/usb-adc-dustsensor/usb-adc-dustsensor.c new file mode 100644 index 0000000..a0b9057 --- /dev/null +++ b/usb-adc-dustsensor/usb-adc-dustsensor.c @@ -0,0 +1,116 @@ +/*
+ * spreadspace avr utils
+ *
+ *
+ * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+ *
+ * This file is part of spreadspace avr utils.
+ *
+ * spreadspace avr utils is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * spreadspace avr utils is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+#include <avr/io.h>
+#include <avr/wdt.h>
+#include <avr/interrupt.h>
+#include <avr/power.h>
+#include <util/delay.h>
+
+#include "util.h"
+#include "led.h"
+
+#include "usbio.h"
+#include <stdio.h>
+
+
+// Dustsensor defines:
+#include <LUFA/Drivers/Peripheral/ADC.h>
+
+#define PIN_HIGH(PORT, PIN) PORT |= (1 << PIN)
+#define PIN_LOW(PORT, PIN) PORT &= ~(1 << PIN)
+
+#define OP_SETBIT |=
+#define OP_CLEARBIT &= ~
+#define OP_CHECK &
+#define PIN_SW(PORTDDRREG, PIN, OP) PORTDDRREG OP (1 << PIN)
+
+#define HIGHv OP_SETBIT
+#define LOWv OP_CLEARBIT
+#define DUSTS_LED(OP) PIN_SW(PORTF, PF0, OP)
+
+#define DUSTS_ADC_NUM 1
+#define DUSTS_ADC_MUX_MASK ADC_CHANNEL1
+
+
+void dusts_init(void)
+{
+ DDRF = (1 << PF0);
+ DUSTS_LED(HIGHv);
+ //ADC_Init(ADC_SINGLE_CONVERSION);
+ ADC_Init(ADC_FREE_RUNNING);
+ ADC_SetupChannel (DUSTS_ADC_NUM);
+}
+
+int16_t dusts_measure(void) {
+ DUSTS_LED(LOWv);
+ _delay_us(280);
+
+ //measure ADC
+ int16_t m = ADC_GetChannelReading(ADC_REFERENCE_AVCC | DUSTS_ADC_MUX_MASK);
+
+ _delay_us(40);
+ DUSTS_LED(HIGHv);
+ return m;
+}
+
+
+
+
+
+void handle_cmd(uint8_t cmd)
+{
+ int16_t mv=0;
+ switch(cmd) {
+ case 'm': mv = dusts_measure(); printf("Dust Value: %d\r\n", mv); break;
+ case 'r': reset2bootloader(); break;
+ default: printf("error\r\n"); return;
+ }
+}
+
+int main(void)
+{
+ MCUSR &= ~(1 << WDRF);
+ wdt_disable();
+ led_init();
+ led_on();
+ cpu_init();
+ usbio_init();
+ dusts_init();
+ sei();
+
+ for(;;) {
+ led_off();
+ int16_t BytesReceived = usbio_bytes_received();
+ while(BytesReceived > 0) {
+ int ReceivedByte = fgetc(stdin);
+ if(ReceivedByte != EOF) {
+ handle_cmd(ReceivedByte);
+ }
+ BytesReceived--;
+ }
+ usbio_task();
+ led_on();
+ _delay_ms(100);
+ }
+}
diff --git a/usb-ajar/Makefile b/usb-ajar/Makefile new file mode 100644 index 0000000..9642455 --- /dev/null +++ b/usb-ajar/Makefile @@ -0,0 +1,46 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := usb-ajar
+BOARD_TYPE := minimus32
+OBJ := $(NAME).o
+LIBS := util led lufa-descriptor-usbserial anyio onewire ds1820
+EXTERNAL_LIBS := lufa
+RESET_FUNC := ../tools/reset_lufa_cdc
+RESET_PARAM := 'r'
+
+LUFA_PATH := ../contrib/LUFA-120219
+LUFA_OPTS = -D USB_DEVICE_ONLY
+LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0
+LUFA_OPTS += -D ORDERED_EP_CONFIG
+LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1
+LUFA_OPTS += -D USE_FLASH_DESCRIPTORS
+LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
+LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT
+
+LUFA_OPTS += -D USB_MANUFACTURER="L\"xro\"" -D USB_MANUFACTURER_LEN=3
+LUFA_OPTS += -D USB_PRODUCT="L\"spreadspace usb-ajar example\"" -D USB_PRODUCT_LEN=28
+
+LUFA_COMPONENTS := USB USBCLASS SERIAL
+
+include ../include.mk
diff --git a/usb-ajar/usb-ajar.c b/usb-ajar/usb-ajar.c new file mode 100644 index 0000000..1db377e --- /dev/null +++ b/usb-ajar/usb-ajar.c @@ -0,0 +1,177 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include <avr/io.h> +#include <avr/wdt.h> +#include <util/delay.h> +#include <avr/interrupt.h> +#include <avr/power.h> +#include <stdio.h> + +#include "util.h" +#include "led.h" +#include "anyio.h" + +#include "onewire.h" +#include "ds1820.h" + +#define PIN_HIGH(PORT, PIN) PORT |= (1 << PIN) +#define PIN_LOW(PORT, PIN) PORT &= ~(1 << PIN) +#define PINMODE_OUTPUT PIN_HIGH //just use DDR instead of PORT +#define PINMODE_INPUT PIN_LOW //just use DDR instead of PORT + +#define OP_SETBIT |= +#define OP_CLEARBIT &= ~ +#define OP_CHECK & +#define PIN_SW(PORTDDRREG, PIN, OP) PORTDDRREG OP (1 << PIN) + +#define HIGHv OP_SETBIT +#define LOWv OP_CLEARBIT + +uint8_t num_temp_sensors_ = 0; + +void tempToUSB(uint8_t bit_resolution) +{ + uint8_t sensor_index = 0; + uint16_t raw_temp = 0; + + if (num_temp_sensors_ == 0) + { + printf("No DS1820 sensors ?? running bus discovery... \r\n"); + num_temp_sensors_ = ds1820_discover(); + } + + for (sensor_index=0; sensor_index < num_temp_sensors_; sensor_index++) + { + ds1820_set_resolution(sensor_index, bit_resolution); + ds1820_start_measuring(sensor_index); + } + + ds1820_wait_conversion_time(bit_resolution); + + for (sensor_index=0; sensor_index < num_temp_sensors_; sensor_index++) + { + raw_temp = ds1820_read_temperature(sensor_index); + if (raw_temp == DS1820_ERROR) + { + printf("CRC comm error\r\n"); + } else { + printf("temp%d: %d.%d\r\n", sensor_index +1, raw_temp / 16, 10 * (raw_temp % 16) / 16); + } + } +} + +void handle_cmd(uint8_t cmd) +{ + switch(cmd) { + case 'r': reset2bootloader(); break; + case '1': num_temp_sensors_ = ds1820_discover(); break; + default: printf("error\r\n"); return; + } + printf("ok\r\n"); +} + +int main(void) +{ + /* Disable watchdog if enabled by bootloader/fuses */ + MCUSR &= ~(1 << WDRF); + wdt_disable(); + + cpu_init(); + led_init(); + anyio_init(115200, 0); + sei(); + + PIN_HIGH(PORTB, PINB1); + PINMODE_INPUT(DDRB, PINB1); + PIN_HIGH(PORTB, PINB0); + PINMODE_INPUT(DDRB, PINB0); + PIN_LOW(PORTD, PIND7); + PINMODE_OUTPUT(DDRD, PIND7); + + owi_init(PINC4, &PINC); + + char door_ajar = 0; + char last_door_ajar = 0; + char gas_leak = 0; + char last_gas_leak = 0; + + num_temp_sensors_ = ds1820_discover(); + uint16_t ms_elapsed = 0; + + led_off(); + led2_on(); + + for(;;) { + int16_t BytesReceived = anyio_bytes_received(); + while(BytesReceived > 0) { + int ReceivedByte = fgetc(stdin); + if(ReceivedByte != EOF) { + handle_cmd(ReceivedByte); + } + BytesReceived--; + } + + door_ajar = PINB & _BV(PINB1); + if (door_ajar != last_door_ajar) { + last_door_ajar = door_ajar; + if (door_ajar) { + printf("BackdoorInfo(ajar): ajar\r\n"); + led_off(); + led2_on(); + } else { + printf("BackdoorInfo(ajar): shut\r\n"); + led_off(); + led2_off(); + } + } + gas_leak = ! (PINB & _BV(PINB0)); + if (gas_leak != last_gas_leak) + { + if (gas_leak) + printf("GasLeakAlert\r\n"); + last_gas_leak = gas_leak; + } + + anyio_task(); + if (door_ajar) { + _delay_ms(100); + ms_elapsed += 100; + led_toggle(); + led2_toggle(); + } else + { + _delay_ms(1200); + ms_elapsed += 1200; + led2_toggle(); + } + + if (ms_elapsed & (1<<14)) + { + if (gas_leak) + printf("GasLeakAlert\r\n"); + ms_elapsed = 0; + tempToUSB(12); + } + } +} diff --git a/usb-dual-serial/Makefile b/usb-dual-serial/Makefile new file mode 100644 index 0000000..4efef9f --- /dev/null +++ b/usb-dual-serial/Makefile @@ -0,0 +1,43 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := usb-dual-serial
+BOARD_TYPE := teensy2
+OBJ := $(NAME).o
+LIBS := util led lufa-descriptor-usbdualserial
+EXTERNAL_LIBS := lufa
+RESET_FUNC := ../tools/reset_lufa_cdc
+RESET_PARAM := 'r'
+
+LUFA_PATH := ../contrib/LUFA-120219
+LUFA_OPTS = -D USB_DEVICE_ONLY
+LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1
+LUFA_OPTS += -D USE_FLASH_DESCRIPTORS
+LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
+
+LUFA_OPTS += -D USB_MANUFACTURER="L\"equinox\"" -D USB_MANUFACTURER_LEN=7
+LUFA_OPTS += -D USB_PRODUCT="L\"spreadspace usb-dual-serial example\"" -D USB_PRODUCT_LEN=35
+
+LUFA_COMPONENTS := USB USBCLASS SERIAL
+
+include ../include.mk
diff --git a/usb-dual-serial/usb-dual-serial.c b/usb-dual-serial/usb-dual-serial.c new file mode 100644 index 0000000..a58f278 --- /dev/null +++ b/usb-dual-serial/usb-dual-serial.c @@ -0,0 +1,238 @@ +/*
+ * spreadspace avr utils
+ *
+ *
+ * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+ *
+ * This file is part of spreadspace avr utils.
+ *
+ * spreadspace avr utils is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * spreadspace avr utils is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+#include <avr/io.h>
+#include <avr/wdt.h>
+#include <avr/interrupt.h>
+#include <avr/power.h>
+
+#include "util.h"
+#include "led.h"
+
+/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+#include <LUFA/Drivers/USB/USB.h>
+#include <LUFA/Drivers/Peripheral/Serial.h>
+#include <LUFA/Drivers/Misc/RingBuffer.h>
+#include "lufa-descriptor-usbdualserial.h"
+
+static RingBuffer_t USBtoUSART_Buffer;
+static uint8_t USBtoUSART_Buffer_Data[128];
+static RingBuffer_t USARTtoUSB_Buffer;
+static uint8_t USARTtoUSB_Buffer_Data[128];
+
+USB_ClassInfo_CDC_Device_t VirtualSerial1_CDC_Interface =
+ {
+ .Config =
+ {
+ .ControlInterfaceNumber = 0,
+
+ .DataINEndpointNumber = CDC1_TX_EPNUM,
+ .DataINEndpointSize = CDC_TXRX_EPSIZE,
+ .DataINEndpointDoubleBank = false,
+
+ .DataOUTEndpointNumber = CDC1_RX_EPNUM,
+ .DataOUTEndpointSize = CDC_TXRX_EPSIZE,
+ .DataOUTEndpointDoubleBank = false,
+
+ .NotificationEndpointNumber = CDC1_NOTIFICATION_EPNUM,
+ .NotificationEndpointSize = CDC_NOTIFICATION_EPSIZE,
+ .NotificationEndpointDoubleBank = false,
+ },
+ };
+
+USB_ClassInfo_CDC_Device_t VirtualSerial2_CDC_Interface =
+ {
+ .Config =
+ {
+ .ControlInterfaceNumber = 2,
+
+ .DataINEndpointNumber = CDC2_TX_EPNUM,
+ .DataINEndpointSize = CDC_TXRX_EPSIZE,
+ .DataINEndpointDoubleBank = false,
+
+ .DataOUTEndpointNumber = CDC2_RX_EPNUM,
+ .DataOUTEndpointSize = CDC_TXRX_EPSIZE,
+ .DataOUTEndpointDoubleBank = false,
+
+ .NotificationEndpointNumber = CDC2_NOTIFICATION_EPNUM,
+ .NotificationEndpointSize = CDC_NOTIFICATION_EPSIZE,
+ .NotificationEndpointDoubleBank = false,
+ },
+ };
+
+void EVENT_USB_Device_ConfigurationChanged(void)
+{
+ CDC_Device_ConfigureEndpoints(&VirtualSerial1_CDC_Interface);
+ CDC_Device_ConfigureEndpoints(&VirtualSerial2_CDC_Interface);
+}
+
+void EVENT_USB_Device_ControlRequest(void)
+{
+ CDC_Device_ProcessControlRequest(&VirtualSerial1_CDC_Interface);
+ CDC_Device_ProcessControlRequest(&VirtualSerial2_CDC_Interface);
+}
+
+void EVENT_CDC_Device_LineEncodingChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo)
+{
+ if(CDCInterfaceInfo != &VirtualSerial1_CDC_Interface)
+ return;
+
+ uint8_t ConfigMask = 0;
+
+ switch (CDCInterfaceInfo->State.LineEncoding.ParityType)
+ {
+ case CDC_PARITY_Odd:
+ ConfigMask = ((1 << UPM11) | (1 << UPM10));
+ break;
+ case CDC_PARITY_Even:
+ ConfigMask = (1 << UPM11);
+ break;
+ }
+
+ if (CDCInterfaceInfo->State.LineEncoding.CharFormat == CDC_LINEENCODING_TwoStopBits)
+ ConfigMask |= (1 << USBS1);
+
+ switch (CDCInterfaceInfo->State.LineEncoding.DataBits)
+ {
+ case 6:
+ ConfigMask |= (1 << UCSZ10);
+ break;
+ case 7:
+ ConfigMask |= (1 << UCSZ11);
+ break;
+ case 8:
+ ConfigMask |= ((1 << UCSZ11) | (1 << UCSZ10));
+ break;
+ }
+
+ /* Must turn off USART before reconfiguring it, otherwise incorrect operation may occur */
+ UCSR1B = 0;
+ UCSR1A = 0;
+ UCSR1C = 0;
+
+ /* Set the new baud rate before configuring the USART */
+ UBRR1 = SERIAL_2X_UBBRVAL(CDCInterfaceInfo->State.LineEncoding.BaudRateBPS);
+
+ /* Reconfigure the USART in double speed mode for a wider baud rate range at the expense of accuracy */
+ UCSR1C = ConfigMask;
+ UCSR1A = (1 << U2X1);
+ UCSR1B = ((1 << RXCIE1) | (1 << TXEN1) | (1 << RXEN1));
+}
+
+ISR(USART1_RX_vect, ISR_BLOCK)
+{
+ uint8_t ReceivedByte = UDR1;
+
+ if (USB_DeviceState == DEVICE_STATE_Configured)
+ RingBuffer_Insert(&USARTtoUSB_Buffer, ReceivedByte);
+}
+
+void usbserial_init(void)
+{
+ RingBuffer_InitBuffer(&USBtoUSART_Buffer, USBtoUSART_Buffer_Data, sizeof(USBtoUSART_Buffer_Data));
+ RingBuffer_InitBuffer(&USARTtoUSB_Buffer, USARTtoUSB_Buffer_Data, sizeof(USARTtoUSB_Buffer_Data));
+ TCCR0B = (1 << CS02);
+}
+
+void usbserial_task(void)
+{
+ if (!(RingBuffer_IsFull(&USBtoUSART_Buffer))) {
+ int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial1_CDC_Interface);
+ if (!(ReceivedByte < 0))
+ RingBuffer_Insert(&USBtoUSART_Buffer, ReceivedByte);
+ }
+
+ uint16_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);
+ if ((TIFR0 & (1 << TOV0)) || (BufferCount > (uint8_t)(sizeof(USARTtoUSB_Buffer_Data) * .75))) {
+ TIFR0 |= (1 << TOV0);
+ while (BufferCount--) {
+ if (CDC_Device_SendByte(&VirtualSerial1_CDC_Interface, RingBuffer_Peek(&USARTtoUSB_Buffer)) != ENDPOINT_READYWAIT_NoError)
+ break;
+
+ RingBuffer_Remove(&USARTtoUSB_Buffer);
+ }
+ }
+
+ if (!(RingBuffer_IsEmpty(&USBtoUSART_Buffer)))
+ Serial_SendByte(RingBuffer_Remove(&USBtoUSART_Buffer));
+}
+/* end LUFA CDC-ACM specific definitions*/
+
+
+
+FILE usb_stream;
+
+void stdio_init(void)
+{
+ CDC_Device_CreateStream(&VirtualSerial2_CDC_Interface, &usb_stream);
+ stdin = &usb_stream;
+ stdout = &usb_stream;
+ stderr = &usb_stream;
+}
+
+void handle_cmd(uint8_t cmd)
+{
+ switch(cmd) {
+ case '0': led_off(); break;
+ case '1': led_on(); break;
+ case 't': led_toggle(); break;
+ case 'r': reset2bootloader(); break;
+ default: printf("unknown command\r\n"); return;
+ }
+ printf("ok\r\n");
+}
+
+int main(void)
+{
+ MCUSR &= ~(1 << WDRF);
+ wdt_disable();
+
+ cpu_init();
+ led_init();
+ USB_Init();
+ stdio_init();
+ usbserial_init();
+ sei();
+
+ for(;;) {
+ int16_t BytesReceived = CDC_Device_BytesReceived(&VirtualSerial2_CDC_Interface);
+ while(BytesReceived > 0) {
+ int ReceivedByte = fgetc(stdin);
+ if(ReceivedByte != EOF) {
+ handle_cmd(ReceivedByte);
+ }
+ BytesReceived--;
+ }
+
+ usbserial_task();
+ CDC_Device_USBTask(&VirtualSerial1_CDC_Interface);
+ CDC_Device_USBTask(&VirtualSerial2_CDC_Interface);
+ USB_USBTask();
+ }
+}
diff --git a/usb-eth/Makefile b/usb-eth/Makefile new file mode 100644 index 0000000..9630145 --- /dev/null +++ b/usb-eth/Makefile @@ -0,0 +1,42 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := usb-eth
+BOARD_TYPE := teensy2
+OBJ := $(NAME).o
+LIBS := util led lufa-descriptor-rndis
+EXTERNAL_LIBS := lufa
+
+LUFA_PATH := ../contrib/LUFA-120219
+
+LUFA_OPTS = -D USB_DEVICE_ONLY
+LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1
+LUFA_OPTS += -D USE_FLASH_DESCRIPTORS
+LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
+
+LUFA_OPTS += -D USB_MANUFACTURER="L\"equinox\"" -D USB_MANUFACTURER_LEN=7
+LUFA_OPTS += -D USB_PRODUCT="L\"spreadspace usb-eth example\"" -D USB_PRODUCT_LEN=27
+
+LUFA_COMPONENTS := USB USBCLASS
+
+include ../include.mk
diff --git a/usb-eth/usb-eth.c b/usb-eth/usb-eth.c new file mode 100644 index 0000000..71e4a3b --- /dev/null +++ b/usb-eth/usb-eth.c @@ -0,0 +1,133 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <avr/io.h> +#include <avr/wdt.h> +#include <avr/interrupt.h> +#include <avr/power.h> +#include <string.h> + +#include "util.h" +#include "led.h" + +/* + LUFA Library + Copyright (C) Dean Camera, 2012. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ +#include <LUFA/Version.h> +#include <LUFA/Drivers/USB/USB.h> +#include "lufa-descriptor-rndis.h" + +#define ADAPTER_MAC_ADDR {0x02, 0x00, 0x02, 0x00, 0x02, 0x00} +#define MY_MAC_ADDR {0x01, 0x02, 0x03, 0x04, 0x05, 0x06} + +/** LUFA RNDIS Class driver interface configuration and state information. This structure is + * passed to all RNDIS Class driver functions, so that multiple instances of the same class + * within a device can be differentiated from one another. + */ +USB_ClassInfo_RNDIS_Device_t Ethernet_RNDIS_Interface = + { + .Config = + { + .ControlInterfaceNumber = 0, + + .DataINEndpointNumber = CDC_TX_EPNUM, + .DataINEndpointSize = CDC_TXRX_EPSIZE, + .DataINEndpointDoubleBank = false, + + .DataOUTEndpointNumber = CDC_RX_EPNUM, + .DataOUTEndpointSize = CDC_TXRX_EPSIZE, + .DataOUTEndpointDoubleBank = false, + + .NotificationEndpointNumber = CDC_NOTIFICATION_EPNUM, + .NotificationEndpointSize = CDC_NOTIFICATION_EPSIZE, + .NotificationEndpointDoubleBank = false, + + .AdapterVendorDescription = "LUFA RNDIS Adapter", + .AdapterMACAddress = {ADAPTER_MAC_ADDR}, + }, + }; + +/** Event handler for the library USB Configuration Changed event. */ +void EVENT_USB_Device_ConfigurationChanged(void) +{ + RNDIS_Device_ConfigureEndpoints(&Ethernet_RNDIS_Interface); +} + +/** Event handler for the library USB Control Request reception event. */ +void EVENT_USB_Device_ControlRequest(void) +{ + RNDIS_Device_ProcessControlRequest(&Ethernet_RNDIS_Interface); +} + +/* end LUFA RNDIS Class driver specific definitions*/ + + +typedef uint8_t mac_addr_t[6]; +typedef struct __attribute__((__packed__)) +{ + mac_addr_t dest; + mac_addr_t src; + uint16_t ether_type; +} ethernet_frame_header_t; + +typedef struct { + uint8_t data[1550]; + uint16_t len; +} ethernet_buf_t; + +ethernet_buf_t eth_recv_buf; +ethernet_frame_header_t* eth_recv_hdr = (ethernet_frame_header_t*)eth_recv_buf.data; +mac_addr_t my_mac = MY_MAC_ADDR; + + +int main(void) +{ + MCUSR &= ~(1 << WDRF); + wdt_disable(); + + cpu_init(); + led_init(); + USB_Init(); + sei(); + + led_off(); + for (;;) { + if (RNDIS_Device_IsPacketReceived(&Ethernet_RNDIS_Interface)) + { + led_on(); + RNDIS_Device_ReadPacket(&Ethernet_RNDIS_Interface, eth_recv_buf.data, &(eth_recv_buf.len)); + + memcpy(eth_recv_hdr->dest, eth_recv_hdr->src, sizeof(mac_addr_t)); + memcpy(eth_recv_hdr->src, my_mac, sizeof(mac_addr_t)); + + RNDIS_Device_SendPacket(&Ethernet_RNDIS_Interface, eth_recv_buf.data, eth_recv_buf.len); + led_off(); + } + + RNDIS_Device_USBTask(&Ethernet_RNDIS_Interface); + USB_USBTask(); + } +} diff --git a/usb-freq/Makefile b/usb-freq/Makefile new file mode 100644 index 0000000..40bcabc --- /dev/null +++ b/usb-freq/Makefile @@ -0,0 +1,46 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := usb-freq
+BOARD_TYPE := teensy2
+OBJ := $(NAME).o
+LIBS := util led lufa-descriptor-usbserial usbio
+EXTERNAL_LIBS := lufa
+RESET_FUNC := ../tools/reset_lufa_cdc
+RESET_PARAM := 'r'
+
+LUFA_PATH := ../contrib/LUFA-120219
+LUFA_OPTS = -D USB_DEVICE_ONLY
+LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0
+LUFA_OPTS += -D ORDERED_EP_CONFIG
+LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1
+LUFA_OPTS += -D USE_FLASH_DESCRIPTORS
+LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
+LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT
+
+LUFA_OPTS += -D USB_MANUFACTURER="L\"equinox\"" -D USB_MANUFACTURER_LEN=7
+LUFA_OPTS += -D USB_PRODUCT="L\"spreadspace usb-freq example\"" -D USB_PRODUCT_LEN=28
+
+LUFA_COMPONENTS := USB USBCLASS
+
+include ../include.mk
diff --git a/usb-freq/usb-freq.c b/usb-freq/usb-freq.c new file mode 100644 index 0000000..b2dc1b0 --- /dev/null +++ b/usb-freq/usb-freq.c @@ -0,0 +1,68 @@ +/*
+ * spreadspace avr utils
+ *
+ *
+ * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+ *
+ * This file is part of spreadspace avr utils.
+ *
+ * spreadspace avr utils is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * spreadspace avr utils is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+#include <avr/io.h>
+#include <avr/wdt.h>
+#include <avr/interrupt.h>
+#include <avr/power.h>
+#include <stdio.h>
+
+#include "util.h"
+#include "led.h"
+#include "usbio.h"
+
+void handle_cmd(uint8_t cmd)
+{
+ switch(cmd) {
+ case '0': led_off(); break;
+ case '1': led_on(); break;
+ case 't': led_toggle(); break;
+ case 'r': reset2bootloader(); break;
+ default: printf("error\r\n"); return;
+ }
+ printf("ok\r\n");
+}
+
+int main(void)
+{
+ MCUSR &= ~(1 << WDRF);
+ wdt_disable();
+
+ cpu_init();
+ led_init();
+ usbio_init();
+ sei();
+
+ for(;;) {
+ int16_t BytesReceived = usbio_bytes_received();
+ while(BytesReceived > 0) {
+ int ReceivedByte = fgetc(stdin);
+ if(ReceivedByte != EOF) {
+ handle_cmd(ReceivedByte);
+ }
+ BytesReceived--;
+ }
+
+ usbio_task();
+ }
+}
diff --git a/usb-keyboardmouse/Makefile b/usb-keyboardmouse/Makefile new file mode 100644 index 0000000..659e618 --- /dev/null +++ b/usb-keyboardmouse/Makefile @@ -0,0 +1,41 @@ +## +## spreadspace avr utils +## +## +## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> +## +## This file is part of spreadspace avr utils. +## +## spreadspace avr utils is free software: you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation, either version 3 of the License, or +## any later version. +## +## spreadspace avr utils is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. +## + +NAME := usb-keyboardmouse +BOARD_TYPE := teensy2 +OBJ := $(NAME).o +LIBS := util led lufa-descriptor-keyboardmouse +EXTERNAL_LIBS := lufa + +LUFA_PATH := ../contrib/LUFA-120219 +LUFA_OPTS = -D USB_DEVICE_ONLY +LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8 +LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1 +LUFA_OPTS += -D USE_FLASH_DESCRIPTORS +LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)" + +LUFA_OPTS += -D USB_MANUFACTURER="L\"equinox\"" -D USB_MANUFACTURER_LEN=7 +LUFA_OPTS += -D USB_PRODUCT="L\"spreadspace usb-keyboardmouse example\"" -D USB_PRODUCT_LEN=37 + +LUFA_COMPONENTS := USB USBCLASS SERIAL + +include ../include.mk diff --git a/usb-keyboardmouse/usb-keyboardmouse.c b/usb-keyboardmouse/usb-keyboardmouse.c new file mode 100644 index 0000000..dd1ea4d --- /dev/null +++ b/usb-keyboardmouse/usb-keyboardmouse.c @@ -0,0 +1,220 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include <avr/io.h> +#include <avr/wdt.h> +#include <avr/interrupt.h> +#include <avr/power.h> +#include <stdio.h> + +#include "util.h" +#include "led.h" + +/* + LUFA Library + Copyright (C) Dean Camera, 2012. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ +#include <LUFA/Drivers/USB/USB.h> +#include "LUFA/Drivers/Peripheral/Serial.h" +#include <LUFA/Drivers/Misc/RingBuffer.h> +#include "lufa-descriptor-keyboardmouse.h" + +static uint8_t PrevKeyboardHIDReportBuffer[sizeof(USB_KeyboardReport_Data_t)]; +static uint8_t PrevMouseHIDReportBuffer[sizeof(USB_MouseReport_Data_t)]; + +USB_ClassInfo_HID_Device_t Keyboard_HID_Interface = + { + .Config = + { + .InterfaceNumber = 0, + + .ReportINEndpointNumber = KEYBOARD_IN_EPNUM, + .ReportINEndpointSize = HID_EPSIZE, + .ReportINEndpointDoubleBank = false, + + .PrevReportINBuffer = PrevKeyboardHIDReportBuffer, + .PrevReportINBufferSize = sizeof(PrevKeyboardHIDReportBuffer), + }, + }; + +USB_ClassInfo_HID_Device_t Mouse_HID_Interface = + { + .Config = + { + .InterfaceNumber = 1, + + .ReportINEndpointNumber = MOUSE_IN_EPNUM, + .ReportINEndpointSize = HID_EPSIZE, + + .PrevReportINBuffer = PrevMouseHIDReportBuffer, + .PrevReportINBufferSize = sizeof(PrevMouseHIDReportBuffer), + }, + }; + + +void EVENT_USB_Device_ConfigurationChanged(void) +{ + HID_Device_ConfigureEndpoints(&Keyboard_HID_Interface); + HID_Device_ConfigureEndpoints(&Mouse_HID_Interface); + + USB_Device_EnableSOFEvents(); +} + +/** Event handler for the library USB Control Request reception event. */ +void EVENT_USB_Device_ControlRequest(void) +{ + HID_Device_ProcessControlRequest(&Keyboard_HID_Interface); + HID_Device_ProcessControlRequest(&Mouse_HID_Interface); +} + +/** Event handler for the USB device Start Of Frame event. */ +void EVENT_USB_Device_StartOfFrame(void) +{ + HID_Device_MillisecondElapsed(&Keyboard_HID_Interface); + HID_Device_MillisecondElapsed(&Mouse_HID_Interface); +} +/* end LUFA CDC-ACM specific definitions*/ + +FILE serial_stream; +static RingBuffer_t keyboard_buffer; +static uint8_t keyboard_buffer_data[16]; +static RingBuffer_t mouse_buffer; +static uint8_t mouse_buffer_data[16]; + +bool CALLBACK_HID_Device_CreateHIDReport(USB_ClassInfo_HID_Device_t* const HIDInterfaceInfo, + uint8_t* const ReportID, + const uint8_t ReportType, + void* ReportData, + uint16_t* const ReportSize) +{ + + if (HIDInterfaceInfo == &Keyboard_HID_Interface) { + USB_KeyboardReport_Data_t* KeyboardReport = (USB_KeyboardReport_Data_t*)ReportData; + + if(!RingBuffer_IsEmpty(&keyboard_buffer)) { + uint8_t received_byte = RingBuffer_Remove(&keyboard_buffer); + switch(received_byte) { + case '1': KeyboardReport->KeyCode[0] = HID_KEYBOARD_SC_1_AND_EXCLAMATION; break; + case '2': KeyboardReport->KeyCode[0] = HID_KEYBOARD_SC_2_AND_AT; break; + case '3': KeyboardReport->KeyCode[0] = HID_KEYBOARD_SC_3_AND_HASHMARK; break; + case '4': KeyboardReport->KeyCode[0] = HID_KEYBOARD_SC_4_AND_DOLLAR; break; + case 'c': KeyboardReport->KeyCode[0] = HID_KEYBOARD_SC_CAPS_LOCK; break; + default: return 0; // no key has been pressed - just return + } + } +// KeyboardReport->Modifier = HID_KEYBOARD_MODIFIER_LEFTSHIFT; + + *ReportSize = sizeof(USB_KeyboardReport_Data_t); + return false; + + } + else + { + USB_MouseReport_Data_t* MouseReport = (USB_MouseReport_Data_t*)ReportData; + + MouseReport->Y = 0; + MouseReport->X = 0; + if(!RingBuffer_IsEmpty(&mouse_buffer)) { + uint8_t received_byte = RingBuffer_Remove(&mouse_buffer); + switch(received_byte) { + case 'w': MouseReport->Y = -1; break; // UP + case 's': MouseReport->Y = 1; break; // DOWN + case 'a': MouseReport->X = -1; break; // LEFT + case 'd': MouseReport->X = 1; break; // RIGHT + case 'q': MouseReport->Button |= (1 << 0); break; // Button 1 + case 'e': MouseReport->Button |= (1 << 1); break; // Button 2 + } + } + *ReportSize = sizeof(USB_MouseReport_Data_t); + return true; + } +} + +void CALLBACK_HID_Device_ProcessHIDReport(USB_ClassInfo_HID_Device_t* const HIDInterfaceInfo, + const uint8_t ReportID, + const uint8_t ReportType, + const void* ReportData, + const uint16_t ReportSize) +{ + if (HIDInterfaceInfo == &Keyboard_HID_Interface) + { + uint8_t* LEDReport = (uint8_t*)ReportData; + + /* if (*LEDReport & HID_KEYBOARD_LED_NUMLOCK) */ + /* // do something */ + + if (*LEDReport & HID_KEYBOARD_LED_CAPSLOCK) + led_on(); + else + led_off(); + + /* if (*LEDReport & HID_KEYBOARD_LED_SCROLLLOCK) */ + /* // do something */ + } +} + +int main(void) +{ + MCUSR &= ~(1 << WDRF); + wdt_disable(); + + cpu_init(); + led_init(); + USB_Init(); + + Serial_Init(115200, false); + Serial_CreateStream(&serial_stream); + stdin = stdout = stderr = &serial_stream; + RingBuffer_InitBuffer(&keyboard_buffer, keyboard_buffer_data, sizeof(keyboard_buffer_data)); + RingBuffer_InitBuffer(&mouse_buffer, mouse_buffer_data, sizeof(mouse_buffer_data)); + + sei(); + + for(;;) { + if(Serial_IsCharReceived()) { + int received_byte = fgetc(stdin); + switch(received_byte) { + case '1': + case '2': + case '3': + case '4': + case 'c': + RingBuffer_Insert(&keyboard_buffer, (uint8_t)received_byte); break; + case 'w': + case 's': + case 'a': + case 'd': + case 'q': + case 'e': + RingBuffer_Insert(&mouse_buffer, (uint8_t)received_byte); break; + } + } + + HID_Device_USBTask(&Keyboard_HID_Interface); + HID_Device_USBTask(&Mouse_HID_Interface); + USB_USBTask(); + } +} diff --git a/usb-led/Makefile b/usb-led/Makefile new file mode 100644 index 0000000..e3b0b57 --- /dev/null +++ b/usb-led/Makefile @@ -0,0 +1,46 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := usb-led
+BOARD_TYPE := teenstep
+OBJ := $(NAME).o
+LIBS := util led lufa-descriptor-usbserial usbio
+EXTERNAL_LIBS := lufa
+RESET_FUNC := ../tools/reset_lufa_cdc
+RESET_PARAM := 'r'
+
+LUFA_PATH := ../contrib/LUFA-120219
+LUFA_OPTS = -D USB_DEVICE_ONLY
+LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0
+LUFA_OPTS += -D ORDERED_EP_CONFIG
+LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1
+LUFA_OPTS += -D USE_FLASH_DESCRIPTORS
+LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
+LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT
+
+LUFA_OPTS += -D USB_MANUFACTURER="L\"equinox\"" -D USB_MANUFACTURER_LEN=7
+LUFA_OPTS += -D USB_PRODUCT="L\"spreadspace usb-led example\"" -D USB_PRODUCT_LEN=27
+
+LUFA_COMPONENTS := USB USBCLASS
+
+include ../include.mk
diff --git a/usb-led/usb-led.c b/usb-led/usb-led.c new file mode 100644 index 0000000..b2dc1b0 --- /dev/null +++ b/usb-led/usb-led.c @@ -0,0 +1,68 @@ +/*
+ * spreadspace avr utils
+ *
+ *
+ * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+ *
+ * This file is part of spreadspace avr utils.
+ *
+ * spreadspace avr utils is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * spreadspace avr utils is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+#include <avr/io.h>
+#include <avr/wdt.h>
+#include <avr/interrupt.h>
+#include <avr/power.h>
+#include <stdio.h>
+
+#include "util.h"
+#include "led.h"
+#include "usbio.h"
+
+void handle_cmd(uint8_t cmd)
+{
+ switch(cmd) {
+ case '0': led_off(); break;
+ case '1': led_on(); break;
+ case 't': led_toggle(); break;
+ case 'r': reset2bootloader(); break;
+ default: printf("error\r\n"); return;
+ }
+ printf("ok\r\n");
+}
+
+int main(void)
+{
+ MCUSR &= ~(1 << WDRF);
+ wdt_disable();
+
+ cpu_init();
+ led_init();
+ usbio_init();
+ sei();
+
+ for(;;) {
+ int16_t BytesReceived = usbio_bytes_received();
+ while(BytesReceived > 0) {
+ int ReceivedByte = fgetc(stdin);
+ if(ReceivedByte != EOF) {
+ handle_cmd(ReceivedByte);
+ }
+ BytesReceived--;
+ }
+
+ usbio_task();
+ }
+}
diff --git a/usb-midi/Makefile b/usb-midi/Makefile new file mode 100644 index 0000000..c52a24d --- /dev/null +++ b/usb-midi/Makefile @@ -0,0 +1,44 @@ +## +## spreadspace avr utils +## +## +## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> +## +## This file is part of spreadspace avr utils. +## +## spreadspace avr utils is free software: you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation, either version 3 of the License, or +## any later version. +## +## spreadspace avr utils is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. +## + +NAME := usb-midi +BOARD_TYPE := rhmixxx +OBJ := $(NAME).o +LIBS := util led lufa-descriptor-midi +EXTERNAL_LIBS := lufa + +LUFA_PATH := ../contrib/LUFA-120219 +LUFA_OPTS = -D USB_DEVICE_ONLY +LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0 +LUFA_OPTS += -D ORDERED_EP_CONFIG +LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8 +LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1 +LUFA_OPTS += -D USE_FLASH_DESCRIPTORS +LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)" +LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT + +LUFA_OPTS += -D USB_MANUFACTURER="L\"Radio Helsinki\"" -D USB_MANUFACTURER_LEN=14 +LUFA_OPTS += -D USB_PRODUCT="L\"rhmixxx midi controller\"" -D USB_PRODUCT_LEN=23 + +LUFA_COMPONENTS := USB USBCLASS SERIAL + +include ../include.mk diff --git a/usb-midi/usb-midi.c b/usb-midi/usb-midi.c new file mode 100644 index 0000000..7b8d68c --- /dev/null +++ b/usb-midi/usb-midi.c @@ -0,0 +1,158 @@ +/* + * spreadspace avr utils + * + * + * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org> + * + * This file is part of spreadspace avr utils. + * + * spreadspace avr utils is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * spreadspace avr utils is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include <avr/io.h> +#include <avr/wdt.h> +#include <avr/interrupt.h> +#include <avr/power.h> +#include <stdio.h> + +/* + LUFA Library + Copyright (C) Dean Camera, 2012. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ +#include <LUFA/Version.h> +#include <LUFA/Drivers/USB/USB.h> +#include "lufa-descriptor-midi.h" +#include "LUFA/Drivers/Peripheral/Serial.h" + +/** LUFA MIDI Class driver interface configuration and state information. This structure is + * passed to all MIDI Class driver functions, so that multiple instances of the same class + * within a device can be differentiated from one another. + */ +USB_ClassInfo_MIDI_Device_t Keyboard_MIDI_Interface = + { + .Config = + { + .StreamingInterfaceNumber = 1, + + .DataINEndpointNumber = MIDI_STREAM_IN_EPNUM, + .DataINEndpointSize = MIDI_STREAM_EPSIZE, + .DataINEndpointDoubleBank = false, + + .DataOUTEndpointNumber = MIDI_STREAM_OUT_EPNUM, + .DataOUTEndpointSize = MIDI_STREAM_EPSIZE, + .DataOUTEndpointDoubleBank = false, + }, + }; + +/** Event handler for the library USB Configuration Changed event. */ +void EVENT_USB_Device_ConfigurationChanged(void) +{ + bool ConfigSuccess = true; + + ConfigSuccess &= MIDI_Device_ConfigureEndpoints(&Keyboard_MIDI_Interface); +} + +/** Event handler for the library USB Control Request reception event. */ +void EVENT_USB_Device_ControlRequest(void) +{ + MIDI_Device_ProcessControlRequest(&Keyboard_MIDI_Interface); +} + +/* end LUFA MIDI Class driver specific definitions*/ + +#include "util.h" +#include "led.h" + +static FILE serial_stream; + +#define KEY_PIN PINA +#define KEY_PORT PORTA +#define KEY_DDR DDRA +#define KEY_BIT 0 + +#define KEY_LP_MAX 255 + +void key_init(void) +{ + KEY_DDR = 0x10; + KEY_PORT = 0xEF; +} + +int main(void) +{ + MCUSR &= ~(1 << WDRF); + wdt_disable(); + + cpu_init(); + led_init(); + key_init(); + + Serial_Init(38400, 0); + Serial_CreateStream(&serial_stream); + stdin = stdout = stderr = &serial_stream; + + USB_Init(); + sei(); + + MIDI_EventPacket_t MIDIEventOn = (MIDI_EventPacket_t) + { + .CableNumber = 0, + .Command = (MIDI_COMMAND_NOTE_ON >> 4), + .Data1 = MIDI_COMMAND_NOTE_ON | 0, + .Data2 = 0, + .Data3 = 0x7F, + }; + MIDI_EventPacket_t MIDIEventOff = (MIDI_EventPacket_t) + { + .CableNumber = 0, + .Command = (MIDI_COMMAND_NOTE_OFF >> 4), + .Data1 = MIDI_COMMAND_NOTE_OFF | 0, + .Data2 = 0, + .Data3 = 0, + }; + + static uint8_t last_state = (1<<KEY_BIT); + static uint8_t lp_cnt = 0; + for(;;) { + + MIDI_EventPacket_t ReceivedMIDIEvent; + while(MIDI_Device_ReceiveEventPacket(&Keyboard_MIDI_Interface, &ReceivedMIDIEvent)) { + led_on(); + printf("%02X %02X %02X\r\n", ReceivedMIDIEvent.Data1, ReceivedMIDIEvent.Data2, ReceivedMIDIEvent.Data3); + led_off(); + } + + uint8_t state = KEY_PIN & (1<<KEY_BIT); + if(state != last_state) + lp_cnt++; + else + lp_cnt += lp_cnt ? -1 : 0; + + if(lp_cnt >= KEY_LP_MAX) { + MIDI_EventPacket_t* MIDIEvent = state ? &MIDIEventOff : &MIDIEventOn; + MIDI_Device_SendEventPacket(&Keyboard_MIDI_Interface, MIDIEvent); + MIDI_Device_Flush(&Keyboard_MIDI_Interface); + + last_state = state; + lp_cnt = 0; + } + + MIDI_Device_USBTask(&Keyboard_MIDI_Interface); + USB_USBTask(); + } +} diff --git a/usb-pwm/Makefile b/usb-pwm/Makefile new file mode 100644 index 0000000..85ba3c8 --- /dev/null +++ b/usb-pwm/Makefile @@ -0,0 +1,46 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := usb-pwm
+BOARD_TYPE := teensy2
+OBJ := $(NAME).o
+LIBS := util led lufa-descriptor-usbserial usbio
+EXTERNAL_LIBS := lufa
+RESET_FUNC := ../tools/reset_lufa_cdc
+RESET_PARAM := 'r'
+
+LUFA_PATH := ../contrib/LUFA-120219
+LUFA_OPTS = -D USB_DEVICE_ONLY
+LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0
+LUFA_OPTS += -D ORDERED_EP_CONFIG
+LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1
+LUFA_OPTS += -D USE_FLASH_DESCRIPTORS
+LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
+LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT
+
+LUFA_OPTS += -D USB_MANUFACTURER="L\"equinox\"" -D USB_MANUFACTURER_LEN=7
+LUFA_OPTS += -D USB_PRODUCT="L\"spreadspace usb-pwm example\"" -D USB_PRODUCT_LEN=27
+
+LUFA_COMPONENTS := USB USBCLASS
+
+include ../include.mk
diff --git a/usb-pwm/usb-pwm.c b/usb-pwm/usb-pwm.c new file mode 100644 index 0000000..a6fe2ad --- /dev/null +++ b/usb-pwm/usb-pwm.c @@ -0,0 +1,112 @@ +/*
+ * spreadspace avr utils
+ *
+ *
+ * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+ *
+ * This file is part of spreadspace avr utils.
+ *
+ * spreadspace avr utils is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * spreadspace avr utils is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+#include <avr/io.h>
+#include <avr/wdt.h>
+#include <avr/interrupt.h>
+#include <avr/power.h>
+#include <stdio.h>
+
+#include "util.h"
+#include "led.h"
+#include "usbio.h"
+
+
+#define PWM_VAL OCR1BL
+
+void pwm_init(void)
+{
+ DDRB |= (1<<PB6);
+ TCCR1B = 0;
+ TCNT1 = 0;
+ OCR1B = 0;
+ TCCR1A = (1<<COM1B1) | (1<<WGM10);
+ TCCR1B = (1<<WGM12);
+}
+
+inline void pwm_on(void)
+{
+ TCCR1B = (TCCR1B & 0xF8) | (1<<CS10);
+}
+
+inline void pwm_off(void)
+{
+ TCCR1B = (TCCR1B & 0xF8);
+ TCNT1 = 0;
+}
+
+inline void pwm_set(uint8_t val)
+{
+ PWM_VAL = val;
+}
+
+inline void pwm_inc(void)
+{
+ if(PWM_VAL < 255)
+ PWM_VAL++;
+}
+
+inline void pwm_dec(void)
+{
+ if(PWM_VAL > 0)
+ PWM_VAL--;
+}
+
+
+void handle_cmd(uint8_t cmd)
+{
+ switch(cmd) {
+ case '0': pwm_off(); led_off(); printf("ok\r\n"); break;
+ case '1': pwm_on(); led_on(); printf("ok\r\n"); break;
+ case '+': pwm_inc(); printf("pwm = %d\r\n", PWM_VAL); break;
+ case '-': pwm_dec(); printf("pwm = %d\r\n", PWM_VAL); break;
+ case 'r': reset2bootloader(); break;
+ default: printf("error\r\n"); return;
+ }
+
+}
+
+int main(void)
+{
+ MCUSR &= ~(1 << WDRF);
+ wdt_disable();
+
+ cpu_init();
+ led_init();
+ usbio_init();
+ pwm_init();
+ sei();
+
+ for(;;) {
+ int16_t BytesReceived = usbio_bytes_received();
+ while(BytesReceived > 0) {
+ int ReceivedByte = fgetc(stdin);
+ if(ReceivedByte != EOF) {
+ handle_cmd(ReceivedByte);
+ }
+ BytesReceived--;
+ }
+
+ usbio_task();
+ }
+}
diff --git a/usb-serial/Makefile b/usb-serial/Makefile new file mode 100644 index 0000000..6cde62d --- /dev/null +++ b/usb-serial/Makefile @@ -0,0 +1,44 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := usb-serial
+BOARD_TYPE := slowpandongle2
+OBJ := $(NAME).o
+LIBS := util led lufa-descriptor-usbserial
+EXTERNAL_LIBS := lufa
+
+LUFA_PATH := ../contrib/LUFA-120219
+LUFA_OPTS = -D USB_DEVICE_ONLY
+LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0
+LUFA_OPTS += -D ORDERED_EP_CONFIG
+LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1
+LUFA_OPTS += -D USE_FLASH_DESCRIPTORS
+LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
+LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT
+
+LUFA_OPTS += -D USB_MANUFACTURER="L\"equinox\"" -D USB_MANUFACTURER_LEN=7
+LUFA_OPTS += -D USB_PRODUCT="L\"spreadspace usb-serial example\"" -D USB_PRODUCT_LEN=30
+
+LUFA_COMPONENTS := USB USBCLASS SERIAL
+
+include ../include.mk
diff --git a/usb-serial/usb-serial.c b/usb-serial/usb-serial.c new file mode 100644 index 0000000..9983d9d --- /dev/null +++ b/usb-serial/usb-serial.c @@ -0,0 +1,281 @@ +/*
+ * spreadspace avr utils
+ *
+ *
+ * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+ *
+ * This file is part of spreadspace avr utils.
+ *
+ * spreadspace avr utils is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * spreadspace avr utils is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+/* this is more or less the same as the LUFA example Project USBtoSerial and
+ this is their LICENSE Header */
+
+/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+/** \file
+ *
+ * Main source file for the USBtoSerial project. This file contains the main tasks of
+ * the project and is responsible for the initial application hardware configuration.
+ */
+
+
+#include <avr/io.h>
+#include <avr/wdt.h>
+#include <avr/interrupt.h>
+#include <avr/power.h>
+
+#include "lufa-descriptor-usbserial.h"
+
+#include "util.h"
+#include "led.h"
+
+#include <LUFA/Version.h>
+#include <LUFA/Drivers/Peripheral/Serial.h>
+#include <LUFA/Drivers/Misc/RingBuffer.h>
+#include <LUFA/Drivers/USB/USB.h>
+
+ /* Function Prototypes: */
+void SetupHardware(void);
+
+void EVENT_USB_Device_Connect(void);
+void EVENT_USB_Device_Disconnect(void);
+void EVENT_USB_Device_ConfigurationChanged(void);
+void EVENT_USB_Device_ControlRequest(void);
+
+void EVENT_CDC_Device_LineEncodingChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo);
+
+/** Circular buffer to hold data from the host before it is sent to the device via the serial port. */
+static RingBuffer_t USBtoUSART_Buffer;
+
+/** Underlying data buffer for \ref USBtoUSART_Buffer, where the stored bytes are located. */
+static uint8_t USBtoUSART_Buffer_Data[128];
+
+/** Circular buffer to hold data from the serial port before it is sent to the host. */
+static RingBuffer_t USARTtoUSB_Buffer;
+
+/** Underlying data buffer for \ref USARTtoUSB_Buffer, where the stored bytes are located. */
+static uint8_t USARTtoUSB_Buffer_Data[128];
+
+/** LUFA CDC Class driver interface configuration and state information. This structure is
+ * passed to all CDC Class driver functions, so that multiple instances of the same class
+ * within a device can be differentiated from one another.
+ */
+USB_ClassInfo_CDC_Device_t VirtualSerial_CDC_Interface =
+ {
+ .Config =
+ {
+ .ControlInterfaceNumber = 0,
+
+ .DataINEndpointNumber = CDC_TX_EPNUM,
+ .DataINEndpointSize = CDC_TXRX_EPSIZE,
+ .DataINEndpointDoubleBank = false,
+
+ .DataOUTEndpointNumber = CDC_RX_EPNUM,
+ .DataOUTEndpointSize = CDC_TXRX_EPSIZE,
+ .DataOUTEndpointDoubleBank = false,
+
+ .NotificationEndpointNumber = CDC_NOTIFICATION_EPNUM,
+ .NotificationEndpointSize = CDC_NOTIFICATION_EPSIZE,
+ .NotificationEndpointDoubleBank = false,
+ },
+ };
+
+
+/** Main program entry point. This routine contains the overall program flow, including initial
+ * setup of all components and the main program loop.
+ */
+int main(void)
+{
+ SetupHardware();
+
+ RingBuffer_InitBuffer(&USBtoUSART_Buffer, USBtoUSART_Buffer_Data, sizeof(USBtoUSART_Buffer_Data));
+ RingBuffer_InitBuffer(&USARTtoUSB_Buffer, USARTtoUSB_Buffer_Data, sizeof(USARTtoUSB_Buffer_Data));
+
+ sei();
+
+ for (;;)
+ {
+ /* Only try to read in bytes from the CDC interface if the transmit buffer is not full */
+ if (!(RingBuffer_IsFull(&USBtoUSART_Buffer)))
+ {
+ int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);
+
+ /* Read bytes from the USB OUT endpoint into the USART transmit buffer */
+ if (!(ReceivedByte < 0))
+ RingBuffer_Insert(&USBtoUSART_Buffer, ReceivedByte);
+ }
+
+ /* Check if the UART receive buffer flush timer has expired or the buffer is nearly full */
+ uint16_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);
+ if ((TIFR0 & (1 << TOV0)) || (BufferCount > (uint8_t)(sizeof(USARTtoUSB_Buffer_Data) * .75)))
+ {
+ /* Clear flush timer expiry flag */
+ TIFR0 |= (1 << TOV0);
+
+ /* Read bytes from the USART receive buffer into the USB IN endpoint */
+ while (BufferCount--)
+ {
+ /* Try to send the next byte of data to the host, abort if there is an error without dequeuing */
+ if (CDC_Device_SendByte(&VirtualSerial_CDC_Interface,
+ RingBuffer_Peek(&USARTtoUSB_Buffer)) != ENDPOINT_READYWAIT_NoError)
+ {
+ break;
+ }
+
+ /* Dequeue the already sent byte from the buffer now we have confirmed that no transmission error occurred */
+ RingBuffer_Remove(&USARTtoUSB_Buffer);
+ }
+ }
+
+ /* Load the next byte from the USART transmit buffer into the USART */
+ if (!(RingBuffer_IsEmpty(&USBtoUSART_Buffer)))
+ Serial_SendByte(RingBuffer_Remove(&USBtoUSART_Buffer));
+
+ CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
+ USB_USBTask();
+ }
+}
+
+/** Configures the board hardware and chip peripherals for the demo's functionality. */
+void SetupHardware(void)
+{
+ /* Disable watchdog if enabled by bootloader/fuses */
+ MCUSR &= ~(1 << WDRF);
+ wdt_disable();
+
+ cpu_init();
+ led_init();
+ USB_Init();
+
+ /* Start the flush timer so that overflows occur rapidly to push received bytes to the USB interface */
+ TCCR0B = (1 << CS02);
+}
+
+/** Event handler for the library USB Connection event. */
+void EVENT_USB_Device_Connect(void)
+{
+ led_on();
+}
+
+/** Event handler for the library USB Disconnection event. */
+void EVENT_USB_Device_Disconnect(void)
+{
+ led_off();
+}
+
+/** Event handler for the library USB Configuration Changed event. */
+void EVENT_USB_Device_ConfigurationChanged(void)
+{
+ CDC_Device_ConfigureEndpoints(&VirtualSerial_CDC_Interface);
+ led_toggle();
+ _delay_ms(10);
+ led_toggle();
+}
+
+/** Event handler for the library USB Control Request reception event. */
+void EVENT_USB_Device_ControlRequest(void)
+{
+ CDC_Device_ProcessControlRequest(&VirtualSerial_CDC_Interface);
+}
+
+/** ISR to manage the reception of data from the serial port, placing received bytes into a circular buffer
+ * for later transmission to the host.
+ */
+ISR(USART1_RX_vect, ISR_BLOCK)
+{
+ uint8_t ReceivedByte = UDR1;
+
+ if (USB_DeviceState == DEVICE_STATE_Configured)
+ RingBuffer_Insert(&USARTtoUSB_Buffer, ReceivedByte);
+}
+
+/** Event handler for the CDC Class driver Line Encoding Changed event.
+ *
+ * \param[in] CDCInterfaceInfo Pointer to the CDC class interface configuration structure being referenced
+ */
+void EVENT_CDC_Device_LineEncodingChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo)
+{
+ uint8_t ConfigMask = 0;
+
+ switch (CDCInterfaceInfo->State.LineEncoding.ParityType)
+ {
+ case CDC_PARITY_Odd:
+ ConfigMask = ((1 << UPM11) | (1 << UPM10));
+ break;
+ case CDC_PARITY_Even:
+ ConfigMask = (1 << UPM11);
+ break;
+ }
+
+ if (CDCInterfaceInfo->State.LineEncoding.CharFormat == CDC_LINEENCODING_TwoStopBits)
+ ConfigMask |= (1 << USBS1);
+
+ switch (CDCInterfaceInfo->State.LineEncoding.DataBits)
+ {
+ case 6:
+ ConfigMask |= (1 << UCSZ10);
+ break;
+ case 7:
+ ConfigMask |= (1 << UCSZ11);
+ break;
+ case 8:
+ ConfigMask |= ((1 << UCSZ11) | (1 << UCSZ10));
+ break;
+ }
+
+ /* Must turn off USART before reconfiguring it, otherwise incorrect operation may occur */
+ UCSR1B = 0;
+ UCSR1A = 0;
+ UCSR1C = 0;
+
+ /* Set the new baud rate before configuring the USART */
+ UBRR1 = SERIAL_2X_UBBRVAL(CDCInterfaceInfo->State.LineEncoding.BaudRateBPS);
+
+ /* Reconfigure the USART in double speed mode for a wider baud rate range at the expense of accuracy */
+ UCSR1C = ConfigMask;
+ UCSR1A = (1 << U2X1);
+ UCSR1B = ((1 << RXCIE1) | (1 << TXEN1) | (1 << RXEN1));
+}
+
diff --git a/usb-spi/Makefile b/usb-spi/Makefile new file mode 100644 index 0000000..ea8ebb8 --- /dev/null +++ b/usb-spi/Makefile @@ -0,0 +1,44 @@ +##
+## spreadspace avr utils
+##
+##
+## Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+##
+## This file is part of spreadspace avr utils.
+##
+## spreadspace avr utils is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## any later version.
+##
+## spreadspace avr utils is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+##
+
+NAME := usb-spi
+BOARD_TYPE := teensy2
+OBJ := $(NAME).o
+LIBS := util led lufa-descriptor-usbserial
+EXTERNAL_LIBS := lufa
+
+LUFA_PATH := ../contrib/LUFA-120219
+LUFA_OPTS = -D USB_DEVICE_ONLY
+LUFA_OPTS += -D DEVICE_STATE_AS_GPIOR=0
+LUFA_OPTS += -D ORDERED_EP_CONFIG
+LUFA_OPTS += -D FIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -D FIXED_NUM_CONFIGURATIONS=1
+LUFA_OPTS += -D USE_FLASH_DESCRIPTORS
+LUFA_OPTS += -D USE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
+LUFA_OPTS += -D INTERRUPT_CONTROL_ENDPOINT
+
+LUFA_OPTS += -D USB_MANUFACTURER="L\"equinox\"" -D USB_MANUFACTURER_LEN=7
+LUFA_OPTS += -D USB_PRODUCT="L\"spreadspace usb-spi example\"" -D USB_PRODUCT_LEN=27
+
+LUFA_COMPONENTS := USB USBCLASS
+
+include ../include.mk
diff --git a/usb-spi/usb-spi.c b/usb-spi/usb-spi.c new file mode 100644 index 0000000..1c000ed --- /dev/null +++ b/usb-spi/usb-spi.c @@ -0,0 +1,199 @@ +/*
+ * spreadspace avr utils
+ *
+ *
+ * Copyright (C) 2013-2014 Christian Pointner <equinox@spreadspace.org>
+ *
+ * This file is part of spreadspace avr utils.
+ *
+ * spreadspace avr utils is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * spreadspace avr utils is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <avr/io.h>
+#include <avr/wdt.h>
+#include <avr/interrupt.h>
+#include <avr/power.h>
+
+#include "util.h"
+#include "led.h"
+
+/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+#include <LUFA/Version.h>
+#include <LUFA/Drivers/Peripheral/SPI.h>
+#include <LUFA/Drivers/Misc/RingBuffer.h>
+#include <LUFA/Drivers/USB/USB.h>
+#include "lufa-descriptor-usbserial.h"
+
+ /* Global I/O Buffers: */
+static RingBuffer_t USBtoSPI_Buffer;
+static uint8_t USBtoSPI_Buffer_Data[128];
+static RingBuffer_t SPItoUSB_Buffer;
+static uint8_t SPItoUSB_Buffer_Data[128];
+
+/** LUFA CDC Class driver interface configuration and state information. This structure is
+ * passed to all CDC Class driver functions, so that multiple instances of the same class
+ * within a device can be differentiated from one another.
+ */
+USB_ClassInfo_CDC_Device_t VirtualSerial_CDC_Interface =
+ {
+ .Config =
+ {
+ .ControlInterfaceNumber = 0,
+
+ .DataINEndpointNumber = CDC_TX_EPNUM,
+ .DataINEndpointSize = CDC_TXRX_EPSIZE,
+ .DataINEndpointDoubleBank = false,
+
+ .DataOUTEndpointNumber = CDC_RX_EPNUM,
+ .DataOUTEndpointSize = CDC_TXRX_EPSIZE,
+ .DataOUTEndpointDoubleBank = false,
+
+ .NotificationEndpointNumber = CDC_NOTIFICATION_EPNUM,
+ .NotificationEndpointSize = CDC_NOTIFICATION_EPSIZE,
+ .NotificationEndpointDoubleBank = false,
+ },
+ };
+
+void EVENT_USB_Device_ConfigurationChanged(void)
+{
+ CDC_Device_ConfigureEndpoints(&VirtualSerial_CDC_Interface);
+}
+
+void EVENT_USB_Device_ControlRequest(void)
+{
+ CDC_Device_ProcessControlRequest(&VirtualSerial_CDC_Interface);
+}
+
+/* end LUFA CDC-ACM specific definitions */
+
+ /* Hardware Defines: */
+#define SPI_CS_DDR DDRB
+#define SPI_CS_PORT PORTB
+#define CS 0
+
+#define RESET_DDR DDRB
+#define RESET_PORT PORTB
+#define RESET 7
+
+void SetupHardware(void)
+{
+ MCUSR &= ~(1 << WDRF);
+ wdt_disable();
+
+ cpu_init();
+ led_init();
+ USB_Init();
+
+ TCCR0B = (1 << CS02);
+
+ SPI_Init(SPI_SPEED_FCPU_DIV_16 | SPI_MODE_MASTER | SPI_ORDER_MSB_FIRST |
+ SPI_SCK_LEAD_RISING | SPI_SAMPLE_LEADING);
+ SPI_CS_DDR |= (1<<CS);
+ SPI_CS_PORT |= (1<<CS);
+
+ RESET_DDR |= (1<<RESET);
+ RESET_PORT |= (1<<RESET);
+
+/* INT0 as input with pull-up */
+ DDRD &= ~(1<<0);
+ PORTD |= (1<<0);
+ EICRA |= (1<<ISC01);
+ EIFR |= (1<<INTF0);
+ EIMSK |= (1<<INT0);
+}
+
+void EVENT_CDC_Device_ControLineStateChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo)
+{
+ if(CDCInterfaceInfo->State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR)
+ RESET_PORT &= ~(1<<RESET);
+ else
+ RESET_PORT |= (1<<RESET);
+}
+
+void EVENT_CDC_Device_BreakSent(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo, const uint8_t Duration)
+{
+ SPI_CS_PORT ^= (1<<CS);
+}
+
+ISR(INT0_vect)
+{
+ SPI_CS_PORT &= ~(1<<CS);
+ led_on();
+
+ uint8_t ReceivedByte = SPI_ReceiveByte();
+ RingBuffer_Insert(&SPItoUSB_Buffer, ReceivedByte);
+
+ led_off();
+ SPI_CS_PORT |= (1<<CS);
+}
+
+void SPI_SendBuffer(void)
+{
+ SPI_CS_PORT &= ~(1<<CS);
+ led_on();
+
+ while(!(RingBuffer_IsEmpty(&USBtoSPI_Buffer))) {
+ SPI_SendByte(RingBuffer_Remove(&USBtoSPI_Buffer));
+ }
+
+ led_off();
+ SPI_CS_PORT |= (1<<CS);
+}
+
+int main(void)
+{
+ SetupHardware();
+
+ RingBuffer_InitBuffer(&USBtoSPI_Buffer, USBtoSPI_Buffer_Data, sizeof(USBtoSPI_Buffer_Data));
+ RingBuffer_InitBuffer(&SPItoUSB_Buffer, SPItoUSB_Buffer_Data, sizeof(SPItoUSB_Buffer_Data));
+
+ sei();
+
+ for (;;) {
+ int16_t BytesReceived = CDC_Device_BytesReceived(&VirtualSerial_CDC_Interface);
+ while(BytesReceived > 0) {
+ if(!(RingBuffer_IsFull(&USBtoSPI_Buffer))) {
+ int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);
+ if (!(ReceivedByte < 0))
+ RingBuffer_Insert(&USBtoSPI_Buffer, ReceivedByte);
+
+ BytesReceived--;
+ }
+ }
+
+ uint16_t BufferCount = RingBuffer_GetCount(&SPItoUSB_Buffer);
+ if ((TIFR0 & (1 << TOV0)) || (BufferCount > (uint8_t)(sizeof(SPItoUSB_Buffer_Data) * .75))) {
+ TIFR0 |= (1 << TOV0);
+ while (BufferCount--) {
+ if (CDC_Device_SendByte(&VirtualSerial_CDC_Interface,
+ RingBuffer_Peek(&SPItoUSB_Buffer)) != ENDPOINT_READYWAIT_NoError)
+ break;
+
+ RingBuffer_Remove(&SPItoUSB_Buffer);
+ }
+ }
+
+ if (!(RingBuffer_IsEmpty(&USBtoSPI_Buffer)))
+ SPI_SendBuffer();
+
+ CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
+ USB_USBTask();
+ }
+}
|