Add new vusb package

This commit is contained in:
optixx 2016-02-09 12:29:43 +01:00
parent 8fe9e51889
commit 31ab89bbae
112 changed files with 16280 additions and 0 deletions

View File

@ -0,0 +1,329 @@
This file documents changes in the firmware-only USB driver for atmel's AVR
microcontrollers. New entries are always appended to the end of the file.
Scroll down to the bottom to see the most recent changes.
2005-04-01:
- Implemented endpoint 1 as interrupt-in endpoint.
- Moved all configuration options to usbconfig.h which is not part of the
driver.
- Changed interface for usbVendorSetup().
- Fixed compatibility with ATMega8 device.
- Various minor optimizations.
2005-04-11:
- Changed interface to application: Use usbFunctionSetup(), usbFunctionRead()
and usbFunctionWrite() now. Added configuration options to choose which
of these functions to compile in.
- Assembler module delivers receive data non-inverted now.
- Made register and bit names compatible with more AVR devices.
2005-05-03:
- Allow address of usbRxBuf on any memory page as long as the buffer does
not cross 256 byte page boundaries.
- Better device compatibility: works with Mega88 now.
- Code optimization in debugging module.
- Documentation updates.
2006-01-02:
- Added (free) default Vendor- and Product-IDs bought from voti.nl.
- Added USBID-License.txt file which defines the rules for using the free
shared VID/PID pair.
- Added Readme.txt to the usbdrv directory which clarifies administrative
issues.
2006-01-25:
- Added "configured state" to become more standards compliant.
- Added "HALT" state for interrupt endpoint.
- Driver passes the "USB Command Verifier" test from usb.org now.
- Made "serial number" a configuration option.
- Minor optimizations, we now recommend compiler option "-Os" for best
results.
- Added a version number to usbdrv.h
2006-02-03:
- New configuration variable USB_BUFFER_SECTION for the memory section where
the USB rx buffer will go. This defaults to ".bss" if not defined. Since
this buffer MUST NOT cross 256 byte pages (not even touch a page at the
end), the user may want to pass a linker option similar to
"-Wl,--section-start=.mybuffer=0x800060".
- Provide structure for usbRequest_t.
- New defines for USB constants.
- Prepared for HID implementations.
- Increased data size limit for interrupt transfers to 8 bytes.
- New macro usbInterruptIsReady() to query interrupt buffer state.
2006-02-18:
- Ensure that the data token which is sent as an ack to an OUT transfer is
always zero sized. This fixes a bug where the host reports an error after
sending an out transfer to the device, although all data arrived at the
device.
- Updated docs in usbdrv.h to reflect changed API in usbFunctionWrite().
* Release 2006-02-20
- Give a compiler warning when compiling with debugging turned on.
- Added Oleg Semyonov's changes for IAR-cc compatibility.
- Added new (optional) functions usbDeviceConnect() and usbDeviceDisconnect()
(also thanks to Oleg!).
- Rearranged tests in usbPoll() to save a couple of instructions in the most
likely case that no actions are pending.
- We need a delay between the SET ADDRESS request until the new address
becomes active. This delay was handled in usbPoll() until now. Since the
spec says that the delay must not exceed 2ms, previous versions required
aggressive polling during the enumeration phase. We have now moved the
handling of the delay into the interrupt routine.
- We must not reply with NAK to a SETUP transaction. We can only achieve this
by making sure that the rx buffer is empty when SETUP tokens are expected.
We therefore don't pass zero sized data packets from the status phase of
a transfer to usbPoll(). This change MAY cause troubles if you rely on
receiving a less than 8 bytes long packet in usbFunctionWrite() to
identify the end of a transfer. usbFunctionWrite() will NEVER be called
with a zero length.
* Release 2006-03-14
- Improved IAR C support: tiny memory model, more devices
- Added template usbconfig.h file under the name usbconfig-prototype.h
* Release 2006-03-26
- Added provision for one more interrupt-in endpoint (endpoint 3).
- Added provision for one interrupt-out endpoint (endpoint 1).
- Added flowcontrol macros for USB.
- Added provision for custom configuration descriptor.
- Allow ANY two port bits for D+ and D-.
- Merged (optional) receive endpoint number into global usbRxToken variable.
- Use USB_CFG_IOPORTNAME instead of USB_CFG_IOPORT. We now construct the
variable name from the single port letter instead of computing the address
of related ports from the output-port address.
* Release 2006-06-26
- Updated documentation in usbdrv.h and usbconfig-prototype.h to reflect the
new features.
- Removed "#warning" directives because IAR does not understand them. Use
unused static variables instead to generate a warning.
- Do not include <avr/io.h> when compiling with IAR.
- Introduced USB_CFG_DESCR_PROPS_* in usbconfig.h to configure how each
USB descriptor should be handled. It is now possible to provide descriptor
data in Flash, RAM or dynamically at runtime.
- STALL is now a status in usbTxLen* instead of a message. We can now conform
to the spec and leave the stall status pending until it is cleared.
- Made usbTxPacketCnt1 and usbTxPacketCnt3 public. This allows the
application code to reset data toggling on interrupt pipes.
* Release 2006-07-18
- Added an #if !defined __ASSEMBLER__ to the warning in usbdrv.h. This fixes
an assembler error.
- usbDeviceDisconnect() takes pull-up resistor to high impedance now.
* Release 2007-02-01
- Merged in some code size improvements from usbtiny (thanks to Dick
Streefland for these optimizations!)
- Special alignment requirement for usbRxBuf not required any more. Thanks
again to Dick Streefland for this hint!
- Reverted to "#warning" instead of unused static variables -- new versions
of IAR CC should handle this directive.
- Changed Open Source license to GNU GPL v2 in order to make linking against
other free libraries easier. We no longer require publication of the
circuit diagrams, but we STRONGLY encourage it. If you improve the driver
itself, PLEASE grant us a royalty free license to your changes for our
commercial license.
* Release 2007-03-29
- New configuration option "USB_PUBLIC" in usbconfig.h.
- Set USB version number to 1.10 instead of 1.01.
- Code used USB_CFG_DESCR_PROPS_STRING_DEVICE and
USB_CFG_DESCR_PROPS_STRING_PRODUCT inconsistently. Changed all occurrences
to USB_CFG_DESCR_PROPS_STRING_PRODUCT.
- New assembler module for 16.5 MHz RC oscillator clock with PLL in receiver
code.
- New assembler module for 16 MHz crystal.
- usbdrvasm.S contains common code only, clock-specific parts have been moved
to usbdrvasm12.S, usbdrvasm16.S and usbdrvasm165.S respectively.
* Release 2007-06-25
- 16 MHz module: Do SE0 check in stuffed bits as well.
* Release 2007-07-07
- Define hi8(x) for IAR compiler to limit result to 8 bits. This is necessary
for negative values.
- Added 15 MHz module contributed by V. Bosch.
- Interrupt vector name can now be configured. This is useful if somebody
wants to use a different hardware interrupt than INT0.
* Release 2007-08-07
- Moved handleIn3 routine in usbdrvasm16.S so that relative jump range is
not exceeded.
- More config options: USB_RX_USER_HOOK(), USB_INITIAL_DATATOKEN,
USB_COUNT_SOF
- USB_INTR_PENDING can now be a memory address, not just I/O
* Release 2007-09-19
- Split out common parts of assembler modules into separate include file
- Made endpoint numbers configurable so that given interface definitions
can be matched. See USB_CFG_EP3_NUMBER in usbconfig-prototype.h.
- Store endpoint number for interrupt/bulk-out so that usbFunctionWriteOut()
can handle any number of endpoints.
- Define usbDeviceConnect() and usbDeviceDisconnect() even if no
USB_CFG_PULLUP_IOPORTNAME is defined. Directly set D+ and D- to 0 in this
case.
* Release 2007-12-01
- Optimize usbDeviceConnect() and usbDeviceDisconnect() for less code size
when USB_CFG_PULLUP_IOPORTNAME is not defined.
* Release 2007-12-13
- Renamed all include-only assembler modules from *.S to *.inc so that
people don't add them to their project sources.
- Distribute leap bits in tx loop more evenly for 16 MHz module.
- Use "macro" and "endm" instead of ".macro" and ".endm" for IAR
- Avoid compiler warnings for constant expr range by casting some values in
USB descriptors.
* Release 2008-01-21
- Fixed bug in 15 and 16 MHz module where the new address set with
SET_ADDRESS was already accepted at the next NAK or ACK we send, not at
the next data packet we send. This caused problems when the host polled
too fast. Thanks to Alexander Neumann for his help and patience debugging
this issue!
* Release 2008-02-05
- Fixed bug in 16.5 MHz module where a register was used in the interrupt
handler before it was pushed. This bug was introduced with version
2007-09-19 when common parts were moved to a separate file.
- Optimized CRC routine (thanks to Reimar Doeffinger).
* Release 2008-02-16
- Removed outdated IAR compatibility stuff (code sections).
- Added hook macros for USB_RESET_HOOK() and USB_SET_ADDRESS_HOOK().
- Added optional routine usbMeasureFrameLength() for calibration of the
internal RC oscillator.
* Release 2008-02-28
- USB_INITIAL_DATATOKEN defaults to USBPID_DATA1 now, which means that we
start with sending USBPID_DATA0.
- Changed defaults in usbconfig-prototype.h
- Added free USB VID/PID pair for MIDI class devices
- Restructured AVR-USB as separate package, not part of PowerSwitch any more.
* Release 2008-04-18
- Restructured usbdrv.c so that it is easier to read and understand.
- Better code optimization with gcc 4.
- If a second interrupt in endpoint is enabled, also add it to config
descriptor.
- Added config option for long transfers (above 254 bytes), see
USB_CFG_LONG_TRANSFERS in usbconfig.h.
- Added 20 MHz module contributed by Jeroen Benschop.
* Release 2008-05-13
- Fixed bug in libs-host/hiddata.c function usbhidGetReport(): length
was not incremented, pointer to length was incremented instead.
- Added code to command line tool(s) which claims an interface. This code
is disabled by default, but may be necessary on newer Linux kernels.
- Added usbconfig.h option "USB_CFG_CHECK_DATA_TOGGLING".
- New header "usbportability.h" prepares ports to other development
environments.
- Long transfers (above 254 bytes) did not work when usbFunctionRead() was
used to supply the data. Fixed this bug. [Thanks to Alexander Neumann!]
- In hiddata.c (example code for sending/receiving data over HID), use
USB_RECIP_DEVICE instead of USB_RECIP_INTERFACE for control transfers so
that we need not claim the interface.
- in usbPoll() loop 20 times polling for RESET state instead of 10 times.
This accounts for the higher clock rates we now support.
- Added a module for 12.8 MHz RC oscillator with PLL in receiver loop.
- Added hook to SOF code so that oscillator can be tuned to USB frame clock.
- Added timeout to waitForJ loop. Helps preventing unexpected hangs.
- Added example code for oscillator tuning to libs-device (thanks to
Henrik Haftmann for the idea to this routine).
- Implemented option USB_CFG_SUPPRESS_INTR_CODE.
* Release 2008-10-22
- Fixed libs-device/osctune.h: OSCCAL is memory address on ATMega88 and
similar, not offset of 0x20 needs to be added.
- Allow distribution under GPLv3 for those who have to link against other
code distributed under GPLv3.
* Release 2008-11-26
- Removed libusb-win32 dependency for hid-data example in Makefile.windows.
It was never required and confused many people.
- Added extern uchar usbRxToken to usbdrv.h.
- Integrated a module with CRC checks at 18 MHz by Lukas Schrittwieser.
* Release 2009-03-23
- Hid-mouse example used settings from hid-data example, fixed that.
- Renamed project to V-USB due to a trademark issue with Atmel(r).
- Changed CommercialLicense.txt and USBID-License.txt to make the
background of USB ID registration clearer.
* Release 2009-04-15
- Changed CommercialLicense.txt to reflect the new range of PIDs from
Jason Kotzin.
- Removed USBID-License.txt in favor of USB-IDs-for-free.txt and
USB-ID-FAQ.txt
- Fixed a bug in the 12.8 MHz module: End Of Packet decection was made in
the center between bit 0 and 1 of each byte. This is where the data lines
are expected to change and the sampled data may therefore be nonsense.
We therefore check EOP ONLY if bits 0 AND 1 have both been read as 0 on D-.
- Fixed a bitstuffing problem in the 16 MHz module: If bit 6 was stuffed,
the unstuffing code in the receiver routine was 1 cycle too long. If
multiple bytes had the unstuffing in bit 6, the error summed up until the
receiver was out of sync.
- Included option for faster CRC routine.
Thanks to Slawomir Fras (BoskiDialer) for this code!
- Updated bits in Configuration Descriptor's bmAttributes according to
USB 1.1 (in particular bit 7, it is a must-be-set bit now).
* Release 2009-08-22
- Moved first DBG1() after odDebugInit() in all examples.
- Use vector INT0_vect instead of SIG_INTERRUPT0 if defined. This makes
V-USB compatible with the new "p" suffix devices (e.g. ATMega328p).
- USB_CFG_CLOCK_KHZ setting is now required in usbconfig.h (no default any
more).
- New option USB_CFG_DRIVER_FLASH_PAGE allows boot loaders on devices with
more than 64 kB flash.
- Built-in configuration descriptor allows custom definition for second
endpoint now.
* Release 2010-07-15
- Fixed bug in usbDriverSetup() which prevented descriptor sizes above 255
bytes.
- Avoid a compiler warning for unused parameter in usbHandleResetHook() when
compiler option -Wextra is enabled.
- Fixed wrong hex value for some IDs in USB-IDs-for-free.txt.
- Keep a define for USBATTR_BUSPOWER, although the flag does not exist
in USB 1.1 any more. Set it to 0. This is for backward compatibility.
* Release 2012-01-09
- Define a separate (defined) type for usbMsgPtr so that projects using a
tiny memory model can define it to an 8 bit type in usbconfig.h. This
change also saves a couple of bytes when using a scalar 16 bit type.
- Inserted "const" keyword for all PROGMEM declarations because new GCC
requires it.
- Fixed problem with dependence of usbportability.h on usbconfig.h. This
problem occurred with IAR CC only.
- Prepared repository for github.com.
* Release 2012-12-06

View File

@ -0,0 +1,166 @@
V-USB Driver Software License Agreement
Version 2012-07-09
THIS LICENSE AGREEMENT GRANTS YOU CERTAIN RIGHTS IN A SOFTWARE. YOU CAN
ENTER INTO THIS AGREEMENT AND ACQUIRE THE RIGHTS OUTLINED BELOW BY PAYING
THE AMOUNT ACCORDING TO SECTION 4 ("PAYMENT") TO OBJECTIVE DEVELOPMENT.
1 DEFINITIONS
1.1 "OBJECTIVE DEVELOPMENT" shall mean OBJECTIVE DEVELOPMENT Software GmbH,
Grosse Schiffgasse 1A/7, 1020 Wien, AUSTRIA.
1.2 "You" shall mean the Licensee.
1.3 "V-USB" shall mean all files included in the package distributed under
the name "vusb" by OBJECTIVE DEVELOPMENT (http://www.obdev.at/vusb/)
unless otherwise noted. This includes the firmware-only USB device
implementation for Atmel AVR microcontrollers, some simple device examples
and host side software examples and libraries.
2 LICENSE GRANTS
2.1 Source Code. OBJECTIVE DEVELOPMENT shall furnish you with the source
code of V-USB.
2.2 Distribution and Use. OBJECTIVE DEVELOPMENT grants you the
non-exclusive right to use, copy and distribute V-USB with your hardware
product(s), restricted by the limitations in section 3 below.
2.3 Modifications. OBJECTIVE DEVELOPMENT grants you the right to modify
the source code and your copy of V-USB according to your needs.
2.4 USB IDs. OBJECTIVE DEVELOPMENT furnishes you with one or two USB
Product ID(s), sent to you in e-mail. These Product IDs are reserved
exclusively for you. OBJECTIVE DEVELOPMENT has obtained USB Product ID
ranges under the Vendor ID 5824 from Wouter van Ooijen (Van Ooijen
Technische Informatica, www.voti.nl) and under the Vendor ID 8352 from
Jason Kotzin (now flirc.tv, Inc.). Both owners of the Vendor IDs have
obtained these IDs from the USB Implementers Forum, Inc. (www.usb.org).
OBJECTIVE DEVELOPMENT disclaims all liability which might arise from the
assignment of USB IDs.
2.5 USB Certification. Although not part of this agreement, we want to make
it clear that you cannot become USB certified when you use V-USB or a USB
Product ID assigned by OBJECTIVE DEVELOPMENT. AVR microcontrollers don't
meet the electrical specifications required by the USB specification and
the USB Implementers Forum certifies only members who bought a Vendor ID of
their own.
3 LICENSE RESTRICTIONS
3.1 Number of Units. Only one of the following three definitions is
applicable. Which one is determined by the amount you pay to OBJECTIVE
DEVELOPMENT, see section 4 ("Payment") below.
Hobby License: You may use V-USB according to section 2 above in no more
than 5 hardware units. These units must not be sold for profit.
Entry Level License: You may use V-USB according to section 2 above in no
more than 150 hardware units.
Professional License: You may use V-USB according to section 2 above in
any number of hardware units, except for large scale production ("unlimited
fair use"). Quantities below 10,000 units are not considered large scale
production. If your reach quantities which are obviously large scale
production, you must pay a license fee of 0.10 EUR per unit for all units
above 10,000.
3.2 Rental. You may not rent, lease, or lend V-USB or otherwise encumber
any copy of V-USB, or any of the rights granted herein.
3.3 Transfer. You may not transfer your rights under this Agreement to
another party without OBJECTIVE DEVELOPMENT's prior written consent. If
such consent is obtained, you may permanently transfer this License to
another party. The recipient of such transfer must agree to all terms and
conditions of this Agreement.
3.4 Reservation of Rights. OBJECTIVE DEVELOPMENT retains all rights not
expressly granted.
3.5 Non-Exclusive Rights. Your license rights under this Agreement are
non-exclusive.
3.6 Third Party Rights. This Agreement cannot grant you rights controlled
by third parties. In particular, you are not allowed to use the USB logo or
other trademarks owned by the USB Implementers Forum, Inc. without their
consent. Since such consent depends on USB certification, it should be
noted that V-USB will not pass certification because it does not
implement checksum verification and the microcontroller ports do not meet
the electrical specifications.
4 PAYMENT
The payment amount depends on the variation of this agreement (according to
section 3.1) into which you want to enter. Concrete prices are listed on
OBJECTIVE DEVELOPMENT's web site, usually at
http://www.obdev.at/vusb/license.html. You agree to pay the amount listed
there to OBJECTIVE DEVELOPMENT or OBJECTIVE DEVELOPMENT's payment processor
or reseller.
5 COPYRIGHT AND OWNERSHIP
V-USB is protected by copyright laws and international copyright
treaties, as well as other intellectual property laws and treaties. V-USB
is licensed, not sold.
6 TERM AND TERMINATION
6.1 Term. This Agreement shall continue indefinitely. However, OBJECTIVE
DEVELOPMENT may terminate this Agreement and revoke the granted license and
USB-IDs if you fail to comply with any of its terms and conditions.
6.2 Survival of Terms. All provisions regarding secrecy, confidentiality
and limitation of liability shall survive termination of this agreement.
7 DISCLAIMER OF WARRANTY AND LIABILITY
LIMITED WARRANTY. V-USB IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, OBJECTIVE
DEVELOPMENT AND ITS SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND
NON-INFRINGEMENT, WITH REGARD TO V-USB, AND THE PROVISION OF OR FAILURE
TO PROVIDE SUPPORT SERVICES. THIS LIMITED WARRANTY GIVES YOU SPECIFIC LEGAL
RIGHTS. YOU MAY HAVE OTHERS, WHICH VARY FROM STATE/JURISDICTION TO
STATE/JURISDICTION.
LIMITATION OF LIABILITY. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW,
IN NO EVENT SHALL OBJECTIVE DEVELOPMENT OR ITS SUPPLIERS BE LIABLE FOR ANY
SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER
(INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS,
BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY
LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE V-USB OR THE
PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES, EVEN IF OBJECTIVE
DEVELOPMENT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN ANY
CASE, OBJECTIVE DEVELOPMENT'S ENTIRE LIABILITY UNDER ANY PROVISION OF THIS
AGREEMENT SHALL BE LIMITED TO THE AMOUNT ACTUALLY PAID BY YOU FOR V-USB.
8 MISCELLANEOUS TERMS
8.1 Marketing. OBJECTIVE DEVELOPMENT has the right to mention for marketing
purposes that you entered into this agreement.
8.2 Entire Agreement. This document represents the entire agreement between
OBJECTIVE DEVELOPMENT and you. It may only be modified in writing signed by
an authorized representative of both, OBJECTIVE DEVELOPMENT and you.
8.3 Severability. In case a provision of these terms and conditions should
be or become partly or entirely invalid, ineffective, or not executable,
the validity of all other provisions shall not be affected.
8.4 Applicable Law. This agreement is governed by the laws of the Republic
of Austria.
8.5 Responsible Courts. The responsible courts in Vienna/Austria will have
exclusive jurisdiction regarding all disputes in connection with this
agreement.

View File

@ -0,0 +1,361 @@
OBJECTIVE DEVELOPMENT GmbH's V-USB driver software is distributed under the
terms and conditions of the GNU GPL version 2 or the GNU GPL version 3. It is
your choice whether you apply the terms of version 2 or version 3. The full
text of GPLv2 is included below. In addition to the requirements in the GPL,
we STRONGLY ENCOURAGE you to do the following:
(1) Publish your entire project on a web site and drop us a note with the URL.
Use the form at http://www.obdev.at/vusb/feedback.html for your submission.
(2) Adhere to minimum publication standards. Please include AT LEAST:
- a circuit diagram in PDF, PNG or GIF format
- full source code for the host software
- a Readme.txt file in ASCII format which describes the purpose of the
project and what can be found in which directories and which files
- a reference to http://www.obdev.at/vusb/
(3) If you improve the driver firmware itself, please give us a free license
to your modifications for our commercial license offerings.
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) 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
this service 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 make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. 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.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
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
convey 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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision 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, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This 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 Library General
Public License instead of this License.

View File

@ -0,0 +1,60 @@
# Name: Makefile
# Project: v-usb
# Author: Christian Starkjohann
# Creation Date: 2012-12-05
# Tabsize: 4
# Copyright: (c) 2012 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
# This is the main Makefile. The two primary targets are "all", to build
# everything which can be built (except tests), and "clean" to remove all
# dependent files. In a repository clone, derived source files are generated
# and deleted as well.
#
# We distinguish between repository clones and source packages by the existence
# of make-files.sh scripts in various subdirectories.
all:
if [ ! -f examples/hid-mouse/firmware/Makefile ]; then \
$(MAKE) files; \
fi
if [ -n "$(uname -s | grep -i mingw)" ]; then \
$(MAKE) windows; \
else \
$(MAKE) unix; \
fi
clean:
$(MAKE) unixclean
if cross-make.sh --help >/dev/null 2>&1; then \
$(MAKE) windowsclean; \
fi
$(MAKE) filesremove
unix unixclean:
target=$$(echo $@ | sed -e 's/unix//g'); \
find . -mindepth 3 -name Makefile -print | while read i; do \
dir=$$(dirname $$i); \
dirname=$$(basename $$dir); \
pushd $$dir >/dev/null; \
if [ "$$dirname" = firmware -a -z "$$target" ]; then \
if ! $(MAKE) hex; then break; fi; \
else \
if ! $(MAKE) $$target; then break; fi;\
fi; \
popd >/dev/null; \
done
windows windowsclean:
target=$$(echo $@ | sed -e 's/windows//g'); \
find . -mindepth 3 -name Makefile.windows -execdir cross-make.sh $$target \; ; \
if [ -z "$$target" ]; then target=hex; fi; \
find . -mindepth 2 -name firmware -exec sh -c "cd '{}'; $(MAKE) $$target" \;
files filesremove:
target=$$(echo $@ | sed -e 's/files//g'); \
find . -mindepth 2 -name make-files.sh -execdir ./make-files.sh $$target \;

View File

@ -0,0 +1,83 @@
This is the Readme file for V-USB and related code. V-USB is Objective
Development's firmware-only USB driver for Atmel's(r) AVR(r) microcontrollers.
For more information please visit http://www.obdev.at/vusb/.
To avoid name confusion: This project was formerly known as AVR-USB. Due to
a trademark issue, it was renamed to V-USB in April 2009.
WHAT IS INCLUDED IN THIS PACKAGE?
=================================
This package consists of the device side USB driver firmware, library code
for device and host and fully working examples for device and host:
Readme.txt .............. The file you are currently reading.
usbdrv .................. V-USB firmware, to be included in your project.
examples ................ Example code for device and host side.
libs-device ............. Useful code snippets for the device firmware.
libs-host ............... Useful code snippets for host-side drivers.
circuits ................ Example circuits using this driver.
Changelog.txt ........... Documentation of changes between versions.
License.txt ............. Free Open Source license for this package (GPL).
CommercialLicense.txt ... Alternative commercial license for this package.
USB-ID-FAQ.txt .......... General infos about USB Product- and Vendor-IDs.
USB-IDs-for-free.txt .... List and terms of use for free shared PIDs.
Each subdirectory contains a separate Readme file which explains its
contents. We recommend that you also read the Readme.txt file in the
usbdrv subdirectory.
PREREQUISITES
=============
The AVR code of V-USB is written in C and assembler. You need either
avr-gcc or IAR CC to compile the project. We recommend avr-gcc because it
is free and easily available. Gcc version 3 generates slightly more
efficient code than version 4 for V-USB. Not every release is tested with
the IAR compiler. Previous versions have been tested with IAR 4.10B/W32 and
4.12A/W32 on an ATmega8 with the "small" and "tiny" memory model.
Ready made avr-gcc tool chains are available for most operating systems:
* Windows: WinAVR http://winavr.sourceforge.net/
* Mac: CrossPack for AVR Development http://www.obdev.at/crosspack/
* Linux and other Unixes: Most free Unixes have optional packages for AVR
development. If not, follow the instructions at
http://www.nongnu.org/avr-libc/user-manual/install_tools.html
Our host side examples are compiled with gcc on all platforms. Gcc is the
default C compiler on Mac, Linux and many other Unixes. On windows, we
recommend MinGW (http://www.mingw.org/). Use the automated MinGW installer
for least troubles. You also need MSYS from the same site to work with
standard Makefiles.
Most examples also depend on libusb. Libusb is available from
http://libusb.sourceforge.net/ for Unix and
http://libusb-win32.sourceforge.net/ for Windows.
TECHNICAL DOCUMENTATION
=======================
The API reference of the driver firmware can be found in usbdrv/usbdrv.h.
Documentation for host and device library files are in the respective header
files. For more information, see our documentation wiki at
http://www.obdev.at/goto.php?t=vusb-wiki.
See the file usbdrv/Readme.txt for more info about the driver itself.
LICENSE
=======
V-USB and related code is distributed under the terms of the GNU General
Public License (GPL) version 2 (see License.txt for details) and the GNU
General Public License (GPL) version 3. It is your choice whether you apply
the terms of version 2 or version 3. In addition to the terms of the GPL, we
strongly encourage you to publish your entire project and mail OBJECTIVE
DEVELOPMENT a link to your publication.
Alternatively, we offer a commercial license without the restrictions of the
GPL. See CommercialLicense.txt for details.
----------------------------------------------------------------------------
(c) 2010 by OBJECTIVE DEVELOPMENT Software GmbH.
http://www.obdev.at/

View File

@ -0,0 +1,149 @@
Version 2012-07-09
==========================
WHY DO WE NEED THESE IDs?
==========================
USB is more than a low level protocol for data transport. It also defines a
common set of requests which must be understood by all devices. And as part
of these common requests, the specification defines data structures, the
USB Descriptors, which are used to describe the properties of the device.
From the perspective of an operating system, it is therefore possible to find
out basic properties of a device (such as e.g. the manufacturer and the name
of the device) without a device-specific driver. This is essential because
the operating system can choose a driver to load based on this information
(Plug-And-Play).
Among the most important properties in the Device Descriptor are the USB
Vendor- and Product-ID. Both are 16 bit integers. The most simple form of
driver matching is based on these IDs. The driver announces the Vendor- and
Product-IDs of the devices it can handle and the operating system loads the
appropriate driver when the device is connected.
It is obvious that this technique only works if the pair Vendor- plus
Product-ID is unique: Only devices which require the same driver can have the
same pair of IDs.
=====================================================
HOW DOES THE USB STANDARD ENSURE THAT IDs ARE UNIQUE?
=====================================================
Since it is so important that USB IDs are unique, the USB Implementers Forum,
Inc. (usb.org) needs a way to enforce this legally. It is not forbidden by
law to build a device and assign it any random numbers as IDs. Usb.org
therefore needs an agreement to regulate the use of USB IDs. The agreement
binds only parties who agreed to it, of course. Everybody else is free to use
any numbers for their IDs.
So how can usb.org ensure that every manufacturer of USB devices enters into
an agreement with them? They do it via trademark licensing. Usb.org has
registered the trademark "USB", all associated logos and related terms. If
you want to put an USB logo on your product or claim that it is USB
compliant, you must license these trademarks from usb.org. And this is where
you enter into an agreement. See the "USB-IF Trademark License Agreement and
Usage Guidelines for the USB-IF Logo" at
http://www.usb.org/developers/logo_license/.
Licensing the USB trademarks requires that you buy a USB Vendor-ID from
usb.org (one-time fee of ca. 2,000 USD), that you become a member of usb.org
(yearly fee of ca. 4,000 USD) and that you meet all the technical
specifications from the USB spec.
This means that most hobbyists and small companies will never be able to
become USB compliant, just because membership is so expensive. And you can't
be compliant with a driver based on V-USB anyway, because the AVR's port pins
don't meet the electrical specifications for USB. So, in principle, all
hobbyists and small companies are free to choose any random numbers for their
IDs. They have nothing to lose...
There is one exception worth noting, though: If you use a sub-component which
implements USB, the vendor of the sub-components may guarantee USB
compliance. This might apply to some or all of FTDI's solutions.
=======================================================================
WHY SHOULD YOU OBTAIN USB IDs EVEN IF YOU DON'T LICENSE USB TRADEMARKS?
=======================================================================
You have learned in the previous section that you are free to choose any
numbers for your IDs anyway. So why not do exactly this? There is still the
technical issue. If you choose IDs which are already in use by somebody else,
operating systems will load the wrong drivers and your device won't work.
Even if you choose IDs which are not currently in use, they may be in use in
the next version of the operating system or even after an automatic update.
So what you need is a pair of Vendor- and Product-IDs for which you have the
guarantee that no USB compliant product uses them. This implies that no
operating system will ever ship with drivers responsible for these IDs.
==============================================
HOW DOES OBJECTIVE DEVELOPMENT HANDLE USB IDs?
==============================================
Objective Development gives away pairs of USB-IDs with their V-USB licenses.
In order to ensure that these IDs are unique, Objective Development has an
agreement with the company/person who has bought the USB Vendor-ID from
usb.org. This agreement ensures that a range of USB Product-IDs is reserved
for assignment by Objective Development and that the owner of the Vendor-ID
won't give it to anybody else.
This means that you have to trust three parties to ensure uniqueness of
your IDs:
- Objective Development, that they don't give the same PID to more than
one person.
- The owner of the Vendor-ID that they don't assign PIDs from the range
assigned to Objective Development to anybody else.
- Usb.org that they don't assign the same Vendor-ID a second time.
==================================
WHO IS THE OWNER OF THE VENDOR-ID?
==================================
Objective Development has obtained ranges of USB Product-IDs under two
Vendor-IDs: Under Vendor-ID 5824 from Wouter van Ooijen (Van Ooijen
Technische Informatica, www.voti.nl) and under Vendor-ID 8352 from Jason
Kotzin (now flirc.tv, Inc.). Both VID owners have received their Vendor-ID
directly from usb.org.
=========================================================================
CAN I USE USB-IDs FROM OBJECTIVE DEVELOPMENT WITH OTHER DRIVERS/HARDWARE?
=========================================================================
The short answer is: Yes. All you get is a guarantee that the IDs are never
assigned to anybody else. What more do you need?
============================
WHAT ABOUT SHARED ID PAIRS?
============================
Objective Development has reserved some PID/VID pairs for shared use. You
have no guarantee of uniqueness for them, except that no USB compliant device
uses them. In order to avoid technical problems, we must ensure that all
devices with the same pair of IDs use the same driver on kernel level. For
details, see the file USB-IDs-for-free.txt.
======================================================
I HAVE HEARD THAT SUB-LICENSING OF USB-IDs IS ILLEGAL?
======================================================
A 16 bit integer number cannot be protected by copyright laws. It is not
sufficiently complex. And since none of the parties involved entered into the
USB-IF Trademark License Agreement, we are not bound by this agreement. So
there is no reason why it should be illegal to sub-license USB-IDs.
=============================================
WHO IS LIABLE IF THERE ARE INCOMPATIBILITIES?
=============================================
Objective Development disclaims all liabilities which might arise from the
assignment of IDs. If you guarantee product features to your customers
without proper disclaimer, YOU are liable for that.

View File

@ -0,0 +1,154 @@
Version 2009-08-22
===========================
FREE USB-IDs FOR SHARED USE
===========================
Objective Development has reserved a set of USB Product-IDs for use according
to the guidelines outlined below. For more information about the concept of
USB IDs please see the file USB-ID-FAQ.txt. Objective Development guarantees
that the IDs listed below are not used by any USB compliant devices.
====================
MECHANISM OF SHARING
====================
From a technical point of view, two different devices can share the same USB
Vendor- and Product-ID if they require the same driver on operating system
level. We make use of this fact by assigning separate IDs for various device
classes. On application layer, devices must be distinguished by their textual
name or serial number. We offer separate sets of IDs for discrimination by
textual name and for serial number.
Examples for shared use of USB IDs are included with V-USB in the "examples"
subdirectory.
======================================
IDs FOR DISCRIMINATION BY TEXTUAL NAME
======================================
If you use one of the IDs listed below, your device and host-side software
must conform to these rules:
(1) The USB device MUST provide a textual representation of the manufacturer
and product identification. The manufacturer identification MUST be available
at least in USB language 0x0409 (English/US).
(2) The textual manufacturer identification MUST contain either an Internet
domain name (e.g. "mycompany.com") registered and owned by you, or an e-mail
address under your control (e.g. "myname@gmx.net"). You can embed the domain
name or e-mail address in any string you like, e.g. "Objective Development
http://www.obdev.at/vusb/".
(3) You are responsible for retaining ownership of the domain or e-mail
address for as long as any of your products are in use.
(4) You may choose any string for the textual product identification, as long
as this string is unique within the scope of your textual manufacturer
identification.
(5) Application side device look-up MUST be based on the textual manufacturer
and product identification in addition to VID/PID matching. The driver
matching MUST be a comparison of the entire strings, NOT a sub-string match.
(6) For devices which implement a particular USB device class (e.g. HID), the
operating system's default class driver MUST be used. If an operating system
driver for Vendor Class devices is needed, this driver must be libusb or
libusb-win32 (see http://libusb.org/ and
http://libusb-win32.sourceforge.net/).
Table if IDs for discrimination by textual name:
PID dec (hex) | VID dec (hex) | Description of use
==============+===============+============================================
1500 (0x05dc) | 5824 (0x16c0) | For Vendor Class devices with libusb
--------------+---------------+--------------------------------------------
1503 (0x05df) | 5824 (0x16c0) | For generic HID class devices (which are
| | NOT mice, keyboards or joysticks)
--------------+---------------+--------------------------------------------
1505 (0x05e1) | 5824 (0x16c0) | For CDC-ACM class devices (modems)
--------------+---------------+--------------------------------------------
1508 (0x05e4) | 5824 (0x16c0) | For MIDI class devices
--------------+---------------+--------------------------------------------
Note that Windows caches the textual product- and vendor-description for
mice, keyboards and joysticks. Name-bsed discrimination is therefore not
recommended for these device classes.
=======================================
IDs FOR DISCRIMINATION BY SERIAL NUMBER
=======================================
If you use one of the IDs listed below, your device and host-side software
must conform to these rules:
(1) The USB device MUST provide a textual representation of the serial
number, unless ONLY the operating system's default class driver is used.
The serial number string MUST be available at least in USB language 0x0409
(English/US).
(2) The serial number MUST start with either an Internet domain name (e.g.
"mycompany.com") registered and owned by you, or an e-mail address under your
control (e.g. "myname@gmx.net"), both terminated with a colon (":") character.
You MAY append any string you like for further discrimination of your devices.
(3) You are responsible for retaining ownership of the domain or e-mail
address for as long as any of your products are in use.
(5) Application side device look-up MUST be based on the serial number string
in addition to VID/PID matching. The matching must start at the first
character of the serial number string and include the colon character
terminating your domain or e-mail address. It MAY stop anywhere after that.
(6) For devices which implement a particular USB device class (e.g. HID), the
operating system's default class driver MUST be used. If an operating system
driver for Vendor Class devices is needed, this driver must be libusb or
libusb-win32 (see http://libusb.org/ and
http://libusb-win32.sourceforge.net/).
(7) If ONLY the operating system's default class driver is used, e.g. for
mice, keyboards, joysticks, CDC or MIDI devices and no discrimination by an
application is needed, the serial number may be omitted.
Table if IDs for discrimination by serial number string:
PID dec (hex) | VID dec (hex) | Description of use
===============+===============+===========================================
10200 (0x27d8) | 5824 (0x16c0) | For Vendor Class devices with libusb
---------------+---------------+-------------------------------------------
10201 (0x27d9) | 5824 (0x16c0) | For generic HID class devices (which are
| | NOT mice, keyboards or joysticks)
---------------+---------------+-------------------------------------------
10202 (0x27da) | 5824 (0x16c0) | For USB Mice
---------------+---------------+-------------------------------------------
10203 (0x27db) | 5824 (0x16c0) | For USB Keyboards
---------------+---------------+-------------------------------------------
10204 (0x27dc) | 5824 (0x16c0) | For USB Joysticks
---------------+---------------+-------------------------------------------
10205 (0x27dd) | 5824 (0x16c0) | For CDC-ACM class devices (modems)
---------------+---------------+-------------------------------------------
10206 (0x27de) | 5824 (0x16c0) | For MIDI class devices
---------------+---------------+-------------------------------------------
=================
ORIGIN OF USB-IDs
=================
OBJECTIVE DEVELOPMENT Software GmbH has obtained all VID/PID pairs listed
here from Wouter van Ooijen (see www.voti.nl) for exclusive disposition.
Wouter van Ooijen has obtained the VID from the USB Implementers Forum, Inc.
(see www.usb.org). The VID is registered for the company name "Van Ooijen
Technische Informatica".
==========
DISCLAIMER
==========
OBJECTIVE DEVELOPMENT Software GmbH disclaims all liability for any
problems which are caused by the shared use of these VID/PID pairs.

View File

@ -0,0 +1,79 @@
This is the Readme file for the V-USB example circuits directory.
CIRCUITS IN THIS DIRECTORY
==========================
Since USB requires 3.3 V levels on D+ and D- but delivers a power supply of
ca. 5 V, some kind of level conversion must be performed. There are several
ways to implement this level conversion, see the example circuits below.
with-vreg.png and with-vreg.sch (EAGLE schematics):
This circuit uses a low drop voltage regulator to reduce the USB supply to
3.3 V. You MUST use a low drop regulator because standard regulators such
as the LM317 require at least ca. 2 V drop. The advantage of this approach
is that it comes closest to the voltage levels required by the USB
specification and that the circuit is powered from a regulated supply. If
no USB cable is used (connector directly soldered on PCB), you can even
omit the 68 Ohm series resistors. The disadvantage is that you may want to
use other chips in your design which require 5 V. Please check that the AVR
used in your design allows the chosen clock rate at 3.3 V.
with-zener.png and with-zener.sch (EAGLE schematics):
This circuit enforces lower voltage levels on D+ and D- with zener diodes.
The zener diodes MUST be low power / low current types to ensure that the
1k5 pull-up resistor on D- generates a voltage of well above 2.5 V (but
below 3.6 V). The advantage of this circuit is its simplicity and that the
circuit can be powered at 5 V (usually precise enough if the cable drop is
neglected). The disadvantage is that some zener diodes have a lower voltage
than 3 V when powered through 1k5 and the choice of components becomes
relevant. In addition to that, the power consumption during USB data
transfer is increased because the current is only limited by the 68 Ohm
series resistor. The zeners may even distort the signal waveforms due to
their capacity.
with-series-diodes.png and with-series-diodes.sch (EAGLE schematics):
This is a simplified low-cost version of the voltage regulator approach.
Instead of using a voltage regulator, we reduce the voltage by the forward
voltage of two silicon diodes (roughly 1.4 V). This gives ca. 3.6 V which
is practically inside the allowed range. The big disadvantage is that the
supply is not regulated -- it even depends strongly on the power
consumption. This cannot be tolerated for analog circuits.
tiny45-rc.png and tiny45-rc.sch (EAGLE schematics):
This is mostly an example for connecting an 8 pin device using the internal
RC oscillator for system clock. This example uses series diodes to limit
the supply, but you may choose any other method. Please note that you must
choose a clock rate of 12.8 or 16.5 MHz because only the receiver modules
for these frequencies have a PLL to allow higher clock rate tolerances.
GENERAL DESIGN NOTES
====================
All examples have D+ on hardware interrupt INT0 because this is the highest
priority interrupt on AVRs. You may use other hardware interrupts (and
configure the options at the end of usbconfig.h accordingly) if you make sure
that no higher priority interrupt is used.
If you use USB_SOF_HOOK or USB_COUNT_SOF in usbconfig.h, you must wire D- to
the interrupt instead. This way the interrupt is triggered on USB Start Of
Frame pulses as well.
Most examples have a 1M pull-down resistor at D+. This pull-up ensures that
in self-powered designs no interrupts occur while USB is not connected. You
may omit this resistor in bus-powered designs. Older examples had a pull-up
resistor instead. This is not compatible with the zener diode approach to
level conversion: 1M pull-up in conjunction with a 3.6 V zener diode give an
invalid logic level.
All examples with ATMega8/88/168 have D+ at port D bit 2 (because this is
hardware interrupt 0) and D- on port D bit 4 because it is also a clock input
for timer/counter 0. This way the firmware can easily check for activity on
D- (USB frame pulses) by checking the counter value in regular intervals. If
no activity is found, the firmware should (according to the USB
specification) put the system into a low power suspend mode.
----------------------------------------------------------------------------
(c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH.
http://www.obdev.at/

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

View File

@ -0,0 +1,102 @@
This is the Readme file for the directory "examples" of V-USB, a firmware-
only USB driver for AVR microcontrollers.
WHAT IS IN THIS DIRECTORY?
==========================
This directory contains examples which are mostly for educational purposes.
Examples can be device firmware only, host software only or both. Here is
a summary:
custom-class
A custom class device with host software based on libusb. It demonstrates
the straight forward way of sending small amounts of data to a device and
receiving data from the device. It does NOT demonstrate how to send large
amounts of data to the device or how to receive data generated on the fly
by the device (how to use usbFunctionWrite() and usbFunctionRead()). See
the hid-data example for how usbFunctionWrite() and usbFunctionRead() are
used.
hid-custom-rq
This example implements the same functionality as the custom-class example
above, but declares the device as HID. This prevents the "give me a driver
CD" dialog on Windows. The device can still be controlled with libusb as in
the previous example (on Windows, the filter version of libusb-win32 must
be installed). In addition to the features presented in custom-class, this
example demonstrates how a HID class device is defined.
hid-mouse
This example implements a mouse device. No host driver is required since
today's operating systems have drivers for USB mice built-in. It
demonstrates how a real-world HID class device is implemented and how
interrupt-in endpoints are used.
hid-data
This example demonstrates how the HID class can be misused to transfer
arbitrary data over HID feature reports. This technique is of great value
on Windows because no driver DLLs are needed (the hid-custom-rq example
still requires the libusb-win32 DLL, although it may be in the program's
directory). The host side application requires no installation, it can
even be started directly from a CD. This example also demonstrates how
to transfer data using usbFunctionWrite() and usbFunctionRead().
usbtool
This is a general purpose development and debugging tool for USB devices.
You can use it during development of your device to test various requests
without special test programs. But it is also an example how all the
libusb API functions are used.
More information about each example can be found in the Readme file in the
respective directory.
Hardware dependencies of AVR code has been kept at a minimum. All examples
should work on any AVR chip which has enough resources to run the driver.
Makefile and usbconfig.h have been configured for the metaboard hardware (see
http://www.obdev.at/goto.php?t=metaboard for details). Edit the target
device, fuse values, clock rate and programmer in Makefile and the I/O pins
dedicated to USB in usbconfig.h.
WHAT IS NOT DEMONSTRATED IN THESE EXAMPLES?
===========================================
These examples show only the most basic functionality. More elaborate
examples and real world applications showing more features of the driver are
available at http://www.obdev.at/vusb/projects.html. Most of these
features are described in our documentation wiki at
http://www.obdev.at/goto.php?t=vusb-wiki.
To mention just a few:
Using RC oscillator for system clock
The 12.8 MHz and 16.5 MHz modules of V-USB have been designed to cope
with clock rate deviations up to 1%. This allows an RC oscillator to be
used. Since the AVR's RC oscillator has a factory precision of only 10%,
it must be calibrated to an external reference. The EasyLogger example
shows how this can be done.
Dynamically generated descriptors
Sometimes you want to implement different typtes of USB device depending
on a jumper or other condition. V-USB has a very flexible interface for
providing USB descriptors. See AVR-Doper for how to provide descriptors
at runtime.
Virtual COM port
Some people prefer a virtual serial interface to communicate with their
device. We strongly discourage this method because it does things
forbidden by the USB specification. If you still want to go this route,
see AVR-CDC.
Implementing suspend mode
V-USB does not implement suspend mode. This means that the device does
not reduce power consumption when the host goes into sleep mode. Device
firmware is free to implement suspend mode, though. See USB2LPT for an
example.
The projects mentioned above can best be found on
http://www.obdev.at/vusb/prjall.html
where all projects are listed.
----------------------------------------------------------------------------
(c) 2009 by OBJECTIVE DEVELOPMENT Software GmbH.
http://www.obdev.at/

View File

@ -0,0 +1,64 @@
This is the Readme file for the custom-class example. In this example, we
show how an LED can be controlled via USB.
WHAT IS DEMONSTRATED?
=====================
This example shows how small amounts of data (several bytes) can be
transferred between the device and the host. In addition to a very basic
USB device, it demonstrates how to build a host side driver application
using libusb or libusb-win32. It does NOT show how usbFunctionWrite() and
usbFunctionRead() are used. See the hid-data example if you want to learn
about these functions.
PREREQUISITES
=============
Target hardware: You need an AVR based circuit based on one of the examples
(see the "circuits" directory at the top level of this package), e.g. the
metaboard (http://www.obdev.at/goto.php?t=metaboard).
AVR development environment: You need the gcc tool chain for the AVR, see
the Prerequisites section in the top level Readme file for how to obtain it.
Host development environment: A C compiler and libusb. See the top level
Readme file, section Prerequisites for more information.
BUILDING THE FIRMWARE
=====================
Change to the "firmware" directory and modify Makefile according to your
architecture (CPU clock, target device, fuse values) and ISP programmer. Then
edit usbconfig.h according to your pin assignments for D+ and D-. The default
settings are for the metaboard hardware. You should have wired an LED with a
current limiting resistor of ca. 270 Ohm to a free I/O pin. Change the
defines in main.c to match the port and bit number.
Type "make hex" to build main.hex, then "make flash" to upload the firmware
to the device. Don't forget to run "make fuse" once to program the fuses. If
you use a prototyping board with boot loader, follow the instructions of the
boot loader instead.
Please note that the first "make hex" copies the driver from the top level
into the firmware directory. If you use a different build system than our
Makefile, you must copy the driver by hand.
BUILDING THE HOST SOFTWARE
==========================
Since the host software is based on libusb or libusb-win32, make sure that
this library is installed. On Unix, ensure that libusb-config is in your
search PATH. On Windows, edit Makefile.windows and set the library path
appropriately. Then type "make" on Unix or "make -f Makefile.windows" on
Windows to build the command line tool.
USING THE COMMAND LINE TOOL
===========================
The command line tool has three valid arguments: "status" to query the
current LED status, "on" to turn on the LED and "off" to turn it off.
----------------------------------------------------------------------------
(c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH.
http://www.obdev.at/

View File

@ -0,0 +1,47 @@
# Name: Makefile
# Project: custom-class example
# Author: Christian Starkjohann
# Creation Date: 2008-04-06
# Tabsize: 4
# Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
# Concigure the following definitions according to your system.
# This Makefile has been tested on Mac OS X, Linux and Windows.
# Use the following 3 lines on Unix (uncomment the framework on Mac OS X):
USBFLAGS = `libusb-config --cflags`
USBLIBS = `libusb-config --libs`
EXE_SUFFIX =
# Use the following 3 lines on Windows and comment out the 3 above. You may
# have to change the include paths to where you installed libusb-win32
#USBFLAGS = -I/usr/local/include
#USBLIBS = -L/usr/local/lib -lusb
#EXE_SUFFIX = .exe
NAME = set-led
OBJECTS = opendevice.o $(NAME).o
CC = gcc
CFLAGS = $(CPPFLAGS) $(USBFLAGS) -O -g -Wall
LIBS = $(USBLIBS)
PROGRAM = $(NAME)$(EXE_SUFFIX)
all: $(PROGRAM)
.c.o:
$(CC) $(CFLAGS) -c $<
$(PROGRAM): $(OBJECTS)
$(CC) -o $(PROGRAM) $(OBJECTS) $(LIBS)
strip: $(PROGRAM)
strip $(PROGRAM)
clean:
rm -f *.o $(PROGRAM)

View File

@ -0,0 +1,17 @@
# Name: Makefile.windows
# Project: custom-class example
# Author: Christian Starkjohann
# Creation Date: 2008-04-06
# Tabsize: 4
# Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
# You may use this file with
# make -f Makefile.windows
# on Windows with MinGW instead of editing the main Makefile.
include Makefile
USBFLAGS = -I/usr/local/mingw/include
USBLIBS = -L/usr/local/mingw/lib -lusb
EXE_SUFFIX = .exe

View File

@ -0,0 +1,202 @@
/* Name: opendevice.c
* Project: V-USB host-side library
* Author: Christian Starkjohann
* Creation Date: 2008-04-10
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
General Description:
The functions in this module can be used to find and open a device based on
libusb or libusb-win32.
*/
#include <stdio.h>
#include "opendevice.h"
/* ------------------------------------------------------------------------- */
#define MATCH_SUCCESS 1
#define MATCH_FAILED 0
#define MATCH_ABORT -1
/* private interface: match text and p, return MATCH_SUCCESS, MATCH_FAILED, or MATCH_ABORT. */
static int _shellStyleMatch(char *text, char *p)
{
int last, matched, reverse;
for(; *p; text++, p++){
if(*text == 0 && *p != '*')
return MATCH_ABORT;
switch(*p){
case '\\':
/* Literal match with following character. */
p++;
/* FALLTHROUGH */
default:
if(*text != *p)
return MATCH_FAILED;
continue;
case '?':
/* Match anything. */
continue;
case '*':
while(*++p == '*')
/* Consecutive stars act just like one. */
continue;
if(*p == 0)
/* Trailing star matches everything. */
return MATCH_SUCCESS;
while(*text)
if((matched = _shellStyleMatch(text++, p)) != MATCH_FAILED)
return matched;
return MATCH_ABORT;
case '[':
reverse = p[1] == '^';
if(reverse) /* Inverted character class. */
p++;
matched = MATCH_FAILED;
if(p[1] == ']' || p[1] == '-')
if(*++p == *text)
matched = MATCH_SUCCESS;
for(last = *p; *++p && *p != ']'; last = *p)
if (*p == '-' && p[1] != ']' ? *text <= *++p && *text >= last : *text == *p)
matched = MATCH_SUCCESS;
if(matched == reverse)
return MATCH_FAILED;
continue;
}
}
return *text == 0;
}
/* public interface for shell style matching: returns 0 if fails, 1 if matches */
static int shellStyleMatch(char *text, char *pattern)
{
if(pattern == NULL) /* NULL pattern is synonymous to "*" */
return 1;
return _shellStyleMatch(text, pattern) == MATCH_SUCCESS;
}
/* ------------------------------------------------------------------------- */
int usbGetStringAscii(usb_dev_handle *dev, int index, char *buf, int buflen)
{
char buffer[256];
int rval, i;
if((rval = usb_get_string_simple(dev, index, buf, buflen)) >= 0) /* use libusb version if it works */
return rval;
if((rval = usb_control_msg(dev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR, (USB_DT_STRING << 8) + index, 0x0409, buffer, sizeof(buffer), 5000)) < 0)
return rval;
if(buffer[1] != USB_DT_STRING){
*buf = 0;
return 0;
}
if((unsigned char)buffer[0] < rval)
rval = (unsigned char)buffer[0];
rval /= 2;
/* lossy conversion to ISO Latin1: */
for(i=1;i<rval;i++){
if(i > buflen) /* destination buffer overflow */
break;
buf[i-1] = buffer[2 * i];
if(buffer[2 * i + 1] != 0) /* outside of ISO Latin1 range */
buf[i-1] = '?';
}
buf[i-1] = 0;
return i-1;
}
/* ------------------------------------------------------------------------- */
int usbOpenDevice(usb_dev_handle **device, int vendorID, char *vendorNamePattern, int productID, char *productNamePattern, char *serialNamePattern, FILE *printMatchingDevicesFp, FILE *warningsFp)
{
struct usb_bus *bus;
struct usb_device *dev;
usb_dev_handle *handle = NULL;
int errorCode = USBOPEN_ERR_NOTFOUND;
usb_find_busses();
usb_find_devices();
for(bus = usb_get_busses(); bus; bus = bus->next){
for(dev = bus->devices; dev; dev = dev->next){ /* iterate over all devices on all busses */
if((vendorID == 0 || dev->descriptor.idVendor == vendorID)
&& (productID == 0 || dev->descriptor.idProduct == productID)){
char vendor[256], product[256], serial[256];
int len;
handle = usb_open(dev); /* we need to open the device in order to query strings */
if(!handle){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot open VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
continue;
}
/* now check whether the names match: */
len = vendor[0] = 0;
if(dev->descriptor.iManufacturer > 0){
len = usbGetStringAscii(handle, dev->descriptor.iManufacturer, vendor, sizeof(vendor));
}
if(len < 0){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot query manufacturer for VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
}else{
errorCode = USBOPEN_ERR_NOTFOUND;
/* printf("seen device from vendor ->%s<-\n", vendor); */
if(shellStyleMatch(vendor, vendorNamePattern)){
len = product[0] = 0;
if(dev->descriptor.iProduct > 0){
len = usbGetStringAscii(handle, dev->descriptor.iProduct, product, sizeof(product));
}
if(len < 0){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot query product for VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
}else{
errorCode = USBOPEN_ERR_NOTFOUND;
/* printf("seen product ->%s<-\n", product); */
if(shellStyleMatch(product, productNamePattern)){
len = serial[0] = 0;
if(dev->descriptor.iSerialNumber > 0){
len = usbGetStringAscii(handle, dev->descriptor.iSerialNumber, serial, sizeof(serial));
}
if(len < 0){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot query serial for VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
}
if(shellStyleMatch(serial, serialNamePattern)){
if(printMatchingDevicesFp != NULL){
if(serial[0] == 0){
fprintf(printMatchingDevicesFp, "VID=0x%04x PID=0x%04x vendor=\"%s\" product=\"%s\"\n", dev->descriptor.idVendor, dev->descriptor.idProduct, vendor, product);
}else{
fprintf(printMatchingDevicesFp, "VID=0x%04x PID=0x%04x vendor=\"%s\" product=\"%s\" serial=\"%s\"\n", dev->descriptor.idVendor, dev->descriptor.idProduct, vendor, product, serial);
}
}else{
break;
}
}
}
}
}
}
usb_close(handle);
handle = NULL;
}
}
if(handle) /* we have found a deice */
break;
}
if(handle != NULL){
errorCode = 0;
*device = handle;
}
if(printMatchingDevicesFp != NULL) /* never return an error for listing only */
errorCode = 0;
return errorCode;
}
/* ------------------------------------------------------------------------- */

View File

@ -0,0 +1,76 @@
/* Name: opendevice.h
* Project: V-USB host-side library
* Author: Christian Starkjohann
* Creation Date: 2008-04-10
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
General Description:
This module offers additional functionality for host side drivers based on
libusb or libusb-win32. It includes a function to find and open a device
based on numeric IDs and textual description. It also includes a function to
obtain textual descriptions from a device.
To use this functionality, simply copy opendevice.c and opendevice.h into your
project and add them to your Makefile. You may modify and redistribute these
files according to the GNU General Public License (GPL) version 2 or 3.
*/
#ifndef __OPENDEVICE_H_INCLUDED__
#define __OPENDEVICE_H_INCLUDED__
#include <usb.h> /* this is libusb, see http://libusb.sourceforge.net/ */
#include <stdio.h>
int usbGetStringAscii(usb_dev_handle *dev, int index, char *buf, int buflen);
/* This function gets a string descriptor from the device. 'index' is the
* string descriptor index. The string is returned in ISO Latin 1 encoding in
* 'buf' and it is terminated with a 0-character. The buffer size must be
* passed in 'buflen' to prevent buffer overflows. A libusb device handle
* must be given in 'dev'.
* Returns: The length of the string (excluding the terminating 0) or
* a negative number in case of an error. If there was an error, use
* usb_strerror() to obtain the error message.
*/
int usbOpenDevice(usb_dev_handle **device, int vendorID, char *vendorNamePattern, int productID, char *productNamePattern, char *serialNamePattern, FILE *printMatchingDevicesFp, FILE *warningsFp);
/* This function iterates over all devices on all USB busses and searches for
* a device. Matching is done first by means of Vendor- and Product-ID (passed
* in 'vendorID' and 'productID'. An ID of 0 matches any numeric ID (wildcard).
* When a device matches by its IDs, matching by names is performed. Name
* matching can be done on textual vendor name ('vendorNamePattern'), product
* name ('productNamePattern') and serial number ('serialNamePattern'). A
* device matches only if all non-null pattern match. If you don't care about
* a string, pass NULL for the pattern. Patterns are Unix shell style pattern:
* '*' stands for 0 or more characters, '?' for one single character, a list
* of characters in square brackets for a single character from the list
* (dashes are allowed to specify a range) and if the lis of characters begins
* with a caret ('^'), it matches one character which is NOT in the list.
* Other parameters to the function: If 'warningsFp' is not NULL, warning
* messages are printed to this file descriptor with fprintf(). If
* 'printMatchingDevicesFp' is not NULL, no device is opened but matching
* devices are printed to the given file descriptor with fprintf().
* If a device is opened, the resulting USB handle is stored in '*device'. A
* pointer to a "usb_dev_handle *" type variable must be passed here.
* Returns: 0 on success, an error code (see defines below) on failure.
*/
/* usbOpenDevice() error codes: */
#define USBOPEN_SUCCESS 0 /* no error */
#define USBOPEN_ERR_ACCESS 1 /* not enough permissions to open device */
#define USBOPEN_ERR_IO 2 /* I/O error */
#define USBOPEN_ERR_NOTFOUND 3 /* device not found */
/* Obdev's free USB IDs, see USB-IDs-for-free.txt for details */
#define USB_VID_OBDEV_SHARED 5824 /* obdev's shared vendor ID */
#define USB_PID_OBDEV_SHARED_CUSTOM 1500 /* shared PID for custom class devices */
#define USB_PID_OBDEV_SHARED_HID 1503 /* shared PID for HIDs except mice & keyboards */
#define USB_PID_OBDEV_SHARED_CDCACM 1505 /* shared PID for CDC Modem devices */
#define USB_PID_OBDEV_SHARED_MIDI 1508 /* shared PID for MIDI class devices */
#endif /* __OPENDEVICE_H_INCLUDED__ */

View File

@ -0,0 +1,134 @@
/* Name: set-led.c
* Project: custom-class, a basic USB example
* Author: Christian Starkjohann
* Creation Date: 2008-04-10
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
General Description:
This is the host-side driver for the custom-class example device. It searches
the USB for the LEDControl device and sends the requests understood by this
device.
This program must be linked with libusb on Unix and libusb-win32 on Windows.
See http://libusb.sourceforge.net/ or http://libusb-win32.sourceforge.net/
respectively.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <usb.h> /* this is libusb */
#include "opendevice.h" /* common code moved to separate module */
#include "../firmware/requests.h" /* custom request numbers */
#include "../firmware/usbconfig.h" /* device's VID/PID and names */
static void usage(char *name)
{
fprintf(stderr, "usage:\n");
fprintf(stderr, " %s on ....... turn on LED\n", name);
fprintf(stderr, " %s off ...... turn off LED\n", name);
fprintf(stderr, " %s status ... ask current status of LED\n", name);
#if ENABLE_TEST
fprintf(stderr, " %s test ..... run driver reliability test\n", name);
#endif /* ENABLE_TEST */
}
int main(int argc, char **argv)
{
usb_dev_handle *handle = NULL;
const unsigned char rawVid[2] = {USB_CFG_VENDOR_ID}, rawPid[2] = {USB_CFG_DEVICE_ID};
char vendor[] = {USB_CFG_VENDOR_NAME, 0}, product[] = {USB_CFG_DEVICE_NAME, 0};
char buffer[4];
int cnt, vid, pid, isOn;
usb_init();
if(argc < 2){ /* we need at least one argument */
usage(argv[0]);
exit(1);
}
/* compute VID/PID from usbconfig.h so that there is a central source of information */
vid = rawVid[1] * 256 + rawVid[0];
pid = rawPid[1] * 256 + rawPid[0];
/* The following function is in opendevice.c: */
if(usbOpenDevice(&handle, vid, vendor, pid, product, NULL, NULL, NULL) != 0){
fprintf(stderr, "Could not find USB device \"%s\" with vid=0x%x pid=0x%x\n", product, vid, pid);
exit(1);
}
/* Since we use only control endpoint 0, we don't need to choose a
* configuration and interface. Reading device descriptor and setting a
* configuration and interface is done through endpoint 0 after all.
* However, newer versions of Linux require that we claim an interface
* even for endpoint 0. Enable the following code if your operating system
* needs it: */
#if 0
int retries = 1, usbConfiguration = 1, usbInterface = 0;
if(usb_set_configuration(handle, usbConfiguration) && showWarnings){
fprintf(stderr, "Warning: could not set configuration: %s\n", usb_strerror());
}
/* now try to claim the interface and detach the kernel HID driver on
* Linux and other operating systems which support the call. */
while((len = usb_claim_interface(handle, usbInterface)) != 0 && retries-- > 0){
#ifdef LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP
if(usb_detach_kernel_driver_np(handle, 0) < 0 && showWarnings){
fprintf(stderr, "Warning: could not detach kernel driver: %s\n", usb_strerror());
}
#endif
}
#endif
if(strcasecmp(argv[1], "status") == 0){
cnt = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN, CUSTOM_RQ_GET_STATUS, 0, 0, buffer, sizeof(buffer), 5000);
if(cnt < 1){
if(cnt < 0){
fprintf(stderr, "USB error: %s\n", usb_strerror());
}else{
fprintf(stderr, "only %d bytes received.\n", cnt);
}
}else{
printf("LED is %s\n", buffer[0] ? "on" : "off");
}
}else if((isOn = (strcasecmp(argv[1], "on") == 0)) || strcasecmp(argv[1], "off") == 0){
cnt = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_OUT, CUSTOM_RQ_SET_STATUS, isOn, 0, buffer, 0, 5000);
if(cnt < 0){
fprintf(stderr, "USB error: %s\n", usb_strerror());
}
#if ENABLE_TEST
}else if(strcasecmp(argv[1], "test") == 0){
int i;
srandomdev();
for(i = 0; i < 50000; i++){
int value = random() & 0xffff, index = random() & 0xffff;
int rxValue, rxIndex;
if((i+1) % 100 == 0){
fprintf(stderr, "\r%05d", i+1);
fflush(stderr);
}
cnt = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN, CUSTOM_RQ_ECHO, value, index, buffer, sizeof(buffer), 5000);
if(cnt < 0){
fprintf(stderr, "\nUSB error in iteration %d: %s\n", i, usb_strerror());
break;
}else if(cnt != 4){
fprintf(stderr, "\nerror in iteration %d: %d bytes received instead of 4\n", i, cnt);
break;
}
rxValue = ((int)buffer[0] & 0xff) | (((int)buffer[1] & 0xff) << 8);
rxIndex = ((int)buffer[2] & 0xff) | (((int)buffer[3] & 0xff) << 8);
if(rxValue != value || rxIndex != index){
fprintf(stderr, "\ndata error in iteration %d:\n", i);
fprintf(stderr, "rxValue = 0x%04x value = 0x%04x\n", rxValue, value);
fprintf(stderr, "rxIndex = 0x%04x index = 0x%04x\n", rxIndex, index);
}
}
fprintf(stderr, "\nTest completed.\n");
#endif /* ENABLE_TEST */
}else{
usage(argv[0]);
exit(1);
}
usb_close(handle);
return 0;
}

View File

@ -0,0 +1,163 @@
# Name: Makefile
# Project: custom-class example
# Author: Christian Starkjohann
# Creation Date: 2008-04-07
# Tabsize: 4
# Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
DEVICE = atmega168
F_CPU = 16000000 # in Hz
FUSE_L = # see below for fuse values for particular devices
FUSE_H =
AVRDUDE = avrdude -c usbasp -p $(DEVICE) # edit this line for your programmer
CFLAGS = -Iusbdrv -I. -DDEBUG_LEVEL=0
OBJECTS = usbdrv/usbdrv.o usbdrv/usbdrvasm.o usbdrv/oddebug.o main.o
COMPILE = avr-gcc -Wall -Os -DF_CPU=$(F_CPU) $(CFLAGS) -mmcu=$(DEVICE)
##############################################################################
# Fuse values for particular devices
##############################################################################
# If your device is not listed here, go to
# http://palmavr.sourceforge.net/cgi-bin/fc.cgi
# and choose options for external crystal clock and no clock divider
#
################################## ATMega8 ##################################
# ATMega8 FUSE_L (Fuse low byte):
# 0x9f = 1 0 0 1 1 1 1 1
# ^ ^ \ / \--+--/
# | | | +------- CKSEL 3..0 (external >8M crystal)
# | | +--------------- SUT 1..0 (crystal osc, BOD enabled)
# | +------------------ BODEN (BrownOut Detector enabled)
# +-------------------- BODLEVEL (2.7V)
# ATMega8 FUSE_H (Fuse high byte):
# 0xc9 = 1 1 0 0 1 0 0 1 <-- BOOTRST (boot reset vector at 0x0000)
# ^ ^ ^ ^ ^ ^ ^------ BOOTSZ0
# | | | | | +-------- BOOTSZ1
# | | | | + --------- EESAVE (don't preserve EEPROM over chip erase)
# | | | +-------------- CKOPT (full output swing)
# | | +---------------- SPIEN (allow serial programming)
# | +------------------ WDTON (WDT not always on)
# +-------------------- RSTDISBL (reset pin is enabled)
#
############################## ATMega48/88/168 ##############################
# ATMega*8 FUSE_L (Fuse low byte):
# 0xdf = 1 1 0 1 1 1 1 1
# ^ ^ \ / \--+--/
# | | | +------- CKSEL 3..0 (external >8M crystal)
# | | +--------------- SUT 1..0 (crystal osc, BOD enabled)
# | +------------------ CKOUT (if 0: Clock output enabled)
# +-------------------- CKDIV8 (if 0: divide by 8)
# ATMega*8 FUSE_H (Fuse high byte):
# 0xde = 1 1 0 1 1 1 1 0
# ^ ^ ^ ^ ^ \-+-/
# | | | | | +------ BODLEVEL 0..2 (110 = 1.8 V)
# | | | | + --------- EESAVE (preserve EEPROM over chip erase)
# | | | +-------------- WDTON (if 0: watchdog always on)
# | | +---------------- SPIEN (allow serial programming)
# | +------------------ DWEN (debug wire enable)
# +-------------------- RSTDISBL (reset pin is enabled)
#
############################## ATTiny25/45/85 ###############################
# ATMega*5 FUSE_L (Fuse low byte):
# 0xef = 1 1 1 0 1 1 1 1
# ^ ^ \+/ \--+--/
# | | | +------- CKSEL 3..0 (clock selection -> crystal @ 12 MHz)
# | | +--------------- SUT 1..0 (BOD enabled, fast rising power)
# | +------------------ CKOUT (clock output on CKOUT pin -> disabled)
# +-------------------- CKDIV8 (divide clock by 8 -> don't divide)
# ATMega*5 FUSE_H (Fuse high byte):
# 0xdd = 1 1 0 1 1 1 0 1
# ^ ^ ^ ^ ^ \-+-/
# | | | | | +------ BODLEVEL 2..0 (brownout trigger level -> 2.7V)
# | | | | +---------- EESAVE (preserve EEPROM on Chip Erase -> not preserved)
# | | | +-------------- WDTON (watchdog timer always on -> disable)
# | | +---------------- SPIEN (enable serial programming -> enabled)
# | +------------------ DWEN (debug wire enable)
# +-------------------- RSTDISBL (disable external reset -> enabled)
#
################################ ATTiny2313 #################################
# ATTiny2313 FUSE_L (Fuse low byte):
# 0xef = 1 1 1 0 1 1 1 1
# ^ ^ \+/ \--+--/
# | | | +------- CKSEL 3..0 (clock selection -> crystal @ 12 MHz)
# | | +--------------- SUT 1..0 (BOD enabled, fast rising power)
# | +------------------ CKOUT (clock output on CKOUT pin -> disabled)
# +-------------------- CKDIV8 (divide clock by 8 -> don't divide)
# ATTiny2313 FUSE_H (Fuse high byte):
# 0xdb = 1 1 0 1 1 0 1 1
# ^ ^ ^ ^ \-+-/ ^
# | | | | | +---- RSTDISBL (disable external reset -> enabled)
# | | | | +-------- BODLEVEL 2..0 (brownout trigger level -> 2.7V)
# | | | +-------------- WDTON (watchdog timer always on -> disable)
# | | +---------------- SPIEN (enable serial programming -> enabled)
# | +------------------ EESAVE (preserve EEPROM on Chip Erase -> not preserved)
# +-------------------- DWEN (debug wire enable)
# symbolic targets:
help:
@echo "This Makefile has no default rule. Use one of the following:"
@echo "make hex ....... to build main.hex"
@echo "make program ... to flash fuses and firmware"
@echo "make fuse ...... to flash the fuses"
@echo "make flash ..... to flash the firmware (use this on metaboard)"
@echo "make clean ..... to delete objects and hex file"
hex: main.hex
program: flash fuse
# rule for programming fuse bits:
fuse:
@[ "$(FUSE_H)" != "" -a "$(FUSE_L)" != "" ] || \
{ echo "*** Edit Makefile and choose values for FUSE_L and FUSE_H!"; exit 1; }
$(AVRDUDE) -U hfuse:w:$(FUSE_H):m -U lfuse:w:$(FUSE_L):m
# rule for uploading firmware:
flash: main.hex
$(AVRDUDE) -U flash:w:main.hex:i
# rule for deleting dependent files (those which can be built by Make):
clean:
rm -f main.hex main.lst main.obj main.cof main.list main.map main.eep.hex main.elf *.o usbdrv/*.o main.s usbdrv/oddebug.s usbdrv/usbdrv.s
# Generic rule for compiling C files:
.c.o:
$(COMPILE) -c $< -o $@
# Generic rule for assembling Assembler source files:
.S.o:
$(COMPILE) -x assembler-with-cpp -c $< -o $@
# "-x assembler-with-cpp" should not be necessary since this is the default
# file type for the .S (with capital S) extension. However, upper case
# characters are not always preserved on Windows. To ensure WinAVR
# compatibility define the file type manually.
# Generic rule for compiling C to assembler, used for debugging only.
.c.s:
$(COMPILE) -S $< -o $@
# file targets:
# Since we don't want to ship the driver multipe times, we copy it into this project:
usbdrv:
cp -r ../../../usbdrv .
main.elf: usbdrv $(OBJECTS) # usbdrv dependency only needed because we copy it
$(COMPILE) -o main.elf $(OBJECTS)
main.hex: main.elf
rm -f main.hex main.eep.hex
avr-objcopy -j .text -j .data -O ihex main.elf main.hex
avr-size main.hex
# debugging targets:
disasm: main.elf
avr-objdump -d main.elf
cpp:
$(COMPILE) -E main.c

View File

@ -0,0 +1,96 @@
/* Name: main.c
* Project: custom-class, a basic USB example
* Author: Christian Starkjohann
* Creation Date: 2008-04-09
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
This example should run on most AVRs with only little changes. No special
hardware resources except INT0 are used. You may have to change usbconfig.h for
different I/O pins for USB. Please note that USB D+ must be the INT0 pin, or
at least be connected to INT0 as well.
We assume that an LED is connected to port B bit 0. If you connect it to a
different port or bit, change the macros below:
*/
#define LED_PORT_DDR DDRB
#define LED_PORT_OUTPUT PORTB
#define LED_BIT 0
#include <avr/io.h>
#include <avr/wdt.h>
#include <avr/interrupt.h> /* for sei() */
#include <util/delay.h> /* for _delay_ms() */
#include <avr/pgmspace.h> /* required by usbdrv.h */
#include "usbdrv.h"
#include "oddebug.h" /* This is also an example for using debug macros */
#include "requests.h" /* The custom request numbers we use */
/* ------------------------------------------------------------------------- */
/* ----------------------------- USB interface ----------------------------- */
/* ------------------------------------------------------------------------- */
usbMsgLen_t usbFunctionSetup(uchar data[8])
{
usbRequest_t *rq = (void *)data;
static uchar dataBuffer[4]; /* buffer must stay valid when usbFunctionSetup returns */
if(rq->bRequest == CUSTOM_RQ_ECHO){ /* echo -- used for reliability tests */
dataBuffer[0] = rq->wValue.bytes[0];
dataBuffer[1] = rq->wValue.bytes[1];
dataBuffer[2] = rq->wIndex.bytes[0];
dataBuffer[3] = rq->wIndex.bytes[1];
usbMsgPtr = dataBuffer; /* tell the driver which data to return */
return 4;
}else if(rq->bRequest == CUSTOM_RQ_SET_STATUS){
if(rq->wValue.bytes[0] & 1){ /* set LED */
LED_PORT_OUTPUT |= _BV(LED_BIT);
}else{ /* clear LED */
LED_PORT_OUTPUT &= ~_BV(LED_BIT);
}
}else if(rq->bRequest == CUSTOM_RQ_GET_STATUS){
dataBuffer[0] = ((LED_PORT_OUTPUT & _BV(LED_BIT)) != 0);
usbMsgPtr = dataBuffer; /* tell the driver which data to return */
return 1; /* tell the driver to send 1 byte */
}
return 0; /* default for not implemented requests: return no data back to host */
}
/* ------------------------------------------------------------------------- */
int __attribute__((noreturn)) main(void)
{
uchar i;
wdt_enable(WDTO_1S);
/* Even if you don't use the watchdog, turn it off here. On newer devices,
* the status of the watchdog (on/off, period) is PRESERVED OVER RESET!
*/
/* RESET status: all port bits are inputs without pull-up.
* That's the way we need D+ and D-. Therefore we don't need any
* additional hardware initialization.
*/
odDebugInit();
DBG1(0x00, 0, 0); /* debug output: main starts */
usbInit();
usbDeviceDisconnect(); /* enforce re-enumeration, do this while interrupts are disabled! */
i = 0;
while(--i){ /* fake USB disconnect for > 250 ms */
wdt_reset();
_delay_ms(1);
}
usbDeviceConnect();
LED_PORT_DDR |= _BV(LED_BIT); /* make the LED bit an output */
sei();
DBG1(0x01, 0, 0); /* debug output: main loop starts */
for(;;){ /* main event loop */
DBG1(0x02, 0, 0); /* debug output: main loop iterates */
wdt_reset();
usbPoll();
}
}
/* ------------------------------------------------------------------------- */

View File

@ -0,0 +1,35 @@
/* Name: requests.h
* Project: custom-class, a basic USB example
* Author: Christian Starkjohann
* Creation Date: 2008-04-09
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/* This header is shared between the firmware and the host software. It
* defines the USB request numbers (and optionally data types) used to
* communicate between the host and the device.
*/
#ifndef __REQUESTS_H_INCLUDED__
#define __REQUESTS_H_INCLUDED__
#define CUSTOM_RQ_ECHO 0
/* Request that the device sends back wValue and wIndex. This is used with
* random data to test the reliability of the communication.
*/
#define CUSTOM_RQ_SET_STATUS 1
/* Set the LED status. Control-OUT.
* The requested status is passed in the "wValue" field of the control
* transfer. No OUT data is sent. Bit 0 of the low byte of wValue controls
* the LED.
*/
#define CUSTOM_RQ_GET_STATUS 2
/* Get the current LED status. Control-IN.
* This control transfer involves a 1 byte data phase where the device sends
* the current status to the host. The status is in bit 0 of the byte.
*/
#endif /* __REQUESTS_H_INCLUDED__ */

View File

@ -0,0 +1,381 @@
/* Name: usbconfig.h
* Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
* Author: Christian Starkjohann
* Creation Date: 2005-04-01
* Tabsize: 4
* Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
#ifndef __usbconfig_h_included__
#define __usbconfig_h_included__
/*
General Description:
This file is an example configuration (with inline documentation) for the USB
driver. It configures V-USB for USB D+ connected to Port D bit 2 (which is
also hardware interrupt 0 on many devices) and USB D- to Port D bit 4. You may
wire the lines to any other port, as long as D+ is also wired to INT0 (or any
other hardware interrupt, as long as it is the highest level interrupt, see
section at the end of this file).
*/
/* ---------------------------- Hardware Config ---------------------------- */
#define USB_CFG_IOPORTNAME D
/* This is the port where the USB bus is connected. When you configure it to
* "B", the registers PORTB, PINB and DDRB will be used.
*/
#define USB_CFG_DMINUS_BIT 4
/* This is the bit number in USB_CFG_IOPORT where the USB D- line is connected.
* This may be any bit in the port.
*/
#define USB_CFG_DPLUS_BIT 2
/* This is the bit number in USB_CFG_IOPORT where the USB D+ line is connected.
* This may be any bit in the port. Please note that D+ must also be connected
* to interrupt pin INT0! [You can also use other interrupts, see section
* "Optional MCU Description" below, or you can connect D- to the interrupt, as
* it is required if you use the USB_COUNT_SOF feature. If you use D- for the
* interrupt, the USB interrupt will also be triggered at Start-Of-Frame
* markers every millisecond.]
*/
#define USB_CFG_CLOCK_KHZ (F_CPU/1000)
/* Clock rate of the AVR in kHz. Legal values are 12000, 12800, 15000, 16000,
* 16500, 18000 and 20000. The 12.8 MHz and 16.5 MHz versions of the code
* require no crystal, they tolerate +/- 1% deviation from the nominal
* frequency. All other rates require a precision of 2000 ppm and thus a
* crystal!
* Since F_CPU should be defined to your actual clock rate anyway, you should
* not need to modify this setting.
*/
#define USB_CFG_CHECK_CRC 0
/* Define this to 1 if you want that the driver checks integrity of incoming
* data packets (CRC checks). CRC checks cost quite a bit of code size and are
* currently only available for 18 MHz crystal clock. You must choose
* USB_CFG_CLOCK_KHZ = 18000 if you enable this option.
*/
/* ----------------------- Optional Hardware Config ------------------------ */
/* #define USB_CFG_PULLUP_IOPORTNAME D */
/* If you connect the 1.5k pullup resistor from D- to a port pin instead of
* V+, you can connect and disconnect the device from firmware by calling
* the macros usbDeviceConnect() and usbDeviceDisconnect() (see usbdrv.h).
* This constant defines the port on which the pullup resistor is connected.
*/
/* #define USB_CFG_PULLUP_BIT 4 */
/* This constant defines the bit number in USB_CFG_PULLUP_IOPORT (defined
* above) where the 1.5k pullup resistor is connected. See description
* above for details.
*/
/* --------------------------- Functional Range ---------------------------- */
#define USB_CFG_HAVE_INTRIN_ENDPOINT 0
/* Define this to 1 if you want to compile a version with two endpoints: The
* default control endpoint 0 and an interrupt-in endpoint (any other endpoint
* number).
*/
#define USB_CFG_HAVE_INTRIN_ENDPOINT3 0
/* Define this to 1 if you want to compile a version with three endpoints: The
* default control endpoint 0, an interrupt-in endpoint 3 (or the number
* configured below) and a catch-all default interrupt-in endpoint as above.
* You must also define USB_CFG_HAVE_INTRIN_ENDPOINT to 1 for this feature.
*/
#define USB_CFG_EP3_NUMBER 3
/* If the so-called endpoint 3 is used, it can now be configured to any other
* endpoint number (except 0) with this macro. Default if undefined is 3.
*/
/* #define USB_INITIAL_DATATOKEN USBPID_DATA1 */
/* The above macro defines the startup condition for data toggling on the
* interrupt/bulk endpoints 1 and 3. Defaults to USBPID_DATA1.
* Since the token is toggled BEFORE sending any data, the first packet is
* sent with the oposite value of this configuration!
*/
#define USB_CFG_IMPLEMENT_HALT 0
/* Define this to 1 if you also want to implement the ENDPOINT_HALT feature
* for endpoint 1 (interrupt endpoint). Although you may not need this feature,
* it is required by the standard. We have made it a config option because it
* bloats the code considerably.
*/
#define USB_CFG_SUPPRESS_INTR_CODE 0
/* Define this to 1 if you want to declare interrupt-in endpoints, but don't
* want to send any data over them. If this macro is defined to 1, functions
* usbSetInterrupt() and usbSetInterrupt3() are omitted. This is useful if
* you need the interrupt-in endpoints in order to comply to an interface
* (e.g. HID), but never want to send any data. This option saves a couple
* of bytes in flash memory and the transmit buffers in RAM.
*/
#define USB_CFG_INTR_POLL_INTERVAL 10
/* If you compile a version with endpoint 1 (interrupt-in), this is the poll
* interval. The value is in milliseconds and must not be less than 10 ms for
* low speed devices.
*/
#define USB_CFG_IS_SELF_POWERED 0
/* Define this to 1 if the device has its own power supply. Set it to 0 if the
* device is powered from the USB bus.
*/
#define USB_CFG_MAX_BUS_POWER 40
/* Set this variable to the maximum USB bus power consumption of your device.
* The value is in milliamperes. [It will be divided by two since USB
* communicates power requirements in units of 2 mA.]
*/
#define USB_CFG_IMPLEMENT_FN_WRITE 0
/* Set this to 1 if you want usbFunctionWrite() to be called for control-out
* transfers. Set it to 0 if you don't need it and want to save a couple of
* bytes.
*/
#define USB_CFG_IMPLEMENT_FN_READ 0
/* Set this to 1 if you need to send control replies which are generated
* "on the fly" when usbFunctionRead() is called. If you only want to send
* data from a static buffer, set it to 0 and return the data from
* usbFunctionSetup(). This saves a couple of bytes.
*/
#define USB_CFG_IMPLEMENT_FN_WRITEOUT 0
/* Define this to 1 if you want to use interrupt-out (or bulk out) endpoints.
* You must implement the function usbFunctionWriteOut() which receives all
* interrupt/bulk data sent to any endpoint other than 0. The endpoint number
* can be found in 'usbRxToken'.
*/
#define USB_CFG_HAVE_FLOWCONTROL 0
/* Define this to 1 if you want flowcontrol over USB data. See the definition
* of the macros usbDisableAllRequests() and usbEnableAllRequests() in
* usbdrv.h.
*/
#define USB_CFG_DRIVER_FLASH_PAGE 0
/* If the device has more than 64 kBytes of flash, define this to the 64 k page
* where the driver's constants (descriptors) are located. Or in other words:
* Define this to 1 for boot loaders on the ATMega128.
*/
#define USB_CFG_LONG_TRANSFERS 0
/* Define this to 1 if you want to send/receive blocks of more than 254 bytes
* in a single control-in or control-out transfer. Note that the capability
* for long transfers increases the driver size.
*/
/* #define USB_RX_USER_HOOK(data, len) if(usbRxToken == (uchar)USBPID_SETUP) blinkLED(); */
/* This macro is a hook if you want to do unconventional things. If it is
* defined, it's inserted at the beginning of received message processing.
* If you eat the received message and don't want default processing to
* proceed, do a return after doing your things. One possible application
* (besides debugging) is to flash a status LED on each packet.
*/
/* #define USB_RESET_HOOK(resetStarts) if(!resetStarts){hadUsbReset();} */
/* This macro is a hook if you need to know when an USB RESET occurs. It has
* one parameter which distinguishes between the start of RESET state and its
* end.
*/
/* #define USB_SET_ADDRESS_HOOK() hadAddressAssigned(); */
/* This macro (if defined) is executed when a USB SET_ADDRESS request was
* received.
*/
#define USB_COUNT_SOF 0
/* define this macro to 1 if you need the global variable "usbSofCount" which
* counts SOF packets. This feature requires that the hardware interrupt is
* connected to D- instead of D+.
*/
/* #ifdef __ASSEMBLER__
* macro myAssemblerMacro
* in YL, TCNT0
* sts timer0Snapshot, YL
* endm
* #endif
* #define USB_SOF_HOOK myAssemblerMacro
* This macro (if defined) is executed in the assembler module when a
* Start Of Frame condition is detected. It is recommended to define it to
* the name of an assembler macro which is defined here as well so that more
* than one assembler instruction can be used. The macro may use the register
* YL and modify SREG. If it lasts longer than a couple of cycles, USB messages
* immediately after an SOF pulse may be lost and must be retried by the host.
* What can you do with this hook? Since the SOF signal occurs exactly every
* 1 ms (unless the host is in sleep mode), you can use it to tune OSCCAL in
* designs running on the internal RC oscillator.
* Please note that Start Of Frame detection works only if D- is wired to the
* interrupt, not D+. THIS IS DIFFERENT THAN MOST EXAMPLES!
*/
#define USB_CFG_CHECK_DATA_TOGGLING 0
/* define this macro to 1 if you want to filter out duplicate data packets
* sent by the host. Duplicates occur only as a consequence of communication
* errors, when the host does not receive an ACK. Please note that you need to
* implement the filtering yourself in usbFunctionWriteOut() and
* usbFunctionWrite(). Use the global usbCurrentDataToken and a static variable
* for each control- and out-endpoint to check for duplicate packets.
*/
#define USB_CFG_HAVE_MEASURE_FRAME_LENGTH 0
/* define this macro to 1 if you want the function usbMeasureFrameLength()
* compiled in. This function can be used to calibrate the AVR's RC oscillator.
*/
#define USB_USE_FAST_CRC 0
/* The assembler module has two implementations for the CRC algorithm. One is
* faster, the other is smaller. This CRC routine is only used for transmitted
* messages where timing is not critical. The faster routine needs 31 cycles
* per byte while the smaller one needs 61 to 69 cycles. The faster routine
* may be worth the 32 bytes bigger code size if you transmit lots of data and
* run the AVR close to its limit.
*/
/* -------------------------- Device Description --------------------------- */
#define USB_CFG_VENDOR_ID 0xc0, 0x16 /* = 0x16c0 = 5824 = voti.nl */
/* USB vendor ID for the device, low byte first. If you have registered your
* own Vendor ID, define it here. Otherwise you may use one of obdev's free
* shared VID/PID pairs. Be sure to read USB-IDs-for-free.txt for rules!
* *** IMPORTANT NOTE ***
* This template uses obdev's shared VID/PID pair for Vendor Class devices
* with libusb: 0x16c0/0x5dc. Use this VID/PID pair ONLY if you understand
* the implications!
*/
#define USB_CFG_DEVICE_ID 0xdc, 0x05 /* = 0x05dc = 1500 */
/* This is the ID of the product, low byte first. It is interpreted in the
* scope of the vendor ID. If you have registered your own VID with usb.org
* or if you have licensed a PID from somebody else, define it here. Otherwise
* you may use one of obdev's free shared VID/PID pairs. See the file
* USB-IDs-for-free.txt for details!
* *** IMPORTANT NOTE ***
* This template uses obdev's shared VID/PID pair for Vendor Class devices
* with libusb: 0x16c0/0x5dc. Use this VID/PID pair ONLY if you understand
* the implications!
*/
#define USB_CFG_DEVICE_VERSION 0x00, 0x01
/* Version number of the device: Minor number first, then major number.
*/
#define USB_CFG_VENDOR_NAME 'o', 'b', 'd', 'e', 'v', '.', 'a', 't'
#define USB_CFG_VENDOR_NAME_LEN 8
/* These two values define the vendor name returned by the USB device. The name
* must be given as a list of characters under single quotes. The characters
* are interpreted as Unicode (UTF-16) entities.
* If you don't want a vendor name string, undefine these macros.
* ALWAYS define a vendor name containing your Internet domain name if you use
* obdev's free shared VID/PID pair. See the file USB-IDs-for-free.txt for
* details.
*/
#define USB_CFG_DEVICE_NAME 'L', 'E', 'D', 'C', 'o', 'n', 't', 'r', 'o', 'l'
#define USB_CFG_DEVICE_NAME_LEN 10
/* Same as above for the device name. If you don't want a device name, undefine
* the macros. See the file USB-IDs-for-free.txt before you assign a name if
* you use a shared VID/PID.
*/
/*#define USB_CFG_SERIAL_NUMBER 'N', 'o', 'n', 'e' */
/*#define USB_CFG_SERIAL_NUMBER_LEN 0 */
/* Same as above for the serial number. If you don't want a serial number,
* undefine the macros.
* It may be useful to provide the serial number through other means than at
* compile time. See the section about descriptor properties below for how
* to fine tune control over USB descriptors such as the string descriptor
* for the serial number.
*/
#define USB_CFG_DEVICE_CLASS 0xff /* set to 0 if deferred to interface */
#define USB_CFG_DEVICE_SUBCLASS 0
/* See USB specification if you want to conform to an existing device class.
* Class 0xff is "vendor specific".
*/
#define USB_CFG_INTERFACE_CLASS 0 /* define class here if not at device level */
#define USB_CFG_INTERFACE_SUBCLASS 0
#define USB_CFG_INTERFACE_PROTOCOL 0
/* See USB specification if you want to conform to an existing device class or
* protocol. The following classes must be set at interface level:
* HID class is 3, no subclass and protocol required (but may be useful!)
* CDC class is 2, use subclass 2 and protocol 1 for ACM
*/
/* #define USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH 42 */
/* Define this to the length of the HID report descriptor, if you implement
* an HID device. Otherwise don't define it or define it to 0.
* If you use this define, you must add a PROGMEM character array named
* "usbHidReportDescriptor" to your code which contains the report descriptor.
* Don't forget to keep the array and this define in sync!
*/
/* #define USB_PUBLIC static */
/* Use the define above if you #include usbdrv.c instead of linking against it.
* This technique saves a couple of bytes in flash memory.
*/
/* ------------------- Fine Control over USB Descriptors ------------------- */
/* If you don't want to use the driver's default USB descriptors, you can
* provide our own. These can be provided as (1) fixed length static data in
* flash memory, (2) fixed length static data in RAM or (3) dynamically at
* runtime in the function usbFunctionDescriptor(). See usbdrv.h for more
* information about this function.
* Descriptor handling is configured through the descriptor's properties. If
* no properties are defined or if they are 0, the default descriptor is used.
* Possible properties are:
* + USB_PROP_IS_DYNAMIC: The data for the descriptor should be fetched
* at runtime via usbFunctionDescriptor(). If the usbMsgPtr mechanism is
* used, the data is in FLASH by default. Add property USB_PROP_IS_RAM if
* you want RAM pointers.
* + USB_PROP_IS_RAM: The data returned by usbFunctionDescriptor() or found
* in static memory is in RAM, not in flash memory.
* + USB_PROP_LENGTH(len): If the data is in static memory (RAM or flash),
* the driver must know the descriptor's length. The descriptor itself is
* found at the address of a well known identifier (see below).
* List of static descriptor names (must be declared PROGMEM if in flash):
* char usbDescriptorDevice[];
* char usbDescriptorConfiguration[];
* char usbDescriptorHidReport[];
* char usbDescriptorString0[];
* int usbDescriptorStringVendor[];
* int usbDescriptorStringDevice[];
* int usbDescriptorStringSerialNumber[];
* Other descriptors can't be provided statically, they must be provided
* dynamically at runtime.
*
* Descriptor properties are or-ed or added together, e.g.:
* #define USB_CFG_DESCR_PROPS_DEVICE (USB_PROP_IS_RAM | USB_PROP_LENGTH(18))
*
* The following descriptors are defined:
* USB_CFG_DESCR_PROPS_DEVICE
* USB_CFG_DESCR_PROPS_CONFIGURATION
* USB_CFG_DESCR_PROPS_STRINGS
* USB_CFG_DESCR_PROPS_STRING_0
* USB_CFG_DESCR_PROPS_STRING_VENDOR
* USB_CFG_DESCR_PROPS_STRING_PRODUCT
* USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
* USB_CFG_DESCR_PROPS_HID
* USB_CFG_DESCR_PROPS_HID_REPORT
* USB_CFG_DESCR_PROPS_UNKNOWN (for all descriptors not handled by the driver)
*
* Note about string descriptors: String descriptors are not just strings, they
* are Unicode strings prefixed with a 2 byte header. Example:
* int serialNumberDescriptor[] = {
* USB_STRING_DESCRIPTOR_HEADER(6),
* 'S', 'e', 'r', 'i', 'a', 'l'
* };
*/
#define USB_CFG_DESCR_PROPS_DEVICE 0
#define USB_CFG_DESCR_PROPS_CONFIGURATION 0
#define USB_CFG_DESCR_PROPS_STRINGS 0
#define USB_CFG_DESCR_PROPS_STRING_0 0
#define USB_CFG_DESCR_PROPS_STRING_VENDOR 0
#define USB_CFG_DESCR_PROPS_STRING_PRODUCT 0
#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER 0
#define USB_CFG_DESCR_PROPS_HID 0
#define USB_CFG_DESCR_PROPS_HID_REPORT 0
#define USB_CFG_DESCR_PROPS_UNKNOWN 0
#define usbMsgPtr_t unsigned short
/* If usbMsgPtr_t is not defined, it defaults to 'uchar *'. We define it to
* a scalar type here because gcc generates slightly shorter code for scalar
* arithmetics than for pointer arithmetics. Remove this define for backward
* type compatibility or define it to an 8 bit type if you use data in RAM only
* and all RAM is below 256 bytes (tiny memory model in IAR CC).
*/
/* ----------------------- Optional MCU Description ------------------------ */
/* The following configurations have working defaults in usbdrv.h. You
* usually don't need to set them explicitly. Only if you want to run
* the driver on a device which is not yet supported or with a compiler
* which is not fully supported (such as IAR C) or if you use a differnt
* interrupt than INT0, you may have to define some of these.
*/
/* #define USB_INTR_CFG MCUCR */
/* #define USB_INTR_CFG_SET ((1 << ISC00) | (1 << ISC01)) */
/* #define USB_INTR_CFG_CLR 0 */
/* #define USB_INTR_ENABLE GIMSK */
/* #define USB_INTR_ENABLE_BIT INT0 */
/* #define USB_INTR_PENDING GIFR */
/* #define USB_INTR_PENDING_BIT INTF0 */
/* #define USB_INTR_VECTOR INT0_vect */
#endif /* __usbconfig_h_included__ */

View File

@ -0,0 +1,28 @@
This is the Readme file for the hid-custom-rq example. This is basically the
same as the custom-class example, except that the device conforms to the USB
HID class.
WHAT IS DEMONSTRATED?
=====================
This example demonstrates how custom requests can be sent to devices which
are otherwise HID compliant. This mechanism can be used to prevent the
"driver CD" dialog on Windows and still control the device with libusb-win32.
It can also be used to extend the functionality of the USB class, e.g. by
setting parameters.
Please note that you should install the filter version of libusb-win32 to
take full advantage or this mode. The device driver version only has access
to devices which have been registered for it with a *.inf file. The filter
version has access to all devices.
MORE INFORMATION
================
For information about how to build this example and how to use the command
line tool see the Readme file in the custom-class example.
----------------------------------------------------------------------------
(c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH.
http://www.obdev.at/

View File

@ -0,0 +1,47 @@
# Name: Makefile
# Project: hid-custom-rq example
# Author: Christian Starkjohann
# Creation Date: 2008-04-06
# Tabsize: 4
# Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
# Concigure the following definitions according to your system.
# This Makefile has been tested on Mac OS X, Linux and Windows.
# Use the following 3 lines on Unix (uncomment the framework on Mac OS X):
USBFLAGS = `libusb-config --cflags`
USBLIBS = `libusb-config --libs`
EXE_SUFFIX =
# Use the following 3 lines on Windows and comment out the 3 above. You may
# have to change the include paths to where you installed libusb-win32
#USBFLAGS = -I/usr/local/include
#USBLIBS = -L/usr/local/lib -lusb
#EXE_SUFFIX = .exe
NAME = set-led
OBJECTS = opendevice.o $(NAME).o
CC = gcc
CFLAGS = $(CPPFLAGS) $(USBFLAGS) -O -g -Wall
LIBS = $(USBLIBS)
PROGRAM = $(NAME)$(EXE_SUFFIX)
all: $(PROGRAM)
.c.o:
$(CC) $(CFLAGS) -c $<
$(PROGRAM): $(OBJECTS)
$(CC) -o $(PROGRAM) $(OBJECTS) $(LIBS)
strip: $(PROGRAM)
strip $(PROGRAM)
clean:
rm -f *.o $(PROGRAM)

View File

@ -0,0 +1,17 @@
# Name: Makefile.windows
# Project: hid-custom-rq example
# Author: Christian Starkjohann
# Creation Date: 2008-04-06
# Tabsize: 4
# Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
# You may use this file with
# make -f Makefile.windows
# on Windows with MinGW instead of editing the main Makefile.
include Makefile
USBFLAGS = -I/usr/local/mingw/include
USBLIBS = -L/usr/local/mingw/lib -lusb
EXE_SUFFIX = .exe

View File

@ -0,0 +1,202 @@
/* Name: opendevice.c
* Project: V-USB host-side library
* Author: Christian Starkjohann
* Creation Date: 2008-04-10
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
General Description:
The functions in this module can be used to find and open a device based on
libusb or libusb-win32.
*/
#include <stdio.h>
#include "opendevice.h"
/* ------------------------------------------------------------------------- */
#define MATCH_SUCCESS 1
#define MATCH_FAILED 0
#define MATCH_ABORT -1
/* private interface: match text and p, return MATCH_SUCCESS, MATCH_FAILED, or MATCH_ABORT. */
static int _shellStyleMatch(char *text, char *p)
{
int last, matched, reverse;
for(; *p; text++, p++){
if(*text == 0 && *p != '*')
return MATCH_ABORT;
switch(*p){
case '\\':
/* Literal match with following character. */
p++;
/* FALLTHROUGH */
default:
if(*text != *p)
return MATCH_FAILED;
continue;
case '?':
/* Match anything. */
continue;
case '*':
while(*++p == '*')
/* Consecutive stars act just like one. */
continue;
if(*p == 0)
/* Trailing star matches everything. */
return MATCH_SUCCESS;
while(*text)
if((matched = _shellStyleMatch(text++, p)) != MATCH_FAILED)
return matched;
return MATCH_ABORT;
case '[':
reverse = p[1] == '^';
if(reverse) /* Inverted character class. */
p++;
matched = MATCH_FAILED;
if(p[1] == ']' || p[1] == '-')
if(*++p == *text)
matched = MATCH_SUCCESS;
for(last = *p; *++p && *p != ']'; last = *p)
if (*p == '-' && p[1] != ']' ? *text <= *++p && *text >= last : *text == *p)
matched = MATCH_SUCCESS;
if(matched == reverse)
return MATCH_FAILED;
continue;
}
}
return *text == 0;
}
/* public interface for shell style matching: returns 0 if fails, 1 if matches */
static int shellStyleMatch(char *text, char *pattern)
{
if(pattern == NULL) /* NULL pattern is synonymous to "*" */
return 1;
return _shellStyleMatch(text, pattern) == MATCH_SUCCESS;
}
/* ------------------------------------------------------------------------- */
int usbGetStringAscii(usb_dev_handle *dev, int index, char *buf, int buflen)
{
char buffer[256];
int rval, i;
if((rval = usb_get_string_simple(dev, index, buf, buflen)) >= 0) /* use libusb version if it works */
return rval;
if((rval = usb_control_msg(dev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR, (USB_DT_STRING << 8) + index, 0x0409, buffer, sizeof(buffer), 5000)) < 0)
return rval;
if(buffer[1] != USB_DT_STRING){
*buf = 0;
return 0;
}
if((unsigned char)buffer[0] < rval)
rval = (unsigned char)buffer[0];
rval /= 2;
/* lossy conversion to ISO Latin1: */
for(i=1;i<rval;i++){
if(i > buflen) /* destination buffer overflow */
break;
buf[i-1] = buffer[2 * i];
if(buffer[2 * i + 1] != 0) /* outside of ISO Latin1 range */
buf[i-1] = '?';
}
buf[i-1] = 0;
return i-1;
}
/* ------------------------------------------------------------------------- */
int usbOpenDevice(usb_dev_handle **device, int vendorID, char *vendorNamePattern, int productID, char *productNamePattern, char *serialNamePattern, FILE *printMatchingDevicesFp, FILE *warningsFp)
{
struct usb_bus *bus;
struct usb_device *dev;
usb_dev_handle *handle = NULL;
int errorCode = USBOPEN_ERR_NOTFOUND;
usb_find_busses();
usb_find_devices();
for(bus = usb_get_busses(); bus; bus = bus->next){
for(dev = bus->devices; dev; dev = dev->next){ /* iterate over all devices on all busses */
if((vendorID == 0 || dev->descriptor.idVendor == vendorID)
&& (productID == 0 || dev->descriptor.idProduct == productID)){
char vendor[256], product[256], serial[256];
int len;
handle = usb_open(dev); /* we need to open the device in order to query strings */
if(!handle){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot open VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
continue;
}
/* now check whether the names match: */
len = vendor[0] = 0;
if(dev->descriptor.iManufacturer > 0){
len = usbGetStringAscii(handle, dev->descriptor.iManufacturer, vendor, sizeof(vendor));
}
if(len < 0){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot query manufacturer for VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
}else{
errorCode = USBOPEN_ERR_NOTFOUND;
/* printf("seen device from vendor ->%s<-\n", vendor); */
if(shellStyleMatch(vendor, vendorNamePattern)){
len = product[0] = 0;
if(dev->descriptor.iProduct > 0){
len = usbGetStringAscii(handle, dev->descriptor.iProduct, product, sizeof(product));
}
if(len < 0){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot query product for VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
}else{
errorCode = USBOPEN_ERR_NOTFOUND;
/* printf("seen product ->%s<-\n", product); */
if(shellStyleMatch(product, productNamePattern)){
len = serial[0] = 0;
if(dev->descriptor.iSerialNumber > 0){
len = usbGetStringAscii(handle, dev->descriptor.iSerialNumber, serial, sizeof(serial));
}
if(len < 0){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot query serial for VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
}
if(shellStyleMatch(serial, serialNamePattern)){
if(printMatchingDevicesFp != NULL){
if(serial[0] == 0){
fprintf(printMatchingDevicesFp, "VID=0x%04x PID=0x%04x vendor=\"%s\" product=\"%s\"\n", dev->descriptor.idVendor, dev->descriptor.idProduct, vendor, product);
}else{
fprintf(printMatchingDevicesFp, "VID=0x%04x PID=0x%04x vendor=\"%s\" product=\"%s\" serial=\"%s\"\n", dev->descriptor.idVendor, dev->descriptor.idProduct, vendor, product, serial);
}
}else{
break;
}
}
}
}
}
}
usb_close(handle);
handle = NULL;
}
}
if(handle) /* we have found a deice */
break;
}
if(handle != NULL){
errorCode = 0;
*device = handle;
}
if(printMatchingDevicesFp != NULL) /* never return an error for listing only */
errorCode = 0;
return errorCode;
}
/* ------------------------------------------------------------------------- */

View File

@ -0,0 +1,76 @@
/* Name: opendevice.h
* Project: V-USB host-side library
* Author: Christian Starkjohann
* Creation Date: 2008-04-10
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
General Description:
This module offers additional functionality for host side drivers based on
libusb or libusb-win32. It includes a function to find and open a device
based on numeric IDs and textual description. It also includes a function to
obtain textual descriptions from a device.
To use this functionality, simply copy opendevice.c and opendevice.h into your
project and add them to your Makefile. You may modify and redistribute these
files according to the GNU General Public License (GPL) version 2 or 3.
*/
#ifndef __OPENDEVICE_H_INCLUDED__
#define __OPENDEVICE_H_INCLUDED__
#include <usb.h> /* this is libusb, see http://libusb.sourceforge.net/ */
#include <stdio.h>
int usbGetStringAscii(usb_dev_handle *dev, int index, char *buf, int buflen);
/* This function gets a string descriptor from the device. 'index' is the
* string descriptor index. The string is returned in ISO Latin 1 encoding in
* 'buf' and it is terminated with a 0-character. The buffer size must be
* passed in 'buflen' to prevent buffer overflows. A libusb device handle
* must be given in 'dev'.
* Returns: The length of the string (excluding the terminating 0) or
* a negative number in case of an error. If there was an error, use
* usb_strerror() to obtain the error message.
*/
int usbOpenDevice(usb_dev_handle **device, int vendorID, char *vendorNamePattern, int productID, char *productNamePattern, char *serialNamePattern, FILE *printMatchingDevicesFp, FILE *warningsFp);
/* This function iterates over all devices on all USB busses and searches for
* a device. Matching is done first by means of Vendor- and Product-ID (passed
* in 'vendorID' and 'productID'. An ID of 0 matches any numeric ID (wildcard).
* When a device matches by its IDs, matching by names is performed. Name
* matching can be done on textual vendor name ('vendorNamePattern'), product
* name ('productNamePattern') and serial number ('serialNamePattern'). A
* device matches only if all non-null pattern match. If you don't care about
* a string, pass NULL for the pattern. Patterns are Unix shell style pattern:
* '*' stands for 0 or more characters, '?' for one single character, a list
* of characters in square brackets for a single character from the list
* (dashes are allowed to specify a range) and if the lis of characters begins
* with a caret ('^'), it matches one character which is NOT in the list.
* Other parameters to the function: If 'warningsFp' is not NULL, warning
* messages are printed to this file descriptor with fprintf(). If
* 'printMatchingDevicesFp' is not NULL, no device is opened but matching
* devices are printed to the given file descriptor with fprintf().
* If a device is opened, the resulting USB handle is stored in '*device'. A
* pointer to a "usb_dev_handle *" type variable must be passed here.
* Returns: 0 on success, an error code (see defines below) on failure.
*/
/* usbOpenDevice() error codes: */
#define USBOPEN_SUCCESS 0 /* no error */
#define USBOPEN_ERR_ACCESS 1 /* not enough permissions to open device */
#define USBOPEN_ERR_IO 2 /* I/O error */
#define USBOPEN_ERR_NOTFOUND 3 /* device not found */
/* Obdev's free USB IDs, see USB-IDs-for-free.txt for details */
#define USB_VID_OBDEV_SHARED 5824 /* obdev's shared vendor ID */
#define USB_PID_OBDEV_SHARED_CUSTOM 1500 /* shared PID for custom class devices */
#define USB_PID_OBDEV_SHARED_HID 1503 /* shared PID for HIDs except mice & keyboards */
#define USB_PID_OBDEV_SHARED_CDCACM 1505 /* shared PID for CDC Modem devices */
#define USB_PID_OBDEV_SHARED_MIDI 1508 /* shared PID for MIDI class devices */
#endif /* __OPENDEVICE_H_INCLUDED__ */

View File

@ -0,0 +1,134 @@
/* Name: set-led.c
* Project: hid-custom-rq example
* Author: Christian Starkjohann
* Creation Date: 2008-04-10
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
General Description:
This is the host-side driver for the custom-class example device. It searches
the USB for the LEDControl device and sends the requests understood by this
device.
This program must be linked with libusb on Unix and libusb-win32 on Windows.
See http://libusb.sourceforge.net/ or http://libusb-win32.sourceforge.net/
respectively.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <usb.h> /* this is libusb */
#include "opendevice.h" /* common code moved to separate module */
#include "../firmware/requests.h" /* custom request numbers */
#include "../firmware/usbconfig.h" /* device's VID/PID and names */
static void usage(char *name)
{
fprintf(stderr, "usage:\n");
fprintf(stderr, " %s on ....... turn on LED\n", name);
fprintf(stderr, " %s off ...... turn off LED\n", name);
fprintf(stderr, " %s status ... ask current status of LED\n", name);
#if ENABLE_TEST
fprintf(stderr, " %s test ..... run driver reliability test\n", name);
#endif /* ENABLE_TEST */
}
int main(int argc, char **argv)
{
usb_dev_handle *handle = NULL;
const unsigned char rawVid[2] = {USB_CFG_VENDOR_ID}, rawPid[2] = {USB_CFG_DEVICE_ID};
char vendor[] = {USB_CFG_VENDOR_NAME, 0}, product[] = {USB_CFG_DEVICE_NAME, 0};
char buffer[4];
int cnt, vid, pid, isOn;
usb_init();
if(argc < 2){ /* we need at least one argument */
usage(argv[0]);
exit(1);
}
/* compute VID/PID from usbconfig.h so that there is a central source of information */
vid = rawVid[1] * 256 + rawVid[0];
pid = rawPid[1] * 256 + rawPid[0];
/* The following function is in opendevice.c: */
if(usbOpenDevice(&handle, vid, vendor, pid, product, NULL, NULL, NULL) != 0){
fprintf(stderr, "Could not find USB device \"%s\" with vid=0x%x pid=0x%x\n", product, vid, pid);
exit(1);
}
/* Since we use only control endpoint 0, we don't need to choose a
* configuration and interface. Reading device descriptor and setting a
* configuration and interface is done through endpoint 0 after all.
* However, newer versions of Linux require that we claim an interface
* even for endpoint 0. Enable the following code if your operating system
* needs it: */
#if 0
int retries = 1, usbConfiguration = 1, usbInterface = 0;
if(usb_set_configuration(handle, usbConfiguration) && showWarnings){
fprintf(stderr, "Warning: could not set configuration: %s\n", usb_strerror());
}
/* now try to claim the interface and detach the kernel HID driver on
* Linux and other operating systems which support the call. */
while((len = usb_claim_interface(handle, usbInterface)) != 0 && retries-- > 0){
#ifdef LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP
if(usb_detach_kernel_driver_np(handle, 0) < 0 && showWarnings){
fprintf(stderr, "Warning: could not detach kernel driver: %s\n", usb_strerror());
}
#endif
}
#endif
if(strcasecmp(argv[1], "status") == 0){
cnt = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN, CUSTOM_RQ_GET_STATUS, 0, 0, buffer, sizeof(buffer), 5000);
if(cnt < 1){
if(cnt < 0){
fprintf(stderr, "USB error: %s\n", usb_strerror());
}else{
fprintf(stderr, "only %d bytes received.\n", cnt);
}
}else{
printf("LED is %s\n", buffer[0] ? "on" : "off");
}
}else if((isOn = (strcasecmp(argv[1], "on") == 0)) || strcasecmp(argv[1], "off") == 0){
cnt = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_OUT, CUSTOM_RQ_SET_STATUS, isOn, 0, buffer, 0, 5000);
if(cnt < 0){
fprintf(stderr, "USB error: %s\n", usb_strerror());
}
#if ENABLE_TEST
}else if(strcasecmp(argv[1], "test") == 0){
int i;
srandomdev();
for(i = 0; i < 50000; i++){
int value = random() & 0xffff, index = random() & 0xffff;
int rxValue, rxIndex;
if((i+1) % 100 == 0){
fprintf(stderr, "\r%05d", i+1);
fflush(stderr);
}
cnt = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN, CUSTOM_RQ_ECHO, value, index, buffer, sizeof(buffer), 5000);
if(cnt < 0){
fprintf(stderr, "\nUSB error in iteration %d: %s\n", i, usb_strerror());
break;
}else if(cnt != 4){
fprintf(stderr, "\nerror in iteration %d: %d bytes received instead of 4\n", i, cnt);
break;
}
rxValue = ((int)buffer[0] & 0xff) | (((int)buffer[1] & 0xff) << 8);
rxIndex = ((int)buffer[2] & 0xff) | (((int)buffer[3] & 0xff) << 8);
if(rxValue != value || rxIndex != index){
fprintf(stderr, "\ndata error in iteration %d:\n", i);
fprintf(stderr, "rxValue = 0x%04x value = 0x%04x\n", rxValue, value);
fprintf(stderr, "rxIndex = 0x%04x index = 0x%04x\n", rxIndex, index);
}
}
fprintf(stderr, "\nTest completed.\n");
#endif /* ENABLE_TEST */
}else{
usage(argv[0]);
exit(1);
}
usb_close(handle);
return 0;
}

View File

@ -0,0 +1,163 @@
# Name: Makefile
# Project: hid-custom-rq example
# Author: Christian Starkjohann
# Creation Date: 2008-04-07
# Tabsize: 4
# Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
DEVICE = atmega168
F_CPU = 16000000 # in Hz
FUSE_L = # see below for fuse values for particular devices
FUSE_H =
AVRDUDE = avrdude -c usbasp -p $(DEVICE) # edit this line for your programmer
CFLAGS = -Iusbdrv -I. -DDEBUG_LEVEL=0
OBJECTS = usbdrv/usbdrv.o usbdrv/usbdrvasm.o usbdrv/oddebug.o main.o
COMPILE = avr-gcc -Wall -Os -DF_CPU=$(F_CPU) $(CFLAGS) -mmcu=$(DEVICE)
##############################################################################
# Fuse values for particular devices
##############################################################################
# If your device is not listed here, go to
# http://palmavr.sourceforge.net/cgi-bin/fc.cgi
# and choose options for external crystal clock and no clock divider
#
################################## ATMega8 ##################################
# ATMega8 FUSE_L (Fuse low byte):
# 0x9f = 1 0 0 1 1 1 1 1
# ^ ^ \ / \--+--/
# | | | +------- CKSEL 3..0 (external >8M crystal)
# | | +--------------- SUT 1..0 (crystal osc, BOD enabled)
# | +------------------ BODEN (BrownOut Detector enabled)
# +-------------------- BODLEVEL (2.7V)
# ATMega8 FUSE_H (Fuse high byte):
# 0xc9 = 1 1 0 0 1 0 0 1 <-- BOOTRST (boot reset vector at 0x0000)
# ^ ^ ^ ^ ^ ^ ^------ BOOTSZ0
# | | | | | +-------- BOOTSZ1
# | | | | + --------- EESAVE (don't preserve EEPROM over chip erase)
# | | | +-------------- CKOPT (full output swing)
# | | +---------------- SPIEN (allow serial programming)
# | +------------------ WDTON (WDT not always on)
# +-------------------- RSTDISBL (reset pin is enabled)
#
############################## ATMega48/88/168 ##############################
# ATMega*8 FUSE_L (Fuse low byte):
# 0xdf = 1 1 0 1 1 1 1 1
# ^ ^ \ / \--+--/
# | | | +------- CKSEL 3..0 (external >8M crystal)
# | | +--------------- SUT 1..0 (crystal osc, BOD enabled)
# | +------------------ CKOUT (if 0: Clock output enabled)
# +-------------------- CKDIV8 (if 0: divide by 8)
# ATMega*8 FUSE_H (Fuse high byte):
# 0xde = 1 1 0 1 1 1 1 0
# ^ ^ ^ ^ ^ \-+-/
# | | | | | +------ BODLEVEL 0..2 (110 = 1.8 V)
# | | | | + --------- EESAVE (preserve EEPROM over chip erase)
# | | | +-------------- WDTON (if 0: watchdog always on)
# | | +---------------- SPIEN (allow serial programming)
# | +------------------ DWEN (debug wire enable)
# +-------------------- RSTDISBL (reset pin is enabled)
#
############################## ATTiny25/45/85 ###############################
# ATMega*5 FUSE_L (Fuse low byte):
# 0xef = 1 1 1 0 1 1 1 1
# ^ ^ \+/ \--+--/
# | | | +------- CKSEL 3..0 (clock selection -> crystal @ 12 MHz)
# | | +--------------- SUT 1..0 (BOD enabled, fast rising power)
# | +------------------ CKOUT (clock output on CKOUT pin -> disabled)
# +-------------------- CKDIV8 (divide clock by 8 -> don't divide)
# ATMega*5 FUSE_H (Fuse high byte):
# 0xdd = 1 1 0 1 1 1 0 1
# ^ ^ ^ ^ ^ \-+-/
# | | | | | +------ BODLEVEL 2..0 (brownout trigger level -> 2.7V)
# | | | | +---------- EESAVE (preserve EEPROM on Chip Erase -> not preserved)
# | | | +-------------- WDTON (watchdog timer always on -> disable)
# | | +---------------- SPIEN (enable serial programming -> enabled)
# | +------------------ DWEN (debug wire enable)
# +-------------------- RSTDISBL (disable external reset -> enabled)
#
################################ ATTiny2313 #################################
# ATTiny2313 FUSE_L (Fuse low byte):
# 0xef = 1 1 1 0 1 1 1 1
# ^ ^ \+/ \--+--/
# | | | +------- CKSEL 3..0 (clock selection -> crystal @ 12 MHz)
# | | +--------------- SUT 1..0 (BOD enabled, fast rising power)
# | +------------------ CKOUT (clock output on CKOUT pin -> disabled)
# +-------------------- CKDIV8 (divide clock by 8 -> don't divide)
# ATTiny2313 FUSE_H (Fuse high byte):
# 0xdb = 1 1 0 1 1 0 1 1
# ^ ^ ^ ^ \-+-/ ^
# | | | | | +---- RSTDISBL (disable external reset -> enabled)
# | | | | +-------- BODLEVEL 2..0 (brownout trigger level -> 2.7V)
# | | | +-------------- WDTON (watchdog timer always on -> disable)
# | | +---------------- SPIEN (enable serial programming -> enabled)
# | +------------------ EESAVE (preserve EEPROM on Chip Erase -> not preserved)
# +-------------------- DWEN (debug wire enable)
# symbolic targets:
help:
@echo "This Makefile has no default rule. Use one of the following:"
@echo "make hex ....... to build main.hex"
@echo "make program ... to flash fuses and firmware"
@echo "make fuse ...... to flash the fuses"
@echo "make flash ..... to flash the firmware (use this on metaboard)"
@echo "make clean ..... to delete objects and hex file"
hex: main.hex
program: flash fuse
# rule for programming fuse bits:
fuse:
@[ "$(FUSE_H)" != "" -a "$(FUSE_L)" != "" ] || \
{ echo "*** Edit Makefile and choose values for FUSE_L and FUSE_H!"; exit 1; }
$(AVRDUDE) -U hfuse:w:$(FUSE_H):m -U lfuse:w:$(FUSE_L):m
# rule for uploading firmware:
flash: main.hex
$(AVRDUDE) -U flash:w:main.hex:i
# rule for deleting dependent files (those which can be built by Make):
clean:
rm -f main.hex main.lst main.obj main.cof main.list main.map main.eep.hex main.elf *.o usbdrv/*.o main.s usbdrv/oddebug.s usbdrv/usbdrv.s
# Generic rule for compiling C files:
.c.o:
$(COMPILE) -c $< -o $@
# Generic rule for assembling Assembler source files:
.S.o:
$(COMPILE) -x assembler-with-cpp -c $< -o $@
# "-x assembler-with-cpp" should not be necessary since this is the default
# file type for the .S (with capital S) extension. However, upper case
# characters are not always preserved on Windows. To ensure WinAVR
# compatibility define the file type manually.
# Generic rule for compiling C to assembler, used for debugging only.
.c.s:
$(COMPILE) -S $< -o $@
# file targets:
# Since we don't want to ship the driver multipe times, we copy it into this project:
usbdrv:
cp -r ../../../usbdrv .
main.elf: usbdrv $(OBJECTS) # usbdrv dependency only needed because we copy it
$(COMPILE) -o main.elf $(OBJECTS)
main.hex: main.elf
rm -f main.hex main.eep.hex
avr-objcopy -j .text -j .data -O ihex main.elf main.hex
avr-size main.hex
# debugging targets:
disasm: main.elf
avr-objdump -d main.elf
cpp:
$(COMPILE) -E main.c

View File

@ -0,0 +1,119 @@
/* Name: main.c
* Project: hid-custom-rq example
* Author: Christian Starkjohann
* Creation Date: 2008-04-07
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
This example should run on most AVRs with only little changes. No special
hardware resources except INT0 are used. You may have to change usbconfig.h for
different I/O pins for USB. Please note that USB D+ must be the INT0 pin, or
at least be connected to INT0 as well.
We assume that an LED is connected to port B bit 0. If you connect it to a
different port or bit, change the macros below:
*/
#define LED_PORT_DDR DDRB
#define LED_PORT_OUTPUT PORTB
#define LED_BIT 0
#include <avr/io.h>
#include <avr/wdt.h>
#include <avr/interrupt.h> /* for sei() */
#include <util/delay.h> /* for _delay_ms() */
#include <avr/pgmspace.h> /* required by usbdrv.h */
#include "usbdrv.h"
#include "oddebug.h" /* This is also an example for using debug macros */
#include "requests.h" /* The custom request numbers we use */
/* ------------------------------------------------------------------------- */
/* ----------------------------- USB interface ----------------------------- */
/* ------------------------------------------------------------------------- */
PROGMEM const char usbHidReportDescriptor[22] = { /* USB report descriptor */
0x06, 0x00, 0xff, // USAGE_PAGE (Generic Desktop)
0x09, 0x01, // USAGE (Vendor Usage 1)
0xa1, 0x01, // COLLECTION (Application)
0x15, 0x00, // LOGICAL_MINIMUM (0)
0x26, 0xff, 0x00, // LOGICAL_MAXIMUM (255)
0x75, 0x08, // REPORT_SIZE (8)
0x95, 0x01, // REPORT_COUNT (1)
0x09, 0x00, // USAGE (Undefined)
0xb2, 0x02, 0x01, // FEATURE (Data,Var,Abs,Buf)
0xc0 // END_COLLECTION
};
/* The descriptor above is a dummy only, it silences the drivers. The report
* it describes consists of one byte of undefined data.
* We don't transfer our data through HID reports, we use custom requests
* instead.
*/
/* ------------------------------------------------------------------------- */
usbMsgLen_t usbFunctionSetup(uchar data[8])
{
usbRequest_t *rq = (void *)data;
if((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_VENDOR){
DBG1(0x50, &rq->bRequest, 1); /* debug output: print our request */
if(rq->bRequest == CUSTOM_RQ_SET_STATUS){
if(rq->wValue.bytes[0] & 1){ /* set LED */
LED_PORT_OUTPUT |= _BV(LED_BIT);
}else{ /* clear LED */
LED_PORT_OUTPUT &= ~_BV(LED_BIT);
}
}else if(rq->bRequest == CUSTOM_RQ_GET_STATUS){
static uchar dataBuffer[1]; /* buffer must stay valid when usbFunctionSetup returns */
dataBuffer[0] = ((LED_PORT_OUTPUT & _BV(LED_BIT)) != 0);
usbMsgPtr = dataBuffer; /* tell the driver which data to return */
return 1; /* tell the driver to send 1 byte */
}
}else{
/* calss requests USBRQ_HID_GET_REPORT and USBRQ_HID_SET_REPORT are
* not implemented since we never call them. The operating system
* won't call them either because our descriptor defines no meaning.
*/
}
return 0; /* default for not implemented requests: return no data back to host */
}
/* ------------------------------------------------------------------------- */
int __attribute__((noreturn)) main(void)
{
uchar i;
wdt_enable(WDTO_1S);
/* Even if you don't use the watchdog, turn it off here. On newer devices,
* the status of the watchdog (on/off, period) is PRESERVED OVER RESET!
*/
/* RESET status: all port bits are inputs without pull-up.
* That's the way we need D+ and D-. Therefore we don't need any
* additional hardware initialization.
*/
odDebugInit();
DBG1(0x00, 0, 0); /* debug output: main starts */
usbInit();
usbDeviceDisconnect(); /* enforce re-enumeration, do this while interrupts are disabled! */
i = 0;
while(--i){ /* fake USB disconnect for > 250 ms */
wdt_reset();
_delay_ms(1);
}
usbDeviceConnect();
LED_PORT_DDR |= _BV(LED_BIT); /* make the LED bit an output */
sei();
DBG1(0x01, 0, 0); /* debug output: main loop starts */
for(;;){ /* main event loop */
#if 0 /* this is a bit too aggressive for a debug output */
DBG2(0x02, 0, 0); /* debug output: main loop iterates */
#endif
wdt_reset();
usbPoll();
}
}
/* ------------------------------------------------------------------------- */

View File

@ -0,0 +1,31 @@
/* Name: requests.h
* Project: custom-class, a basic USB example
* Author: Christian Starkjohann
* Creation Date: 2008-04-09
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/* This header is shared between the firmware and the host software. It
* defines the USB request numbers (and optionally data types) used to
* communicate between the host and the device.
*/
#ifndef __REQUESTS_H_INCLUDED__
#define __REQUESTS_H_INCLUDED__
#define CUSTOM_RQ_SET_STATUS 1
/* Set the LED status. Control-OUT.
* The requested status is passed in the "wValue" field of the control
* transfer. No OUT data is sent. Bit 0 of the low byte of wValue controls
* the LED.
*/
#define CUSTOM_RQ_GET_STATUS 2
/* Get the current LED status. Control-IN.
* This control transfer involves a 1 byte data phase where the device sends
* the current status to the host. The status is in bit 0 of the byte.
*/
#endif /* __REQUESTS_H_INCLUDED__ */

View File

@ -0,0 +1,381 @@
/* Name: usbconfig.h
* Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
* Author: Christian Starkjohann
* Creation Date: 2005-04-01
* Tabsize: 4
* Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
#ifndef __usbconfig_h_included__
#define __usbconfig_h_included__
/*
General Description:
This file is an example configuration (with inline documentation) for the USB
driver. It configures V-USB for USB D+ connected to Port D bit 2 (which is
also hardware interrupt 0 on many devices) and USB D- to Port D bit 4. You may
wire the lines to any other port, as long as D+ is also wired to INT0 (or any
other hardware interrupt, as long as it is the highest level interrupt, see
section at the end of this file).
*/
/* ---------------------------- Hardware Config ---------------------------- */
#define USB_CFG_IOPORTNAME D
/* This is the port where the USB bus is connected. When you configure it to
* "B", the registers PORTB, PINB and DDRB will be used.
*/
#define USB_CFG_DMINUS_BIT 4
/* This is the bit number in USB_CFG_IOPORT where the USB D- line is connected.
* This may be any bit in the port.
*/
#define USB_CFG_DPLUS_BIT 2
/* This is the bit number in USB_CFG_IOPORT where the USB D+ line is connected.
* This may be any bit in the port. Please note that D+ must also be connected
* to interrupt pin INT0! [You can also use other interrupts, see section
* "Optional MCU Description" below, or you can connect D- to the interrupt, as
* it is required if you use the USB_COUNT_SOF feature. If you use D- for the
* interrupt, the USB interrupt will also be triggered at Start-Of-Frame
* markers every millisecond.]
*/
#define USB_CFG_CLOCK_KHZ (F_CPU/1000)
/* Clock rate of the AVR in kHz. Legal values are 12000, 12800, 15000, 16000,
* 16500, 18000 and 20000. The 12.8 MHz and 16.5 MHz versions of the code
* require no crystal, they tolerate +/- 1% deviation from the nominal
* frequency. All other rates require a precision of 2000 ppm and thus a
* crystal!
* Since F_CPU should be defined to your actual clock rate anyway, you should
* not need to modify this setting.
*/
#define USB_CFG_CHECK_CRC 0
/* Define this to 1 if you want that the driver checks integrity of incoming
* data packets (CRC checks). CRC checks cost quite a bit of code size and are
* currently only available for 18 MHz crystal clock. You must choose
* USB_CFG_CLOCK_KHZ = 18000 if you enable this option.
*/
/* ----------------------- Optional Hardware Config ------------------------ */
/* #define USB_CFG_PULLUP_IOPORTNAME D */
/* If you connect the 1.5k pullup resistor from D- to a port pin instead of
* V+, you can connect and disconnect the device from firmware by calling
* the macros usbDeviceConnect() and usbDeviceDisconnect() (see usbdrv.h).
* This constant defines the port on which the pullup resistor is connected.
*/
/* #define USB_CFG_PULLUP_BIT 4 */
/* This constant defines the bit number in USB_CFG_PULLUP_IOPORT (defined
* above) where the 1.5k pullup resistor is connected. See description
* above for details.
*/
/* --------------------------- Functional Range ---------------------------- */
#define USB_CFG_HAVE_INTRIN_ENDPOINT 1
/* Define this to 1 if you want to compile a version with two endpoints: The
* default control endpoint 0 and an interrupt-in endpoint (any other endpoint
* number).
*/
#define USB_CFG_HAVE_INTRIN_ENDPOINT3 0
/* Define this to 1 if you want to compile a version with three endpoints: The
* default control endpoint 0, an interrupt-in endpoint 3 (or the number
* configured below) and a catch-all default interrupt-in endpoint as above.
* You must also define USB_CFG_HAVE_INTRIN_ENDPOINT to 1 for this feature.
*/
#define USB_CFG_EP3_NUMBER 3
/* If the so-called endpoint 3 is used, it can now be configured to any other
* endpoint number (except 0) with this macro. Default if undefined is 3.
*/
/* #define USB_INITIAL_DATATOKEN USBPID_DATA1 */
/* The above macro defines the startup condition for data toggling on the
* interrupt/bulk endpoints 1 and 3. Defaults to USBPID_DATA1.
* Since the token is toggled BEFORE sending any data, the first packet is
* sent with the oposite value of this configuration!
*/
#define USB_CFG_IMPLEMENT_HALT 0
/* Define this to 1 if you also want to implement the ENDPOINT_HALT feature
* for endpoint 1 (interrupt endpoint). Although you may not need this feature,
* it is required by the standard. We have made it a config option because it
* bloats the code considerably.
*/
#define USB_CFG_SUPPRESS_INTR_CODE 0
/* Define this to 1 if you want to declare interrupt-in endpoints, but don't
* want to send any data over them. If this macro is defined to 1, functions
* usbSetInterrupt() and usbSetInterrupt3() are omitted. This is useful if
* you need the interrupt-in endpoints in order to comply to an interface
* (e.g. HID), but never want to send any data. This option saves a couple
* of bytes in flash memory and the transmit buffers in RAM.
*/
#define USB_CFG_INTR_POLL_INTERVAL 100
/* If you compile a version with endpoint 1 (interrupt-in), this is the poll
* interval. The value is in milliseconds and must not be less than 10 ms for
* low speed devices.
*/
#define USB_CFG_IS_SELF_POWERED 0
/* Define this to 1 if the device has its own power supply. Set it to 0 if the
* device is powered from the USB bus.
*/
#define USB_CFG_MAX_BUS_POWER 40
/* Set this variable to the maximum USB bus power consumption of your device.
* The value is in milliamperes. [It will be divided by two since USB
* communicates power requirements in units of 2 mA.]
*/
#define USB_CFG_IMPLEMENT_FN_WRITE 0
/* Set this to 1 if you want usbFunctionWrite() to be called for control-out
* transfers. Set it to 0 if you don't need it and want to save a couple of
* bytes.
*/
#define USB_CFG_IMPLEMENT_FN_READ 0
/* Set this to 1 if you need to send control replies which are generated
* "on the fly" when usbFunctionRead() is called. If you only want to send
* data from a static buffer, set it to 0 and return the data from
* usbFunctionSetup(). This saves a couple of bytes.
*/
#define USB_CFG_IMPLEMENT_FN_WRITEOUT 0
/* Define this to 1 if you want to use interrupt-out (or bulk out) endpoints.
* You must implement the function usbFunctionWriteOut() which receives all
* interrupt/bulk data sent to any endpoint other than 0. The endpoint number
* can be found in 'usbRxToken'.
*/
#define USB_CFG_HAVE_FLOWCONTROL 0
/* Define this to 1 if you want flowcontrol over USB data. See the definition
* of the macros usbDisableAllRequests() and usbEnableAllRequests() in
* usbdrv.h.
*/
#define USB_CFG_DRIVER_FLASH_PAGE 0
/* If the device has more than 64 kBytes of flash, define this to the 64 k page
* where the driver's constants (descriptors) are located. Or in other words:
* Define this to 1 for boot loaders on the ATMega128.
*/
#define USB_CFG_LONG_TRANSFERS 0
/* Define this to 1 if you want to send/receive blocks of more than 254 bytes
* in a single control-in or control-out transfer. Note that the capability
* for long transfers increases the driver size.
*/
/* #define USB_RX_USER_HOOK(data, len) if(usbRxToken == (uchar)USBPID_SETUP) blinkLED(); */
/* This macro is a hook if you want to do unconventional things. If it is
* defined, it's inserted at the beginning of received message processing.
* If you eat the received message and don't want default processing to
* proceed, do a return after doing your things. One possible application
* (besides debugging) is to flash a status LED on each packet.
*/
/* #define USB_RESET_HOOK(resetStarts) if(!resetStarts){hadUsbReset();} */
/* This macro is a hook if you need to know when an USB RESET occurs. It has
* one parameter which distinguishes between the start of RESET state and its
* end.
*/
/* #define USB_SET_ADDRESS_HOOK() hadAddressAssigned(); */
/* This macro (if defined) is executed when a USB SET_ADDRESS request was
* received.
*/
#define USB_COUNT_SOF 0
/* define this macro to 1 if you need the global variable "usbSofCount" which
* counts SOF packets. This feature requires that the hardware interrupt is
* connected to D- instead of D+.
*/
/* #ifdef __ASSEMBLER__
* macro myAssemblerMacro
* in YL, TCNT0
* sts timer0Snapshot, YL
* endm
* #endif
* #define USB_SOF_HOOK myAssemblerMacro
* This macro (if defined) is executed in the assembler module when a
* Start Of Frame condition is detected. It is recommended to define it to
* the name of an assembler macro which is defined here as well so that more
* than one assembler instruction can be used. The macro may use the register
* YL and modify SREG. If it lasts longer than a couple of cycles, USB messages
* immediately after an SOF pulse may be lost and must be retried by the host.
* What can you do with this hook? Since the SOF signal occurs exactly every
* 1 ms (unless the host is in sleep mode), you can use it to tune OSCCAL in
* designs running on the internal RC oscillator.
* Please note that Start Of Frame detection works only if D- is wired to the
* interrupt, not D+. THIS IS DIFFERENT THAN MOST EXAMPLES!
*/
#define USB_CFG_CHECK_DATA_TOGGLING 0
/* define this macro to 1 if you want to filter out duplicate data packets
* sent by the host. Duplicates occur only as a consequence of communication
* errors, when the host does not receive an ACK. Please note that you need to
* implement the filtering yourself in usbFunctionWriteOut() and
* usbFunctionWrite(). Use the global usbCurrentDataToken and a static variable
* for each control- and out-endpoint to check for duplicate packets.
*/
#define USB_CFG_HAVE_MEASURE_FRAME_LENGTH 0
/* define this macro to 1 if you want the function usbMeasureFrameLength()
* compiled in. This function can be used to calibrate the AVR's RC oscillator.
*/
#define USB_USE_FAST_CRC 0
/* The assembler module has two implementations for the CRC algorithm. One is
* faster, the other is smaller. This CRC routine is only used for transmitted
* messages where timing is not critical. The faster routine needs 31 cycles
* per byte while the smaller one needs 61 to 69 cycles. The faster routine
* may be worth the 32 bytes bigger code size if you transmit lots of data and
* run the AVR close to its limit.
*/
/* -------------------------- Device Description --------------------------- */
#define USB_CFG_VENDOR_ID 0xc0, 0x16 /* = 0x16c0 = 5824 = voti.nl */
/* USB vendor ID for the device, low byte first. If you have registered your
* own Vendor ID, define it here. Otherwise you may use one of obdev's free
* shared VID/PID pairs. Be sure to read USB-IDs-for-free.txt for rules!
* *** IMPORTANT NOTE ***
* This template uses obdev's shared VID/PID pair for Vendor Class devices
* with libusb: 0x16c0/0x5dc. Use this VID/PID pair ONLY if you understand
* the implications!
*/
#define USB_CFG_DEVICE_ID 0xdf, 0x05 /* obdev's shared PID for HIDs */
/* This is the ID of the product, low byte first. It is interpreted in the
* scope of the vendor ID. If you have registered your own VID with usb.org
* or if you have licensed a PID from somebody else, define it here. Otherwise
* you may use one of obdev's free shared VID/PID pairs. See the file
* USB-IDs-for-free.txt for details!
* *** IMPORTANT NOTE ***
* This template uses obdev's shared VID/PID pair for Vendor Class devices
* with libusb: 0x16c0/0x5dc. Use this VID/PID pair ONLY if you understand
* the implications!
*/
#define USB_CFG_DEVICE_VERSION 0x00, 0x01
/* Version number of the device: Minor number first, then major number.
*/
#define USB_CFG_VENDOR_NAME 'o', 'b', 'd', 'e', 'v', '.', 'a', 't'
#define USB_CFG_VENDOR_NAME_LEN 8
/* These two values define the vendor name returned by the USB device. The name
* must be given as a list of characters under single quotes. The characters
* are interpreted as Unicode (UTF-16) entities.
* If you don't want a vendor name string, undefine these macros.
* ALWAYS define a vendor name containing your Internet domain name if you use
* obdev's free shared VID/PID pair. See the file USB-IDs-for-free.txt for
* details.
*/
#define USB_CFG_DEVICE_NAME 'L', 'E', 'D', 'C', 't', 'l', 'H', 'I', 'D'
#define USB_CFG_DEVICE_NAME_LEN 9
/* Same as above for the device name. If you don't want a device name, undefine
* the macros. See the file USB-IDs-for-free.txt before you assign a name if
* you use a shared VID/PID.
*/
/*#define USB_CFG_SERIAL_NUMBER 'N', 'o', 'n', 'e' */
/*#define USB_CFG_SERIAL_NUMBER_LEN 0 */
/* Same as above for the serial number. If you don't want a serial number,
* undefine the macros.
* It may be useful to provide the serial number through other means than at
* compile time. See the section about descriptor properties below for how
* to fine tune control over USB descriptors such as the string descriptor
* for the serial number.
*/
#define USB_CFG_DEVICE_CLASS 0
#define USB_CFG_DEVICE_SUBCLASS 0
/* See USB specification if you want to conform to an existing device class.
* Class 0xff is "vendor specific".
*/
#define USB_CFG_INTERFACE_CLASS 3
#define USB_CFG_INTERFACE_SUBCLASS 0
#define USB_CFG_INTERFACE_PROTOCOL 0
/* See USB specification if you want to conform to an existing device class or
* protocol. The following classes must be set at interface level:
* HID class is 3, no subclass and protocol required (but may be useful!)
* CDC class is 2, use subclass 2 and protocol 1 for ACM
*/
#define USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH 22
/* Define this to the length of the HID report descriptor, if you implement
* an HID device. Otherwise don't define it or define it to 0.
* If you use this define, you must add a PROGMEM character array named
* "usbHidReportDescriptor" to your code which contains the report descriptor.
* Don't forget to keep the array and this define in sync!
*/
/* #define USB_PUBLIC static */
/* Use the define above if you #include usbdrv.c instead of linking against it.
* This technique saves a couple of bytes in flash memory.
*/
/* ------------------- Fine Control over USB Descriptors ------------------- */
/* If you don't want to use the driver's default USB descriptors, you can
* provide our own. These can be provided as (1) fixed length static data in
* flash memory, (2) fixed length static data in RAM or (3) dynamically at
* runtime in the function usbFunctionDescriptor(). See usbdrv.h for more
* information about this function.
* Descriptor handling is configured through the descriptor's properties. If
* no properties are defined or if they are 0, the default descriptor is used.
* Possible properties are:
* + USB_PROP_IS_DYNAMIC: The data for the descriptor should be fetched
* at runtime via usbFunctionDescriptor(). If the usbMsgPtr mechanism is
* used, the data is in FLASH by default. Add property USB_PROP_IS_RAM if
* you want RAM pointers.
* + USB_PROP_IS_RAM: The data returned by usbFunctionDescriptor() or found
* in static memory is in RAM, not in flash memory.
* + USB_PROP_LENGTH(len): If the data is in static memory (RAM or flash),
* the driver must know the descriptor's length. The descriptor itself is
* found at the address of a well known identifier (see below).
* List of static descriptor names (must be declared PROGMEM if in flash):
* char usbDescriptorDevice[];
* char usbDescriptorConfiguration[];
* char usbDescriptorHidReport[];
* char usbDescriptorString0[];
* int usbDescriptorStringVendor[];
* int usbDescriptorStringDevice[];
* int usbDescriptorStringSerialNumber[];
* Other descriptors can't be provided statically, they must be provided
* dynamically at runtime.
*
* Descriptor properties are or-ed or added together, e.g.:
* #define USB_CFG_DESCR_PROPS_DEVICE (USB_PROP_IS_RAM | USB_PROP_LENGTH(18))
*
* The following descriptors are defined:
* USB_CFG_DESCR_PROPS_DEVICE
* USB_CFG_DESCR_PROPS_CONFIGURATION
* USB_CFG_DESCR_PROPS_STRINGS
* USB_CFG_DESCR_PROPS_STRING_0
* USB_CFG_DESCR_PROPS_STRING_VENDOR
* USB_CFG_DESCR_PROPS_STRING_PRODUCT
* USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
* USB_CFG_DESCR_PROPS_HID
* USB_CFG_DESCR_PROPS_HID_REPORT
* USB_CFG_DESCR_PROPS_UNKNOWN (for all descriptors not handled by the driver)
*
* Note about string descriptors: String descriptors are not just strings, they
* are Unicode strings prefixed with a 2 byte header. Example:
* int serialNumberDescriptor[] = {
* USB_STRING_DESCRIPTOR_HEADER(6),
* 'S', 'e', 'r', 'i', 'a', 'l'
* };
*/
#define USB_CFG_DESCR_PROPS_DEVICE 0
#define USB_CFG_DESCR_PROPS_CONFIGURATION 0
#define USB_CFG_DESCR_PROPS_STRINGS 0
#define USB_CFG_DESCR_PROPS_STRING_0 0
#define USB_CFG_DESCR_PROPS_STRING_VENDOR 0
#define USB_CFG_DESCR_PROPS_STRING_PRODUCT 0
#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER 0
#define USB_CFG_DESCR_PROPS_HID 0
#define USB_CFG_DESCR_PROPS_HID_REPORT 0
#define USB_CFG_DESCR_PROPS_UNKNOWN 0
#define usbMsgPtr_t unsigned short
/* If usbMsgPtr_t is not defined, it defaults to 'uchar *'. We define it to
* a scalar type here because gcc generates slightly shorter code for scalar
* arithmetics than for pointer arithmetics. Remove this define for backward
* type compatibility or define it to an 8 bit type if you use data in RAM only
* and all RAM is below 256 bytes (tiny memory model in IAR CC).
*/
/* ----------------------- Optional MCU Description ------------------------ */
/* The following configurations have working defaults in usbdrv.h. You
* usually don't need to set them explicitly. Only if you want to run
* the driver on a device which is not yet supported or with a compiler
* which is not fully supported (such as IAR C) or if you use a differnt
* interrupt than INT0, you may have to define some of these.
*/
/* #define USB_INTR_CFG MCUCR */
/* #define USB_INTR_CFG_SET ((1 << ISC00) | (1 << ISC01)) */
/* #define USB_INTR_CFG_CLR 0 */
/* #define USB_INTR_ENABLE GIMSK */
/* #define USB_INTR_ENABLE_BIT INT0 */
/* #define USB_INTR_PENDING GIFR */
/* #define USB_INTR_PENDING_BIT INTF0 */
/* #define USB_INTR_VECTOR INT0_vect */
#endif /* __usbconfig_h_included__ */

View File

@ -0,0 +1,75 @@
This is the Readme file for the hid-data example. In this example, we show
how blocks of data can be exchanged with the device using only functionality
compliant to the HID class. Since class drivers for HID are included with
Windows, you don't need to install drivers on Windows.
WHAT IS DEMONSTRATED?
=====================
This example demonstrates how the HID class can be misused to transfer fixed
size blocks of data (up to the driver's transfer size limit) over HID feature
reports. This technique is of great value on Windows because no driver DLLs
are needed (the hid-custom-rq example still requires the libusb-win32 DLL,
although it may be in the program's directory). The host side application
requires no installation, it can even be started directly from a CD. This
example also demonstrates how to transfer data using usbFunctionWrite() and
usbFunctionRead().
PREREQUISITES
=============
Target hardware: You need an AVR based circuit based on one of the examples
(see the "circuits" directory at the top level of this package), e.g. the
metaboard (http://www.obdev.at/goto.php?t=metaboard).
AVR development environment: You need the gcc tool chain for the AVR, see
the Prerequisites section in the top level Readme file for how to obtain it.
Host development environment: A C compiler and libusb on Unix. On Windows
you need the Driver Development Kit (DDK) Instead of libusb. MinGW ships
with a free version of the DDK.
BUILDING THE FIRMWARE
=====================
Change to the "firmware" directory and modify Makefile according to your
architecture (CPU clock, target device, fuse values) and ISP programmer. Then
edit usbconfig.h according to your pin assignments for D+ and D-. The default
settings are for the metaboard hardware.
Type "make hex" to build main.hex, then "make flash" to upload the firmware
to the device. Don't forget to run "make fuse" once to program the fuses. If
you use a prototyping board with boot loader, follow the instructions of the
boot loader instead.
Please note that the first "make hex" copies the driver from the top level
into the firmware directory. If you use a different build system than our
Makefile, you must copy the driver by hand.
BUILDING THE HOST SOFTWARE
==========================
Make sure that you have libusb (on Unix) or the DDK (on Windows) installed.
We recommend MinGW on Windows since it includes a free version of the DDK.
Then change to directory "commandline" and run "make" on Unix or
"make -f Makefile.windows" on Windows.
USING THE COMMAND LINE TOOL
===========================
The device implements a data store of 128 bytes in EEPROM. You can send a
block of 128 bytes to the device or read the block using the command line
tool.
To send a block to the device, use e.g.
hidtool write 0x01,0x02,0x03,0x04,...
and to receive the block, use
hidtool read
----------------------------------------------------------------------------
(c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH.
http://www.obdev.at/

View File

@ -0,0 +1,41 @@
# Name: Makefile
# Project: hid-data example
# Author: Christian Starkjohann
# Creation Date: 2008-04-11
# Tabsize: 4
# Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
# Please read the definitions below and edit them as appropriate for your
# system:
# Use the following 3 lines on Unix and Mac OS X:
USBFLAGS= `libusb-config --cflags`
USBLIBS= `libusb-config --libs`
EXE_SUFFIX=
# Use the following 3 lines on Windows and comment out the 3 above:
#USBFLAGS=
#USBLIBS= -lhid -lusb -lsetupapi
#EXE_SUFFIX= .exe
CC= gcc
CFLAGS= -O -Wall $(USBFLAGS)
LIBS= $(USBLIBS)
OBJ= hidtool.o hiddata.o
PROGRAM= hidtool$(EXE_SUFFIX)
all: $(PROGRAM)
$(PROGRAM): $(OBJ)
$(CC) -o $(PROGRAM) $(OBJ) $(LIBS)
strip: $(PROGRAM)
strip $(PROGRAM)
clean:
rm -f $(OBJ) $(PROGRAM)
.c.o:
$(CC) $(ARCH_COMPILE) $(CFLAGS) -c $*.c -o $*.o

View File

@ -0,0 +1,17 @@
# Name: Makefile.windows
# Project: hid-data example
# Author: Christian Starkjohann
# Creation Date: 2008-04-11
# Tabsize: 4
# Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
# You may use this file with
# make -f Makefile.windows
# on Windows with MinGW instead of editing the main Makefile.
include Makefile
USBFLAGS=
USBLIBS= -lhid -lsetupapi
EXE_SUFFIX= .exe

View File

@ -0,0 +1,323 @@
/* Name: hiddata.c
* Author: Christian Starkjohann
* Creation Date: 2008-04-11
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
#include <stdio.h>
#include "hiddata.h"
/* ######################################################################## */
#if defined(WIN32) /* ##################################################### */
/* ######################################################################## */
#include <windows.h>
#include <setupapi.h>
#include "hidsdi.h"
#include <ddk/hidpi.h>
#ifdef DEBUG
#define DEBUG_PRINT(arg) printf arg
#else
#define DEBUG_PRINT(arg)
#endif
/* ------------------------------------------------------------------------ */
static void convertUniToAscii(char *buffer)
{
unsigned short *uni = (void *)buffer;
char *ascii = buffer;
while(*uni != 0){
if(*uni >= 256){
*ascii++ = '?';
}else{
*ascii++ = *uni++;
}
}
*ascii++ = 0;
}
int usbhidOpenDevice(usbDevice_t **device, int vendor, char *vendorName, int product, char *productName, int usesReportIDs)
{
GUID hidGuid; /* GUID for HID driver */
HDEVINFO deviceInfoList;
SP_DEVICE_INTERFACE_DATA deviceInfo;
SP_DEVICE_INTERFACE_DETAIL_DATA *deviceDetails = NULL;
DWORD size;
int i, openFlag = 0; /* may be FILE_FLAG_OVERLAPPED */
int errorCode = USBOPEN_ERR_NOTFOUND;
HANDLE handle = INVALID_HANDLE_VALUE;
HIDD_ATTRIBUTES deviceAttributes;
HidD_GetHidGuid(&hidGuid);
deviceInfoList = SetupDiGetClassDevs(&hidGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
deviceInfo.cbSize = sizeof(deviceInfo);
for(i=0;;i++){
if(handle != INVALID_HANDLE_VALUE){
CloseHandle(handle);
handle = INVALID_HANDLE_VALUE;
}
if(!SetupDiEnumDeviceInterfaces(deviceInfoList, 0, &hidGuid, i, &deviceInfo))
break; /* no more entries */
/* first do a dummy call just to determine the actual size required */
SetupDiGetDeviceInterfaceDetail(deviceInfoList, &deviceInfo, NULL, 0, &size, NULL);
if(deviceDetails != NULL)
free(deviceDetails);
deviceDetails = malloc(size);
deviceDetails->cbSize = sizeof(*deviceDetails);
/* this call is for real: */
SetupDiGetDeviceInterfaceDetail(deviceInfoList, &deviceInfo, deviceDetails, size, &size, NULL);
DEBUG_PRINT(("checking HID path \"%s\"\n", deviceDetails->DevicePath));
#if 0
/* If we want to access a mouse our keyboard, we can only use feature
* requests as the device is locked by Windows. It must be opened
* with ACCESS_TYPE_NONE.
*/
handle = CreateFile(deviceDetails->DevicePath, ACCESS_TYPE_NONE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, openFlag, NULL);
#endif
/* attempt opening for R/W -- we don't care about devices which can't be accessed */
handle = CreateFile(deviceDetails->DevicePath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, openFlag, NULL);
if(handle == INVALID_HANDLE_VALUE){
DEBUG_PRINT(("opening failed: %d\n", (int)GetLastError()));
/* errorCode = USBOPEN_ERR_ACCESS; opening will always fail for mouse -- ignore */
continue;
}
deviceAttributes.Size = sizeof(deviceAttributes);
HidD_GetAttributes(handle, &deviceAttributes);
DEBUG_PRINT(("device attributes: vid=%d pid=%d\n", deviceAttributes.VendorID, deviceAttributes.ProductID));
if(deviceAttributes.VendorID != vendor || deviceAttributes.ProductID != product)
continue; /* ignore this device */
errorCode = USBOPEN_ERR_NOTFOUND;
if(vendorName != NULL && productName != NULL){
char buffer[512];
if(!HidD_GetManufacturerString(handle, buffer, sizeof(buffer))){
DEBUG_PRINT(("error obtaining vendor name\n"));
errorCode = USBOPEN_ERR_IO;
continue;
}
convertUniToAscii(buffer);
DEBUG_PRINT(("vendorName = \"%s\"\n", buffer));
if(strcmp(vendorName, buffer) != 0)
continue;
if(!HidD_GetProductString(handle, buffer, sizeof(buffer))){
DEBUG_PRINT(("error obtaining product name\n"));
errorCode = USBOPEN_ERR_IO;
continue;
}
convertUniToAscii(buffer);
DEBUG_PRINT(("productName = \"%s\"\n", buffer));
if(strcmp(productName, buffer) != 0)
continue;
}
break; /* we have found the device we are looking for! */
}
SetupDiDestroyDeviceInfoList(deviceInfoList);
if(deviceDetails != NULL)
free(deviceDetails);
if(handle != INVALID_HANDLE_VALUE){
*device = (usbDevice_t *)handle;
errorCode = 0;
}
return errorCode;
}
/* ------------------------------------------------------------------------ */
void usbhidCloseDevice(usbDevice_t *device)
{
CloseHandle((HANDLE)device);
}
/* ------------------------------------------------------------------------ */
int usbhidSetReport(usbDevice_t *device, char *buffer, int len)
{
BOOLEAN rval;
rval = HidD_SetFeature((HANDLE)device, buffer, len);
return rval == 0 ? USBOPEN_ERR_IO : 0;
}
/* ------------------------------------------------------------------------ */
int usbhidGetReport(usbDevice_t *device, int reportNumber, char *buffer, int *len)
{
BOOLEAN rval = 0;
buffer[0] = reportNumber;
rval = HidD_GetFeature((HANDLE)device, buffer, *len);
return rval == 0 ? USBOPEN_ERR_IO : 0;
}
/* ------------------------------------------------------------------------ */
/* ######################################################################## */
#else /* defined WIN32 #################################################### */
/* ######################################################################## */
#include <string.h>
#include <usb.h>
#define usbDevice usb_dev_handle /* use libusb's device structure */
/* ------------------------------------------------------------------------- */
#define USBRQ_HID_GET_REPORT 0x01
#define USBRQ_HID_SET_REPORT 0x09
#define USB_HID_REPORT_TYPE_FEATURE 3
static int usesReportIDs;
/* ------------------------------------------------------------------------- */
static int usbhidGetStringAscii(usb_dev_handle *dev, int index, char *buf, int buflen)
{
char buffer[256];
int rval, i;
if((rval = usb_get_string_simple(dev, index, buf, buflen)) >= 0) /* use libusb version if it works */
return rval;
if((rval = usb_control_msg(dev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR, (USB_DT_STRING << 8) + index, 0x0409, buffer, sizeof(buffer), 5000)) < 0)
return rval;
if(buffer[1] != USB_DT_STRING){
*buf = 0;
return 0;
}
if((unsigned char)buffer[0] < rval)
rval = (unsigned char)buffer[0];
rval /= 2;
/* lossy conversion to ISO Latin1: */
for(i=1;i<rval;i++){
if(i > buflen) /* destination buffer overflow */
break;
buf[i-1] = buffer[2 * i];
if(buffer[2 * i + 1] != 0) /* outside of ISO Latin1 range */
buf[i-1] = '?';
}
buf[i-1] = 0;
return i-1;
}
int usbhidOpenDevice(usbDevice_t **device, int vendor, char *vendorName, int product, char *productName, int _usesReportIDs)
{
struct usb_bus *bus;
struct usb_device *dev;
usb_dev_handle *handle = NULL;
int errorCode = USBOPEN_ERR_NOTFOUND;
static int didUsbInit = 0;
if(!didUsbInit){
usb_init();
didUsbInit = 1;
}
usb_find_busses();
usb_find_devices();
for(bus=usb_get_busses(); bus; bus=bus->next){
for(dev=bus->devices; dev; dev=dev->next){
if(dev->descriptor.idVendor == vendor && dev->descriptor.idProduct == product){
char string[256];
int len;
handle = usb_open(dev); /* we need to open the device in order to query strings */
if(!handle){
errorCode = USBOPEN_ERR_ACCESS;
fprintf(stderr, "Warning: cannot open USB device: %s\n", usb_strerror());
continue;
}
if(vendorName == NULL && productName == NULL){ /* name does not matter */
break;
}
/* now check whether the names match: */
len = usbhidGetStringAscii(handle, dev->descriptor.iManufacturer, string, sizeof(string));
if(len < 0){
errorCode = USBOPEN_ERR_IO;
fprintf(stderr, "Warning: cannot query manufacturer for device: %s\n", usb_strerror());
}else{
errorCode = USBOPEN_ERR_NOTFOUND;
/* fprintf(stderr, "seen device from vendor ->%s<-\n", string); */
if(strcmp(string, vendorName) == 0){
len = usbhidGetStringAscii(handle, dev->descriptor.iProduct, string, sizeof(string));
if(len < 0){
errorCode = USBOPEN_ERR_IO;
fprintf(stderr, "Warning: cannot query product for device: %s\n", usb_strerror());
}else{
errorCode = USBOPEN_ERR_NOTFOUND;
/* fprintf(stderr, "seen product ->%s<-\n", string); */
if(strcmp(string, productName) == 0)
break;
}
}
}
usb_close(handle);
handle = NULL;
}
}
if(handle)
break;
}
if(handle != NULL){
errorCode = 0;
*device = (void *)handle;
usesReportIDs = _usesReportIDs;
}
return errorCode;
}
/* ------------------------------------------------------------------------- */
void usbhidCloseDevice(usbDevice_t *device)
{
if(device != NULL)
usb_close((void *)device);
}
/* ------------------------------------------------------------------------- */
int usbhidSetReport(usbDevice_t *device, char *buffer, int len)
{
int bytesSent, reportId = buffer[0];
if(!usesReportIDs){
buffer++; /* skip dummy report ID */
len--;
}
bytesSent = usb_control_msg((void *)device, USB_TYPE_CLASS | USB_RECIP_DEVICE | USB_ENDPOINT_OUT, USBRQ_HID_SET_REPORT, USB_HID_REPORT_TYPE_FEATURE << 8 | (reportId & 0xff), 0, buffer, len, 5000);
if(bytesSent != len){
if(bytesSent < 0)
fprintf(stderr, "Error sending message: %s\n", usb_strerror());
return USBOPEN_ERR_IO;
}
return 0;
}
/* ------------------------------------------------------------------------- */
int usbhidGetReport(usbDevice_t *device, int reportNumber, char *buffer, int *len)
{
int bytesReceived, maxLen = *len;
if(!usesReportIDs){
buffer++; /* make room for dummy report ID */
maxLen--;
}
bytesReceived = usb_control_msg((void *)device, USB_TYPE_CLASS | USB_RECIP_DEVICE | USB_ENDPOINT_IN, USBRQ_HID_GET_REPORT, USB_HID_REPORT_TYPE_FEATURE << 8 | reportNumber, 0, buffer, maxLen, 5000);
if(bytesReceived < 0){
fprintf(stderr, "Error sending message: %s\n", usb_strerror());
return USBOPEN_ERR_IO;
}
*len = bytesReceived;
if(!usesReportIDs){
buffer[-1] = reportNumber; /* add dummy report ID */
(*len)++;
}
return 0;
}
/* ######################################################################## */
#endif /* defined WIN32 ################################################### */
/* ######################################################################## */

View File

@ -0,0 +1,70 @@
/* Name: hiddata.h
* Author: Christian Starkjohann
* Creation Date: 2008-04-11
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
#ifndef __HIDDATA_H_INCLUDED__
#define __HIDDATA_H_INCLUDED__
/*
General Description:
This module implements an abstraction layer for data transfer over HID feature
requests. The implementation uses native Windows functions on Windows so that
no driver installation is required and libusb on Unix. You must link the
appropriate libraries in either case: "-lhid -lusb -lsetupapi" on Windows and
`libusb-config --libs` on Unix.
*/
/* ------------------------------------------------------------------------ */
#define USBOPEN_SUCCESS 0 /* no error */
#define USBOPEN_ERR_ACCESS 1 /* not enough permissions to open device */
#define USBOPEN_ERR_IO 2 /* I/O error */
#define USBOPEN_ERR_NOTFOUND 3 /* device not found */
/* ------------------------------------------------------------------------ */
typedef struct usbDevice usbDevice_t;
/* Opaque data type representing the USB device. This can be a Windows handle
* or a libusb handle, depending on the backend implementation.
*/
/* ------------------------------------------------------------------------ */
int usbhidOpenDevice(usbDevice_t **device, int vendorID, char *vendorName, int productID, char *productName, int usesReportIDs);
/* This function opens a USB device. 'vendorID' and 'productID' are the numeric
* Vendor-ID and Product-ID of the device we want to open. If 'vendorName' and
* 'productName' are both not NULL, only devices with matching manufacturer-
* and product name strings are accepted. If the device uses report IDs,
* 'usesReportIDs' must be set to a non-zero value.
* Returns: If a matching device has been found, USBOPEN_SUCCESS is returned
* and '*device' is set to an opaque pointer representing the device. The
* device must be closed with usbhidCloseDevice(). If the device has not been
* found or opening failed, an error code is returned.
*/
void usbhidCloseDevice(usbDevice_t *device);
/* Every device opened with usbhidOpenDevice() must be closed with this function.
*/
int usbhidSetReport(usbDevice_t *device, char *buffer, int len);
/* This function sends a feature report to the device. The report ID must be
* in the first byte of buffer and the length 'len' of the report is specified
* including this report ID. If no report IDs are used, buffer[0] must be set
* to 0 (dummy report ID).
* Returns: 0 on success, an error code otherwise.
*/
int usbhidGetReport(usbDevice_t *device, int reportID, char *buffer, int *len);
/* This function obtains a feature report from the device. The requested
* report-ID is passed in 'reportID'. The caller must pass a buffer of the size
* of the expected report in 'buffer' and initialize the variable pointed to by
* 'len' to the total size of this buffer. Upon successful return, the report
* (prefixed with the report-ID) is in 'buffer' and the actual length of the
* report is returned in '*len'.
* Returns: 0 on success, an error code otherwise.
*/
/* ------------------------------------------------------------------------ */
#endif /* __HIDDATA_H_INCLUDED__ */

View File

@ -0,0 +1,48 @@
/* Name: hidsdi.h
* Author: Christian Starkjohann
* Creation Date: 2006-02-02
* Tabsize: 4
* Copyright: (c) 2006-2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
General Description
This file is a replacement for hidsdi.h from the Windows DDK. It defines some
of the types and function prototypes of this header for our project. If you
have the Windows DDK version of this file or a version shipped with MinGW, use
that instead.
*/
#ifndef _HIDSDI_H
#define _HIDSDI_H
#include <pshpack4.h>
#include <ddk/hidusage.h>
#include <ddk/hidpi.h>
typedef struct{
ULONG Size;
USHORT VendorID;
USHORT ProductID;
USHORT VersionNumber;
}HIDD_ATTRIBUTES;
void __stdcall HidD_GetHidGuid(OUT LPGUID hidGuid);
BOOLEAN __stdcall HidD_GetAttributes(IN HANDLE device, OUT HIDD_ATTRIBUTES *attributes);
BOOLEAN __stdcall HidD_GetManufacturerString(IN HANDLE device, OUT void *buffer, IN ULONG bufferLen);
BOOLEAN __stdcall HidD_GetProductString(IN HANDLE device, OUT void *buffer, IN ULONG bufferLen);
BOOLEAN __stdcall HidD_GetSerialNumberString(IN HANDLE device, OUT void *buffer, IN ULONG bufferLen);
BOOLEAN __stdcall HidD_GetFeature(IN HANDLE device, OUT void *reportBuffer, IN ULONG bufferLen);
BOOLEAN __stdcall HidD_SetFeature(IN HANDLE device, IN void *reportBuffer, IN ULONG bufferLen);
BOOLEAN __stdcall HidD_GetNumInputBuffers(IN HANDLE device, OUT ULONG *numBuffers);
BOOLEAN __stdcall HidD_SetNumInputBuffers(IN HANDLE device, OUT ULONG numBuffers);
#include <poppack.h>
#endif

View File

@ -0,0 +1,126 @@
/* Name: hidtool.c
* Project: hid-data example
* Author: Christian Starkjohann
* Creation Date: 2008-04-11
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "hiddata.h"
#include "../firmware/usbconfig.h" /* for device VID, PID, vendor name and product name */
/* ------------------------------------------------------------------------- */
static char *usbErrorMessage(int errCode)
{
static char buffer[80];
switch(errCode){
case USBOPEN_ERR_ACCESS: return "Access to device denied";
case USBOPEN_ERR_NOTFOUND: return "The specified device was not found";
case USBOPEN_ERR_IO: return "Communication error with device";
default:
sprintf(buffer, "Unknown USB error %d", errCode);
return buffer;
}
return NULL; /* not reached */
}
static usbDevice_t *openDevice(void)
{
usbDevice_t *dev = NULL;
unsigned char rawVid[2] = {USB_CFG_VENDOR_ID}, rawPid[2] = {USB_CFG_DEVICE_ID};
char vendorName[] = {USB_CFG_VENDOR_NAME, 0}, productName[] = {USB_CFG_DEVICE_NAME, 0};
int vid = rawVid[0] + 256 * rawVid[1];
int pid = rawPid[0] + 256 * rawPid[1];
int err;
if((err = usbhidOpenDevice(&dev, vid, vendorName, pid, productName, 0)) != 0){
fprintf(stderr, "error finding %s: %s\n", productName, usbErrorMessage(err));
return NULL;
}
return dev;
}
/* ------------------------------------------------------------------------- */
static void hexdump(char *buffer, int len)
{
int i;
FILE *fp = stdout;
for(i = 0; i < len; i++){
if(i != 0){
if(i % 16 == 0){
fprintf(fp, "\n");
}else{
fprintf(fp, " ");
}
}
fprintf(fp, "0x%02x", buffer[i] & 0xff);
}
if(i != 0)
fprintf(fp, "\n");
}
static int hexread(char *buffer, char *string, int buflen)
{
char *s;
int pos = 0;
while((s = strtok(string, ", ")) != NULL && pos < buflen){
string = NULL;
buffer[pos++] = (char)strtol(s, NULL, 0);
}
return pos;
}
/* ------------------------------------------------------------------------- */
static void usage(char *myName)
{
fprintf(stderr, "usage:\n");
fprintf(stderr, " %s read\n", myName);
fprintf(stderr, " %s write <listofbytes>\n", myName);
}
int main(int argc, char **argv)
{
usbDevice_t *dev;
char buffer[129]; /* room for dummy report ID */
int err;
if(argc < 2){
usage(argv[0]);
exit(1);
}
if((dev = openDevice()) == NULL)
exit(1);
if(strcasecmp(argv[1], "read") == 0){
int len = sizeof(buffer);
if((err = usbhidGetReport(dev, 0, buffer, &len)) != 0){
fprintf(stderr, "error reading data: %s\n", usbErrorMessage(err));
}else{
hexdump(buffer + 1, sizeof(buffer) - 1);
}
}else if(strcasecmp(argv[1], "write") == 0){
int i, pos;
memset(buffer, 0, sizeof(buffer));
for(pos = 1, i = 2; i < argc && pos < sizeof(buffer); i++){
pos += hexread(buffer + pos, argv[i], sizeof(buffer) - pos);
}
if((err = usbhidSetReport(dev, buffer, sizeof(buffer))) != 0) /* add a dummy report ID */
fprintf(stderr, "error writing data: %s\n", usbErrorMessage(err));
}else{
usage(argv[0]);
exit(1);
}
usbhidCloseDevice(dev);
return 0;
}
/* ------------------------------------------------------------------------- */

View File

@ -0,0 +1,163 @@
# Name: Makefile
# Project: hid-data example
# Author: Christian Starkjohann
# Creation Date: 2008-04-07
# Tabsize: 4
# Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
DEVICE = atmega168
F_CPU = 16000000 # in Hz
FUSE_L = # see below for fuse values for particular devices
FUSE_H =
AVRDUDE = avrdude -c usbasp -p $(DEVICE) # edit this line for your programmer
CFLAGS = -Iusbdrv -I. -DDEBUG_LEVEL=0
OBJECTS = usbdrv/usbdrv.o usbdrv/usbdrvasm.o usbdrv/oddebug.o main.o
COMPILE = avr-gcc -Wall -Os -DF_CPU=$(F_CPU) $(CFLAGS) -mmcu=$(DEVICE)
##############################################################################
# Fuse values for particular devices
##############################################################################
# If your device is not listed here, go to
# http://palmavr.sourceforge.net/cgi-bin/fc.cgi
# and choose options for external crystal clock and no clock divider
#
################################## ATMega8 ##################################
# ATMega8 FUSE_L (Fuse low byte):
# 0x9f = 1 0 0 1 1 1 1 1
# ^ ^ \ / \--+--/
# | | | +------- CKSEL 3..0 (external >8M crystal)
# | | +--------------- SUT 1..0 (crystal osc, BOD enabled)
# | +------------------ BODEN (BrownOut Detector enabled)
# +-------------------- BODLEVEL (2.7V)
# ATMega8 FUSE_H (Fuse high byte):
# 0xc9 = 1 1 0 0 1 0 0 1 <-- BOOTRST (boot reset vector at 0x0000)
# ^ ^ ^ ^ ^ ^ ^------ BOOTSZ0
# | | | | | +-------- BOOTSZ1
# | | | | + --------- EESAVE (don't preserve EEPROM over chip erase)
# | | | +-------------- CKOPT (full output swing)
# | | +---------------- SPIEN (allow serial programming)
# | +------------------ WDTON (WDT not always on)
# +-------------------- RSTDISBL (reset pin is enabled)
#
############################## ATMega48/88/168 ##############################
# ATMega*8 FUSE_L (Fuse low byte):
# 0xdf = 1 1 0 1 1 1 1 1
# ^ ^ \ / \--+--/
# | | | +------- CKSEL 3..0 (external >8M crystal)
# | | +--------------- SUT 1..0 (crystal osc, BOD enabled)
# | +------------------ CKOUT (if 0: Clock output enabled)
# +-------------------- CKDIV8 (if 0: divide by 8)
# ATMega*8 FUSE_H (Fuse high byte):
# 0xde = 1 1 0 1 1 1 1 0
# ^ ^ ^ ^ ^ \-+-/
# | | | | | +------ BODLEVEL 0..2 (110 = 1.8 V)
# | | | | + --------- EESAVE (preserve EEPROM over chip erase)
# | | | +-------------- WDTON (if 0: watchdog always on)
# | | +---------------- SPIEN (allow serial programming)
# | +------------------ DWEN (debug wire enable)
# +-------------------- RSTDISBL (reset pin is enabled)
#
############################## ATTiny25/45/85 ###############################
# ATMega*5 FUSE_L (Fuse low byte):
# 0xef = 1 1 1 0 1 1 1 1
# ^ ^ \+/ \--+--/
# | | | +------- CKSEL 3..0 (clock selection -> crystal @ 12 MHz)
# | | +--------------- SUT 1..0 (BOD enabled, fast rising power)
# | +------------------ CKOUT (clock output on CKOUT pin -> disabled)
# +-------------------- CKDIV8 (divide clock by 8 -> don't divide)
# ATMega*5 FUSE_H (Fuse high byte):
# 0xdd = 1 1 0 1 1 1 0 1
# ^ ^ ^ ^ ^ \-+-/
# | | | | | +------ BODLEVEL 2..0 (brownout trigger level -> 2.7V)
# | | | | +---------- EESAVE (preserve EEPROM on Chip Erase -> not preserved)
# | | | +-------------- WDTON (watchdog timer always on -> disable)
# | | +---------------- SPIEN (enable serial programming -> enabled)
# | +------------------ DWEN (debug wire enable)
# +-------------------- RSTDISBL (disable external reset -> enabled)
#
################################ ATTiny2313 #################################
# ATTiny2313 FUSE_L (Fuse low byte):
# 0xef = 1 1 1 0 1 1 1 1
# ^ ^ \+/ \--+--/
# | | | +------- CKSEL 3..0 (clock selection -> crystal @ 12 MHz)
# | | +--------------- SUT 1..0 (BOD enabled, fast rising power)
# | +------------------ CKOUT (clock output on CKOUT pin -> disabled)
# +-------------------- CKDIV8 (divide clock by 8 -> don't divide)
# ATTiny2313 FUSE_H (Fuse high byte):
# 0xdb = 1 1 0 1 1 0 1 1
# ^ ^ ^ ^ \-+-/ ^
# | | | | | +---- RSTDISBL (disable external reset -> enabled)
# | | | | +-------- BODLEVEL 2..0 (brownout trigger level -> 2.7V)
# | | | +-------------- WDTON (watchdog timer always on -> disable)
# | | +---------------- SPIEN (enable serial programming -> enabled)
# | +------------------ EESAVE (preserve EEPROM on Chip Erase -> not preserved)
# +-------------------- DWEN (debug wire enable)
# symbolic targets:
help:
@echo "This Makefile has no default rule. Use one of the following:"
@echo "make hex ....... to build main.hex"
@echo "make program ... to flash fuses and firmware"
@echo "make fuse ...... to flash the fuses"
@echo "make flash ..... to flash the firmware (use this on metaboard)"
@echo "make clean ..... to delete objects and hex file"
hex: main.hex
program: flash fuse
# rule for programming fuse bits:
fuse:
@[ "$(FUSE_H)" != "" -a "$(FUSE_L)" != "" ] || \
{ echo "*** Edit Makefile and choose values for FUSE_L and FUSE_H!"; exit 1; }
$(AVRDUDE) -U hfuse:w:$(FUSE_H):m -U lfuse:w:$(FUSE_L):m
# rule for uploading firmware:
flash: main.hex
$(AVRDUDE) -U flash:w:main.hex:i
# rule for deleting dependent files (those which can be built by Make):
clean:
rm -f main.hex main.lst main.obj main.cof main.list main.map main.eep.hex main.elf *.o usbdrv/*.o main.s usbdrv/oddebug.s usbdrv/usbdrv.s
# Generic rule for compiling C files:
.c.o:
$(COMPILE) -c $< -o $@
# Generic rule for assembling Assembler source files:
.S.o:
$(COMPILE) -x assembler-with-cpp -c $< -o $@
# "-x assembler-with-cpp" should not be necessary since this is the default
# file type for the .S (with capital S) extension. However, upper case
# characters are not always preserved on Windows. To ensure WinAVR
# compatibility define the file type manually.
# Generic rule for compiling C to assembler, used for debugging only.
.c.s:
$(COMPILE) -S $< -o $@
# file targets:
# Since we don't want to ship the driver multipe times, we copy it into this project:
usbdrv:
cp -r ../../../usbdrv .
main.elf: usbdrv $(OBJECTS) # usbdrv dependency only needed because we copy it
$(COMPILE) -o main.elf $(OBJECTS)
main.hex: main.elf
rm -f main.hex main.eep.hex
avr-objcopy -j .text -j .data -O ihex main.elf main.hex
avr-size main.hex
# debugging targets:
disasm: main.elf
avr-objdump -d main.elf
cpp:
$(COMPILE) -E main.c

View File

@ -0,0 +1,140 @@
/* Name: main.c
* Project: hid-data, example how to use HID for data transfer
* Author: Christian Starkjohann
* Creation Date: 2008-04-11
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
This example should run on most AVRs with only little changes. No special
hardware resources except INT0 are used. You may have to change usbconfig.h for
different I/O pins for USB. Please note that USB D+ must be the INT0 pin, or
at least be connected to INT0 as well.
*/
#include <avr/io.h>
#include <avr/wdt.h>
#include <avr/interrupt.h> /* for sei() */
#include <util/delay.h> /* for _delay_ms() */
#include <avr/eeprom.h>
#include <avr/pgmspace.h> /* required by usbdrv.h */
#include "usbdrv.h"
#include "oddebug.h" /* This is also an example for using debug macros */
/* ------------------------------------------------------------------------- */
/* ----------------------------- USB interface ----------------------------- */
/* ------------------------------------------------------------------------- */
PROGMEM const char usbHidReportDescriptor[22] = { /* USB report descriptor */
0x06, 0x00, 0xff, // USAGE_PAGE (Generic Desktop)
0x09, 0x01, // USAGE (Vendor Usage 1)
0xa1, 0x01, // COLLECTION (Application)
0x15, 0x00, // LOGICAL_MINIMUM (0)
0x26, 0xff, 0x00, // LOGICAL_MAXIMUM (255)
0x75, 0x08, // REPORT_SIZE (8)
0x95, 0x80, // REPORT_COUNT (128)
0x09, 0x00, // USAGE (Undefined)
0xb2, 0x02, 0x01, // FEATURE (Data,Var,Abs,Buf)
0xc0 // END_COLLECTION
};
/* Since we define only one feature report, we don't use report-IDs (which
* would be the first byte of the report). The entire report consists of 128
* opaque data bytes.
*/
/* The following variables store the status of the current data transfer */
static uchar currentAddress;
static uchar bytesRemaining;
/* ------------------------------------------------------------------------- */
/* usbFunctionRead() is called when the host requests a chunk of data from
* the device. For more information see the documentation in usbdrv/usbdrv.h.
*/
uchar usbFunctionRead(uchar *data, uchar len)
{
if(len > bytesRemaining)
len = bytesRemaining;
eeprom_read_block(data, (uchar *)0 + currentAddress, len);
currentAddress += len;
bytesRemaining -= len;
return len;
}
/* usbFunctionWrite() is called when the host sends a chunk of data to the
* device. For more information see the documentation in usbdrv/usbdrv.h.
*/
uchar usbFunctionWrite(uchar *data, uchar len)
{
if(bytesRemaining == 0)
return 1; /* end of transfer */
if(len > bytesRemaining)
len = bytesRemaining;
eeprom_write_block(data, (uchar *)0 + currentAddress, len);
currentAddress += len;
bytesRemaining -= len;
return bytesRemaining == 0; /* return 1 if this was the last chunk */
}
/* ------------------------------------------------------------------------- */
usbMsgLen_t usbFunctionSetup(uchar data[8])
{
usbRequest_t *rq = (void *)data;
if((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS){ /* HID class request */
if(rq->bRequest == USBRQ_HID_GET_REPORT){ /* wValue: ReportType (highbyte), ReportID (lowbyte) */
/* since we have only one report type, we can ignore the report-ID */
bytesRemaining = 128;
currentAddress = 0;
return USB_NO_MSG; /* use usbFunctionRead() to obtain data */
}else if(rq->bRequest == USBRQ_HID_SET_REPORT){
/* since we have only one report type, we can ignore the report-ID */
bytesRemaining = 128;
currentAddress = 0;
return USB_NO_MSG; /* use usbFunctionWrite() to receive data from host */
}
}else{
/* ignore vendor type requests, we don't use any */
}
return 0;
}
/* ------------------------------------------------------------------------- */
int main(void)
{
uchar i;
wdt_enable(WDTO_1S);
/* Even if you don't use the watchdog, turn it off here. On newer devices,
* the status of the watchdog (on/off, period) is PRESERVED OVER RESET!
*/
/* RESET status: all port bits are inputs without pull-up.
* That's the way we need D+ and D-. Therefore we don't need any
* additional hardware initialization.
*/
odDebugInit();
DBG1(0x00, 0, 0); /* debug output: main starts */
usbInit();
usbDeviceDisconnect(); /* enforce re-enumeration, do this while interrupts are disabled! */
i = 0;
while(--i){ /* fake USB disconnect for > 250 ms */
wdt_reset();
_delay_ms(1);
}
usbDeviceConnect();
sei();
DBG1(0x01, 0, 0); /* debug output: main loop starts */
for(;;){ /* main event loop */
DBG1(0x02, 0, 0); /* debug output: main loop iterates */
wdt_reset();
usbPoll();
}
return 0;
}
/* ------------------------------------------------------------------------- */

View File

@ -0,0 +1,381 @@
/* Name: usbconfig.h
* Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
* Author: Christian Starkjohann
* Creation Date: 2005-04-01
* Tabsize: 4
* Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
#ifndef __usbconfig_h_included__
#define __usbconfig_h_included__
/*
General Description:
This file is an example configuration (with inline documentation) for the USB
driver. It configures V-USB for USB D+ connected to Port D bit 2 (which is
also hardware interrupt 0 on many devices) and USB D- to Port D bit 4. You may
wire the lines to any other port, as long as D+ is also wired to INT0 (or any
other hardware interrupt, as long as it is the highest level interrupt, see
section at the end of this file).
*/
/* ---------------------------- Hardware Config ---------------------------- */
#define USB_CFG_IOPORTNAME D
/* This is the port where the USB bus is connected. When you configure it to
* "B", the registers PORTB, PINB and DDRB will be used.
*/
#define USB_CFG_DMINUS_BIT 4
/* This is the bit number in USB_CFG_IOPORT where the USB D- line is connected.
* This may be any bit in the port.
*/
#define USB_CFG_DPLUS_BIT 2
/* This is the bit number in USB_CFG_IOPORT where the USB D+ line is connected.
* This may be any bit in the port. Please note that D+ must also be connected
* to interrupt pin INT0! [You can also use other interrupts, see section
* "Optional MCU Description" below, or you can connect D- to the interrupt, as
* it is required if you use the USB_COUNT_SOF feature. If you use D- for the
* interrupt, the USB interrupt will also be triggered at Start-Of-Frame
* markers every millisecond.]
*/
#define USB_CFG_CLOCK_KHZ (F_CPU/1000)
/* Clock rate of the AVR in kHz. Legal values are 12000, 12800, 15000, 16000,
* 16500, 18000 and 20000. The 12.8 MHz and 16.5 MHz versions of the code
* require no crystal, they tolerate +/- 1% deviation from the nominal
* frequency. All other rates require a precision of 2000 ppm and thus a
* crystal!
* Since F_CPU should be defined to your actual clock rate anyway, you should
* not need to modify this setting.
*/
#define USB_CFG_CHECK_CRC 0
/* Define this to 1 if you want that the driver checks integrity of incoming
* data packets (CRC checks). CRC checks cost quite a bit of code size and are
* currently only available for 18 MHz crystal clock. You must choose
* USB_CFG_CLOCK_KHZ = 18000 if you enable this option.
*/
/* ----------------------- Optional Hardware Config ------------------------ */
/* #define USB_CFG_PULLUP_IOPORTNAME D */
/* If you connect the 1.5k pullup resistor from D- to a port pin instead of
* V+, you can connect and disconnect the device from firmware by calling
* the macros usbDeviceConnect() and usbDeviceDisconnect() (see usbdrv.h).
* This constant defines the port on which the pullup resistor is connected.
*/
/* #define USB_CFG_PULLUP_BIT 4 */
/* This constant defines the bit number in USB_CFG_PULLUP_IOPORT (defined
* above) where the 1.5k pullup resistor is connected. See description
* above for details.
*/
/* --------------------------- Functional Range ---------------------------- */
#define USB_CFG_HAVE_INTRIN_ENDPOINT 1
/* Define this to 1 if you want to compile a version with two endpoints: The
* default control endpoint 0 and an interrupt-in endpoint (any other endpoint
* number).
*/
#define USB_CFG_HAVE_INTRIN_ENDPOINT3 0
/* Define this to 1 if you want to compile a version with three endpoints: The
* default control endpoint 0, an interrupt-in endpoint 3 (or the number
* configured below) and a catch-all default interrupt-in endpoint as above.
* You must also define USB_CFG_HAVE_INTRIN_ENDPOINT to 1 for this feature.
*/
#define USB_CFG_EP3_NUMBER 3
/* If the so-called endpoint 3 is used, it can now be configured to any other
* endpoint number (except 0) with this macro. Default if undefined is 3.
*/
/* #define USB_INITIAL_DATATOKEN USBPID_DATA1 */
/* The above macro defines the startup condition for data toggling on the
* interrupt/bulk endpoints 1 and 3. Defaults to USBPID_DATA1.
* Since the token is toggled BEFORE sending any data, the first packet is
* sent with the oposite value of this configuration!
*/
#define USB_CFG_IMPLEMENT_HALT 0
/* Define this to 1 if you also want to implement the ENDPOINT_HALT feature
* for endpoint 1 (interrupt endpoint). Although you may not need this feature,
* it is required by the standard. We have made it a config option because it
* bloats the code considerably.
*/
#define USB_CFG_SUPPRESS_INTR_CODE 0
/* Define this to 1 if you want to declare interrupt-in endpoints, but don't
* want to send any data over them. If this macro is defined to 1, functions
* usbSetInterrupt() and usbSetInterrupt3() are omitted. This is useful if
* you need the interrupt-in endpoints in order to comply to an interface
* (e.g. HID), but never want to send any data. This option saves a couple
* of bytes in flash memory and the transmit buffers in RAM.
*/
#define USB_CFG_INTR_POLL_INTERVAL 100
/* If you compile a version with endpoint 1 (interrupt-in), this is the poll
* interval. The value is in milliseconds and must not be less than 10 ms for
* low speed devices.
*/
#define USB_CFG_IS_SELF_POWERED 0
/* Define this to 1 if the device has its own power supply. Set it to 0 if the
* device is powered from the USB bus.
*/
#define USB_CFG_MAX_BUS_POWER 20
/* Set this variable to the maximum USB bus power consumption of your device.
* The value is in milliamperes. [It will be divided by two since USB
* communicates power requirements in units of 2 mA.]
*/
#define USB_CFG_IMPLEMENT_FN_WRITE 1
/* Set this to 1 if you want usbFunctionWrite() to be called for control-out
* transfers. Set it to 0 if you don't need it and want to save a couple of
* bytes.
*/
#define USB_CFG_IMPLEMENT_FN_READ 1
/* Set this to 1 if you need to send control replies which are generated
* "on the fly" when usbFunctionRead() is called. If you only want to send
* data from a static buffer, set it to 0 and return the data from
* usbFunctionSetup(). This saves a couple of bytes.
*/
#define USB_CFG_IMPLEMENT_FN_WRITEOUT 0
/* Define this to 1 if you want to use interrupt-out (or bulk out) endpoints.
* You must implement the function usbFunctionWriteOut() which receives all
* interrupt/bulk data sent to any endpoint other than 0. The endpoint number
* can be found in 'usbRxToken'.
*/
#define USB_CFG_HAVE_FLOWCONTROL 0
/* Define this to 1 if you want flowcontrol over USB data. See the definition
* of the macros usbDisableAllRequests() and usbEnableAllRequests() in
* usbdrv.h.
*/
#define USB_CFG_DRIVER_FLASH_PAGE 0
/* If the device has more than 64 kBytes of flash, define this to the 64 k page
* where the driver's constants (descriptors) are located. Or in other words:
* Define this to 1 for boot loaders on the ATMega128.
*/
#define USB_CFG_LONG_TRANSFERS 0
/* Define this to 1 if you want to send/receive blocks of more than 254 bytes
* in a single control-in or control-out transfer. Note that the capability
* for long transfers increases the driver size.
*/
/* #define USB_RX_USER_HOOK(data, len) if(usbRxToken == (uchar)USBPID_SETUP) blinkLED(); */
/* This macro is a hook if you want to do unconventional things. If it is
* defined, it's inserted at the beginning of received message processing.
* If you eat the received message and don't want default processing to
* proceed, do a return after doing your things. One possible application
* (besides debugging) is to flash a status LED on each packet.
*/
/* #define USB_RESET_HOOK(resetStarts) if(!resetStarts){hadUsbReset();} */
/* This macro is a hook if you need to know when an USB RESET occurs. It has
* one parameter which distinguishes between the start of RESET state and its
* end.
*/
/* #define USB_SET_ADDRESS_HOOK() hadAddressAssigned(); */
/* This macro (if defined) is executed when a USB SET_ADDRESS request was
* received.
*/
#define USB_COUNT_SOF 0
/* define this macro to 1 if you need the global variable "usbSofCount" which
* counts SOF packets. This feature requires that the hardware interrupt is
* connected to D- instead of D+.
*/
/* #ifdef __ASSEMBLER__
* macro myAssemblerMacro
* in YL, TCNT0
* sts timer0Snapshot, YL
* endm
* #endif
* #define USB_SOF_HOOK myAssemblerMacro
* This macro (if defined) is executed in the assembler module when a
* Start Of Frame condition is detected. It is recommended to define it to
* the name of an assembler macro which is defined here as well so that more
* than one assembler instruction can be used. The macro may use the register
* YL and modify SREG. If it lasts longer than a couple of cycles, USB messages
* immediately after an SOF pulse may be lost and must be retried by the host.
* What can you do with this hook? Since the SOF signal occurs exactly every
* 1 ms (unless the host is in sleep mode), you can use it to tune OSCCAL in
* designs running on the internal RC oscillator.
* Please note that Start Of Frame detection works only if D- is wired to the
* interrupt, not D+. THIS IS DIFFERENT THAN MOST EXAMPLES!
*/
#define USB_CFG_CHECK_DATA_TOGGLING 0
/* define this macro to 1 if you want to filter out duplicate data packets
* sent by the host. Duplicates occur only as a consequence of communication
* errors, when the host does not receive an ACK. Please note that you need to
* implement the filtering yourself in usbFunctionWriteOut() and
* usbFunctionWrite(). Use the global usbCurrentDataToken and a static variable
* for each control- and out-endpoint to check for duplicate packets.
*/
#define USB_CFG_HAVE_MEASURE_FRAME_LENGTH 0
/* define this macro to 1 if you want the function usbMeasureFrameLength()
* compiled in. This function can be used to calibrate the AVR's RC oscillator.
*/
#define USB_USE_FAST_CRC 0
/* The assembler module has two implementations for the CRC algorithm. One is
* faster, the other is smaller. This CRC routine is only used for transmitted
* messages where timing is not critical. The faster routine needs 31 cycles
* per byte while the smaller one needs 61 to 69 cycles. The faster routine
* may be worth the 32 bytes bigger code size if you transmit lots of data and
* run the AVR close to its limit.
*/
/* -------------------------- Device Description --------------------------- */
#define USB_CFG_VENDOR_ID 0xc0, 0x16 /* = 0x16c0 = 5824 = voti.nl */
/* USB vendor ID for the device, low byte first. If you have registered your
* own Vendor ID, define it here. Otherwise you may use one of obdev's free
* shared VID/PID pairs. Be sure to read USB-IDs-for-free.txt for rules!
* *** IMPORTANT NOTE ***
* This template uses obdev's shared VID/PID pair for Vendor Class devices
* with libusb: 0x16c0/0x5dc. Use this VID/PID pair ONLY if you understand
* the implications!
*/
#define USB_CFG_DEVICE_ID 0xdf, 0x05 /* obdev's shared PID for HIDs */
/* This is the ID of the product, low byte first. It is interpreted in the
* scope of the vendor ID. If you have registered your own VID with usb.org
* or if you have licensed a PID from somebody else, define it here. Otherwise
* you may use one of obdev's free shared VID/PID pairs. See the file
* USB-IDs-for-free.txt for details!
* *** IMPORTANT NOTE ***
* This template uses obdev's shared VID/PID pair for Vendor Class devices
* with libusb: 0x16c0/0x5dc. Use this VID/PID pair ONLY if you understand
* the implications!
*/
#define USB_CFG_DEVICE_VERSION 0x00, 0x01
/* Version number of the device: Minor number first, then major number.
*/
#define USB_CFG_VENDOR_NAME 'o', 'b', 'd', 'e', 'v', '.', 'a', 't'
#define USB_CFG_VENDOR_NAME_LEN 8
/* These two values define the vendor name returned by the USB device. The name
* must be given as a list of characters under single quotes. The characters
* are interpreted as Unicode (UTF-16) entities.
* If you don't want a vendor name string, undefine these macros.
* ALWAYS define a vendor name containing your Internet domain name if you use
* obdev's free shared VID/PID pair. See the file USB-IDs-for-free.txt for
* details.
*/
#define USB_CFG_DEVICE_NAME 'D', 'a', 't', 'a', 'S', 't', 'o', 'r', 'e'
#define USB_CFG_DEVICE_NAME_LEN 9
/* Same as above for the device name. If you don't want a device name, undefine
* the macros. See the file USB-IDs-for-free.txt before you assign a name if
* you use a shared VID/PID.
*/
/*#define USB_CFG_SERIAL_NUMBER 'N', 'o', 'n', 'e' */
/*#define USB_CFG_SERIAL_NUMBER_LEN 0 */
/* Same as above for the serial number. If you don't want a serial number,
* undefine the macros.
* It may be useful to provide the serial number through other means than at
* compile time. See the section about descriptor properties below for how
* to fine tune control over USB descriptors such as the string descriptor
* for the serial number.
*/
#define USB_CFG_DEVICE_CLASS 0
#define USB_CFG_DEVICE_SUBCLASS 0
/* See USB specification if you want to conform to an existing device class.
* Class 0xff is "vendor specific".
*/
#define USB_CFG_INTERFACE_CLASS 3
#define USB_CFG_INTERFACE_SUBCLASS 0
#define USB_CFG_INTERFACE_PROTOCOL 0
/* See USB specification if you want to conform to an existing device class or
* protocol. The following classes must be set at interface level:
* HID class is 3, no subclass and protocol required (but may be useful!)
* CDC class is 2, use subclass 2 and protocol 1 for ACM
*/
#define USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH 22
/* Define this to the length of the HID report descriptor, if you implement
* an HID device. Otherwise don't define it or define it to 0.
* If you use this define, you must add a PROGMEM character array named
* "usbHidReportDescriptor" to your code which contains the report descriptor.
* Don't forget to keep the array and this define in sync!
*/
/* #define USB_PUBLIC static */
/* Use the define above if you #include usbdrv.c instead of linking against it.
* This technique saves a couple of bytes in flash memory.
*/
/* ------------------- Fine Control over USB Descriptors ------------------- */
/* If you don't want to use the driver's default USB descriptors, you can
* provide our own. These can be provided as (1) fixed length static data in
* flash memory, (2) fixed length static data in RAM or (3) dynamically at
* runtime in the function usbFunctionDescriptor(). See usbdrv.h for more
* information about this function.
* Descriptor handling is configured through the descriptor's properties. If
* no properties are defined or if they are 0, the default descriptor is used.
* Possible properties are:
* + USB_PROP_IS_DYNAMIC: The data for the descriptor should be fetched
* at runtime via usbFunctionDescriptor(). If the usbMsgPtr mechanism is
* used, the data is in FLASH by default. Add property USB_PROP_IS_RAM if
* you want RAM pointers.
* + USB_PROP_IS_RAM: The data returned by usbFunctionDescriptor() or found
* in static memory is in RAM, not in flash memory.
* + USB_PROP_LENGTH(len): If the data is in static memory (RAM or flash),
* the driver must know the descriptor's length. The descriptor itself is
* found at the address of a well known identifier (see below).
* List of static descriptor names (must be declared PROGMEM if in flash):
* char usbDescriptorDevice[];
* char usbDescriptorConfiguration[];
* char usbDescriptorHidReport[];
* char usbDescriptorString0[];
* int usbDescriptorStringVendor[];
* int usbDescriptorStringDevice[];
* int usbDescriptorStringSerialNumber[];
* Other descriptors can't be provided statically, they must be provided
* dynamically at runtime.
*
* Descriptor properties are or-ed or added together, e.g.:
* #define USB_CFG_DESCR_PROPS_DEVICE (USB_PROP_IS_RAM | USB_PROP_LENGTH(18))
*
* The following descriptors are defined:
* USB_CFG_DESCR_PROPS_DEVICE
* USB_CFG_DESCR_PROPS_CONFIGURATION
* USB_CFG_DESCR_PROPS_STRINGS
* USB_CFG_DESCR_PROPS_STRING_0
* USB_CFG_DESCR_PROPS_STRING_VENDOR
* USB_CFG_DESCR_PROPS_STRING_PRODUCT
* USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
* USB_CFG_DESCR_PROPS_HID
* USB_CFG_DESCR_PROPS_HID_REPORT
* USB_CFG_DESCR_PROPS_UNKNOWN (for all descriptors not handled by the driver)
*
* Note about string descriptors: String descriptors are not just strings, they
* are Unicode strings prefixed with a 2 byte header. Example:
* int serialNumberDescriptor[] = {
* USB_STRING_DESCRIPTOR_HEADER(6),
* 'S', 'e', 'r', 'i', 'a', 'l'
* };
*/
#define USB_CFG_DESCR_PROPS_DEVICE 0
#define USB_CFG_DESCR_PROPS_CONFIGURATION 0
#define USB_CFG_DESCR_PROPS_STRINGS 0
#define USB_CFG_DESCR_PROPS_STRING_0 0
#define USB_CFG_DESCR_PROPS_STRING_VENDOR 0
#define USB_CFG_DESCR_PROPS_STRING_PRODUCT 0
#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER 0
#define USB_CFG_DESCR_PROPS_HID 0
#define USB_CFG_DESCR_PROPS_HID_REPORT 0
#define USB_CFG_DESCR_PROPS_UNKNOWN 0
#define usbMsgPtr_t unsigned short
/* If usbMsgPtr_t is not defined, it defaults to 'uchar *'. We define it to
* a scalar type here because gcc generates slightly shorter code for scalar
* arithmetics than for pointer arithmetics. Remove this define for backward
* type compatibility or define it to an 8 bit type if you use data in RAM only
* and all RAM is below 256 bytes (tiny memory model in IAR CC).
*/
/* ----------------------- Optional MCU Description ------------------------ */
/* The following configurations have working defaults in usbdrv.h. You
* usually don't need to set them explicitly. Only if you want to run
* the driver on a device which is not yet supported or with a compiler
* which is not fully supported (such as IAR C) or if you use a differnt
* interrupt than INT0, you may have to define some of these.
*/
/* #define USB_INTR_CFG MCUCR */
/* #define USB_INTR_CFG_SET ((1 << ISC00) | (1 << ISC01)) */
/* #define USB_INTR_CFG_CLR 0 */
/* #define USB_INTR_ENABLE GIMSK */
/* #define USB_INTR_ENABLE_BIT INT0 */
/* #define USB_INTR_PENDING GIFR */
/* #define USB_INTR_PENDING_BIT INTF0 */
/* #define USB_INTR_VECTOR INT0_vect */
#endif /* __usbconfig_h_included__ */

View File

@ -0,0 +1,48 @@
This is the Readme file for hid-mouse, an example of a USB mouse device. In
order to have as little dependencies on hardware and architecture as
possible, mouse movements are computed internally so that the mouse pointer
moves in a circle.
WHAT IS DEMONSTRATED?
=====================
This example demonstrates how HID class devices are implemented. The example
is kept as simple as possible, except the report descriptor which is taken
from a real-world mouse.
It does NOT include a host side driver because all modern operating systems
include one. It does NOT implement USBRQ_HID_SET_REPORT and report-IDs. See
the "hid-data" example for this topic. It does NOT implement any special
features such as suspend mode etc.
PREREQUISITES
=============
Target hardware: You need an AVR based circuit based on one of the examples
(see the "circuits" directory at the top level of this package), e.g. the
metaboard (http://www.obdev.at/goto.php?t=metaboard).
AVR development environment: You need the gcc tool chain for the AVR, see
the Prerequisites section in the top level Readme file for how to obtain it.
BUILDING THE FIRMWARE
=====================
Change to the "firmware" directory and modify Makefile according to your
architecture (CPU clock, target device, fuse values) and ISP programmer. Then
edit usbconfig.h according to your pin assignments for D+ and D-. The default
settings are for the metaboard hardware.
Type "make hex" to build main.hex, then "make flash" to upload the firmware
to the device. Don't forget to run "make fuse" once to program the fuses. If
you use a prototyping board with boot loader, follow the instructions of the
boot loader instead.
Please note that the first "make hex" copies the driver from the top level
into the firmware directory. If you use a different build system than our
Makefile, you must copy the driver by hand.
----------------------------------------------------------------------------
(c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH.
http://www.obdev.at/

View File

@ -0,0 +1,163 @@
# Name: Makefile
# Project: hid-mouse example
# Author: Christian Starkjohann
# Creation Date: 2008-04-07
# Tabsize: 4
# Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
DEVICE = atmega168
F_CPU = 16000000 # in Hz
FUSE_L = # see below for fuse values for particular devices
FUSE_H =
AVRDUDE = avrdude -c usbasp -p $(DEVICE) # edit this line for your programmer
CFLAGS = -Iusbdrv -I. -DDEBUG_LEVEL=0
OBJECTS = usbdrv/usbdrv.o usbdrv/usbdrvasm.o usbdrv/oddebug.o main.o
COMPILE = avr-gcc -Wall -Os -DF_CPU=$(F_CPU) $(CFLAGS) -mmcu=$(DEVICE)
##############################################################################
# Fuse values for particular devices
##############################################################################
# If your device is not listed here, go to
# http://palmavr.sourceforge.net/cgi-bin/fc.cgi
# and choose options for external crystal clock and no clock divider
#
################################## ATMega8 ##################################
# ATMega8 FUSE_L (Fuse low byte):
# 0x9f = 1 0 0 1 1 1 1 1
# ^ ^ \ / \--+--/
# | | | +------- CKSEL 3..0 (external >8M crystal)
# | | +--------------- SUT 1..0 (crystal osc, BOD enabled)
# | +------------------ BODEN (BrownOut Detector enabled)
# +-------------------- BODLEVEL (2.7V)
# ATMega8 FUSE_H (Fuse high byte):
# 0xc9 = 1 1 0 0 1 0 0 1 <-- BOOTRST (boot reset vector at 0x0000)
# ^ ^ ^ ^ ^ ^ ^------ BOOTSZ0
# | | | | | +-------- BOOTSZ1
# | | | | + --------- EESAVE (don't preserve EEPROM over chip erase)
# | | | +-------------- CKOPT (full output swing)
# | | +---------------- SPIEN (allow serial programming)
# | +------------------ WDTON (WDT not always on)
# +-------------------- RSTDISBL (reset pin is enabled)
#
############################## ATMega48/88/168 ##############################
# ATMega*8 FUSE_L (Fuse low byte):
# 0xdf = 1 1 0 1 1 1 1 1
# ^ ^ \ / \--+--/
# | | | +------- CKSEL 3..0 (external >8M crystal)
# | | +--------------- SUT 1..0 (crystal osc, BOD enabled)
# | +------------------ CKOUT (if 0: Clock output enabled)
# +-------------------- CKDIV8 (if 0: divide by 8)
# ATMega*8 FUSE_H (Fuse high byte):
# 0xde = 1 1 0 1 1 1 1 0
# ^ ^ ^ ^ ^ \-+-/
# | | | | | +------ BODLEVEL 0..2 (110 = 1.8 V)
# | | | | + --------- EESAVE (preserve EEPROM over chip erase)
# | | | +-------------- WDTON (if 0: watchdog always on)
# | | +---------------- SPIEN (allow serial programming)
# | +------------------ DWEN (debug wire enable)
# +-------------------- RSTDISBL (reset pin is enabled)
#
############################## ATTiny25/45/85 ###############################
# ATMega*5 FUSE_L (Fuse low byte):
# 0xef = 1 1 1 0 1 1 1 1
# ^ ^ \+/ \--+--/
# | | | +------- CKSEL 3..0 (clock selection -> crystal @ 12 MHz)
# | | +--------------- SUT 1..0 (BOD enabled, fast rising power)
# | +------------------ CKOUT (clock output on CKOUT pin -> disabled)
# +-------------------- CKDIV8 (divide clock by 8 -> don't divide)
# ATMega*5 FUSE_H (Fuse high byte):
# 0xdd = 1 1 0 1 1 1 0 1
# ^ ^ ^ ^ ^ \-+-/
# | | | | | +------ BODLEVEL 2..0 (brownout trigger level -> 2.7V)
# | | | | +---------- EESAVE (preserve EEPROM on Chip Erase -> not preserved)
# | | | +-------------- WDTON (watchdog timer always on -> disable)
# | | +---------------- SPIEN (enable serial programming -> enabled)
# | +------------------ DWEN (debug wire enable)
# +-------------------- RSTDISBL (disable external reset -> enabled)
#
################################ ATTiny2313 #################################
# ATTiny2313 FUSE_L (Fuse low byte):
# 0xef = 1 1 1 0 1 1 1 1
# ^ ^ \+/ \--+--/
# | | | +------- CKSEL 3..0 (clock selection -> crystal @ 12 MHz)
# | | +--------------- SUT 1..0 (BOD enabled, fast rising power)
# | +------------------ CKOUT (clock output on CKOUT pin -> disabled)
# +-------------------- CKDIV8 (divide clock by 8 -> don't divide)
# ATTiny2313 FUSE_H (Fuse high byte):
# 0xdb = 1 1 0 1 1 0 1 1
# ^ ^ ^ ^ \-+-/ ^
# | | | | | +---- RSTDISBL (disable external reset -> enabled)
# | | | | +-------- BODLEVEL 2..0 (brownout trigger level -> 2.7V)
# | | | +-------------- WDTON (watchdog timer always on -> disable)
# | | +---------------- SPIEN (enable serial programming -> enabled)
# | +------------------ EESAVE (preserve EEPROM on Chip Erase -> not preserved)
# +-------------------- DWEN (debug wire enable)
# symbolic targets:
help:
@echo "This Makefile has no default rule. Use one of the following:"
@echo "make hex ....... to build main.hex"
@echo "make program ... to flash fuses and firmware"
@echo "make fuse ...... to flash the fuses"
@echo "make flash ..... to flash the firmware (use this on metaboard)"
@echo "make clean ..... to delete objects and hex file"
hex: main.hex
program: flash fuse
# rule for programming fuse bits:
fuse:
@[ "$(FUSE_H)" != "" -a "$(FUSE_L)" != "" ] || \
{ echo "*** Edit Makefile and choose values for FUSE_L and FUSE_H!"; exit 1; }
$(AVRDUDE) -U hfuse:w:$(FUSE_H):m -U lfuse:w:$(FUSE_L):m
# rule for uploading firmware:
flash: main.hex
$(AVRDUDE) -U flash:w:main.hex:i
# rule for deleting dependent files (those which can be built by Make):
clean:
rm -f main.hex main.lst main.obj main.cof main.list main.map main.eep.hex main.elf *.o usbdrv/*.o main.s usbdrv/oddebug.s usbdrv/usbdrv.s
# Generic rule for compiling C files:
.c.o:
$(COMPILE) -c $< -o $@
# Generic rule for assembling Assembler source files:
.S.o:
$(COMPILE) -x assembler-with-cpp -c $< -o $@
# "-x assembler-with-cpp" should not be necessary since this is the default
# file type for the .S (with capital S) extension. However, upper case
# characters are not always preserved on Windows. To ensure WinAVR
# compatibility define the file type manually.
# Generic rule for compiling C to assembler, used for debugging only.
.c.s:
$(COMPILE) -S $< -o $@
# file targets:
# Since we don't want to ship the driver multipe times, we copy it into this project:
usbdrv:
cp -r ../../../usbdrv .
main.elf: usbdrv $(OBJECTS) # usbdrv dependency only needed because we copy it
$(COMPILE) -o main.elf $(OBJECTS)
main.hex: main.elf
rm -f main.hex main.eep.hex
avr-objcopy -j .text -j .data -O ihex main.elf main.hex
avr-size main.hex
# debugging targets:
disasm: main.elf
avr-objdump -d main.elf
cpp:
$(COMPILE) -E main.c

View File

@ -0,0 +1,163 @@
/* Name: main.c
* Project: hid-mouse, a very simple HID example
* Author: Christian Starkjohann
* Creation Date: 2008-04-07
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
This example should run on most AVRs with only little changes. No special
hardware resources except INT0 are used. You may have to change usbconfig.h for
different I/O pins for USB. Please note that USB D+ must be the INT0 pin, or
at least be connected to INT0 as well.
We use VID/PID 0x046D/0xC00E which is taken from a Logitech mouse. Don't
publish any hardware using these IDs! This is for demonstration only!
*/
#include <avr/io.h>
#include <avr/wdt.h>
#include <avr/interrupt.h> /* for sei() */
#include <util/delay.h> /* for _delay_ms() */
#include <avr/pgmspace.h> /* required by usbdrv.h */
#include "usbdrv.h"
#include "oddebug.h" /* This is also an example for using debug macros */
/* ------------------------------------------------------------------------- */
/* ----------------------------- USB interface ----------------------------- */
/* ------------------------------------------------------------------------- */
PROGMEM const char usbHidReportDescriptor[52] = { /* USB report descriptor, size must match usbconfig.h */
0x05, 0x01, // USAGE_PAGE (Generic Desktop)
0x09, 0x02, // USAGE (Mouse)
0xa1, 0x01, // COLLECTION (Application)
0x09, 0x01, // USAGE (Pointer)
0xA1, 0x00, // COLLECTION (Physical)
0x05, 0x09, // USAGE_PAGE (Button)
0x19, 0x01, // USAGE_MINIMUM
0x29, 0x03, // USAGE_MAXIMUM
0x15, 0x00, // LOGICAL_MINIMUM (0)
0x25, 0x01, // LOGICAL_MAXIMUM (1)
0x95, 0x03, // REPORT_COUNT (3)
0x75, 0x01, // REPORT_SIZE (1)
0x81, 0x02, // INPUT (Data,Var,Abs)
0x95, 0x01, // REPORT_COUNT (1)
0x75, 0x05, // REPORT_SIZE (5)
0x81, 0x03, // INPUT (Const,Var,Abs)
0x05, 0x01, // USAGE_PAGE (Generic Desktop)
0x09, 0x30, // USAGE (X)
0x09, 0x31, // USAGE (Y)
0x09, 0x38, // USAGE (Wheel)
0x15, 0x81, // LOGICAL_MINIMUM (-127)
0x25, 0x7F, // LOGICAL_MAXIMUM (127)
0x75, 0x08, // REPORT_SIZE (8)
0x95, 0x03, // REPORT_COUNT (3)
0x81, 0x06, // INPUT (Data,Var,Rel)
0xC0, // END_COLLECTION
0xC0, // END COLLECTION
};
/* This is the same report descriptor as seen in a Logitech mouse. The data
* described by this descriptor consists of 4 bytes:
* . . . . . B2 B1 B0 .... one byte with mouse button states
* X7 X6 X5 X4 X3 X2 X1 X0 .... 8 bit signed relative coordinate x
* Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 .... 8 bit signed relative coordinate y
* W7 W6 W5 W4 W3 W2 W1 W0 .... 8 bit signed relative coordinate wheel
*/
typedef struct{
uchar buttonMask;
char dx;
char dy;
char dWheel;
}report_t;
static report_t reportBuffer;
static int sinus = 7 << 6, cosinus = 0;
static uchar idleRate; /* repeat rate for keyboards, never used for mice */
/* The following function advances sin/cos by a fixed angle
* and stores the difference to the previous coordinates in the report
* descriptor.
* The algorithm is the simulation of a second order differential equation.
*/
static void advanceCircleByFixedAngle(void)
{
char d;
#define DIVIDE_BY_64(val) (val + (val > 0 ? 32 : -32)) >> 6 /* rounding divide */
reportBuffer.dx = d = DIVIDE_BY_64(cosinus);
sinus += d;
reportBuffer.dy = d = DIVIDE_BY_64(sinus);
cosinus -= d;
}
/* ------------------------------------------------------------------------- */
usbMsgLen_t usbFunctionSetup(uchar data[8])
{
usbRequest_t *rq = (void *)data;
/* The following requests are never used. But since they are required by
* the specification, we implement them in this example.
*/
if((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS){ /* class request type */
DBG1(0x50, &rq->bRequest, 1); /* debug output: print our request */
if(rq->bRequest == USBRQ_HID_GET_REPORT){ /* wValue: ReportType (highbyte), ReportID (lowbyte) */
/* we only have one report type, so don't look at wValue */
usbMsgPtr = (void *)&reportBuffer;
return sizeof(reportBuffer);
}else if(rq->bRequest == USBRQ_HID_GET_IDLE){
usbMsgPtr = &idleRate;
return 1;
}else if(rq->bRequest == USBRQ_HID_SET_IDLE){
idleRate = rq->wValue.bytes[1];
}
}else{
/* no vendor specific requests implemented */
}
return 0; /* default for not implemented requests: return no data back to host */
}
/* ------------------------------------------------------------------------- */
int __attribute__((noreturn)) main(void)
{
uchar i;
wdt_enable(WDTO_1S);
/* Even if you don't use the watchdog, turn it off here. On newer devices,
* the status of the watchdog (on/off, period) is PRESERVED OVER RESET!
*/
/* RESET status: all port bits are inputs without pull-up.
* That's the way we need D+ and D-. Therefore we don't need any
* additional hardware initialization.
*/
odDebugInit();
DBG1(0x00, 0, 0); /* debug output: main starts */
usbInit();
usbDeviceDisconnect(); /* enforce re-enumeration, do this while interrupts are disabled! */
i = 0;
while(--i){ /* fake USB disconnect for > 250 ms */
wdt_reset();
_delay_ms(1);
}
usbDeviceConnect();
sei();
DBG1(0x01, 0, 0); /* debug output: main loop starts */
for(;;){ /* main event loop */
DBG1(0x02, 0, 0); /* debug output: main loop iterates */
wdt_reset();
usbPoll();
if(usbInterruptIsReady()){
/* called after every poll of the interrupt endpoint */
advanceCircleByFixedAngle();
DBG1(0x03, 0, 0); /* debug output: interrupt report prepared */
usbSetInterrupt((void *)&reportBuffer, sizeof(reportBuffer));
}
}
}
/* ------------------------------------------------------------------------- */

View File

@ -0,0 +1,381 @@
/* Name: usbconfig.h
* Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
* Author: Christian Starkjohann
* Creation Date: 2005-04-01
* Tabsize: 4
* Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
#ifndef __usbconfig_h_included__
#define __usbconfig_h_included__
/*
General Description:
This file is an example configuration (with inline documentation) for the USB
driver. It configures V-USB for USB D+ connected to Port D bit 2 (which is
also hardware interrupt 0 on many devices) and USB D- to Port D bit 4. You may
wire the lines to any other port, as long as D+ is also wired to INT0 (or any
other hardware interrupt, as long as it is the highest level interrupt, see
section at the end of this file).
*/
/* ---------------------------- Hardware Config ---------------------------- */
#define USB_CFG_IOPORTNAME D
/* This is the port where the USB bus is connected. When you configure it to
* "B", the registers PORTB, PINB and DDRB will be used.
*/
#define USB_CFG_DMINUS_BIT 4
/* This is the bit number in USB_CFG_IOPORT where the USB D- line is connected.
* This may be any bit in the port.
*/
#define USB_CFG_DPLUS_BIT 2
/* This is the bit number in USB_CFG_IOPORT where the USB D+ line is connected.
* This may be any bit in the port. Please note that D+ must also be connected
* to interrupt pin INT0! [You can also use other interrupts, see section
* "Optional MCU Description" below, or you can connect D- to the interrupt, as
* it is required if you use the USB_COUNT_SOF feature. If you use D- for the
* interrupt, the USB interrupt will also be triggered at Start-Of-Frame
* markers every millisecond.]
*/
#define USB_CFG_CLOCK_KHZ (F_CPU/1000)
/* Clock rate of the AVR in kHz. Legal values are 12000, 12800, 15000, 16000,
* 16500, 18000 and 20000. The 12.8 MHz and 16.5 MHz versions of the code
* require no crystal, they tolerate +/- 1% deviation from the nominal
* frequency. All other rates require a precision of 2000 ppm and thus a
* crystal!
* Since F_CPU should be defined to your actual clock rate anyway, you should
* not need to modify this setting.
*/
#define USB_CFG_CHECK_CRC 0
/* Define this to 1 if you want that the driver checks integrity of incoming
* data packets (CRC checks). CRC checks cost quite a bit of code size and are
* currently only available for 18 MHz crystal clock. You must choose
* USB_CFG_CLOCK_KHZ = 18000 if you enable this option.
*/
/* ----------------------- Optional Hardware Config ------------------------ */
/* #define USB_CFG_PULLUP_IOPORTNAME D */
/* If you connect the 1.5k pullup resistor from D- to a port pin instead of
* V+, you can connect and disconnect the device from firmware by calling
* the macros usbDeviceConnect() and usbDeviceDisconnect() (see usbdrv.h).
* This constant defines the port on which the pullup resistor is connected.
*/
/* #define USB_CFG_PULLUP_BIT 4 */
/* This constant defines the bit number in USB_CFG_PULLUP_IOPORT (defined
* above) where the 1.5k pullup resistor is connected. See description
* above for details.
*/
/* --------------------------- Functional Range ---------------------------- */
#define USB_CFG_HAVE_INTRIN_ENDPOINT 1
/* Define this to 1 if you want to compile a version with two endpoints: The
* default control endpoint 0 and an interrupt-in endpoint (any other endpoint
* number).
*/
#define USB_CFG_HAVE_INTRIN_ENDPOINT3 0
/* Define this to 1 if you want to compile a version with three endpoints: The
* default control endpoint 0, an interrupt-in endpoint 3 (or the number
* configured below) and a catch-all default interrupt-in endpoint as above.
* You must also define USB_CFG_HAVE_INTRIN_ENDPOINT to 1 for this feature.
*/
#define USB_CFG_EP3_NUMBER 3
/* If the so-called endpoint 3 is used, it can now be configured to any other
* endpoint number (except 0) with this macro. Default if undefined is 3.
*/
/* #define USB_INITIAL_DATATOKEN USBPID_DATA1 */
/* The above macro defines the startup condition for data toggling on the
* interrupt/bulk endpoints 1 and 3. Defaults to USBPID_DATA1.
* Since the token is toggled BEFORE sending any data, the first packet is
* sent with the oposite value of this configuration!
*/
#define USB_CFG_IMPLEMENT_HALT 0
/* Define this to 1 if you also want to implement the ENDPOINT_HALT feature
* for endpoint 1 (interrupt endpoint). Although you may not need this feature,
* it is required by the standard. We have made it a config option because it
* bloats the code considerably.
*/
#define USB_CFG_SUPPRESS_INTR_CODE 0
/* Define this to 1 if you want to declare interrupt-in endpoints, but don't
* want to send any data over them. If this macro is defined to 1, functions
* usbSetInterrupt() and usbSetInterrupt3() are omitted. This is useful if
* you need the interrupt-in endpoints in order to comply to an interface
* (e.g. HID), but never want to send any data. This option saves a couple
* of bytes in flash memory and the transmit buffers in RAM.
*/
#define USB_CFG_INTR_POLL_INTERVAL 100
/* If you compile a version with endpoint 1 (interrupt-in), this is the poll
* interval. The value is in milliseconds and must not be less than 10 ms for
* low speed devices.
*/
#define USB_CFG_IS_SELF_POWERED 0
/* Define this to 1 if the device has its own power supply. Set it to 0 if the
* device is powered from the USB bus.
*/
#define USB_CFG_MAX_BUS_POWER 20
/* Set this variable to the maximum USB bus power consumption of your device.
* The value is in milliamperes. [It will be divided by two since USB
* communicates power requirements in units of 2 mA.]
*/
#define USB_CFG_IMPLEMENT_FN_WRITE 0
/* Set this to 1 if you want usbFunctionWrite() to be called for control-out
* transfers. Set it to 0 if you don't need it and want to save a couple of
* bytes.
*/
#define USB_CFG_IMPLEMENT_FN_READ 0
/* Set this to 1 if you need to send control replies which are generated
* "on the fly" when usbFunctionRead() is called. If you only want to send
* data from a static buffer, set it to 0 and return the data from
* usbFunctionSetup(). This saves a couple of bytes.
*/
#define USB_CFG_IMPLEMENT_FN_WRITEOUT 0
/* Define this to 1 if you want to use interrupt-out (or bulk out) endpoints.
* You must implement the function usbFunctionWriteOut() which receives all
* interrupt/bulk data sent to any endpoint other than 0. The endpoint number
* can be found in 'usbRxToken'.
*/
#define USB_CFG_HAVE_FLOWCONTROL 0
/* Define this to 1 if you want flowcontrol over USB data. See the definition
* of the macros usbDisableAllRequests() and usbEnableAllRequests() in
* usbdrv.h.
*/
#define USB_CFG_DRIVER_FLASH_PAGE 0
/* If the device has more than 64 kBytes of flash, define this to the 64 k page
* where the driver's constants (descriptors) are located. Or in other words:
* Define this to 1 for boot loaders on the ATMega128.
*/
#define USB_CFG_LONG_TRANSFERS 0
/* Define this to 1 if you want to send/receive blocks of more than 254 bytes
* in a single control-in or control-out transfer. Note that the capability
* for long transfers increases the driver size.
*/
/* #define USB_RX_USER_HOOK(data, len) if(usbRxToken == (uchar)USBPID_SETUP) blinkLED(); */
/* This macro is a hook if you want to do unconventional things. If it is
* defined, it's inserted at the beginning of received message processing.
* If you eat the received message and don't want default processing to
* proceed, do a return after doing your things. One possible application
* (besides debugging) is to flash a status LED on each packet.
*/
/* #define USB_RESET_HOOK(resetStarts) if(!resetStarts){hadUsbReset();} */
/* This macro is a hook if you need to know when an USB RESET occurs. It has
* one parameter which distinguishes between the start of RESET state and its
* end.
*/
/* #define USB_SET_ADDRESS_HOOK() hadAddressAssigned(); */
/* This macro (if defined) is executed when a USB SET_ADDRESS request was
* received.
*/
#define USB_COUNT_SOF 0
/* define this macro to 1 if you need the global variable "usbSofCount" which
* counts SOF packets. This feature requires that the hardware interrupt is
* connected to D- instead of D+.
*/
/* #ifdef __ASSEMBLER__
* macro myAssemblerMacro
* in YL, TCNT0
* sts timer0Snapshot, YL
* endm
* #endif
* #define USB_SOF_HOOK myAssemblerMacro
* This macro (if defined) is executed in the assembler module when a
* Start Of Frame condition is detected. It is recommended to define it to
* the name of an assembler macro which is defined here as well so that more
* than one assembler instruction can be used. The macro may use the register
* YL and modify SREG. If it lasts longer than a couple of cycles, USB messages
* immediately after an SOF pulse may be lost and must be retried by the host.
* What can you do with this hook? Since the SOF signal occurs exactly every
* 1 ms (unless the host is in sleep mode), you can use it to tune OSCCAL in
* designs running on the internal RC oscillator.
* Please note that Start Of Frame detection works only if D- is wired to the
* interrupt, not D+. THIS IS DIFFERENT THAN MOST EXAMPLES!
*/
#define USB_CFG_CHECK_DATA_TOGGLING 0
/* define this macro to 1 if you want to filter out duplicate data packets
* sent by the host. Duplicates occur only as a consequence of communication
* errors, when the host does not receive an ACK. Please note that you need to
* implement the filtering yourself in usbFunctionWriteOut() and
* usbFunctionWrite(). Use the global usbCurrentDataToken and a static variable
* for each control- and out-endpoint to check for duplicate packets.
*/
#define USB_CFG_HAVE_MEASURE_FRAME_LENGTH 0
/* define this macro to 1 if you want the function usbMeasureFrameLength()
* compiled in. This function can be used to calibrate the AVR's RC oscillator.
*/
#define USB_USE_FAST_CRC 0
/* The assembler module has two implementations for the CRC algorithm. One is
* faster, the other is smaller. This CRC routine is only used for transmitted
* messages where timing is not critical. The faster routine needs 31 cycles
* per byte while the smaller one needs 61 to 69 cycles. The faster routine
* may be worth the 32 bytes bigger code size if you transmit lots of data and
* run the AVR close to its limit.
*/
/* -------------------------- Device Description --------------------------- */
#define USB_CFG_VENDOR_ID 0xc0, 0x16 /* = 0x16c0 = 5824 = voti.nl */
/* USB vendor ID for the device, low byte first. If you have registered your
* own Vendor ID, define it here. Otherwise you may use one of obdev's free
* shared VID/PID pairs. Be sure to read USB-IDs-for-free.txt for rules!
* *** IMPORTANT NOTE ***
* This template uses obdev's shared VID/PID pair for Vendor Class devices
* with libusb: 0x16c0/0x5dc. Use this VID/PID pair ONLY if you understand
* the implications!
*/
#define USB_CFG_DEVICE_ID 0xe8, 0x03 /* VOTI's lab use PID */
/* This is the ID of the product, low byte first. It is interpreted in the
* scope of the vendor ID. If you have registered your own VID with usb.org
* or if you have licensed a PID from somebody else, define it here. Otherwise
* you may use one of obdev's free shared VID/PID pairs. See the file
* USB-IDs-for-free.txt for details!
* *** IMPORTANT NOTE ***
* This template uses obdev's shared VID/PID pair for Vendor Class devices
* with libusb: 0x16c0/0x5dc. Use this VID/PID pair ONLY if you understand
* the implications!
*/
#define USB_CFG_DEVICE_VERSION 0x00, 0x01
/* Version number of the device: Minor number first, then major number.
*/
#define USB_CFG_VENDOR_NAME 'o', 'b', 'd', 'e', 'v', '.', 'a', 't'
#define USB_CFG_VENDOR_NAME_LEN 8
/* These two values define the vendor name returned by the USB device. The name
* must be given as a list of characters under single quotes. The characters
* are interpreted as Unicode (UTF-16) entities.
* If you don't want a vendor name string, undefine these macros.
* ALWAYS define a vendor name containing your Internet domain name if you use
* obdev's free shared VID/PID pair. See the file USB-IDs-for-free.txt for
* details.
*/
#define USB_CFG_DEVICE_NAME 'M', 'o', 'u', 's', 'e'
#define USB_CFG_DEVICE_NAME_LEN 5
/* Same as above for the device name. If you don't want a device name, undefine
* the macros. See the file USB-IDs-for-free.txt before you assign a name if
* you use a shared VID/PID.
*/
/*#define USB_CFG_SERIAL_NUMBER 'N', 'o', 'n', 'e' */
/*#define USB_CFG_SERIAL_NUMBER_LEN 0 */
/* Same as above for the serial number. If you don't want a serial number,
* undefine the macros.
* It may be useful to provide the serial number through other means than at
* compile time. See the section about descriptor properties below for how
* to fine tune control over USB descriptors such as the string descriptor
* for the serial number.
*/
#define USB_CFG_DEVICE_CLASS 0
#define USB_CFG_DEVICE_SUBCLASS 0
/* See USB specification if you want to conform to an existing device class.
* Class 0xff is "vendor specific".
*/
#define USB_CFG_INTERFACE_CLASS 3
#define USB_CFG_INTERFACE_SUBCLASS 0
#define USB_CFG_INTERFACE_PROTOCOL 0
/* See USB specification if you want to conform to an existing device class or
* protocol. The following classes must be set at interface level:
* HID class is 3, no subclass and protocol required (but may be useful!)
* CDC class is 2, use subclass 2 and protocol 1 for ACM
*/
#define USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH 52
/* Define this to the length of the HID report descriptor, if you implement
* an HID device. Otherwise don't define it or define it to 0.
* If you use this define, you must add a PROGMEM character array named
* "usbHidReportDescriptor" to your code which contains the report descriptor.
* Don't forget to keep the array and this define in sync!
*/
/* #define USB_PUBLIC static */
/* Use the define above if you #include usbdrv.c instead of linking against it.
* This technique saves a couple of bytes in flash memory.
*/
/* ------------------- Fine Control over USB Descriptors ------------------- */
/* If you don't want to use the driver's default USB descriptors, you can
* provide our own. These can be provided as (1) fixed length static data in
* flash memory, (2) fixed length static data in RAM or (3) dynamically at
* runtime in the function usbFunctionDescriptor(). See usbdrv.h for more
* information about this function.
* Descriptor handling is configured through the descriptor's properties. If
* no properties are defined or if they are 0, the default descriptor is used.
* Possible properties are:
* + USB_PROP_IS_DYNAMIC: The data for the descriptor should be fetched
* at runtime via usbFunctionDescriptor(). If the usbMsgPtr mechanism is
* used, the data is in FLASH by default. Add property USB_PROP_IS_RAM if
* you want RAM pointers.
* + USB_PROP_IS_RAM: The data returned by usbFunctionDescriptor() or found
* in static memory is in RAM, not in flash memory.
* + USB_PROP_LENGTH(len): If the data is in static memory (RAM or flash),
* the driver must know the descriptor's length. The descriptor itself is
* found at the address of a well known identifier (see below).
* List of static descriptor names (must be declared PROGMEM if in flash):
* char usbDescriptorDevice[];
* char usbDescriptorConfiguration[];
* char usbDescriptorHidReport[];
* char usbDescriptorString0[];
* int usbDescriptorStringVendor[];
* int usbDescriptorStringDevice[];
* int usbDescriptorStringSerialNumber[];
* Other descriptors can't be provided statically, they must be provided
* dynamically at runtime.
*
* Descriptor properties are or-ed or added together, e.g.:
* #define USB_CFG_DESCR_PROPS_DEVICE (USB_PROP_IS_RAM | USB_PROP_LENGTH(18))
*
* The following descriptors are defined:
* USB_CFG_DESCR_PROPS_DEVICE
* USB_CFG_DESCR_PROPS_CONFIGURATION
* USB_CFG_DESCR_PROPS_STRINGS
* USB_CFG_DESCR_PROPS_STRING_0
* USB_CFG_DESCR_PROPS_STRING_VENDOR
* USB_CFG_DESCR_PROPS_STRING_PRODUCT
* USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
* USB_CFG_DESCR_PROPS_HID
* USB_CFG_DESCR_PROPS_HID_REPORT
* USB_CFG_DESCR_PROPS_UNKNOWN (for all descriptors not handled by the driver)
*
* Note about string descriptors: String descriptors are not just strings, they
* are Unicode strings prefixed with a 2 byte header. Example:
* int serialNumberDescriptor[] = {
* USB_STRING_DESCRIPTOR_HEADER(6),
* 'S', 'e', 'r', 'i', 'a', 'l'
* };
*/
#define USB_CFG_DESCR_PROPS_DEVICE 0
#define USB_CFG_DESCR_PROPS_CONFIGURATION 0
#define USB_CFG_DESCR_PROPS_STRINGS 0
#define USB_CFG_DESCR_PROPS_STRING_0 0
#define USB_CFG_DESCR_PROPS_STRING_VENDOR 0
#define USB_CFG_DESCR_PROPS_STRING_PRODUCT 0
#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER 0
#define USB_CFG_DESCR_PROPS_HID 0
#define USB_CFG_DESCR_PROPS_HID_REPORT 0
#define USB_CFG_DESCR_PROPS_UNKNOWN 0
#define usbMsgPtr_t unsigned short
/* If usbMsgPtr_t is not defined, it defaults to 'uchar *'. We define it to
* a scalar type here because gcc generates slightly shorter code for scalar
* arithmetics than for pointer arithmetics. Remove this define for backward
* type compatibility or define it to an 8 bit type if you use data in RAM only
* and all RAM is below 256 bytes (tiny memory model in IAR CC).
*/
/* ----------------------- Optional MCU Description ------------------------ */
/* The following configurations have working defaults in usbdrv.h. You
* usually don't need to set them explicitly. Only if you want to run
* the driver on a device which is not yet supported or with a compiler
* which is not fully supported (such as IAR C) or if you use a differnt
* interrupt than INT0, you may have to define some of these.
*/
/* #define USB_INTR_CFG MCUCR */
/* #define USB_INTR_CFG_SET ((1 << ISC00) | (1 << ISC01)) */
/* #define USB_INTR_CFG_CLR 0 */
/* #define USB_INTR_ENABLE GIMSK */
/* #define USB_INTR_ENABLE_BIT INT0 */
/* #define USB_INTR_PENDING GIFR */
/* #define USB_INTR_PENDING_BIT INTF0 */
/* #define USB_INTR_VECTOR INT0_vect */
#endif /* __usbconfig_h_included__ */

View File

@ -0,0 +1,47 @@
# Name: Makefile
# Project: usbtool
# Author: Christian Starkjohann
# Creation Date: 2008-04-06
# Tabsize: 4
# Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
# Concigure the following definitions according to your system.
# This Makefile has been tested on Mac OS X, Linux and Windows.
# Use the following 3 lines on Unix (uncomment the framework on Mac OS X):
USBFLAGS = `libusb-config --cflags`
USBLIBS = `libusb-config --libs`
EXE_SUFFIX =
# Use the following 3 lines on Windows and comment out the 3 above. You may
# have to change the include paths to where you installed libusb-win32
#USBFLAGS = -I/usr/local/include
#USBLIBS = -L/usr/local/lib -lusb
#EXE_SUFFIX = .exe
NAME = usbtool
OBJECTS = opendevice.o $(NAME).o
CC = gcc
CFLAGS = $(CPPFLAGS) $(USBFLAGS) -O -g -Wall
LIBS = $(USBLIBS)
PROGRAM = $(NAME)$(EXE_SUFFIX)
all: $(PROGRAM)
.c.o:
$(CC) $(CFLAGS) -c $<
$(PROGRAM): $(OBJECTS)
$(CC) -o $(PROGRAM) $(OBJECTS) $(LIBS)
strip: $(PROGRAM)
strip $(PROGRAM)
clean:
rm -f *.o $(PROGRAM)

View File

@ -0,0 +1,17 @@
# Name: Makefile.windows
# Project: usbtool
# Author: Christian Starkjohann
# Creation Date: 2008-04-06
# Tabsize: 4
# Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
# You may use this file with
# make -f Makefile.windows
# on Windows with MinGW instead of editing the main Makefile.
include Makefile
USBFLAGS = -I/usr/local/mingw/include
USBLIBS = -L/usr/local/mingw/lib -lusb
EXE_SUFFIX = .exe

View File

@ -0,0 +1,209 @@
This is the Readme file for usbtool, a general purpose command line utility
which can send USB requests to arbitrary devices. Usbtool is based on libusb.
WHAT IS USBTOOL GOOD FOR?
=========================
When you implement a communication protocol like USB, you must usually write
two programs: one on each end of the communication. For USB, this means that
you must write a firmware for the device and driver software for the host.
Usbtool can save you the work of writing the host software, at least during
firmware development and testing. Usbtool can send control-in and -out
requests to arbitrary devices and send and receive data on interrupt- and
bulk-endpoints.
Usbtool is not only a useful developer tool, it's also an example for using
libusb for communication with the device.
SYNOPSIS
========
usbtool [options] <command>
COMMANDS
========
list
This command prints a list of devices found on all available USB busses.
Options -v, -V, -p and -P can be used to filter the list.
control in|out <type> <recipient> <request> <value> <index>
Sends a control-in or control-out request to the device. The request
parameters are:
type ........ Type of request, can be "standard", "class", "vendor" or
"reserved". The type determines which software module in
the device is responsible for answering the request:
Standard requests are answered by the driver, class
requests by the class implementation (e.g. HID, CDC) and
vendor requests by custom code.
recipient ... Recipient of the request in the device. Can be "device",
"interface", "endpoint" or "other". For standard and
class requests, the specification defines a recipient for
each request. For vendor requests, choose whatever your
code expects.
request ..... 8 bit numeric value identifying the request.
value ....... 16 bit numeric value passed to the device.
index ....... another 16 bit numeric value passed to the device.
Use options -v, -V, -p and -P to single out a particular device. Use
options -d or -D to to send data in an OUT request. Use options -n, -O
and -b to determine what to do with data received in an IN request.
interrupt in|out
Sends or receives data on an interrupt-out resp. -in endpoint.
Use options -v, -V, -p and -P to single out a particular device. Use
options -d or -D to to send data to an OUT endpoint. Use options -n, -O
and -b to determine what to do with data received from an IN endpoint.
Use option -e to set the endpoint number, -c to choose a configuration
-i to claim a particular interface.
bulk in|out
Same as "interrupt in" and "interrupt out", but for bulk endpoints.
OPTIONS
=======
Most options have already been mentioned at the commands which use them.
here is a complete list:
-h or -?
Prints a short help.
-v <vendor-id>
Numeric vendor ID, can be "*" to allow any VID. Take only devices with
matching vendor ID into account.
-p <product-id>
Numeric product ID, can be "*" to allow any PID. Take only devices with
matching product ID into account.
-V <vendor-name-pattern>
Shell style matching pattern for vendor name. Take only devices into
account which have a vendor name that matches this pattern.
-P <product-name-pattern>
Shell style matching pattern for product name. Take only devices into
account which have a product name that matches this pattern.
-S <serial-pattern>
Shell style matching pattern for serial number. Take only devices into
account which have a serial number that matches this pattern.
-d <databytes>
Data bytes to send to the device, comma separated list of numeric values.
E.g.: "1,2,3,4,5".
-D <file>
Binary data sent to the device should be taken from this file.
-O <file>
Write received data bytes to the given file. Format is either hex or
binary, depending on the -b flag. By default, received data is printed
to standard output.
-b
Request binary output format for files and standard output. Default is
a hexadecimal listing.
-n <count>
Numeric value: Maximum number of bytes to receive. This value is passed
directly to the libusb API functions.
-e <endpoint>
Numeric value: Endpoint number for interrupt and bulk commands.
-t <timeout>
Numeric value: Timeout in milliseconds for the request. This value is
passed directly to the libusb API functions.
-c <configuration>
Numeric value: Interrupt and bulk endpoints can usually only be used if
a configuration and an interface has been chosen. Use -c and -i to
specify configuration and interface values.
-i <interface>
Numeric value: Interrupt and bulk endpoints can usually only be used if
a configuration and an interface has been chosen. Use -c and -i to
specify configuration and interface values.
-w
Usbtool may be too verbose with warnings for some applications. Use this
option to suppress USB warnings.
NUMERIC VALUES
==============
All numeric values can be given in hexadecimal, decimal or octal. Hex values
are identified by their 0x or 0X prefix, octal values by a leading "0" (the
digit zero) and decimal values because they start with a non-zero digit. An
optional sign character is allowed. The special value "*" is translated to
zero and stands for "any value" in some contexts.
SHELL STYLE MATCHING PATTERNS
=============================
Some options take shell style matching patterns as an argument. This refers
to Unix shells and their file wildcard operations:
+ "*" (asterisk character) matches any number (0 to infinite) of any
characters.
+ "?" matches exactly one arbitrary character.
+ A list of characters in square brackets (e.g. "[abc]") matches any of the
characters in the list. If a dash ("-") is in the list, it must be the
first or the last character. If a caret ("^") is in the list, it must
not be the first character. A closing square bracket ("]") must be the
first character in the list. A range of characters can be specified in
the way "[a-z]". This matches all characters with numeric representation
(usually ASCII) starting with "a" and ending with "z". The entire
construct matches only one character.
+ A list of characters in square brackets starting with a caret ("^"), e.g.
("[^abc]") matches any character NOT in the list. The other rules are as
above.
+ "\" (backslash) followed by any character matches that following
character. This can be used to escape "*", "?", "[" and "\".
BUILDING USBTOOL
================
Usbtool uses libusb on Unix and libusb-win32 on Windows. These libraries can
be obtained from http://libusb.sourceforge.net/ and
http://libusb-win32.sourceforge.net/ respectively. On Unix, a simple "make"
should compile the sources (although you may have to edit Makefile to
include or remove additional libraries). On Windows, we recommend that you
use MinGW and MSYS. See the top level Readme file for details. Edit
Makefile.windows according to your library installation paths and build with
"make -f Makefile.windows".
EXAMPLES
========
To list all devices connected to your computer, do
usbtool -w list
To check whether our selection options single out the desired device, use eg.
usbtool -w -P LEDControl list
This command shows all LEDControl devices connected or prints nothing if
none is found. LEDControl is the device from the "custom-class" example.
You can also send commands to the LEDControl device using usbtool. From
the file requests.h in custom-class/firmware, we know that the set-status
request has numeric value 1 and the get-status request is 2. See this file
for details of the protocol used. We can therefore query the status with
usbtool -w -P LEDControl control in vendor device 2 0 0
This command prints 0x00 if the LED is off or 0x01 if it is on. To turn the
LED on, use
usbtool -w -P LEDControl control out vendor device 1 1 0
and to turn it off, use
usbtool -w -P LEDControl control out vendor device 1 0 0
----------------------------------------------------------------------------
(c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH.
http://www.obdev.at/

View File

@ -0,0 +1,202 @@
/* Name: opendevice.c
* Project: V-USB host-side library
* Author: Christian Starkjohann
* Creation Date: 2008-04-10
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
General Description:
The functions in this module can be used to find and open a device based on
libusb or libusb-win32.
*/
#include <stdio.h>
#include "opendevice.h"
/* ------------------------------------------------------------------------- */
#define MATCH_SUCCESS 1
#define MATCH_FAILED 0
#define MATCH_ABORT -1
/* private interface: match text and p, return MATCH_SUCCESS, MATCH_FAILED, or MATCH_ABORT. */
static int _shellStyleMatch(char *text, char *p)
{
int last, matched, reverse;
for(; *p; text++, p++){
if(*text == 0 && *p != '*')
return MATCH_ABORT;
switch(*p){
case '\\':
/* Literal match with following character. */
p++;
/* FALLTHROUGH */
default:
if(*text != *p)
return MATCH_FAILED;
continue;
case '?':
/* Match anything. */
continue;
case '*':
while(*++p == '*')
/* Consecutive stars act just like one. */
continue;
if(*p == 0)
/* Trailing star matches everything. */
return MATCH_SUCCESS;
while(*text)
if((matched = _shellStyleMatch(text++, p)) != MATCH_FAILED)
return matched;
return MATCH_ABORT;
case '[':
reverse = p[1] == '^';
if(reverse) /* Inverted character class. */
p++;
matched = MATCH_FAILED;
if(p[1] == ']' || p[1] == '-')
if(*++p == *text)
matched = MATCH_SUCCESS;
for(last = *p; *++p && *p != ']'; last = *p)
if (*p == '-' && p[1] != ']' ? *text <= *++p && *text >= last : *text == *p)
matched = MATCH_SUCCESS;
if(matched == reverse)
return MATCH_FAILED;
continue;
}
}
return *text == 0;
}
/* public interface for shell style matching: returns 0 if fails, 1 if matches */
static int shellStyleMatch(char *text, char *pattern)
{
if(pattern == NULL) /* NULL pattern is synonymous to "*" */
return 1;
return _shellStyleMatch(text, pattern) == MATCH_SUCCESS;
}
/* ------------------------------------------------------------------------- */
int usbGetStringAscii(usb_dev_handle *dev, int index, char *buf, int buflen)
{
char buffer[256];
int rval, i;
if((rval = usb_get_string_simple(dev, index, buf, buflen)) >= 0) /* use libusb version if it works */
return rval;
if((rval = usb_control_msg(dev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR, (USB_DT_STRING << 8) + index, 0x0409, buffer, sizeof(buffer), 5000)) < 0)
return rval;
if(buffer[1] != USB_DT_STRING){
*buf = 0;
return 0;
}
if((unsigned char)buffer[0] < rval)
rval = (unsigned char)buffer[0];
rval /= 2;
/* lossy conversion to ISO Latin1: */
for(i=1;i<rval;i++){
if(i > buflen) /* destination buffer overflow */
break;
buf[i-1] = buffer[2 * i];
if(buffer[2 * i + 1] != 0) /* outside of ISO Latin1 range */
buf[i-1] = '?';
}
buf[i-1] = 0;
return i-1;
}
/* ------------------------------------------------------------------------- */
int usbOpenDevice(usb_dev_handle **device, int vendorID, char *vendorNamePattern, int productID, char *productNamePattern, char *serialNamePattern, FILE *printMatchingDevicesFp, FILE *warningsFp)
{
struct usb_bus *bus;
struct usb_device *dev;
usb_dev_handle *handle = NULL;
int errorCode = USBOPEN_ERR_NOTFOUND;
usb_find_busses();
usb_find_devices();
for(bus = usb_get_busses(); bus; bus = bus->next){
for(dev = bus->devices; dev; dev = dev->next){ /* iterate over all devices on all busses */
if((vendorID == 0 || dev->descriptor.idVendor == vendorID)
&& (productID == 0 || dev->descriptor.idProduct == productID)){
char vendor[256], product[256], serial[256];
int len;
handle = usb_open(dev); /* we need to open the device in order to query strings */
if(!handle){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot open VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
continue;
}
/* now check whether the names match: */
len = vendor[0] = 0;
if(dev->descriptor.iManufacturer > 0){
len = usbGetStringAscii(handle, dev->descriptor.iManufacturer, vendor, sizeof(vendor));
}
if(len < 0){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot query manufacturer for VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
}else{
errorCode = USBOPEN_ERR_NOTFOUND;
/* printf("seen device from vendor ->%s<-\n", vendor); */
if(shellStyleMatch(vendor, vendorNamePattern)){
len = product[0] = 0;
if(dev->descriptor.iProduct > 0){
len = usbGetStringAscii(handle, dev->descriptor.iProduct, product, sizeof(product));
}
if(len < 0){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot query product for VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
}else{
errorCode = USBOPEN_ERR_NOTFOUND;
/* printf("seen product ->%s<-\n", product); */
if(shellStyleMatch(product, productNamePattern)){
len = serial[0] = 0;
if(dev->descriptor.iSerialNumber > 0){
len = usbGetStringAscii(handle, dev->descriptor.iSerialNumber, serial, sizeof(serial));
}
if(len < 0){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot query serial for VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
}
if(shellStyleMatch(serial, serialNamePattern)){
if(printMatchingDevicesFp != NULL){
if(serial[0] == 0){
fprintf(printMatchingDevicesFp, "VID=0x%04x PID=0x%04x vendor=\"%s\" product=\"%s\"\n", dev->descriptor.idVendor, dev->descriptor.idProduct, vendor, product);
}else{
fprintf(printMatchingDevicesFp, "VID=0x%04x PID=0x%04x vendor=\"%s\" product=\"%s\" serial=\"%s\"\n", dev->descriptor.idVendor, dev->descriptor.idProduct, vendor, product, serial);
}
}else{
break;
}
}
}
}
}
}
usb_close(handle);
handle = NULL;
}
}
if(handle) /* we have found a deice */
break;
}
if(handle != NULL){
errorCode = 0;
*device = handle;
}
if(printMatchingDevicesFp != NULL) /* never return an error for listing only */
errorCode = 0;
return errorCode;
}
/* ------------------------------------------------------------------------- */

View File

@ -0,0 +1,76 @@
/* Name: opendevice.h
* Project: V-USB host-side library
* Author: Christian Starkjohann
* Creation Date: 2008-04-10
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
General Description:
This module offers additional functionality for host side drivers based on
libusb or libusb-win32. It includes a function to find and open a device
based on numeric IDs and textual description. It also includes a function to
obtain textual descriptions from a device.
To use this functionality, simply copy opendevice.c and opendevice.h into your
project and add them to your Makefile. You may modify and redistribute these
files according to the GNU General Public License (GPL) version 2 or 3.
*/
#ifndef __OPENDEVICE_H_INCLUDED__
#define __OPENDEVICE_H_INCLUDED__
#include <usb.h> /* this is libusb, see http://libusb.sourceforge.net/ */
#include <stdio.h>
int usbGetStringAscii(usb_dev_handle *dev, int index, char *buf, int buflen);
/* This function gets a string descriptor from the device. 'index' is the
* string descriptor index. The string is returned in ISO Latin 1 encoding in
* 'buf' and it is terminated with a 0-character. The buffer size must be
* passed in 'buflen' to prevent buffer overflows. A libusb device handle
* must be given in 'dev'.
* Returns: The length of the string (excluding the terminating 0) or
* a negative number in case of an error. If there was an error, use
* usb_strerror() to obtain the error message.
*/
int usbOpenDevice(usb_dev_handle **device, int vendorID, char *vendorNamePattern, int productID, char *productNamePattern, char *serialNamePattern, FILE *printMatchingDevicesFp, FILE *warningsFp);
/* This function iterates over all devices on all USB busses and searches for
* a device. Matching is done first by means of Vendor- and Product-ID (passed
* in 'vendorID' and 'productID'. An ID of 0 matches any numeric ID (wildcard).
* When a device matches by its IDs, matching by names is performed. Name
* matching can be done on textual vendor name ('vendorNamePattern'), product
* name ('productNamePattern') and serial number ('serialNamePattern'). A
* device matches only if all non-null pattern match. If you don't care about
* a string, pass NULL for the pattern. Patterns are Unix shell style pattern:
* '*' stands for 0 or more characters, '?' for one single character, a list
* of characters in square brackets for a single character from the list
* (dashes are allowed to specify a range) and if the lis of characters begins
* with a caret ('^'), it matches one character which is NOT in the list.
* Other parameters to the function: If 'warningsFp' is not NULL, warning
* messages are printed to this file descriptor with fprintf(). If
* 'printMatchingDevicesFp' is not NULL, no device is opened but matching
* devices are printed to the given file descriptor with fprintf().
* If a device is opened, the resulting USB handle is stored in '*device'. A
* pointer to a "usb_dev_handle *" type variable must be passed here.
* Returns: 0 on success, an error code (see defines below) on failure.
*/
/* usbOpenDevice() error codes: */
#define USBOPEN_SUCCESS 0 /* no error */
#define USBOPEN_ERR_ACCESS 1 /* not enough permissions to open device */
#define USBOPEN_ERR_IO 2 /* I/O error */
#define USBOPEN_ERR_NOTFOUND 3 /* device not found */
/* Obdev's free USB IDs, see USB-IDs-for-free.txt for details */
#define USB_VID_OBDEV_SHARED 5824 /* obdev's shared vendor ID */
#define USB_PID_OBDEV_SHARED_CUSTOM 1500 /* shared PID for custom class devices */
#define USB_PID_OBDEV_SHARED_HID 1503 /* shared PID for HIDs except mice & keyboards */
#define USB_PID_OBDEV_SHARED_CDCACM 1505 /* shared PID for CDC Modem devices */
#define USB_PID_OBDEV_SHARED_MIDI 1508 /* shared PID for MIDI class devices */
#endif /* __OPENDEVICE_H_INCLUDED__ */

View File

@ -0,0 +1,355 @@
/* Name: usbtool.c
* Project: V-USB examples, host side
* Author: Christian Starkjohann
* Creation Date: 2008-04-06
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
General Description:
This command line tool can perform various USB requests at arbitrary
USB devices. It is intended as universal host side tool for experimentation
and debugging purposes. It must be linked with libusb, a library for accessing
the USB bus from Linux, FreeBSD, Mac OS X and other Unix operating systems.
Libusb can be obtained from http://libusb.sourceforge.net/.
On Windows use libusb-win32 from http://libusb-win32.sourceforge.net/.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdarg.h>
#include <ctype.h>
#include <errno.h>
#include <usb.h> /* this is libusb, see http://libusb.sourceforge.net/ */
#include "opendevice.h" /* common code moved to separate module */
#define DEFAULT_USB_VID 0 /* any */
#define DEFAULT_USB_PID 0 /* any */
static void usage(char *name)
{
fprintf(stderr, "usage: %s [options] <command>\n", name);
fprintf(stderr,
"Options are:\n"
" -h or -? (print this help and exit)\n"
" -v <vendor-id> (defaults to 0x%x, can be '*' for any VID)\n"
" -p <product-id> (defaults to 0x%x, can be '*' for any PID)\n"
" -V <vendor-name-pattern> (shell style matching, defaults to '*')\n"
" -P <product-name-pattern> (shell style matching, defaults to '*')\n"
" -S <serial-pattern> (shell style matching, defaults to '*')\n"
" -d <databytes> (data byte for request, comma separated list)\n"
" -D <file> (binary data for request taken from file)\n"
" -O <file> (write received data bytes to file)\n"
" -b (binary output format, default is hex)\n"
" -n <count> (maximum number of bytes to receive)\n"
" -e <endpoint> (specify endpoint for some commands)\n"
" -t <timeout> (specify USB timeout in milliseconds)\n"
" -c <configuration> (device configuration to choose)\n"
" -i <interface> (configuration interface to claim)\n"
" -w (suppress USB warnings, default is verbose)\n"
"\n"
"Commands are:\n"
" list (list all matching devices by name)\n"
" control in|out <type> <recipient> <request> <value> <index> (send control request)\n"
" interrupt in|out (send or receive interrupt data)\n"
" bulk in|out (send or receive bulk data)\n"
"For valid enum values for <type> and <recipient> pass \"x\" for the value.\n"
"Objective Development's free VID/PID pairs are:\n"
" 5824/1500 for vendor class devices\n"
" 5824/1503 for HID class devices excluding mice and keyboards\n"
" 5824/1505 for CDC-ACM class devices\n"
" 5824/1508 for MIDI class devices\n"
, DEFAULT_USB_VID, DEFAULT_USB_PID
);
}
static int vendorID = DEFAULT_USB_VID;
static int productID = DEFAULT_USB_PID;
static char *vendorNamePattern = "*";
static char *productNamePattern = "*";
static char *serialPattern = "*";
static char *sendBytes = NULL;
static int sendByteCount;
static char *outputFile = NULL;
static int endpoint = 0;
static int outputFormatIsBinary = 0;
static int showWarnings = 1;
static int usbTimeout = 5000;
static int usbCount = 128;
static int usbConfiguration = 1;
static int usbInterface = 0;
static int usbDirection, usbType, usbRecipient, usbRequest, usbValue, usbIndex; /* arguments of control transfer */
/* ------------------------------------------------------------------------- */
/* ASCII to integer (number parsing) which allows hex (0x prefix),
* octal (0 prefix) and decimal (1-9 prefix) input.
*/
static int myAtoi(char *text)
{
long l;
char *endPtr;
if(strcmp(text, "*") == 0)
return 0;
l = strtol(text, &endPtr, 0);
if(endPtr == text){
fprintf(stderr, "warning: can't parse numeric parameter ->%s<-, defaults to 0.\n", text);
l = 0;
}else if(*endPtr != 0){
fprintf(stderr, "warning: numeric parameter ->%s<- only partially parsed.\n", text);
}
return l;
}
static int parseEnum(char *text, ...)
{
va_list vlist;
char *entries[64];
int i, numEntries;
va_start(vlist, text);
for(i = 0; i < 64; i++){
entries[i] = va_arg(vlist, char *);
if(entries[i] == NULL)
break;
}
numEntries = i;
va_end(vlist);
for(i = 0; i < numEntries; i++){
if(strcasecmp(text, entries[i]) == 0)
return i;
}
if(isdigit(*text)){
return myAtoi(text);
}
fprintf(stderr, "Enum value \"%s\" not allowed. Allowed values are:\n", text);
for(i = 0; i < numEntries; i++){
fprintf(stderr, " %s\n", entries[i]);
}
exit(1);
}
/* ------------------------------------------------------------------------- */
#define ACTION_LIST 0
#define ACTION_CONTROL 1
#define ACTION_INTERRUPT 2
#define ACTION_BULK 3
int main(int argc, char **argv)
{
usb_dev_handle *handle = NULL;
int opt, len, action, argcnt;
char *myName = argv[0], *s, *rxBuffer = NULL;
FILE *fp;
while((opt = getopt(argc, argv, "?hv:p:V:P:S:d:D:O:e:n:tbw")) != -1){
switch(opt){
case 'h':
case '?': /* -h or -? (print this help and exit) */
usage(myName);
exit(1);
case 'v': /* -v <vendor-id> (defaults to 0x%x, can be '*' for any VID) */
vendorID = myAtoi(optarg);
break;
case 'p': /* -p <product-id> (defaults to 0x%x, can be '*' for any PID) */
productID = myAtoi(optarg);
break;
case 'V': /* -V <vendor-name-pattern> (shell style matching, defaults to '*') */
vendorNamePattern = optarg;
break;
case 'P': /* -P <product-name-pattern> (shell style matching, defaults to '*') */
productNamePattern = optarg;
break;
case 'S': /* -S <serial-pattern> (shell style matching, defaults to '*') */
serialPattern = optarg;
break;
case 'd': /* -d <databytes> (data bytes for requests given on command line) */
while((s = strtok(optarg, ", ")) != NULL){
optarg = NULL;
if(sendBytes != NULL){
sendBytes = realloc(sendBytes, sendByteCount + 1);
}else{
sendBytes = malloc(sendByteCount + 1);
}
sendBytes[sendByteCount++] = myAtoi(s);
}
break;
case 'D': /* -D <file> (data bytes for request taken from file) */
if((fp = fopen(optarg, "rb")) == NULL){
fprintf(stderr, "error opening %s: %s\n", optarg, strerror(errno));
exit(1);
}
fseek(fp, 0, SEEK_END);
len = ftell(fp);
fseek(fp, 0, SEEK_SET);
if(sendBytes != NULL){
sendBytes = realloc(sendBytes, sendByteCount + len);
}else{
sendBytes = malloc(sendByteCount + len);
}
fread(sendBytes + sendByteCount, 1, len, fp); /* would need error checking */
sendByteCount += len;
fclose(fp);
break;
case 'O': /* -O <file> (write received data bytes to file) */
outputFile = optarg;
break;
case 'e': /* -e <endpoint> (specify endpoint for some commands) */
endpoint = myAtoi(optarg);
break;
case 't': /* -t <timeout> (specify USB timeout in milliseconds) */
usbTimeout = myAtoi(optarg);
break;
case 'b': /* -b (binary output format, default is hex) */
outputFormatIsBinary = 1;
break;
case 'n': /* -n <count> (maximum number of bytes to receive) */
usbCount = myAtoi(optarg);
break;
case 'c': /* -c <configuration> (device configuration to choose) */
usbConfiguration = myAtoi(optarg);
break;
case 'i': /* -i <interface> (configuration interface to claim) */
usbInterface = myAtoi(optarg);
break;
case 'w': /* -w (suppress USB warnings, default is verbose) */
showWarnings = 0;
break;
default:
fprintf(stderr, "Option -%c unknown\n", opt);
exit(1);
}
}
argc -= optind;
argv += optind;
if(argc < 1){
usage(myName);
exit(1);
}
argcnt = 2;
if(strcasecmp(argv[0], "list") == 0){
action = ACTION_LIST;
argcnt = 1;
}else if(strcasecmp(argv[0], "control") == 0){
action = ACTION_CONTROL;
argcnt = 7;
}else if(strcasecmp(argv[0], "interrupt") == 0){
action = ACTION_INTERRUPT;
}else if(strcasecmp(argv[0], "bulk") == 0){
action = ACTION_BULK;
}else{
fprintf(stderr, "command %s not known\n", argv[0]);
usage(myName);
exit(1);
}
if(argc < argcnt){
fprintf(stderr, "Not enough arguments.\n");
usage(myName);
exit(1);
}
if(argc > argcnt){
fprintf(stderr, "Warning: only %d arguments expected, rest ignored.\n", argcnt);
}
usb_init();
if(usbOpenDevice(&handle, vendorID, vendorNamePattern, productID, productNamePattern, serialPattern, action == ACTION_LIST ? stdout : NULL, showWarnings ? stderr : NULL) != 0){
fprintf(stderr, "Could not find USB device with VID=0x%x PID=0x%x Vname=%s Pname=%s Serial=%s\n", vendorID, productID, vendorNamePattern, productNamePattern, serialPattern);
exit(1);
}
if(action == ACTION_LIST)
exit(0); /* we've done what we were asked to do already */
usbDirection = parseEnum(argv[1], "out", "in", NULL);
if(usbDirection){ /* IN transfer */
rxBuffer = malloc(usbCount);
}
if(action == ACTION_CONTROL){
int requestType;
usbType = parseEnum(argv[2], "standard", "class", "vendor", "reserved", NULL);
usbRecipient = parseEnum(argv[3], "device", "interface", "endpoint", "other", NULL);
usbRequest = myAtoi(argv[4]);
usbValue = myAtoi(argv[5]);
usbIndex = myAtoi(argv[6]);
requestType = ((usbDirection & 1) << 7) | ((usbType & 3) << 5) | (usbRecipient & 0x1f);
if(usbDirection){ /* IN transfer */
len = usb_control_msg(handle, requestType, usbRequest, usbValue, usbIndex, rxBuffer, usbCount, usbTimeout);
}else{ /* OUT transfer */
len = usb_control_msg(handle, requestType, usbRequest, usbValue, usbIndex, sendBytes, sendByteCount, usbTimeout);
}
}else{ /* must be ACTION_INTERRUPT or ACTION_BULK */
int retries = 1;
if(usb_set_configuration(handle, usbConfiguration) && showWarnings){
fprintf(stderr, "Warning: could not set configuration: %s\n", usb_strerror());
}
/* now try to claim the interface and detach the kernel HID driver on
* linux and other operating systems which support the call.
*/
while((len = usb_claim_interface(handle, usbInterface)) != 0 && retries-- > 0){
#ifdef LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP
if(usb_detach_kernel_driver_np(handle, 0) < 0 && showWarnings){
fprintf(stderr, "Warning: could not detach kernel driver: %s\n", usb_strerror());
}
#endif
}
if(len != 0 && showWarnings)
fprintf(stderr, "Warning: could not claim interface: %s\n", usb_strerror());
if(action == ACTION_INTERRUPT){
if(usbDirection){ /* IN transfer */
len = usb_interrupt_read(handle, endpoint, rxBuffer, usbCount, usbTimeout);
}else{
len = usb_interrupt_write(handle, endpoint, sendBytes, sendByteCount, usbTimeout);
}
}else{
if(usbDirection){ /* IN transfer */
len = usb_bulk_read(handle, endpoint, rxBuffer, usbCount, usbTimeout);
}else{
len = usb_bulk_write(handle, endpoint, sendBytes, sendByteCount, usbTimeout);
}
}
}
if(len < 0){
fprintf(stderr, "USB error: %s\n", usb_strerror());
exit(1);
}
if(usbDirection == 0) /* OUT */
printf("%d bytes sent.\n", len);
if(rxBuffer != NULL){
FILE *fp = stdout;
if(outputFile != NULL){
fp = fopen(outputFile, outputFormatIsBinary ? "wb" : "w");
if(fp == NULL){
fprintf(stderr, "Error writing \"%s\": %s\n", outputFile, strerror(errno));
exit(1);
}
}
if(outputFormatIsBinary){
fwrite(rxBuffer, 1, len, fp);
}else{
int i;
for(i = 0; i < len; i++){
if(i != 0){
if(i % 16 == 0){
fprintf(fp, "\n");
}else{
fprintf(fp, " ");
}
}
fprintf(fp, "0x%02x", rxBuffer[i] & 0xff);
}
if(i != 0)
fprintf(fp, "\n");
}
}
usb_close(handle);
if(rxBuffer != NULL)
free(rxBuffer);
return 0;
}

View File

@ -0,0 +1,22 @@
This is the Readme file for the libs-device directory. This directory contains
code snippets which may be useful for USB device firmware.
WHAT IS INCLUDED IN THIS DIRECTORY?
===================================
osccal.c and osccal.h
This module contains a function which calibrates the AVR's built-in RC
oscillator based on the USB frame clock. See osccal.h for a documentation
of the API.
osctune.h
This header file contains a code snippet for usbconfig.h. With this code,
you can keep the AVR's internal RC oscillator in sync with the USB frame
clock. This is a continuous synchronization, not a single calibration at
USB reset as with osccal.c above. Please note that this code works only
if D- is wired to the interrupt, not D+.
----------------------------------------------------------------------------
(c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH.
http://www.obdev.at/

View File

@ -0,0 +1,62 @@
/* Name: osccal.c
* Author: Christian Starkjohann
* Creation Date: 2008-04-10
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
#include <avr/io.h>
#ifndef uchar
#define uchar unsigned char
#endif
/* ------------------------------------------------------------------------- */
/* ------------------------ Oscillator Calibration ------------------------- */
/* ------------------------------------------------------------------------- */
/* Calibrate the RC oscillator. Our timing reference is the Start Of Frame
* signal (a single SE0 bit) repeating every millisecond immediately after
* a USB RESET. We first do a binary search for the OSCCAL value and then
* optimize this value with a neighboorhod search.
*/
void calibrateOscillator(void)
{
uchar step = 128;
uchar trialValue = 0, optimumValue;
int x, optimumDev, targetValue = (unsigned)(1499 * (double)F_CPU / 10.5e6 + 0.5);
/* do a binary search: */
do{
OSCCAL = trialValue + step;
x = usbMeasureFrameLength(); /* proportional to current real frequency */
if(x < targetValue) /* frequency still too low */
trialValue += step;
step >>= 1;
}while(step > 0);
/* We have a precision of +/- 1 for optimum OSCCAL here */
/* now do a neighborhood search for optimum value */
optimumValue = trialValue;
optimumDev = x; /* this is certainly far away from optimum */
for(OSCCAL = trialValue - 1; OSCCAL <= trialValue + 1; OSCCAL++){
x = usbMeasureFrameLength() - targetValue;
if(x < 0)
x = -x;
if(x < optimumDev){
optimumDev = x;
optimumValue = OSCCAL;
}
}
OSCCAL = optimumValue;
}
/*
Note: This calibration algorithm may try OSCCAL values of up to 192 even if
the optimum value is far below 192. It may therefore exceed the allowed clock
frequency of the CPU in low voltage designs!
You may replace this search algorithm with any other algorithm you like if
you have additional constraints such as a maximum CPU clock.
For version 5.x RC oscillators (those with a split range of 2x128 steps, e.g.
ATTiny25, ATTiny45, ATTiny85), it may be useful to search for the optimum in
both regions.
*/

View File

@ -0,0 +1,62 @@
/* Name: osccal.h
* Author: Christian Starkjohann
* Creation Date: 2008-04-10
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
General Description:
This module contains a function which calibrates the AVR's internal RC
oscillator so that the CPU runs at F_CPU (F_CPU is a macro which must be
defined when the module is compiled, best passed in the compiler command
line). The time reference is the USB frame clock of 1 kHz available
immediately after a USB RESET condition. Timing is done by counting CPU
cycles, so all interrupts must be disabled while the calibration runs. For
low level timing measurements, usbMeasureFrameLength() is called. This
function must be enabled in usbconfig.h by defining
USB_CFG_HAVE_MEASURE_FRAME_LENGTH to 1. It is recommended to call
calibrateOscillator() from the reset hook in usbconfig.h:
#ifndef __ASSEMBLER__
#include <avr/interrupt.h> // for sei()
extern void calibrateOscillator(void);
#endif
#define USB_RESET_HOOK(resetStarts) if(!resetStarts){cli(); calibrateOscillator(); sei();}
This routine is an alternative to the continuous synchronization described
in osctune.h.
Algorithm used:
calibrateOscillator() first does a binary search in the OSCCAL register for
the best matching oscillator frequency. Then it does a next neighbor search
to find the value with the lowest clock rate deviation. It is guaranteed to
find the best match among neighboring values, but for version 5 oscillators
(which have a discontinuous relationship between OSCCAL and frequency) a
better match might be available in another OSCCAL region.
Limitations:
This calibration algorithm may try OSCCAL values of up to 192 even if the
optimum value is far below 192. It may therefore exceed the allowed clock
frequency of the CPU in low voltage designs!
Precision depends on the OSCCAL vs. frequency dependency of the oscillator.
Typical precision for an ATMega168 (derived from the OSCCAL vs. F_RC diagram
in the data sheet) should be in the range of 0.4%. Only the 12.8 MHz and
16.5 MHz versions of V-USB (with built-in receiver PLL) can tolerate this
deviation! All other frequency modules require at least 0.2% precision.
*/
#ifndef __OSCCAL_H_INCLUDED__
#define __OSCCAL_H_INCLUDED__
void calibrateOscillator(void);
/* This function calibrates the RC oscillator so that the CPU runs at F_CPU.
* It MUST be called immediately after the end of a USB RESET condition!
* Disable all interrupts during the call!
* It is recommended that you store the resulting value in EEPROM so that a
* good guess value is available after the next reset.
*/
#endif /* __OSCCAL_H_INCLUDED__ */

View File

@ -0,0 +1,87 @@
/* Name: osctune.h
* Author: Christian Starkjohann
* Creation Date: 2008-10-18
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
General Description:
This file is declared as C-header file although it is mostly documentation
how the RC oscillator can be kept in sync to the USB frame rate. The code
shown here must be added to usbconfig.h or this header file is included from
there. This code works only if D- is wired to the interrupt, not D+!!!
This is an alternative to the osccal routine in osccal.c. It has the advantage
that the synchronization is done continuously and that it has more compact
code size. The disadvantages are slow synchronization (it may take a while
until the driver works), that messages immediately after the SOF pulse may be
lost (and need to be retried by the host) and that the interrupt is on D-
contrary to most examples.
You may want to store a good calibration value in EEPROM for the next startup.
You know that the calibration value is good when the first USB message is
received. Do not store the value on every received message because the EEPROM
has a limited endurance.
Notes:
(*) You must declare the global character variable "lastTimer0Value" in your
main code.
(*) Timer 0 must be free running (not written by your code) and the prescaling
must be consistent with the TIMER0_PRESCALING define.
(*) Good values for Timer 0 prescaling depend on how precise the clock must
be tuned and how far away from the default clock rate the target clock is.
For precise tuning, choose a low prescaler factor, for a broad range of tuning
choose a high one. A prescaler factor of 64 is good for the entire OSCCAL
range and allows a precision of better than +/-1%. A prescaler factor of 8
allows tuning to slightly more than +/-6% of the default frequency and is
more precise than one step of OSCCAL. It is therefore not suitable to tune an
8 MHz oscillator to 12.5 MHz.
Thanks to Henrik Haftmann for the idea to this routine!
*/
#define TIMER0_PRESCALING 64 /* must match the configuration for TIMER0 in main */
#define TOLERATED_DEVIATION_PPT 5 /* max clock deviation before we tune in 1/10 % */
/* derived constants: */
#define EXPECTED_TIMER0_INCREMENT ((F_CPU / (1000 * TIMER0_PRESCALING)) & 0xff)
#define TOLERATED_DEVIATION (TOLERATED_DEVIATION_PPT * F_CPU / (1000000 * TIMER0_PRESCALING))
#ifdef __ASSEMBLER__
macro tuneOsccal
push YH ;[0]
in YL, TCNT0 ;[2]
lds YH, lastTimer0Value ;[3]
sts lastTimer0Value, YL ;[5]
sub YL, YH ;[7] time passed since last frame
subi YL, EXPECTED_TIMER0_INCREMENT ;[8]
#if OSCCAL > 0x3f /* outside I/O addressable range */
lds YH, OSCCAL ;[6]
#else
in YH, OSCCAL ;[6] assembler modle uses __SFR_OFFSET == 0
#endif
cpi YL, TOLERATED_DEVIATION + 1 ;[10]
brmi notTooHigh ;[11]
subi YH, 1 ;[12] clock rate was too high
; brcs tuningOverflow ; optionally check for overflow
rjmp osctuneDone ;[13]
notTooHigh:
cpi YL, -TOLERATED_DEVIATION ;[13]
brpl osctuneDone ;[14] not too low
inc YH ;[15] clock rate was too low
; breq tuningOverflow ; optionally check for overflow
osctuneDone:
#if OSCCAL > 0x3f /* outside I/O addressable range */
sts OSCCAL, YH ;[12-13] store tuned value
#else
out OSCCAL, YH ;[12-13] store tuned value
#endif
tuningOverflow:
pop YH ;[17]
endm ;[19] max number of cycles
#endif
#define USB_SOF_HOOK tuneOsccal

View File

@ -0,0 +1,26 @@
This is the Readme file for the libs-host directory. This directory contains
code snippets which may be useful for host side USB software.
WHAT IS INCLUDED IN THIS DIRECTORY?
===================================
opendevice.c and opendevice.h
This module contains a function to find and open a device given its
numeric IDs (VID, PID), names (vendor name and product name) and serial
number. It is based on libusb/libusb-win32 and returns a libusb device
handle. See opendevice.h for an API documentation.
hiddata.c and hiddata.h
This module contains functions for data transfer over HID feature reports.
It is based on libusb on Unix and native Windows functions on Windows. No
driver DLL is needed on Windows. See hiddata.h for an API documentation.
hidsdi.h
This DDK header file is missing in the free MinGW version of the Windows
DDK. Use this version if you get an "include file not found" error.
----------------------------------------------------------------------------
(c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH.
http://www.obdev.at/

View File

@ -0,0 +1,323 @@
/* Name: hiddata.c
* Author: Christian Starkjohann
* Creation Date: 2008-04-11
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
#include <stdio.h>
#include "hiddata.h"
/* ######################################################################## */
#if defined(WIN32) /* ##################################################### */
/* ######################################################################## */
#include <windows.h>
#include <setupapi.h>
#include "hidsdi.h"
#include <ddk/hidpi.h>
#ifdef DEBUG
#define DEBUG_PRINT(arg) printf arg
#else
#define DEBUG_PRINT(arg)
#endif
/* ------------------------------------------------------------------------ */
static void convertUniToAscii(char *buffer)
{
unsigned short *uni = (void *)buffer;
char *ascii = buffer;
while(*uni != 0){
if(*uni >= 256){
*ascii++ = '?';
}else{
*ascii++ = *uni++;
}
}
*ascii++ = 0;
}
int usbhidOpenDevice(usbDevice_t **device, int vendor, char *vendorName, int product, char *productName, int usesReportIDs)
{
GUID hidGuid; /* GUID for HID driver */
HDEVINFO deviceInfoList;
SP_DEVICE_INTERFACE_DATA deviceInfo;
SP_DEVICE_INTERFACE_DETAIL_DATA *deviceDetails = NULL;
DWORD size;
int i, openFlag = 0; /* may be FILE_FLAG_OVERLAPPED */
int errorCode = USBOPEN_ERR_NOTFOUND;
HANDLE handle = INVALID_HANDLE_VALUE;
HIDD_ATTRIBUTES deviceAttributes;
HidD_GetHidGuid(&hidGuid);
deviceInfoList = SetupDiGetClassDevs(&hidGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
deviceInfo.cbSize = sizeof(deviceInfo);
for(i=0;;i++){
if(handle != INVALID_HANDLE_VALUE){
CloseHandle(handle);
handle = INVALID_HANDLE_VALUE;
}
if(!SetupDiEnumDeviceInterfaces(deviceInfoList, 0, &hidGuid, i, &deviceInfo))
break; /* no more entries */
/* first do a dummy call just to determine the actual size required */
SetupDiGetDeviceInterfaceDetail(deviceInfoList, &deviceInfo, NULL, 0, &size, NULL);
if(deviceDetails != NULL)
free(deviceDetails);
deviceDetails = malloc(size);
deviceDetails->cbSize = sizeof(*deviceDetails);
/* this call is for real: */
SetupDiGetDeviceInterfaceDetail(deviceInfoList, &deviceInfo, deviceDetails, size, &size, NULL);
DEBUG_PRINT(("checking HID path \"%s\"\n", deviceDetails->DevicePath));
#if 0
/* If we want to access a mouse our keyboard, we can only use feature
* requests as the device is locked by Windows. It must be opened
* with ACCESS_TYPE_NONE.
*/
handle = CreateFile(deviceDetails->DevicePath, ACCESS_TYPE_NONE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, openFlag, NULL);
#endif
/* attempt opening for R/W -- we don't care about devices which can't be accessed */
handle = CreateFile(deviceDetails->DevicePath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, openFlag, NULL);
if(handle == INVALID_HANDLE_VALUE){
DEBUG_PRINT(("opening failed: %d\n", (int)GetLastError()));
/* errorCode = USBOPEN_ERR_ACCESS; opening will always fail for mouse -- ignore */
continue;
}
deviceAttributes.Size = sizeof(deviceAttributes);
HidD_GetAttributes(handle, &deviceAttributes);
DEBUG_PRINT(("device attributes: vid=%d pid=%d\n", deviceAttributes.VendorID, deviceAttributes.ProductID));
if(deviceAttributes.VendorID != vendor || deviceAttributes.ProductID != product)
continue; /* ignore this device */
errorCode = USBOPEN_ERR_NOTFOUND;
if(vendorName != NULL && productName != NULL){
char buffer[512];
if(!HidD_GetManufacturerString(handle, buffer, sizeof(buffer))){
DEBUG_PRINT(("error obtaining vendor name\n"));
errorCode = USBOPEN_ERR_IO;
continue;
}
convertUniToAscii(buffer);
DEBUG_PRINT(("vendorName = \"%s\"\n", buffer));
if(strcmp(vendorName, buffer) != 0)
continue;
if(!HidD_GetProductString(handle, buffer, sizeof(buffer))){
DEBUG_PRINT(("error obtaining product name\n"));
errorCode = USBOPEN_ERR_IO;
continue;
}
convertUniToAscii(buffer);
DEBUG_PRINT(("productName = \"%s\"\n", buffer));
if(strcmp(productName, buffer) != 0)
continue;
}
break; /* we have found the device we are looking for! */
}
SetupDiDestroyDeviceInfoList(deviceInfoList);
if(deviceDetails != NULL)
free(deviceDetails);
if(handle != INVALID_HANDLE_VALUE){
*device = (usbDevice_t *)handle;
errorCode = 0;
}
return errorCode;
}
/* ------------------------------------------------------------------------ */
void usbhidCloseDevice(usbDevice_t *device)
{
CloseHandle((HANDLE)device);
}
/* ------------------------------------------------------------------------ */
int usbhidSetReport(usbDevice_t *device, char *buffer, int len)
{
BOOLEAN rval;
rval = HidD_SetFeature((HANDLE)device, buffer, len);
return rval == 0 ? USBOPEN_ERR_IO : 0;
}
/* ------------------------------------------------------------------------ */
int usbhidGetReport(usbDevice_t *device, int reportNumber, char *buffer, int *len)
{
BOOLEAN rval = 0;
buffer[0] = reportNumber;
rval = HidD_GetFeature((HANDLE)device, buffer, *len);
return rval == 0 ? USBOPEN_ERR_IO : 0;
}
/* ------------------------------------------------------------------------ */
/* ######################################################################## */
#else /* defined WIN32 #################################################### */
/* ######################################################################## */
#include <string.h>
#include <usb.h>
#define usbDevice usb_dev_handle /* use libusb's device structure */
/* ------------------------------------------------------------------------- */
#define USBRQ_HID_GET_REPORT 0x01
#define USBRQ_HID_SET_REPORT 0x09
#define USB_HID_REPORT_TYPE_FEATURE 3
static int usesReportIDs;
/* ------------------------------------------------------------------------- */
static int usbhidGetStringAscii(usb_dev_handle *dev, int index, char *buf, int buflen)
{
char buffer[256];
int rval, i;
if((rval = usb_get_string_simple(dev, index, buf, buflen)) >= 0) /* use libusb version if it works */
return rval;
if((rval = usb_control_msg(dev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR, (USB_DT_STRING << 8) + index, 0x0409, buffer, sizeof(buffer), 5000)) < 0)
return rval;
if(buffer[1] != USB_DT_STRING){
*buf = 0;
return 0;
}
if((unsigned char)buffer[0] < rval)
rval = (unsigned char)buffer[0];
rval /= 2;
/* lossy conversion to ISO Latin1: */
for(i=1;i<rval;i++){
if(i > buflen) /* destination buffer overflow */
break;
buf[i-1] = buffer[2 * i];
if(buffer[2 * i + 1] != 0) /* outside of ISO Latin1 range */
buf[i-1] = '?';
}
buf[i-1] = 0;
return i-1;
}
int usbhidOpenDevice(usbDevice_t **device, int vendor, char *vendorName, int product, char *productName, int _usesReportIDs)
{
struct usb_bus *bus;
struct usb_device *dev;
usb_dev_handle *handle = NULL;
int errorCode = USBOPEN_ERR_NOTFOUND;
static int didUsbInit = 0;
if(!didUsbInit){
usb_init();
didUsbInit = 1;
}
usb_find_busses();
usb_find_devices();
for(bus=usb_get_busses(); bus; bus=bus->next){
for(dev=bus->devices; dev; dev=dev->next){
if(dev->descriptor.idVendor == vendor && dev->descriptor.idProduct == product){
char string[256];
int len;
handle = usb_open(dev); /* we need to open the device in order to query strings */
if(!handle){
errorCode = USBOPEN_ERR_ACCESS;
fprintf(stderr, "Warning: cannot open USB device: %s\n", usb_strerror());
continue;
}
if(vendorName == NULL && productName == NULL){ /* name does not matter */
break;
}
/* now check whether the names match: */
len = usbhidGetStringAscii(handle, dev->descriptor.iManufacturer, string, sizeof(string));
if(len < 0){
errorCode = USBOPEN_ERR_IO;
fprintf(stderr, "Warning: cannot query manufacturer for device: %s\n", usb_strerror());
}else{
errorCode = USBOPEN_ERR_NOTFOUND;
/* fprintf(stderr, "seen device from vendor ->%s<-\n", string); */
if(strcmp(string, vendorName) == 0){
len = usbhidGetStringAscii(handle, dev->descriptor.iProduct, string, sizeof(string));
if(len < 0){
errorCode = USBOPEN_ERR_IO;
fprintf(stderr, "Warning: cannot query product for device: %s\n", usb_strerror());
}else{
errorCode = USBOPEN_ERR_NOTFOUND;
/* fprintf(stderr, "seen product ->%s<-\n", string); */
if(strcmp(string, productName) == 0)
break;
}
}
}
usb_close(handle);
handle = NULL;
}
}
if(handle)
break;
}
if(handle != NULL){
errorCode = 0;
*device = (void *)handle;
usesReportIDs = _usesReportIDs;
}
return errorCode;
}
/* ------------------------------------------------------------------------- */
void usbhidCloseDevice(usbDevice_t *device)
{
if(device != NULL)
usb_close((void *)device);
}
/* ------------------------------------------------------------------------- */
int usbhidSetReport(usbDevice_t *device, char *buffer, int len)
{
int bytesSent, reportId = buffer[0];
if(!usesReportIDs){
buffer++; /* skip dummy report ID */
len--;
}
bytesSent = usb_control_msg((void *)device, USB_TYPE_CLASS | USB_RECIP_DEVICE | USB_ENDPOINT_OUT, USBRQ_HID_SET_REPORT, USB_HID_REPORT_TYPE_FEATURE << 8 | (reportId & 0xff), 0, buffer, len, 5000);
if(bytesSent != len){
if(bytesSent < 0)
fprintf(stderr, "Error sending message: %s\n", usb_strerror());
return USBOPEN_ERR_IO;
}
return 0;
}
/* ------------------------------------------------------------------------- */
int usbhidGetReport(usbDevice_t *device, int reportNumber, char *buffer, int *len)
{
int bytesReceived, maxLen = *len;
if(!usesReportIDs){
buffer++; /* make room for dummy report ID */
maxLen--;
}
bytesReceived = usb_control_msg((void *)device, USB_TYPE_CLASS | USB_RECIP_DEVICE | USB_ENDPOINT_IN, USBRQ_HID_GET_REPORT, USB_HID_REPORT_TYPE_FEATURE << 8 | reportNumber, 0, buffer, maxLen, 5000);
if(bytesReceived < 0){
fprintf(stderr, "Error sending message: %s\n", usb_strerror());
return USBOPEN_ERR_IO;
}
*len = bytesReceived;
if(!usesReportIDs){
buffer[-1] = reportNumber; /* add dummy report ID */
(*len)++;
}
return 0;
}
/* ######################################################################## */
#endif /* defined WIN32 ################################################### */
/* ######################################################################## */

View File

@ -0,0 +1,70 @@
/* Name: hiddata.h
* Author: Christian Starkjohann
* Creation Date: 2008-04-11
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
#ifndef __HIDDATA_H_INCLUDED__
#define __HIDDATA_H_INCLUDED__
/*
General Description:
This module implements an abstraction layer for data transfer over HID feature
requests. The implementation uses native Windows functions on Windows so that
no driver installation is required and libusb on Unix. You must link the
appropriate libraries in either case: "-lhid -lusb -lsetupapi" on Windows and
`libusb-config --libs` on Unix.
*/
/* ------------------------------------------------------------------------ */
#define USBOPEN_SUCCESS 0 /* no error */
#define USBOPEN_ERR_ACCESS 1 /* not enough permissions to open device */
#define USBOPEN_ERR_IO 2 /* I/O error */
#define USBOPEN_ERR_NOTFOUND 3 /* device not found */
/* ------------------------------------------------------------------------ */
typedef struct usbDevice usbDevice_t;
/* Opaque data type representing the USB device. This can be a Windows handle
* or a libusb handle, depending on the backend implementation.
*/
/* ------------------------------------------------------------------------ */
int usbhidOpenDevice(usbDevice_t **device, int vendorID, char *vendorName, int productID, char *productName, int usesReportIDs);
/* This function opens a USB device. 'vendorID' and 'productID' are the numeric
* Vendor-ID and Product-ID of the device we want to open. If 'vendorName' and
* 'productName' are both not NULL, only devices with matching manufacturer-
* and product name strings are accepted. If the device uses report IDs,
* 'usesReportIDs' must be set to a non-zero value.
* Returns: If a matching device has been found, USBOPEN_SUCCESS is returned
* and '*device' is set to an opaque pointer representing the device. The
* device must be closed with usbhidCloseDevice(). If the device has not been
* found or opening failed, an error code is returned.
*/
void usbhidCloseDevice(usbDevice_t *device);
/* Every device opened with usbhidOpenDevice() must be closed with this function.
*/
int usbhidSetReport(usbDevice_t *device, char *buffer, int len);
/* This function sends a feature report to the device. The report ID must be
* in the first byte of buffer and the length 'len' of the report is specified
* including this report ID. If no report IDs are used, buffer[0] must be set
* to 0 (dummy report ID).
* Returns: 0 on success, an error code otherwise.
*/
int usbhidGetReport(usbDevice_t *device, int reportID, char *buffer, int *len);
/* This function obtains a feature report from the device. The requested
* report-ID is passed in 'reportID'. The caller must pass a buffer of the size
* of the expected report in 'buffer' and initialize the variable pointed to by
* 'len' to the total size of this buffer. Upon successful return, the report
* (prefixed with the report-ID) is in 'buffer' and the actual length of the
* report is returned in '*len'.
* Returns: 0 on success, an error code otherwise.
*/
/* ------------------------------------------------------------------------ */
#endif /* __HIDDATA_H_INCLUDED__ */

View File

@ -0,0 +1,48 @@
/* Name: hidsdi.h
* Author: Christian Starkjohann
* Creation Date: 2006-02-02
* Tabsize: 4
* Copyright: (c) 2006-2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
General Description
This file is a replacement for hidsdi.h from the Windows DDK. It defines some
of the types and function prototypes of this header for our project. If you
have the Windows DDK version of this file or a version shipped with MinGW, use
that instead.
*/
#ifndef _HIDSDI_H
#define _HIDSDI_H
#include <pshpack4.h>
#include <ddk/hidusage.h>
#include <ddk/hidpi.h>
typedef struct{
ULONG Size;
USHORT VendorID;
USHORT ProductID;
USHORT VersionNumber;
}HIDD_ATTRIBUTES;
void __stdcall HidD_GetHidGuid(OUT LPGUID hidGuid);
BOOLEAN __stdcall HidD_GetAttributes(IN HANDLE device, OUT HIDD_ATTRIBUTES *attributes);
BOOLEAN __stdcall HidD_GetManufacturerString(IN HANDLE device, OUT void *buffer, IN ULONG bufferLen);
BOOLEAN __stdcall HidD_GetProductString(IN HANDLE device, OUT void *buffer, IN ULONG bufferLen);
BOOLEAN __stdcall HidD_GetSerialNumberString(IN HANDLE device, OUT void *buffer, IN ULONG bufferLen);
BOOLEAN __stdcall HidD_GetFeature(IN HANDLE device, OUT void *reportBuffer, IN ULONG bufferLen);
BOOLEAN __stdcall HidD_SetFeature(IN HANDLE device, IN void *reportBuffer, IN ULONG bufferLen);
BOOLEAN __stdcall HidD_GetNumInputBuffers(IN HANDLE device, OUT ULONG *numBuffers);
BOOLEAN __stdcall HidD_SetNumInputBuffers(IN HANDLE device, OUT ULONG numBuffers);
#include <poppack.h>
#endif

View File

@ -0,0 +1,202 @@
/* Name: opendevice.c
* Project: V-USB host-side library
* Author: Christian Starkjohann
* Creation Date: 2008-04-10
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
General Description:
The functions in this module can be used to find and open a device based on
libusb or libusb-win32.
*/
#include <stdio.h>
#include "opendevice.h"
/* ------------------------------------------------------------------------- */
#define MATCH_SUCCESS 1
#define MATCH_FAILED 0
#define MATCH_ABORT -1
/* private interface: match text and p, return MATCH_SUCCESS, MATCH_FAILED, or MATCH_ABORT. */
static int _shellStyleMatch(char *text, char *p)
{
int last, matched, reverse;
for(; *p; text++, p++){
if(*text == 0 && *p != '*')
return MATCH_ABORT;
switch(*p){
case '\\':
/* Literal match with following character. */
p++;
/* FALLTHROUGH */
default:
if(*text != *p)
return MATCH_FAILED;
continue;
case '?':
/* Match anything. */
continue;
case '*':
while(*++p == '*')
/* Consecutive stars act just like one. */
continue;
if(*p == 0)
/* Trailing star matches everything. */
return MATCH_SUCCESS;
while(*text)
if((matched = _shellStyleMatch(text++, p)) != MATCH_FAILED)
return matched;
return MATCH_ABORT;
case '[':
reverse = p[1] == '^';
if(reverse) /* Inverted character class. */
p++;
matched = MATCH_FAILED;
if(p[1] == ']' || p[1] == '-')
if(*++p == *text)
matched = MATCH_SUCCESS;
for(last = *p; *++p && *p != ']'; last = *p)
if (*p == '-' && p[1] != ']' ? *text <= *++p && *text >= last : *text == *p)
matched = MATCH_SUCCESS;
if(matched == reverse)
return MATCH_FAILED;
continue;
}
}
return *text == 0;
}
/* public interface for shell style matching: returns 0 if fails, 1 if matches */
static int shellStyleMatch(char *text, char *pattern)
{
if(pattern == NULL) /* NULL pattern is synonymous to "*" */
return 1;
return _shellStyleMatch(text, pattern) == MATCH_SUCCESS;
}
/* ------------------------------------------------------------------------- */
int usbGetStringAscii(usb_dev_handle *dev, int index, char *buf, int buflen)
{
char buffer[256];
int rval, i;
if((rval = usb_get_string_simple(dev, index, buf, buflen)) >= 0) /* use libusb version if it works */
return rval;
if((rval = usb_control_msg(dev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR, (USB_DT_STRING << 8) + index, 0x0409, buffer, sizeof(buffer), 5000)) < 0)
return rval;
if(buffer[1] != USB_DT_STRING){
*buf = 0;
return 0;
}
if((unsigned char)buffer[0] < rval)
rval = (unsigned char)buffer[0];
rval /= 2;
/* lossy conversion to ISO Latin1: */
for(i=1;i<rval;i++){
if(i > buflen) /* destination buffer overflow */
break;
buf[i-1] = buffer[2 * i];
if(buffer[2 * i + 1] != 0) /* outside of ISO Latin1 range */
buf[i-1] = '?';
}
buf[i-1] = 0;
return i-1;
}
/* ------------------------------------------------------------------------- */
int usbOpenDevice(usb_dev_handle **device, int vendorID, char *vendorNamePattern, int productID, char *productNamePattern, char *serialNamePattern, FILE *printMatchingDevicesFp, FILE *warningsFp)
{
struct usb_bus *bus;
struct usb_device *dev;
usb_dev_handle *handle = NULL;
int errorCode = USBOPEN_ERR_NOTFOUND;
usb_find_busses();
usb_find_devices();
for(bus = usb_get_busses(); bus; bus = bus->next){
for(dev = bus->devices; dev; dev = dev->next){ /* iterate over all devices on all busses */
if((vendorID == 0 || dev->descriptor.idVendor == vendorID)
&& (productID == 0 || dev->descriptor.idProduct == productID)){
char vendor[256], product[256], serial[256];
int len;
handle = usb_open(dev); /* we need to open the device in order to query strings */
if(!handle){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot open VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
continue;
}
/* now check whether the names match: */
len = vendor[0] = 0;
if(dev->descriptor.iManufacturer > 0){
len = usbGetStringAscii(handle, dev->descriptor.iManufacturer, vendor, sizeof(vendor));
}
if(len < 0){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot query manufacturer for VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
}else{
errorCode = USBOPEN_ERR_NOTFOUND;
/* printf("seen device from vendor ->%s<-\n", vendor); */
if(shellStyleMatch(vendor, vendorNamePattern)){
len = product[0] = 0;
if(dev->descriptor.iProduct > 0){
len = usbGetStringAscii(handle, dev->descriptor.iProduct, product, sizeof(product));
}
if(len < 0){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot query product for VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
}else{
errorCode = USBOPEN_ERR_NOTFOUND;
/* printf("seen product ->%s<-\n", product); */
if(shellStyleMatch(product, productNamePattern)){
len = serial[0] = 0;
if(dev->descriptor.iSerialNumber > 0){
len = usbGetStringAscii(handle, dev->descriptor.iSerialNumber, serial, sizeof(serial));
}
if(len < 0){
errorCode = USBOPEN_ERR_ACCESS;
if(warningsFp != NULL)
fprintf(warningsFp, "Warning: cannot query serial for VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
}
if(shellStyleMatch(serial, serialNamePattern)){
if(printMatchingDevicesFp != NULL){
if(serial[0] == 0){
fprintf(printMatchingDevicesFp, "VID=0x%04x PID=0x%04x vendor=\"%s\" product=\"%s\"\n", dev->descriptor.idVendor, dev->descriptor.idProduct, vendor, product);
}else{
fprintf(printMatchingDevicesFp, "VID=0x%04x PID=0x%04x vendor=\"%s\" product=\"%s\" serial=\"%s\"\n", dev->descriptor.idVendor, dev->descriptor.idProduct, vendor, product, serial);
}
}else{
break;
}
}
}
}
}
}
usb_close(handle);
handle = NULL;
}
}
if(handle) /* we have found a deice */
break;
}
if(handle != NULL){
errorCode = 0;
*device = handle;
}
if(printMatchingDevicesFp != NULL) /* never return an error for listing only */
errorCode = 0;
return errorCode;
}
/* ------------------------------------------------------------------------- */

View File

@ -0,0 +1,76 @@
/* Name: opendevice.h
* Project: V-USB host-side library
* Author: Christian Starkjohann
* Creation Date: 2008-04-10
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
General Description:
This module offers additional functionality for host side drivers based on
libusb or libusb-win32. It includes a function to find and open a device
based on numeric IDs and textual description. It also includes a function to
obtain textual descriptions from a device.
To use this functionality, simply copy opendevice.c and opendevice.h into your
project and add them to your Makefile. You may modify and redistribute these
files according to the GNU General Public License (GPL) version 2 or 3.
*/
#ifndef __OPENDEVICE_H_INCLUDED__
#define __OPENDEVICE_H_INCLUDED__
#include <usb.h> /* this is libusb, see http://libusb.sourceforge.net/ */
#include <stdio.h>
int usbGetStringAscii(usb_dev_handle *dev, int index, char *buf, int buflen);
/* This function gets a string descriptor from the device. 'index' is the
* string descriptor index. The string is returned in ISO Latin 1 encoding in
* 'buf' and it is terminated with a 0-character. The buffer size must be
* passed in 'buflen' to prevent buffer overflows. A libusb device handle
* must be given in 'dev'.
* Returns: The length of the string (excluding the terminating 0) or
* a negative number in case of an error. If there was an error, use
* usb_strerror() to obtain the error message.
*/
int usbOpenDevice(usb_dev_handle **device, int vendorID, char *vendorNamePattern, int productID, char *productNamePattern, char *serialNamePattern, FILE *printMatchingDevicesFp, FILE *warningsFp);
/* This function iterates over all devices on all USB busses and searches for
* a device. Matching is done first by means of Vendor- and Product-ID (passed
* in 'vendorID' and 'productID'. An ID of 0 matches any numeric ID (wildcard).
* When a device matches by its IDs, matching by names is performed. Name
* matching can be done on textual vendor name ('vendorNamePattern'), product
* name ('productNamePattern') and serial number ('serialNamePattern'). A
* device matches only if all non-null pattern match. If you don't care about
* a string, pass NULL for the pattern. Patterns are Unix shell style pattern:
* '*' stands for 0 or more characters, '?' for one single character, a list
* of characters in square brackets for a single character from the list
* (dashes are allowed to specify a range) and if the lis of characters begins
* with a caret ('^'), it matches one character which is NOT in the list.
* Other parameters to the function: If 'warningsFp' is not NULL, warning
* messages are printed to this file descriptor with fprintf(). If
* 'printMatchingDevicesFp' is not NULL, no device is opened but matching
* devices are printed to the given file descriptor with fprintf().
* If a device is opened, the resulting USB handle is stored in '*device'. A
* pointer to a "usb_dev_handle *" type variable must be passed here.
* Returns: 0 on success, an error code (see defines below) on failure.
*/
/* usbOpenDevice() error codes: */
#define USBOPEN_SUCCESS 0 /* no error */
#define USBOPEN_ERR_ACCESS 1 /* not enough permissions to open device */
#define USBOPEN_ERR_IO 2 /* I/O error */
#define USBOPEN_ERR_NOTFOUND 3 /* device not found */
/* Obdev's free USB IDs, see USB-IDs-for-free.txt for details */
#define USB_VID_OBDEV_SHARED 5824 /* obdev's shared vendor ID */
#define USB_PID_OBDEV_SHARED_CUSTOM 1500 /* shared PID for custom class devices */
#define USB_PID_OBDEV_SHARED_HID 1503 /* shared PID for HIDs except mice & keyboards */
#define USB_PID_OBDEV_SHARED_CDCACM 1505 /* shared PID for CDC Modem devices */
#define USB_PID_OBDEV_SHARED_MIDI 1508 /* shared PID for MIDI class devices */
#endif /* __OPENDEVICE_H_INCLUDED__ */

View File

@ -0,0 +1,126 @@
# Name: Makefile
# Project: custom-class example
# Author: Christian Starkjohann
# Creation Date: 2008-04-07
# Tabsize: 4
# Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
DEVICE = attiny2313
F_CPU = 16000000 # in Hz
DEFINES =
CFLAGS = $(DEFINES) -Iusbdrv -I. -DDEBUG_LEVEL=0
OBJECTS = usbdrv/usbdrv.o usbdrv/usbdrvasm.o usbdrv/oddebug.o main.o
COMPILE = avr-gcc -Wall -Os -DF_CPU=$(F_CPU) $(CFLAGS) -mmcu=$(DEVICE)
SIZES_TMP = /tmp/sizetmp.txt
# symbolic targets:
help:
@echo "This Makefile has no default rule. Use one of the following:"
@echo "make clean ..... to delete objects and hex file"
@echo "make sizes ..... compute code and RAM sizes for various options"
@echo "make test ...... test with all features whether everything compiles"
sizes sizes.txt:
rm -f $(SIZES_TMP) sizes.txt
$(MAKE) null.elf
avr-size null.elf | tail -1 | awk '{print "null", $$1+$$2, $$3+$$2}' >$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf
avr-size main.elf | tail -1 | awk '{print "Minimum_with_16_MHz", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf F_CPU=12000000
avr-size main.elf | tail -1 | awk '{print "Minimum_with_12_MHz", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf F_CPU=12800000
avr-size main.elf | tail -1 | awk '{print "Minimum_with_12_8_MHz", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf F_CPU=15000000
avr-size main.elf | tail -1 | awk '{print "Minimum_with_15_MHz", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf F_CPU=16500000
avr-size main.elf | tail -1 | awk '{print "Minimum_with_16_5_MHz", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf F_CPU=18000000
avr-size main.elf | tail -1 | awk '{print "Minimum_with_18_MHz+CRC", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf F_CPU=20000000
avr-size main.elf | tail -1 | awk '{print "Minimum_with_20_MHz", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf DEFINES=-DUSB_CFG_IMPLEMENT_FN_WRITE=1
avr-size main.elf | tail -1 | awk '{print "With_usbFunctionWrite", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf DEFINES=-DUSB_CFG_IMPLEMENT_FN_READ=1
avr-size main.elf | tail -1 | awk '{print "With_usbFunctionRead", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf "DEFINES=-DUSB_CFG_IMPLEMENT_FN_READ=1 -DUSB_CFG_IMPLEMENT_FN_WRITE=1"
avr-size main.elf | tail -1 | awk '{print "With_usbFunctionRead_and_Write", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf "DEFINES=-DUSB_CFG_IMPLEMENT_FN_WRITEOUT=1"
avr-size main.elf | tail -1 | awk '{print "With_usbFunctionWriteOut", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf "DEFINES=-DUSB_CFG_HAVE_INTRIN_ENDPOINT=1"
avr-size main.elf | tail -1 | awk '{print "With_Interrupt_In_Endpoint_1", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf "DEFINES=-DUSB_CFG_IMPLEMENT_HALT=1 -DUSB_CFG_HAVE_INTRIN_ENDPOINT=1"
avr-size main.elf | tail -1 | awk '{print "With_Interrupt_In_Endpoint_1_and_Halt", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf "DEFINES=-DUSB_CFG_HAVE_INTRIN_ENDPOINT3=1"
avr-size main.elf | tail -1 | awk '{print "With_Interrupt_In_Endpoint_1_and_3", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf "DEFINES=-DUSE_DYNAMIC_DESCRIPTOR=1"
avr-size main.elf | tail -1 | awk '{print "With_Dynamic_Descriptor", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
$(MAKE) clean; $(MAKE) main.elf "DEFINES=-DUSB_CFG_LONG_TRANSFERS=1"
avr-size main.elf | tail -1 | awk '{print "With_Long_Transfers", $$1+$$2, $$3+$$2}' >>$(SIZES_TMP)
cat $(SIZES_TMP) | awk 'BEGIN{printf("%39s %5s %5s %5s %5s\n"), "Variation", "Flash", "RAM", "+F", "+RAM"}\
/^null/{nullRom=$$2; nullRam=$$3; next} \
{rom=$$2-nullRom; ram=$$3-nullRam; if(!refRom){refRom=rom; refRam=ram} \
printf("%39s %5d %5d %+5d %+5d\n", $$1, rom, ram, rom-refRom, ram-refRam)}' | tee sizes.txt
rm $(SIZES_TMP)
test:
for freq in 12000000 12800000 15000000 16000000 16500000 18000000 20000000; do \
for opt in USB_COUNT_SOF USB_CFG_HAVE_INTRIN_ENDPOINT USB_CFG_HAVE_INTRIN_ENDPOINT3 USB_CFG_HAVE_MEASURE_FRAME_LENGTH USB_CFG_LONG_TRANSFERS; do \
$(MAKE) clean; $(MAKE) main.elf F_CPU=$$freq "DEFINES=-D$$opt=1" || exit 1; \
$(MAKE) clean; $(MAKE) main.elf F_CPU=$$freq "DEFINES=-D$$opt=1 -DDUSB_CFG_IMPLEMENT_FN_WRITEOUT=1" || exit 1; \
done \
done
# The following rule is used to check the compiler
devices: #exclude devices without RAM for stack and atmega603 for gcc 3
excludes="at90s1200 attiny11 attiny12 attiny15 attiny28"; \
for gccVersion in 3 4; do \
avr-gcc-select $$gccVersion; \
for device in `echo | avr-gcc -xc -mmcu=x - 2>&1 | egrep '^ *at[a-zA-Z0-9_-]+$$'`; do \
if echo "$$excludes" | grep "$$device" >/dev/null; then continue; fi; \
if [ "$$gccVersion" = 3 -a "$$device" = atmega603 ]; then continue; fi; \
$(MAKE) clean; $(MAKE) null.elf DEVICE=$$device || exit 1; \
done \
done
$(MAKE) clean
avr-gcc-select 3
@echo "+++ Device test succeeded!"
# rule for deleting dependent files (those which can be built by Make):
clean:
rm -f *.hex *.lst *.map *.elf *.o
rm -rf usbdrv
# Generic rule for compiling C files:
.c.o:
$(COMPILE) -c $< -o $@
# Generic rule for assembling Assembler source files:
.S.o:
$(COMPILE) -x assembler-with-cpp -c $< -o $@
# "-x assembler-with-cpp" should not be necessary since this is the default
# file type for the .S (with capital S) extension. However, upper case
# characters are not always preserved on Windows. To ensure WinAVR
# compatibility define the file type manually.
# Generic rule for compiling C to assembler, used for debugging only.
.c.s:
$(COMPILE) -S $< -o $@
# file targets:
# Since we don't want to ship the driver multipe times, we copy it into this project:
usbdrv:
cp -r ../usbdrv .
main.elf: usbdrv $(OBJECTS) # usbdrv dependency only needed because we copy it
$(COMPILE) -o main.elf $(OBJECTS)
main_i.elf: usbdrv main.o usbdrv/usbdrvasm.o # usbdrv dependency only needed because we copy it
$(COMPILE) -o main_i.elf main.o usbdrv/usbdrvasm.o
null.elf: null.o
$(COMPILE) -o null.elf null.o

View File

@ -0,0 +1,13 @@
This is the Readme file for the directory "tests" of V-USB, a firmware-only
USB driver for AVR microcontrollers.
WHAT IS IN THIS DIRECTORY?
==========================
This directory is for driver development only. It contains tests to check
whether all branches of #ifdef code compile as they should and whether the
code size of the driver increased.
----------------------------------------------------------------------------
(c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH.
http://www.obdev.at/

View File

@ -0,0 +1,44 @@
#!/usr/bin/awk -f
# Name: compare-sizes.awk
# Project: v-usb
# Author: Christian Starkjohann
# Creation Date: 2008-04-29
# Tabsize: 4
# Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
# License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
BEGIN{
opt = 0;
if(ARGC != 3){
printf("usage: compare-sizes.awk file1 file2\n");
printf(" computes size differences between two size lists\n");
exit 1;
}
file1 = ARGV[1];
file2 = ARGV[2];
}
{
if(($2 + 0) != 0){
if(!hadOption[$1]){
hadOption[$1] = 1;
options[opt++] = $1;
}
flash[FILENAME, $1] = $2;
ram[FILENAME, $1] = $3;
}
}
END{
if(opt > 0){
printf ("%39s %6s %5s\n", "Variation", "+Flash", "+RAM");
}
for(i = 0; i < opt; i++){
option = options[i];
if(!flash[file2, option] || !flash[file1, option]){
printf("%39s %6s %5s\n", option, "n/a", "n/a");
}else{
printf("%39s %+6d %+5d\n", option, flash[file2, option] - flash[file1, option], ram[file2, option] - ram[file1, option]);
}
}
}

View File

@ -0,0 +1,158 @@
/* Name: main.c
* Project: Testing driver features
* Author: Christian Starkjohann
* Creation Date: 2008-04-29
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
This module is a do-nothing test code linking against (or including) the USB
driver. It is used to determine the code size for various options and to
check whether the code compiles with all options.
*/
#include <avr/io.h>
#include <avr/interrupt.h> /* for sei() */
#include <avr/pgmspace.h> /* required by usbdrv.h */
#include <util/delay.h> /* for _delay_ms() */
#include "usbdrv.h"
#if USE_INCLUDE
#include "usbdrv.c"
#endif
/* ------------------------------------------------------------------------- */
/* ----------------------------- USB interface ----------------------------- */
/* ------------------------------------------------------------------------- */
#if USB_CFG_IMPLEMENT_FN_WRITE
uchar usbFunctionWrite(uchar *data, uchar len)
{
return 1;
}
#endif
#if USB_CFG_IMPLEMENT_FN_READ
uchar usbFunctionRead(uchar *data, uchar len)
{
return len;
}
#endif
#if USB_CFG_IMPLEMENT_FN_WRITEOUT
void usbFunctionWriteOut(uchar *data, uchar len)
{
}
#endif
#if USE_DYNAMIC_DESCRIPTOR
static PROGMEM const char myDescriptorDevice[] = { /* USB device descriptor */
18, /* sizeof(usbDescriptorDevice): length of descriptor in bytes */
USBDESCR_DEVICE, /* descriptor type */
0x10, 0x01, /* USB version supported */
USB_CFG_DEVICE_CLASS,
USB_CFG_DEVICE_SUBCLASS,
0, /* protocol */
8, /* max packet size */
/* the following two casts affect the first byte of the constant only, but
* that's sufficient to avoid a warning with the default values.
*/
(char)USB_CFG_VENDOR_ID,/* 2 bytes */
(char)USB_CFG_DEVICE_ID,/* 2 bytes */
USB_CFG_DEVICE_VERSION, /* 2 bytes */
USB_CFG_DESCR_PROPS_STRING_VENDOR != 0 ? 1 : 0, /* manufacturer string index */
USB_CFG_DESCR_PROPS_STRING_PRODUCT != 0 ? 2 : 0, /* product string index */
USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER != 0 ? 3 : 0, /* serial number string index */
1, /* number of configurations */
};
static PROGMEM const char myDescriptorConfiguration[] = { /* USB configuration descriptor */
9, /* sizeof(usbDescriptorConfiguration): length of descriptor in bytes */
USBDESCR_CONFIG, /* descriptor type */
18 + 7 * USB_CFG_HAVE_INTRIN_ENDPOINT + (USB_CFG_DESCR_PROPS_HID & 0xff), 0,
/* total length of data returned (including inlined descriptors) */
1, /* number of interfaces in this configuration */
1, /* index of this configuration */
0, /* configuration name string index */
#if USB_CFG_IS_SELF_POWERED
USBATTR_SELFPOWER, /* attributes */
#else
0, /* attributes */
#endif
USB_CFG_MAX_BUS_POWER/2, /* max USB current in 2mA units */
/* interface descriptor follows inline: */
9, /* sizeof(usbDescrInterface): length of descriptor in bytes */
USBDESCR_INTERFACE, /* descriptor type */
0, /* index of this interface */
0, /* alternate setting for this interface */
USB_CFG_HAVE_INTRIN_ENDPOINT, /* endpoints excl 0: number of endpoint descriptors to follow */
USB_CFG_INTERFACE_CLASS,
USB_CFG_INTERFACE_SUBCLASS,
USB_CFG_INTERFACE_PROTOCOL,
0, /* string index for interface */
#if (USB_CFG_DESCR_PROPS_HID & 0xff) /* HID descriptor */
9, /* sizeof(usbDescrHID): length of descriptor in bytes */
USBDESCR_HID, /* descriptor type: HID */
0x01, 0x01, /* BCD representation of HID version */
0x00, /* target country code */
0x01, /* number of HID Report (or other HID class) Descriptor infos to follow */
0x22, /* descriptor type: report */
USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH, 0, /* total length of report descriptor */
#endif
#if USB_CFG_HAVE_INTRIN_ENDPOINT /* endpoint descriptor for endpoint 1 */
7, /* sizeof(usbDescrEndpoint) */
USBDESCR_ENDPOINT, /* descriptor type = endpoint */
(char)0x81, /* IN endpoint number 1 */
0x03, /* attrib: Interrupt endpoint */
8, 0, /* maximum packet size */
USB_CFG_INTR_POLL_INTERVAL, /* in ms */
#endif
};
USB_PUBLIC usbMsgLen_t usbFunctionDescriptor(usbRequest_t *rq)
{
uchar *p = 0, len = 0;
if(rq->wValue.bytes[1] == USBDESCR_DEVICE){
p = (uchar *)myDescriptorDevice;
len = sizeof(myDescriptorDevice);
}else{ /* must be configuration descriptor */
p = (uchar *)(myDescriptorConfiguration);
len = sizeof(myDescriptorConfiguration);
}
usbMsgPtr = (usbMsgPtr_t)p;
return len;
}
#endif
USB_PUBLIC usbMsgLen_t usbFunctionSetup(uchar data[8])
{
usbRequest_t *rq = (void *)data;
if(rq->bRequest == 0) /* request using usbFunctionRead()/usbFunctionWrite() */
return 0xff;
return 0; /* default for not implemented requests: return no data back to host */
}
/* ------------------------------------------------------------------------- */
int main(void)
{
uchar i;
usbInit();
usbDeviceDisconnect(); /* enforce re-enumeration, do this while interrupts are disabled! */
i = 0;
while(--i){ /* fake USB disconnect for > 250 ms */
_delay_ms(1);
}
usbDeviceConnect();
sei();
for(;;){ /* main event loop */
usbPoll();
}
return 0;
}
/* ------------------------------------------------------------------------- */

View File

@ -0,0 +1,25 @@
/* Name: null.c
* Project: Testing driver features
* Author: Christian Starkjohann
* Creation Date: 2008-04-29
* Tabsize: 4
* Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/*
This is a NULL main() function to find out the code size required by libusb's
startup code, interrupt vectors etc.
*/
#include <avr/io.h>
/* ------------------------------------------------------------------------- */
int main(void)
{
for(;;);
return 0;
}
/* ------------------------------------------------------------------------- */

View File

@ -0,0 +1,13 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1154 45 +0 +0
Minimum_with_12_MHz 1274 45 +120 +0
Minimum_with_15_MHz 1260 45 +106 +0
Minimum_with_16_5_MHz 1276 45 +122 +0
With_usbFunctionWrite 1214 45 +60 +0
With_usbFunctionRead 1200 45 +46 +0
With_usbFunctionRead_and_Write 1246 45 +92 +0
With_usbFunctionWriteOut 1178 45 +24 +0
With_Interrupt_In_Endpoint_1 1284 58 +130 +13
With_Interrupt_In_Endpoint_1_and_Halt 1372 58 +218 +13
With_Interrupt_In_Endpoint_1_and_3 1386 69 +232 +24
With_Dynamic_Descriptor 1186 45 +32 +0

View File

@ -0,0 +1,13 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1208 45 +0 +0
Minimum_with_12_MHz 1328 45 +120 +0
Minimum_with_15_MHz 1314 45 +106 +0
Minimum_with_16_5_MHz 1330 45 +122 +0
With_usbFunctionWrite 1268 45 +60 +0
With_usbFunctionRead 1264 45 +56 +0
With_usbFunctionRead_and_Write 1314 45 +106 +0
With_usbFunctionWriteOut 1218 45 +10 +0
With_Interrupt_In_Endpoint_1 1340 58 +132 +13
With_Interrupt_In_Endpoint_1_and_Halt 1414 58 +206 +13
With_Interrupt_In_Endpoint_1_and_3 1426 69 +218 +24
With_Dynamic_Descriptor 1238 45 +30 +0

View File

@ -0,0 +1,15 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1154 45 +0 +0
Minimum_with_12_MHz 1274 45 +120 +0
Minimum_with_15_MHz 1260 45 +106 +0
Minimum_with_16_5_MHz 1276 45 +122 +0
Minimum_with_20_MHz 1136 45 -18 +0
With_usbFunctionWrite 1214 45 +60 +0
With_usbFunctionRead 1192 45 +38 +0
With_usbFunctionRead_and_Write 1234 45 +80 +0
With_usbFunctionWriteOut 1178 45 +24 +0
With_Interrupt_In_Endpoint_1 1280 57 +126 +12
With_Interrupt_In_Endpoint_1_and_Halt 1370 57 +216 +12
With_Interrupt_In_Endpoint_1_and_3 1346 69 +192 +24
With_Dynamic_Descriptor 1182 45 +28 +0
With_Long_Transfers 1200 47 +46 +2

View File

@ -0,0 +1,15 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1192 45 +0 +0
Minimum_with_12_MHz 1312 45 +120 +0
Minimum_with_15_MHz 1298 45 +106 +0
Minimum_with_16_5_MHz 1314 45 +122 +0
Minimum_with_20_MHz 1174 45 -18 +0
With_usbFunctionWrite 1246 45 +54 +0
With_usbFunctionRead 1242 45 +50 +0
With_usbFunctionRead_and_Write 1280 45 +88 +0
With_usbFunctionWriteOut 1208 45 +16 +0
With_Interrupt_In_Endpoint_1 1320 57 +128 +12
With_Interrupt_In_Endpoint_1_and_Halt 1410 57 +218 +12
With_Interrupt_In_Endpoint_1_and_3 1428 69 +236 +24
With_Dynamic_Descriptor 1212 45 +20 +0
With_Long_Transfers 1270 47 +78 +2

View File

@ -0,0 +1,16 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1152 45 +0 +0
Minimum_with_12_MHz 1202 45 +50 +0
Minimum_with_12_8_MHz 1522 45 +370 +0
Minimum_with_15_MHz 1258 45 +106 +0
Minimum_with_16_5_MHz 1274 45 +122 +0
Minimum_with_20_MHz 1134 45 -18 +0
With_usbFunctionWrite 1212 45 +60 +0
With_usbFunctionRead 1190 45 +38 +0
With_usbFunctionRead_and_Write 1232 45 +80 +0
With_usbFunctionWriteOut 1176 45 +24 +0
With_Interrupt_In_Endpoint_1 1278 57 +126 +12
With_Interrupt_In_Endpoint_1_and_Halt 1368 57 +216 +12
With_Interrupt_In_Endpoint_1_and_3 1344 69 +192 +24
With_Dynamic_Descriptor 1180 45 +28 +0
With_Long_Transfers 1198 47 +46 +2

View File

@ -0,0 +1,16 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1194 45 +0 +0
Minimum_with_12_MHz 1244 45 +50 +0
Minimum_with_12_8_MHz 1564 45 +370 +0
Minimum_with_15_MHz 1300 45 +106 +0
Minimum_with_16_5_MHz 1316 45 +122 +0
Minimum_with_20_MHz 1176 45 -18 +0
With_usbFunctionWrite 1248 45 +54 +0
With_usbFunctionRead 1244 45 +50 +0
With_usbFunctionRead_and_Write 1282 45 +88 +0
With_usbFunctionWriteOut 1210 45 +16 +0
With_Interrupt_In_Endpoint_1 1322 57 +128 +12
With_Interrupt_In_Endpoint_1_and_Halt 1412 57 +218 +12
With_Interrupt_In_Endpoint_1_and_3 1430 69 +236 +24
With_Dynamic_Descriptor 1214 45 +20 +0
With_Long_Transfers 1272 47 +78 +2

View File

@ -0,0 +1,16 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1152 45 +0 +0
Minimum_with_12_MHz 1202 45 +50 +0
Minimum_with_12_8_MHz 1522 45 +370 +0
Minimum_with_15_MHz 1258 45 +106 +0
Minimum_with_16_5_MHz 1274 45 +122 +0
Minimum_with_20_MHz 1134 45 -18 +0
With_usbFunctionWrite 1212 45 +60 +0
With_usbFunctionRead 1190 45 +38 +0
With_usbFunctionRead_and_Write 1232 45 +80 +0
With_usbFunctionWriteOut 1176 45 +24 +0
With_Interrupt_In_Endpoint_1 1278 57 +126 +12
With_Interrupt_In_Endpoint_1_and_Halt 1368 57 +216 +12
With_Interrupt_In_Endpoint_1_and_3 1344 69 +192 +24
With_Dynamic_Descriptor 1180 45 +28 +0
With_Long_Transfers 1198 47 +46 +2

View File

@ -0,0 +1,16 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1194 45 +0 +0
Minimum_with_12_MHz 1244 45 +50 +0
Minimum_with_12_8_MHz 1564 45 +370 +0
Minimum_with_15_MHz 1300 45 +106 +0
Minimum_with_16_5_MHz 1316 45 +122 +0
Minimum_with_20_MHz 1176 45 -18 +0
With_usbFunctionWrite 1248 45 +54 +0
With_usbFunctionRead 1244 45 +50 +0
With_usbFunctionRead_and_Write 1282 45 +88 +0
With_usbFunctionWriteOut 1210 45 +16 +0
With_Interrupt_In_Endpoint_1 1322 57 +128 +12
With_Interrupt_In_Endpoint_1_and_Halt 1412 57 +218 +12
With_Interrupt_In_Endpoint_1_and_3 1430 69 +236 +24
With_Dynamic_Descriptor 1214 45 +20 +0
With_Long_Transfers 1272 47 +78 +2

View File

@ -0,0 +1,17 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1152 45 +0 +0
Minimum_with_12_MHz 1202 45 +50 +0
Minimum_with_12_8_MHz 1522 45 +370 +0
Minimum_with_15_MHz 1258 45 +106 +0
Minimum_with_16_5_MHz 1274 45 +122 +0
Minimum_with_18_MHz+CRC 2268 45 +1116 +0
Minimum_with_20_MHz 1134 45 -18 +0
With_usbFunctionWrite 1212 45 +60 +0
With_usbFunctionRead 1190 45 +38 +0
With_usbFunctionRead_and_Write 1232 45 +80 +0
With_usbFunctionWriteOut 1176 45 +24 +0
With_Interrupt_In_Endpoint_1 1278 57 +126 +12
With_Interrupt_In_Endpoint_1_and_Halt 1368 57 +216 +12
With_Interrupt_In_Endpoint_1_and_3 1344 69 +192 +24
With_Dynamic_Descriptor 1180 45 +28 +0
With_Long_Transfers 1198 47 +46 +2

View File

@ -0,0 +1,17 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1224 45 +0 +0
Minimum_with_12_MHz 1274 45 +50 +0
Minimum_with_12_8_MHz 1594 45 +370 +0
Minimum_with_15_MHz 1330 45 +106 +0
Minimum_with_16_5_MHz 1346 45 +122 +0
Minimum_with_18_MHz+CRC 2298 45 +1074 +0
Minimum_with_20_MHz 1206 45 -18 +0
With_usbFunctionWrite 1284 45 +60 +0
With_usbFunctionRead 1280 45 +56 +0
With_usbFunctionRead_and_Write 1318 45 +94 +0
With_usbFunctionWriteOut 1246 45 +22 +0
With_Interrupt_In_Endpoint_1 1358 57 +134 +12
With_Interrupt_In_Endpoint_1_and_Halt 1448 57 +224 +12
With_Interrupt_In_Endpoint_1_and_3 1466 69 +242 +24
With_Dynamic_Descriptor 1250 45 +26 +0
With_Long_Transfers 1302 47 +78 +2

View File

@ -0,0 +1,17 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1152 45 +0 +0
Minimum_with_12_MHz 1202 45 +50 +0
Minimum_with_12_8_MHz 1522 45 +370 +0
Minimum_with_15_MHz 1258 45 +106 +0
Minimum_with_16_5_MHz 1274 45 +122 +0
Minimum_with_18_MHz+CRC 2268 45 +1116 +0
Minimum_with_20_MHz 1134 45 -18 +0
With_usbFunctionWrite 1212 45 +60 +0
With_usbFunctionRead 1190 45 +38 +0
With_usbFunctionRead_and_Write 1232 45 +80 +0
With_usbFunctionWriteOut 1176 45 +24 +0
With_Interrupt_In_Endpoint_1 1278 57 +126 +12
With_Interrupt_In_Endpoint_1_and_Halt 1368 57 +216 +12
With_Interrupt_In_Endpoint_1_and_3 1344 69 +192 +24
With_Dynamic_Descriptor 1180 45 +28 +0
With_Long_Transfers 1198 47 +46 +2

View File

@ -0,0 +1,17 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1224 45 +0 +0
Minimum_with_12_MHz 1274 45 +50 +0
Minimum_with_12_8_MHz 1594 45 +370 +0
Minimum_with_15_MHz 1330 45 +106 +0
Minimum_with_16_5_MHz 1346 45 +122 +0
Minimum_with_18_MHz+CRC 2298 45 +1074 +0
Minimum_with_20_MHz 1206 45 -18 +0
With_usbFunctionWrite 1284 45 +60 +0
With_usbFunctionRead 1280 45 +56 +0
With_usbFunctionRead_and_Write 1318 45 +94 +0
With_usbFunctionWriteOut 1246 45 +22 +0
With_Interrupt_In_Endpoint_1 1358 57 +134 +12
With_Interrupt_In_Endpoint_1_and_Halt 1448 57 +224 +12
With_Interrupt_In_Endpoint_1_and_3 1466 69 +242 +24
With_Dynamic_Descriptor 1250 45 +26 +0
With_Long_Transfers 1302 47 +78 +2

View File

@ -0,0 +1,17 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1152 45 +0 +0
Minimum_with_12_MHz 1202 45 +50 +0
Minimum_with_12_8_MHz 1518 45 +366 +0
Minimum_with_15_MHz 1258 45 +106 +0
Minimum_with_16_5_MHz 1274 45 +122 +0
Minimum_with_18_MHz+CRC 2268 45 +1116 +0
Minimum_with_20_MHz 1134 45 -18 +0
With_usbFunctionWrite 1212 45 +60 +0
With_usbFunctionRead 1190 45 +38 +0
With_usbFunctionRead_and_Write 1232 45 +80 +0
With_usbFunctionWriteOut 1176 45 +24 +0
With_Interrupt_In_Endpoint_1 1278 57 +126 +12
With_Interrupt_In_Endpoint_1_and_Halt 1368 57 +216 +12
With_Interrupt_In_Endpoint_1_and_3 1344 69 +192 +24
With_Dynamic_Descriptor 1180 45 +28 +0
With_Long_Transfers 1198 47 +46 +2

View File

@ -0,0 +1,17 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1226 45 +0 +0
Minimum_with_12_MHz 1276 45 +50 +0
Minimum_with_12_8_MHz 1592 45 +366 +0
Minimum_with_15_MHz 1332 45 +106 +0
Minimum_with_16_5_MHz 1348 45 +122 +0
Minimum_with_18_MHz+CRC 2298 45 +1072 +0
Minimum_with_20_MHz 1208 45 -18 +0
With_usbFunctionWrite 1286 45 +60 +0
With_usbFunctionRead 1282 45 +56 +0
With_usbFunctionRead_and_Write 1320 45 +94 +0
With_usbFunctionWriteOut 1248 45 +22 +0
With_Interrupt_In_Endpoint_1 1360 57 +134 +12
With_Interrupt_In_Endpoint_1_and_Halt 1450 57 +224 +12
With_Interrupt_In_Endpoint_1_and_3 1418 69 +192 +24
With_Dynamic_Descriptor 1252 45 +26 +0
With_Long_Transfers 1304 47 +78 +2

View File

@ -0,0 +1,17 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1152 45 +0 +0
Minimum_with_12_MHz 1202 45 +50 +0
Minimum_with_12_8_MHz 1518 45 +366 +0
Minimum_with_15_MHz 1258 45 +106 +0
Minimum_with_16_5_MHz 1274 45 +122 +0
Minimum_with_18_MHz+CRC 2268 45 +1116 +0
Minimum_with_20_MHz 1134 45 -18 +0
With_usbFunctionWrite 1212 45 +60 +0
With_usbFunctionRead 1190 45 +38 +0
With_usbFunctionRead_and_Write 1232 45 +80 +0
With_usbFunctionWriteOut 1176 45 +24 +0
With_Interrupt_In_Endpoint_1 1278 57 +126 +12
With_Interrupt_In_Endpoint_1_and_Halt 1368 57 +216 +12
With_Interrupt_In_Endpoint_1_and_3 1344 69 +192 +24
With_Dynamic_Descriptor 1180 45 +28 +0
With_Long_Transfers 1206 47 +54 +2

View File

@ -0,0 +1,17 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1226 45 +0 +0
Minimum_with_12_MHz 1276 45 +50 +0
Minimum_with_12_8_MHz 1592 45 +366 +0
Minimum_with_15_MHz 1332 45 +106 +0
Minimum_with_16_5_MHz 1348 45 +122 +0
Minimum_with_18_MHz+CRC 2298 45 +1072 +0
Minimum_with_20_MHz 1208 45 -18 +0
With_usbFunctionWrite 1286 45 +60 +0
With_usbFunctionRead 1282 45 +56 +0
With_usbFunctionRead_and_Write 1320 45 +94 +0
With_usbFunctionWriteOut 1248 45 +22 +0
With_Interrupt_In_Endpoint_1 1360 57 +134 +12
With_Interrupt_In_Endpoint_1_and_Halt 1450 57 +224 +12
With_Interrupt_In_Endpoint_1_and_3 1418 69 +192 +24
With_Dynamic_Descriptor 1252 45 +26 +0
With_Long_Transfers 1300 47 +74 +2

View File

@ -0,0 +1,17 @@
Variation Flash RAM +F +RAM
Minimum_with_16_MHz 1192 45 +0 +0
Minimum_with_12_MHz 1242 45 +50 +0
Minimum_with_12_8_MHz 1558 45 +366 +0
Minimum_with_15_MHz 1298 45 +106 +0
Minimum_with_16_5_MHz 1314 45 +122 +0
Minimum_with_18_MHz+CRC 2262 45 +1070 +0
Minimum_with_20_MHz 1174 45 -18 +0
With_usbFunctionWrite 1252 45 +60 +0
With_usbFunctionRead 1248 45 +56 +0
With_usbFunctionRead_and_Write 1286 45 +94 +0
With_usbFunctionWriteOut 1214 45 +22 +0
With_Interrupt_In_Endpoint_1 1328 57 +136 +12
With_Interrupt_In_Endpoint_1_and_Halt 1420 57 +228 +12
With_Interrupt_In_Endpoint_1_and_3 1386 69 +194 +24
With_Dynamic_Descriptor 1198 45 +6 +0
With_Long_Transfers 1236 47 +44 +2

View File

@ -0,0 +1,295 @@
/* Name: usbconfig.h
* Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
* Author: Christian Starkjohann
* Creation Date: 2005-04-01
* Tabsize: 4
* Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
#ifndef __usbconfig_h_included__
#define __usbconfig_h_included__
/*
General Description:
This is the config file for tests. It is not updated to the latest set of
features. Don't use it as a prototype, use usbconfig-prototype.h instead!
*/
/* ---------------------------- Hardware Config ---------------------------- */
#define USB_CFG_IOPORTNAME D
#define USB_CFG_DMINUS_BIT 4
#define USB_CFG_DPLUS_BIT 2
#define USB_CFG_CLOCK_KHZ (F_CPU/1000)
#define USB_CFG_CHECK_CRC (USB_CFG_CLOCK_KHZ == 18000)
/* ----------------------- Optional Hardware Config ------------------------ */
/* #define USB_CFG_PULLUP_IOPORTNAME D */
/* If you connect the 1.5k pullup resistor from D- to a port pin instead of
* V+, you can connect and disconnect the device from firmware by calling
* the macros usbDeviceConnect() and usbDeviceDisconnect() (see usbdrv.h).
* This constant defines the port on which the pullup resistor is connected.
*/
/* #define USB_CFG_PULLUP_BIT 4 */
/* This constant defines the bit number in USB_CFG_PULLUP_IOPORT (defined
* above) where the 1.5k pullup resistor is connected. See description
* above for details.
*/
/* --------------------------- Functional Range ---------------------------- */
#ifndef USB_CFG_HAVE_INTRIN_ENDPOINT3
#define USB_CFG_HAVE_INTRIN_ENDPOINT3 0
#endif
/* Define this to 1 if you want to compile a version with three endpoints: The
* default control endpoint 0, an interrupt-in endpoint 3 (or the number
* configured below) and a catch-all default interrupt-in endpoint as above.
* You must also define USB_CFG_HAVE_INTRIN_ENDPOINT to 1 for this feature.
*/
#ifndef USB_CFG_HAVE_INTRIN_ENDPOINT
#define USB_CFG_HAVE_INTRIN_ENDPOINT USB_CFG_HAVE_INTRIN_ENDPOINT3
#endif
/* Define this to 1 if you want to compile a version with two endpoints: The
* default control endpoint 0 and an interrupt-in endpoint (any other endpoint
* number).
*/
#define USB_CFG_EP3_NUMBER 3
/* If the so-called endpoint 3 is used, it can now be configured to any other
* endpoint number (except 0) with this macro. Default if undefined is 3.
*/
/* #define USB_INITIAL_DATATOKEN USBPID_DATA1 */
/* The above macro defines the startup condition for data toggling on the
* interrupt/bulk endpoints 1 and 3. Defaults to USBPID_DATA1.
* Since the token is toggled BEFORE sending any data, the first packet is
* sent with the oposite value of this configuration!
*/
//#define USB_CFG_IMPLEMENT_HALT 0
/* Define this to 1 if you also want to implement the ENDPOINT_HALT feature
* for endpoint 1 (interrupt endpoint). Although you may not need this feature,
* it is required by the standard. We have made it a config option because it
* bloats the code considerably.
*/
#define USB_CFG_INTR_POLL_INTERVAL 10
/* If you compile a version with endpoint 1 (interrupt-in), this is the poll
* interval. The value is in milliseconds and must not be less than 10 ms for
* low speed devices.
*/
#define USB_CFG_IS_SELF_POWERED 0
/* Define this to 1 if the device has its own power supply. Set it to 0 if the
* device is powered from the USB bus.
*/
#define USB_CFG_MAX_BUS_POWER 40
/* Set this variable to the maximum USB bus power consumption of your device.
* The value is in milliamperes. [It will be divided by two since USB
* communicates power requirements in units of 2 mA.]
*/
//#define USB_CFG_IMPLEMENT_FN_WRITE 0
/* Set this to 1 if you want usbFunctionWrite() to be called for control-out
* transfers. Set it to 0 if you don't need it and want to save a couple of
* bytes.
*/
//#define USB_CFG_IMPLEMENT_FN_READ 0
/* Set this to 1 if you need to send control replies which are generated
* "on the fly" when usbFunctionRead() is called. If you only want to send
* data from a static buffer, set it to 0 and return the data from
* usbFunctionSetup(). This saves a couple of bytes.
*/
//#define USB_CFG_IMPLEMENT_FN_WRITEOUT 0
/* Define this to 1 if you want to use interrupt-out (or bulk out) endpoints.
* You must implement the function usbFunctionWriteOut() which receives all
* interrupt/bulk data sent to any endpoint other than 0. The endpoint number
* can be found in 'usbRxToken'.
*/
#define USB_CFG_HAVE_FLOWCONTROL 0
/* Define this to 1 if you want flowcontrol over USB data. See the definition
* of the macros usbDisableAllRequests() and usbEnableAllRequests() in
* usbdrv.h.
*/
//#define USB_CFG_LONG_TRANSFERS 0
/* Define this to 1 if you want to send/receive blocks of more than 254 bytes
* in a single control-in or control-out transfer. Note that the capability
* for long transfers increases the driver size.
*/
/* #define USB_RX_USER_HOOK(data, len) if(usbRxToken == (uchar)USBPID_SETUP) blinkLED(); */
/* This macro is a hook if you want to do unconventional things. If it is
* defined, it's inserted at the beginning of received message processing.
* If you eat the received message and don't want default processing to
* proceed, do a return after doing your things. One possible application
* (besides debugging) is to flash a status LED on each packet.
*/
/* #define USB_RESET_HOOK(resetStarts) if(!resetStarts){hadUsbReset();} */
/* This macro is a hook if you need to know when an USB RESET occurs. It has
* one parameter which distinguishes between the start of RESET state and its
* end.
*/
/* #define USB_SET_ADDRESS_HOOK() hadAddressAssigned(); */
/* This macro (if defined) is executed when a USB SET_ADDRESS request was
* received.
*/
//#define USB_COUNT_SOF 0
/* define this macro to 1 if you need the global variable "usbSofCount" which
* counts SOF packets. This feature requires that the hardware interrupt is
* connected to D- instead of D+.
*/
//#define USB_CFG_HAVE_MEASURE_FRAME_LENGTH 0
/* define this macro to 1 if you want the function usbMeasureFrameLength()
* compiled in. This function can be used to calibrate the AVR's RC oscillator.
*/
/* -------------------------- Device Description --------------------------- */
#define USB_CFG_VENDOR_ID 0xc0, 0x16
/* USB vendor ID for the device, low byte first. If you have registered your
* own Vendor ID, define it here. Otherwise you use one of obdev's free shared
* VID/PID pairs. Be sure to read USB-IDs-for-free.txt for rules!
*/
#define USB_CFG_DEVICE_ID 0x08, 0x3e /* 1000 dec, "free for lab use" */
/* This is the ID of the product, low byte first. It is interpreted in the
* scope of the vendor ID. If you have registered your own VID with usb.org
* or if you have licensed a PID from somebody else, define it here. Otherwise
* you use obdev's free shared VID/PID pair. Be sure to read the rules in
* USB-IDs-for-free.txt!
*/
#define USB_CFG_DEVICE_VERSION 0x00, 0x01
/* Version number of the device: Minor number first, then major number.
*/
#define USB_CFG_VENDOR_NAME 'o', 'b', 'd', 'e', 'v', '.', 'a', 't'
#define USB_CFG_VENDOR_NAME_LEN 8
/* These two values define the vendor name returned by the USB device. The name
* must be given as a list of characters under single quotes. The characters
* are interpreted as Unicode (UTF-16) entities.
* If you don't want a vendor name string, undefine these macros.
* ALWAYS define a vendor name containing your Internet domain name if you use
* obdev's free shared VID/PID pair. See the file USB-IDs-for-free.txt for
* details.
*/
#define USB_CFG_DEVICE_NAME 'T', 'e', 's', 't'
#define USB_CFG_DEVICE_NAME_LEN 4
/* Same as above for the device name. If you don't want a device name, undefine
* the macros. See the file USB-IDs-for-free.txt before you assign a name if
* you use a shared VID/PID.
*/
/*#define USB_CFG_SERIAL_NUMBER 'N', 'o', 'n', 'e' */
/*#define USB_CFG_SERIAL_NUMBER_LEN 0 */
/* Same as above for the serial number. If you don't want a serial number,
* undefine the macros.
* It may be useful to provide the serial number through other means than at
* compile time. See the section about descriptor properties below for how
* to fine tune control over USB descriptors such as the string descriptor
* for the serial number.
*/
#define USB_CFG_DEVICE_CLASS 0xff /* set to 0 if deferred to interface */
#define USB_CFG_DEVICE_SUBCLASS 0
/* See USB specification if you want to conform to an existing device class.
* Class 0xff is "vendor specific".
*/
#define USB_CFG_INTERFACE_CLASS 0 /* define class here if not at device level */
#define USB_CFG_INTERFACE_SUBCLASS 0
#define USB_CFG_INTERFACE_PROTOCOL 0
/* See USB specification if you want to conform to an existing device class or
* protocol. The following classes must be set at interface level:
* HID class is 3, no subclass and protocol required (but may be useful!)
* CDC class is 2, use subclass 2 and protocol 1 for ACM
*/
/* #define USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH 42 */
/* Define this to the length of the HID report descriptor, if you implement
* an HID device. Otherwise don't define it or define it to 0.
* If you use this define, you must add a PROGMEM character array named
* "usbHidReportDescriptor" to your code which contains the report descriptor.
* Don't forget to keep the array and this define in sync!
*/
/* #define USB_PUBLIC static */
/* Use the define above if you #include usbdrv.c instead of linking against it.
* This technique saves a couple of bytes in flash memory.
*/
/* ------------------- Fine Control over USB Descriptors ------------------- */
/* If you don't want to use the driver's default USB descriptors, you can
* provide our own. These can be provided as (1) fixed length static data in
* flash memory, (2) fixed length static data in RAM or (3) dynamically at
* runtime in the function usbFunctionDescriptor(). See usbdrv.h for more
* information about this function.
* Descriptor handling is configured through the descriptor's properties. If
* no properties are defined or if they are 0, the default descriptor is used.
* Possible properties are:
* + USB_PROP_IS_DYNAMIC: The data for the descriptor should be fetched
* at runtime via usbFunctionDescriptor().
* + USB_PROP_IS_RAM: The data returned by usbFunctionDescriptor() or found
* in static memory is in RAM, not in flash memory.
* + USB_PROP_LENGTH(len): If the data is in static memory (RAM or flash),
* the driver must know the descriptor's length. The descriptor itself is
* found at the address of a well known identifier (see below).
* List of static descriptor names (must be declared PROGMEM if in flash):
* char usbDescriptorDevice[];
* char usbDescriptorConfiguration[];
* char usbDescriptorHidReport[];
* char usbDescriptorString0[];
* int usbDescriptorStringVendor[];
* int usbDescriptorStringDevice[];
* int usbDescriptorStringSerialNumber[];
* Other descriptors can't be provided statically, they must be provided
* dynamically at runtime.
*
* Descriptor properties are or-ed or added together, e.g.:
* #define USB_CFG_DESCR_PROPS_DEVICE (USB_PROP_IS_RAM | USB_PROP_LENGTH(18))
*
* The following descriptors are defined:
* USB_CFG_DESCR_PROPS_DEVICE
* USB_CFG_DESCR_PROPS_CONFIGURATION
* USB_CFG_DESCR_PROPS_STRINGS
* USB_CFG_DESCR_PROPS_STRING_0
* USB_CFG_DESCR_PROPS_STRING_VENDOR
* USB_CFG_DESCR_PROPS_STRING_PRODUCT
* USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
* USB_CFG_DESCR_PROPS_HID
* USB_CFG_DESCR_PROPS_HID_REPORT
* USB_CFG_DESCR_PROPS_UNKNOWN (for all descriptors not handled by the driver)
*
*/
#if USE_DYNAMIC_DESCRIPTOR
#define USB_CFG_DESCR_PROPS_DEVICE USB_PROP_IS_DYNAMIC
#define USB_CFG_DESCR_PROPS_CONFIGURATION USB_PROP_IS_DYNAMIC
#else
#define USB_CFG_DESCR_PROPS_DEVICE 0
#define USB_CFG_DESCR_PROPS_CONFIGURATION 0
#endif
#define USB_CFG_DESCR_PROPS_STRINGS 0
#define USB_CFG_DESCR_PROPS_STRING_0 0
#define USB_CFG_DESCR_PROPS_STRING_VENDOR 0
#define USB_CFG_DESCR_PROPS_STRING_PRODUCT 0
#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER 0
#define USB_CFG_DESCR_PROPS_HID 0
#define USB_CFG_DESCR_PROPS_HID_REPORT 0
#define USB_CFG_DESCR_PROPS_UNKNOWN 0
#define usbMsgPtr_t unsigned short
/* If usbMsgPtr_t is not defined, it defaults to 'uchar *'. We define it to
* a scalar type here because gcc generates slightly shorter code for scalar
* arithmetics than for pointer arithmetics. Remove this define for backward
* type compatibility or define it to an 8 bit type if you use data in RAM only
* and all RAM is below 256 bytes (tiny memory model in IAR CC).
*/
/* ----------------------- Optional MCU Description ------------------------ */
/* The following configurations have working defaults in usbdrv.h. You
* usually don't need to set them explicitly. Only if you want to run
* the driver on a device which is not yet supported or with a compiler
* which is not fully supported (such as IAR C) or if you use a differnt
* interrupt than INT0, you may have to define some of these.
*/
/* #define USB_INTR_CFG MCUCR */
/* #define USB_INTR_CFG_SET ((1 << ISC00) | (1 << ISC01)) */
/* #define USB_INTR_CFG_CLR 0 */
/* #define USB_INTR_ENABLE GIMSK */
/* #define USB_INTR_ENABLE_BIT INT0 */
/* #define USB_INTR_PENDING GIFR */
/* #define USB_INTR_PENDING_BIT INTF0 */
/* #define USB_INTR_VECTOR INT0_vect */
#endif /* __usbconfig_h_included__ */

View File

@ -0,0 +1,329 @@
This file documents changes in the firmware-only USB driver for atmel's AVR
microcontrollers. New entries are always appended to the end of the file.
Scroll down to the bottom to see the most recent changes.
2005-04-01:
- Implemented endpoint 1 as interrupt-in endpoint.
- Moved all configuration options to usbconfig.h which is not part of the
driver.
- Changed interface for usbVendorSetup().
- Fixed compatibility with ATMega8 device.
- Various minor optimizations.
2005-04-11:
- Changed interface to application: Use usbFunctionSetup(), usbFunctionRead()
and usbFunctionWrite() now. Added configuration options to choose which
of these functions to compile in.
- Assembler module delivers receive data non-inverted now.
- Made register and bit names compatible with more AVR devices.
2005-05-03:
- Allow address of usbRxBuf on any memory page as long as the buffer does
not cross 256 byte page boundaries.
- Better device compatibility: works with Mega88 now.
- Code optimization in debugging module.
- Documentation updates.
2006-01-02:
- Added (free) default Vendor- and Product-IDs bought from voti.nl.
- Added USBID-License.txt file which defines the rules for using the free
shared VID/PID pair.
- Added Readme.txt to the usbdrv directory which clarifies administrative
issues.
2006-01-25:
- Added "configured state" to become more standards compliant.
- Added "HALT" state for interrupt endpoint.
- Driver passes the "USB Command Verifier" test from usb.org now.
- Made "serial number" a configuration option.
- Minor optimizations, we now recommend compiler option "-Os" for best
results.
- Added a version number to usbdrv.h
2006-02-03:
- New configuration variable USB_BUFFER_SECTION for the memory section where
the USB rx buffer will go. This defaults to ".bss" if not defined. Since
this buffer MUST NOT cross 256 byte pages (not even touch a page at the
end), the user may want to pass a linker option similar to
"-Wl,--section-start=.mybuffer=0x800060".
- Provide structure for usbRequest_t.
- New defines for USB constants.
- Prepared for HID implementations.
- Increased data size limit for interrupt transfers to 8 bytes.
- New macro usbInterruptIsReady() to query interrupt buffer state.
2006-02-18:
- Ensure that the data token which is sent as an ack to an OUT transfer is
always zero sized. This fixes a bug where the host reports an error after
sending an out transfer to the device, although all data arrived at the
device.
- Updated docs in usbdrv.h to reflect changed API in usbFunctionWrite().
* Release 2006-02-20
- Give a compiler warning when compiling with debugging turned on.
- Added Oleg Semyonov's changes for IAR-cc compatibility.
- Added new (optional) functions usbDeviceConnect() and usbDeviceDisconnect()
(also thanks to Oleg!).
- Rearranged tests in usbPoll() to save a couple of instructions in the most
likely case that no actions are pending.
- We need a delay between the SET ADDRESS request until the new address
becomes active. This delay was handled in usbPoll() until now. Since the
spec says that the delay must not exceed 2ms, previous versions required
aggressive polling during the enumeration phase. We have now moved the
handling of the delay into the interrupt routine.
- We must not reply with NAK to a SETUP transaction. We can only achieve this
by making sure that the rx buffer is empty when SETUP tokens are expected.
We therefore don't pass zero sized data packets from the status phase of
a transfer to usbPoll(). This change MAY cause troubles if you rely on
receiving a less than 8 bytes long packet in usbFunctionWrite() to
identify the end of a transfer. usbFunctionWrite() will NEVER be called
with a zero length.
* Release 2006-03-14
- Improved IAR C support: tiny memory model, more devices
- Added template usbconfig.h file under the name usbconfig-prototype.h
* Release 2006-03-26
- Added provision for one more interrupt-in endpoint (endpoint 3).
- Added provision for one interrupt-out endpoint (endpoint 1).
- Added flowcontrol macros for USB.
- Added provision for custom configuration descriptor.
- Allow ANY two port bits for D+ and D-.
- Merged (optional) receive endpoint number into global usbRxToken variable.
- Use USB_CFG_IOPORTNAME instead of USB_CFG_IOPORT. We now construct the
variable name from the single port letter instead of computing the address
of related ports from the output-port address.
* Release 2006-06-26
- Updated documentation in usbdrv.h and usbconfig-prototype.h to reflect the
new features.
- Removed "#warning" directives because IAR does not understand them. Use
unused static variables instead to generate a warning.
- Do not include <avr/io.h> when compiling with IAR.
- Introduced USB_CFG_DESCR_PROPS_* in usbconfig.h to configure how each
USB descriptor should be handled. It is now possible to provide descriptor
data in Flash, RAM or dynamically at runtime.
- STALL is now a status in usbTxLen* instead of a message. We can now conform
to the spec and leave the stall status pending until it is cleared.
- Made usbTxPacketCnt1 and usbTxPacketCnt3 public. This allows the
application code to reset data toggling on interrupt pipes.
* Release 2006-07-18
- Added an #if !defined __ASSEMBLER__ to the warning in usbdrv.h. This fixes
an assembler error.
- usbDeviceDisconnect() takes pull-up resistor to high impedance now.
* Release 2007-02-01
- Merged in some code size improvements from usbtiny (thanks to Dick
Streefland for these optimizations!)
- Special alignment requirement for usbRxBuf not required any more. Thanks
again to Dick Streefland for this hint!
- Reverted to "#warning" instead of unused static variables -- new versions
of IAR CC should handle this directive.
- Changed Open Source license to GNU GPL v2 in order to make linking against
other free libraries easier. We no longer require publication of the
circuit diagrams, but we STRONGLY encourage it. If you improve the driver
itself, PLEASE grant us a royalty free license to your changes for our
commercial license.
* Release 2007-03-29
- New configuration option "USB_PUBLIC" in usbconfig.h.
- Set USB version number to 1.10 instead of 1.01.
- Code used USB_CFG_DESCR_PROPS_STRING_DEVICE and
USB_CFG_DESCR_PROPS_STRING_PRODUCT inconsistently. Changed all occurrences
to USB_CFG_DESCR_PROPS_STRING_PRODUCT.
- New assembler module for 16.5 MHz RC oscillator clock with PLL in receiver
code.
- New assembler module for 16 MHz crystal.
- usbdrvasm.S contains common code only, clock-specific parts have been moved
to usbdrvasm12.S, usbdrvasm16.S and usbdrvasm165.S respectively.
* Release 2007-06-25
- 16 MHz module: Do SE0 check in stuffed bits as well.
* Release 2007-07-07
- Define hi8(x) for IAR compiler to limit result to 8 bits. This is necessary
for negative values.
- Added 15 MHz module contributed by V. Bosch.
- Interrupt vector name can now be configured. This is useful if somebody
wants to use a different hardware interrupt than INT0.
* Release 2007-08-07
- Moved handleIn3 routine in usbdrvasm16.S so that relative jump range is
not exceeded.
- More config options: USB_RX_USER_HOOK(), USB_INITIAL_DATATOKEN,
USB_COUNT_SOF
- USB_INTR_PENDING can now be a memory address, not just I/O
* Release 2007-09-19
- Split out common parts of assembler modules into separate include file
- Made endpoint numbers configurable so that given interface definitions
can be matched. See USB_CFG_EP3_NUMBER in usbconfig-prototype.h.
- Store endpoint number for interrupt/bulk-out so that usbFunctionWriteOut()
can handle any number of endpoints.
- Define usbDeviceConnect() and usbDeviceDisconnect() even if no
USB_CFG_PULLUP_IOPORTNAME is defined. Directly set D+ and D- to 0 in this
case.
* Release 2007-12-01
- Optimize usbDeviceConnect() and usbDeviceDisconnect() for less code size
when USB_CFG_PULLUP_IOPORTNAME is not defined.
* Release 2007-12-13
- Renamed all include-only assembler modules from *.S to *.inc so that
people don't add them to their project sources.
- Distribute leap bits in tx loop more evenly for 16 MHz module.
- Use "macro" and "endm" instead of ".macro" and ".endm" for IAR
- Avoid compiler warnings for constant expr range by casting some values in
USB descriptors.
* Release 2008-01-21
- Fixed bug in 15 and 16 MHz module where the new address set with
SET_ADDRESS was already accepted at the next NAK or ACK we send, not at
the next data packet we send. This caused problems when the host polled
too fast. Thanks to Alexander Neumann for his help and patience debugging
this issue!
* Release 2008-02-05
- Fixed bug in 16.5 MHz module where a register was used in the interrupt
handler before it was pushed. This bug was introduced with version
2007-09-19 when common parts were moved to a separate file.
- Optimized CRC routine (thanks to Reimar Doeffinger).
* Release 2008-02-16
- Removed outdated IAR compatibility stuff (code sections).
- Added hook macros for USB_RESET_HOOK() and USB_SET_ADDRESS_HOOK().
- Added optional routine usbMeasureFrameLength() for calibration of the
internal RC oscillator.
* Release 2008-02-28
- USB_INITIAL_DATATOKEN defaults to USBPID_DATA1 now, which means that we
start with sending USBPID_DATA0.
- Changed defaults in usbconfig-prototype.h
- Added free USB VID/PID pair for MIDI class devices
- Restructured AVR-USB as separate package, not part of PowerSwitch any more.
* Release 2008-04-18
- Restructured usbdrv.c so that it is easier to read and understand.
- Better code optimization with gcc 4.
- If a second interrupt in endpoint is enabled, also add it to config
descriptor.
- Added config option for long transfers (above 254 bytes), see
USB_CFG_LONG_TRANSFERS in usbconfig.h.
- Added 20 MHz module contributed by Jeroen Benschop.
* Release 2008-05-13
- Fixed bug in libs-host/hiddata.c function usbhidGetReport(): length
was not incremented, pointer to length was incremented instead.
- Added code to command line tool(s) which claims an interface. This code
is disabled by default, but may be necessary on newer Linux kernels.
- Added usbconfig.h option "USB_CFG_CHECK_DATA_TOGGLING".
- New header "usbportability.h" prepares ports to other development
environments.
- Long transfers (above 254 bytes) did not work when usbFunctionRead() was
used to supply the data. Fixed this bug. [Thanks to Alexander Neumann!]
- In hiddata.c (example code for sending/receiving data over HID), use
USB_RECIP_DEVICE instead of USB_RECIP_INTERFACE for control transfers so
that we need not claim the interface.
- in usbPoll() loop 20 times polling for RESET state instead of 10 times.
This accounts for the higher clock rates we now support.
- Added a module for 12.8 MHz RC oscillator with PLL in receiver loop.
- Added hook to SOF code so that oscillator can be tuned to USB frame clock.
- Added timeout to waitForJ loop. Helps preventing unexpected hangs.
- Added example code for oscillator tuning to libs-device (thanks to
Henrik Haftmann for the idea to this routine).
- Implemented option USB_CFG_SUPPRESS_INTR_CODE.
* Release 2008-10-22
- Fixed libs-device/osctune.h: OSCCAL is memory address on ATMega88 and
similar, not offset of 0x20 needs to be added.
- Allow distribution under GPLv3 for those who have to link against other
code distributed under GPLv3.
* Release 2008-11-26
- Removed libusb-win32 dependency for hid-data example in Makefile.windows.
It was never required and confused many people.
- Added extern uchar usbRxToken to usbdrv.h.
- Integrated a module with CRC checks at 18 MHz by Lukas Schrittwieser.
* Release 2009-03-23
- Hid-mouse example used settings from hid-data example, fixed that.
- Renamed project to V-USB due to a trademark issue with Atmel(r).
- Changed CommercialLicense.txt and USBID-License.txt to make the
background of USB ID registration clearer.
* Release 2009-04-15
- Changed CommercialLicense.txt to reflect the new range of PIDs from
Jason Kotzin.
- Removed USBID-License.txt in favor of USB-IDs-for-free.txt and
USB-ID-FAQ.txt
- Fixed a bug in the 12.8 MHz module: End Of Packet decection was made in
the center between bit 0 and 1 of each byte. This is where the data lines
are expected to change and the sampled data may therefore be nonsense.
We therefore check EOP ONLY if bits 0 AND 1 have both been read as 0 on D-.
- Fixed a bitstuffing problem in the 16 MHz module: If bit 6 was stuffed,
the unstuffing code in the receiver routine was 1 cycle too long. If
multiple bytes had the unstuffing in bit 6, the error summed up until the
receiver was out of sync.
- Included option for faster CRC routine.
Thanks to Slawomir Fras (BoskiDialer) for this code!
- Updated bits in Configuration Descriptor's bmAttributes according to
USB 1.1 (in particular bit 7, it is a must-be-set bit now).
* Release 2009-08-22
- Moved first DBG1() after odDebugInit() in all examples.
- Use vector INT0_vect instead of SIG_INTERRUPT0 if defined. This makes
V-USB compatible with the new "p" suffix devices (e.g. ATMega328p).
- USB_CFG_CLOCK_KHZ setting is now required in usbconfig.h (no default any
more).
- New option USB_CFG_DRIVER_FLASH_PAGE allows boot loaders on devices with
more than 64 kB flash.
- Built-in configuration descriptor allows custom definition for second
endpoint now.
* Release 2010-07-15
- Fixed bug in usbDriverSetup() which prevented descriptor sizes above 255
bytes.
- Avoid a compiler warning for unused parameter in usbHandleResetHook() when
compiler option -Wextra is enabled.
- Fixed wrong hex value for some IDs in USB-IDs-for-free.txt.
- Keep a define for USBATTR_BUSPOWER, although the flag does not exist
in USB 1.1 any more. Set it to 0. This is for backward compatibility.
* Release 2012-01-09
- Define a separate (defined) type for usbMsgPtr so that projects using a
tiny memory model can define it to an 8 bit type in usbconfig.h. This
change also saves a couple of bytes when using a scalar 16 bit type.
- Inserted "const" keyword for all PROGMEM declarations because new GCC
requires it.
- Fixed problem with dependence of usbportability.h on usbconfig.h. This
problem occurred with IAR CC only.
- Prepared repository for github.com.
* Release 2012-12-06

View File

@ -0,0 +1,166 @@
V-USB Driver Software License Agreement
Version 2012-07-09
THIS LICENSE AGREEMENT GRANTS YOU CERTAIN RIGHTS IN A SOFTWARE. YOU CAN
ENTER INTO THIS AGREEMENT AND ACQUIRE THE RIGHTS OUTLINED BELOW BY PAYING
THE AMOUNT ACCORDING TO SECTION 4 ("PAYMENT") TO OBJECTIVE DEVELOPMENT.
1 DEFINITIONS
1.1 "OBJECTIVE DEVELOPMENT" shall mean OBJECTIVE DEVELOPMENT Software GmbH,
Grosse Schiffgasse 1A/7, 1020 Wien, AUSTRIA.
1.2 "You" shall mean the Licensee.
1.3 "V-USB" shall mean all files included in the package distributed under
the name "vusb" by OBJECTIVE DEVELOPMENT (http://www.obdev.at/vusb/)
unless otherwise noted. This includes the firmware-only USB device
implementation for Atmel AVR microcontrollers, some simple device examples
and host side software examples and libraries.
2 LICENSE GRANTS
2.1 Source Code. OBJECTIVE DEVELOPMENT shall furnish you with the source
code of V-USB.
2.2 Distribution and Use. OBJECTIVE DEVELOPMENT grants you the
non-exclusive right to use, copy and distribute V-USB with your hardware
product(s), restricted by the limitations in section 3 below.
2.3 Modifications. OBJECTIVE DEVELOPMENT grants you the right to modify
the source code and your copy of V-USB according to your needs.
2.4 USB IDs. OBJECTIVE DEVELOPMENT furnishes you with one or two USB
Product ID(s), sent to you in e-mail. These Product IDs are reserved
exclusively for you. OBJECTIVE DEVELOPMENT has obtained USB Product ID
ranges under the Vendor ID 5824 from Wouter van Ooijen (Van Ooijen
Technische Informatica, www.voti.nl) and under the Vendor ID 8352 from
Jason Kotzin (now flirc.tv, Inc.). Both owners of the Vendor IDs have
obtained these IDs from the USB Implementers Forum, Inc. (www.usb.org).
OBJECTIVE DEVELOPMENT disclaims all liability which might arise from the
assignment of USB IDs.
2.5 USB Certification. Although not part of this agreement, we want to make
it clear that you cannot become USB certified when you use V-USB or a USB
Product ID assigned by OBJECTIVE DEVELOPMENT. AVR microcontrollers don't
meet the electrical specifications required by the USB specification and
the USB Implementers Forum certifies only members who bought a Vendor ID of
their own.
3 LICENSE RESTRICTIONS
3.1 Number of Units. Only one of the following three definitions is
applicable. Which one is determined by the amount you pay to OBJECTIVE
DEVELOPMENT, see section 4 ("Payment") below.
Hobby License: You may use V-USB according to section 2 above in no more
than 5 hardware units. These units must not be sold for profit.
Entry Level License: You may use V-USB according to section 2 above in no
more than 150 hardware units.
Professional License: You may use V-USB according to section 2 above in
any number of hardware units, except for large scale production ("unlimited
fair use"). Quantities below 10,000 units are not considered large scale
production. If your reach quantities which are obviously large scale
production, you must pay a license fee of 0.10 EUR per unit for all units
above 10,000.
3.2 Rental. You may not rent, lease, or lend V-USB or otherwise encumber
any copy of V-USB, or any of the rights granted herein.
3.3 Transfer. You may not transfer your rights under this Agreement to
another party without OBJECTIVE DEVELOPMENT's prior written consent. If
such consent is obtained, you may permanently transfer this License to
another party. The recipient of such transfer must agree to all terms and
conditions of this Agreement.
3.4 Reservation of Rights. OBJECTIVE DEVELOPMENT retains all rights not
expressly granted.
3.5 Non-Exclusive Rights. Your license rights under this Agreement are
non-exclusive.
3.6 Third Party Rights. This Agreement cannot grant you rights controlled
by third parties. In particular, you are not allowed to use the USB logo or
other trademarks owned by the USB Implementers Forum, Inc. without their
consent. Since such consent depends on USB certification, it should be
noted that V-USB will not pass certification because it does not
implement checksum verification and the microcontroller ports do not meet
the electrical specifications.
4 PAYMENT
The payment amount depends on the variation of this agreement (according to
section 3.1) into which you want to enter. Concrete prices are listed on
OBJECTIVE DEVELOPMENT's web site, usually at
http://www.obdev.at/vusb/license.html. You agree to pay the amount listed
there to OBJECTIVE DEVELOPMENT or OBJECTIVE DEVELOPMENT's payment processor
or reseller.
5 COPYRIGHT AND OWNERSHIP
V-USB is protected by copyright laws and international copyright
treaties, as well as other intellectual property laws and treaties. V-USB
is licensed, not sold.
6 TERM AND TERMINATION
6.1 Term. This Agreement shall continue indefinitely. However, OBJECTIVE
DEVELOPMENT may terminate this Agreement and revoke the granted license and
USB-IDs if you fail to comply with any of its terms and conditions.
6.2 Survival of Terms. All provisions regarding secrecy, confidentiality
and limitation of liability shall survive termination of this agreement.
7 DISCLAIMER OF WARRANTY AND LIABILITY
LIMITED WARRANTY. V-USB IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, OBJECTIVE
DEVELOPMENT AND ITS SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND
NON-INFRINGEMENT, WITH REGARD TO V-USB, AND THE PROVISION OF OR FAILURE
TO PROVIDE SUPPORT SERVICES. THIS LIMITED WARRANTY GIVES YOU SPECIFIC LEGAL
RIGHTS. YOU MAY HAVE OTHERS, WHICH VARY FROM STATE/JURISDICTION TO
STATE/JURISDICTION.
LIMITATION OF LIABILITY. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW,
IN NO EVENT SHALL OBJECTIVE DEVELOPMENT OR ITS SUPPLIERS BE LIABLE FOR ANY
SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER
(INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS,
BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY
LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE V-USB OR THE
PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES, EVEN IF OBJECTIVE
DEVELOPMENT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN ANY
CASE, OBJECTIVE DEVELOPMENT'S ENTIRE LIABILITY UNDER ANY PROVISION OF THIS
AGREEMENT SHALL BE LIMITED TO THE AMOUNT ACTUALLY PAID BY YOU FOR V-USB.
8 MISCELLANEOUS TERMS
8.1 Marketing. OBJECTIVE DEVELOPMENT has the right to mention for marketing
purposes that you entered into this agreement.
8.2 Entire Agreement. This document represents the entire agreement between
OBJECTIVE DEVELOPMENT and you. It may only be modified in writing signed by
an authorized representative of both, OBJECTIVE DEVELOPMENT and you.
8.3 Severability. In case a provision of these terms and conditions should
be or become partly or entirely invalid, ineffective, or not executable,
the validity of all other provisions shall not be affected.
8.4 Applicable Law. This agreement is governed by the laws of the Republic
of Austria.
8.5 Responsible Courts. The responsible courts in Vienna/Austria will have
exclusive jurisdiction regarding all disputes in connection with this
agreement.

View File

@ -0,0 +1,361 @@
OBJECTIVE DEVELOPMENT GmbH's V-USB driver software is distributed under the
terms and conditions of the GNU GPL version 2 or the GNU GPL version 3. It is
your choice whether you apply the terms of version 2 or version 3. The full
text of GPLv2 is included below. In addition to the requirements in the GPL,
we STRONGLY ENCOURAGE you to do the following:
(1) Publish your entire project on a web site and drop us a note with the URL.
Use the form at http://www.obdev.at/vusb/feedback.html for your submission.
(2) Adhere to minimum publication standards. Please include AT LEAST:
- a circuit diagram in PDF, PNG or GIF format
- full source code for the host software
- a Readme.txt file in ASCII format which describes the purpose of the
project and what can be found in which directories and which files
- a reference to http://www.obdev.at/vusb/
(3) If you improve the driver firmware itself, please give us a free license
to your modifications for our commercial license offerings.
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) 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
this service 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 make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. 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.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
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
convey 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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision 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, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This 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 Library General
Public License instead of this License.

View File

@ -0,0 +1,172 @@
This is the Readme file to Objective Development's firmware-only USB driver
for Atmel AVR microcontrollers. For more information please visit
http://www.obdev.at/vusb/
This directory contains the USB firmware only. Copy it as-is to your own
project and add all .c and .S files to your project (these files are marked
with an asterisk in the list below). Then copy usbconfig-prototype.h as
usbconfig.h to your project and edit it according to your configuration.
TECHNICAL DOCUMENTATION
=======================
The technical documentation (API) for the firmware driver is contained in the
file "usbdrv.h". Please read all of it carefully! Configuration options are
documented in "usbconfig-prototype.h".
The driver consists of the following files:
Readme.txt ............. The file you are currently reading.
Changelog.txt .......... Release notes for all versions of the driver.
usbdrv.h ............... Driver interface definitions and technical docs.
* usbdrv.c ............... High level language part of the driver. Link this
module to your code!
* usbdrvasm.S ............ Assembler part of the driver. This module is mostly
a stub and includes one of the usbdrvasm*.S files
depending on processor clock. Link this module to
your code!
usbdrvasm*.inc ......... Assembler routines for particular clock frequencies.
Included by usbdrvasm.S, don't link it directly!
asmcommon.inc .......... Common assembler routines. Included by
usbdrvasm*.inc, don't link it directly!
usbconfig-prototype.h .. Prototype for your own usbdrv.h file.
* oddebug.c .............. Debug functions. Only used when DEBUG_LEVEL is
defined to a value greater than 0. Link this module
to your code!
oddebug.h .............. Interface definitions of the debug module.
usbportability.h ....... Header with compiler-dependent stuff.
usbdrvasm.asm .......... Compatibility stub for IAR-C-compiler. Use this
module instead of usbdrvasm.S when you assembler
with IAR's tools.
License.txt ............ Open Source license for this driver.
CommercialLicense.txt .. Optional commercial license for this driver.
USB-ID-FAQ.txt ......... General infos about USB Product- and Vendor-IDs.
USB-IDs-for-free.txt ... List and terms of use for free shared PIDs.
(*) ... These files should be linked to your project.
CPU CORE CLOCK FREQUENCY
========================
We supply assembler modules for clock frequencies of 12 MHz, 12.8 MHz, 15 MHz,
16 MHz, 16.5 MHz 18 MHz and 20 MHz. Other clock rates are not supported. The
actual clock rate must be configured in usbconfig.h.
12 MHz Clock
This is the traditional clock rate of V-USB because it's the lowest clock
rate where the timing constraints of the USB spec can be met.
15 MHz Clock
Similar to 12 MHz, but some NOPs inserted. On the other hand, the higher clock
rate allows for some loops which make the resulting code size somewhat smaller
than the 12 MHz version.
16 MHz Clock
This clock rate has been added for users of the Arduino board and other
ready-made boards which come with a fixed 16 MHz crystal. It's also an option
if you need the slightly higher clock rate for performance reasons. Since
16 MHz is not divisible by the USB low speed bit clock of 1.5 MHz, the code
is somewhat tricky and has to insert a leap cycle every third byte.
12.8 MHz and 16.5 MHz Clock
The assembler modules for these clock rates differ from the other modules
because they have been built for an RC oscillator with only 1% precision. The
receiver code inserts leap cycles to compensate for clock deviations. 1% is
also the precision which can be achieved by calibrating the internal RC
oscillator of the AVR. Please note that only AVRs with internal 64 MHz PLL
oscillator can reach 16.5 MHz with the RC oscillator. This includes the very
popular ATTiny25, ATTiny45, ATTiny85 series as well as the ATTiny26. Almost
all AVRs can reach 12.8 MHz, although this is outside the specified range.
See the EasyLogger example at http://www.obdev.at/vusb/easylogger.html for
code which calibrates the RC oscillator based on the USB frame clock.
18 MHz Clock
This module is closer to the USB specification because it performs an on the
fly CRC check for incoming packets. Packets with invalid checksum are
discarded as required by the spec. If you also implement checks for data
PID toggling on application level (see option USB_CFG_CHECK_DATA_TOGGLING
in usbconfig.h for more info), this ensures data integrity. Due to the CRC
tables and alignment requirements, this code is bigger than modules for other
clock rates. To activate this module, you must define USB_CFG_CHECK_CRC to 1
and USB_CFG_CLOCK_KHZ to 18000 in usbconfig.h.
20 MHz Clock
This module is for people who won't do it with less than the maximum. Since
20 MHz is not divisible by the USB low speed bit clock of 1.5 MHz, the code
uses similar tricks as the 16 MHz module to insert leap cycles.
USB IDENTIFIERS
===============
Every USB device needs a vendor- and a product-identifier (VID and PID). VIDs
are obtained from usb.org for a price of 1,500 USD. Once you have a VID, you
can assign PIDs at will.
Since an entry level cost of 1,500 USD is too high for most small companies
and hobbyists, we provide some VID/PID pairs for free. See the file
USB-IDs-for-free.txt for details.
Objective Development also has some license offerings which include product
IDs. See http://www.obdev.at/vusb/ for details.
DEVELOPMENT SYSTEM
==================
This driver has been developed and optimized for the GNU compiler version 3
and 4. We recommend that you use the GNU compiler suite because it is freely
available. V-USB has also been ported to the IAR compiler and assembler. It
has been tested with IAR 4.10B/W32 and 4.12A/W32 on an ATmega8 with the
"small" and "tiny" memory model. Not every release is tested with IAR CC and
the driver may therefore fail to compile with IAR. Please note that gcc is
more efficient for usbdrv.c because this module has been deliberately
optimized for gcc.
Gcc version 3 produces smaller code than version 4 due to new optimizing
capabilities which don't always improve things on 8 bit CPUs. The code size
generated by gcc 4 can be reduced with the compiler options
-fno-move-loop-invariants, -fno-tree-scev-cprop and
-fno-inline-small-functions in addition to -Os. On devices with more than
8k of flash memory, we also recommend the linker option --relax (written as
-Wl,--relax for gcc) to convert absolute calls into relative where possible.
For more information about optimizing options see:
http://www.tty1.net/blog/2008-04-29-avr-gcc-optimisations_en.html
These optimizations are good for gcc 4.x. Version 3.x of gcc does not support
most of these options and produces good code anyway.
USING V-USB FOR FREE
====================
The AVR firmware driver is published under the GNU General Public License
Version 2 (GPL2) and the GNU General Public License Version 3 (GPL3). It is
your choice whether you apply the terms of version 2 or version 3.
If you decide for the free GPL2 or GPL3, we STRONGLY ENCOURAGE you to do the
following things IN ADDITION to the obligations from the GPL:
(1) Publish your entire project on a web site and drop us a note with the URL.
Use the form at http://www.obdev.at/vusb/feedback.html for your submission.
If you don't have a web site, you can publish the project in obdev's
documentation wiki at
http://www.obdev.at/goto.php?t=vusb-wiki&p=hosted-projects.
(2) Adhere to minimum publication standards. Please include AT LEAST:
- a circuit diagram in PDF, PNG or GIF format
- full source code for the host software
- a Readme.txt file in ASCII format which describes the purpose of the
project and what can be found in which directories and which files
- a reference to http://www.obdev.at/vusb/
(3) If you improve the driver firmware itself, please give us a free license
to your modifications for our commercial license offerings.
COMMERCIAL LICENSES FOR V-USB
=============================
If you don't want to publish your source code under the terms of the GPL,
you can simply pay money for V-USB. As an additional benefit you get
USB PIDs for free, reserved exclusively to you. See the file
"CommercialLicense.txt" for details.

View File

@ -0,0 +1,149 @@
Version 2012-07-09
==========================
WHY DO WE NEED THESE IDs?
==========================
USB is more than a low level protocol for data transport. It also defines a
common set of requests which must be understood by all devices. And as part
of these common requests, the specification defines data structures, the
USB Descriptors, which are used to describe the properties of the device.
From the perspective of an operating system, it is therefore possible to find
out basic properties of a device (such as e.g. the manufacturer and the name
of the device) without a device-specific driver. This is essential because
the operating system can choose a driver to load based on this information
(Plug-And-Play).
Among the most important properties in the Device Descriptor are the USB
Vendor- and Product-ID. Both are 16 bit integers. The most simple form of
driver matching is based on these IDs. The driver announces the Vendor- and
Product-IDs of the devices it can handle and the operating system loads the
appropriate driver when the device is connected.
It is obvious that this technique only works if the pair Vendor- plus
Product-ID is unique: Only devices which require the same driver can have the
same pair of IDs.
=====================================================
HOW DOES THE USB STANDARD ENSURE THAT IDs ARE UNIQUE?
=====================================================
Since it is so important that USB IDs are unique, the USB Implementers Forum,
Inc. (usb.org) needs a way to enforce this legally. It is not forbidden by
law to build a device and assign it any random numbers as IDs. Usb.org
therefore needs an agreement to regulate the use of USB IDs. The agreement
binds only parties who agreed to it, of course. Everybody else is free to use
any numbers for their IDs.
So how can usb.org ensure that every manufacturer of USB devices enters into
an agreement with them? They do it via trademark licensing. Usb.org has
registered the trademark "USB", all associated logos and related terms. If
you want to put an USB logo on your product or claim that it is USB
compliant, you must license these trademarks from usb.org. And this is where
you enter into an agreement. See the "USB-IF Trademark License Agreement and
Usage Guidelines for the USB-IF Logo" at
http://www.usb.org/developers/logo_license/.
Licensing the USB trademarks requires that you buy a USB Vendor-ID from
usb.org (one-time fee of ca. 2,000 USD), that you become a member of usb.org
(yearly fee of ca. 4,000 USD) and that you meet all the technical
specifications from the USB spec.
This means that most hobbyists and small companies will never be able to
become USB compliant, just because membership is so expensive. And you can't
be compliant with a driver based on V-USB anyway, because the AVR's port pins
don't meet the electrical specifications for USB. So, in principle, all
hobbyists and small companies are free to choose any random numbers for their
IDs. They have nothing to lose...
There is one exception worth noting, though: If you use a sub-component which
implements USB, the vendor of the sub-components may guarantee USB
compliance. This might apply to some or all of FTDI's solutions.
=======================================================================
WHY SHOULD YOU OBTAIN USB IDs EVEN IF YOU DON'T LICENSE USB TRADEMARKS?
=======================================================================
You have learned in the previous section that you are free to choose any
numbers for your IDs anyway. So why not do exactly this? There is still the
technical issue. If you choose IDs which are already in use by somebody else,
operating systems will load the wrong drivers and your device won't work.
Even if you choose IDs which are not currently in use, they may be in use in
the next version of the operating system or even after an automatic update.
So what you need is a pair of Vendor- and Product-IDs for which you have the
guarantee that no USB compliant product uses them. This implies that no
operating system will ever ship with drivers responsible for these IDs.
==============================================
HOW DOES OBJECTIVE DEVELOPMENT HANDLE USB IDs?
==============================================
Objective Development gives away pairs of USB-IDs with their V-USB licenses.
In order to ensure that these IDs are unique, Objective Development has an
agreement with the company/person who has bought the USB Vendor-ID from
usb.org. This agreement ensures that a range of USB Product-IDs is reserved
for assignment by Objective Development and that the owner of the Vendor-ID
won't give it to anybody else.
This means that you have to trust three parties to ensure uniqueness of
your IDs:
- Objective Development, that they don't give the same PID to more than
one person.
- The owner of the Vendor-ID that they don't assign PIDs from the range
assigned to Objective Development to anybody else.
- Usb.org that they don't assign the same Vendor-ID a second time.
==================================
WHO IS THE OWNER OF THE VENDOR-ID?
==================================
Objective Development has obtained ranges of USB Product-IDs under two
Vendor-IDs: Under Vendor-ID 5824 from Wouter van Ooijen (Van Ooijen
Technische Informatica, www.voti.nl) and under Vendor-ID 8352 from Jason
Kotzin (now flirc.tv, Inc.). Both VID owners have received their Vendor-ID
directly from usb.org.
=========================================================================
CAN I USE USB-IDs FROM OBJECTIVE DEVELOPMENT WITH OTHER DRIVERS/HARDWARE?
=========================================================================
The short answer is: Yes. All you get is a guarantee that the IDs are never
assigned to anybody else. What more do you need?
============================
WHAT ABOUT SHARED ID PAIRS?
============================
Objective Development has reserved some PID/VID pairs for shared use. You
have no guarantee of uniqueness for them, except that no USB compliant device
uses them. In order to avoid technical problems, we must ensure that all
devices with the same pair of IDs use the same driver on kernel level. For
details, see the file USB-IDs-for-free.txt.
======================================================
I HAVE HEARD THAT SUB-LICENSING OF USB-IDs IS ILLEGAL?
======================================================
A 16 bit integer number cannot be protected by copyright laws. It is not
sufficiently complex. And since none of the parties involved entered into the
USB-IF Trademark License Agreement, we are not bound by this agreement. So
there is no reason why it should be illegal to sub-license USB-IDs.
=============================================
WHO IS LIABLE IF THERE ARE INCOMPATIBILITIES?
=============================================
Objective Development disclaims all liabilities which might arise from the
assignment of IDs. If you guarantee product features to your customers
without proper disclaimer, YOU are liable for that.

View File

@ -0,0 +1,154 @@
Version 2009-08-22
===========================
FREE USB-IDs FOR SHARED USE
===========================
Objective Development has reserved a set of USB Product-IDs for use according
to the guidelines outlined below. For more information about the concept of
USB IDs please see the file USB-ID-FAQ.txt. Objective Development guarantees
that the IDs listed below are not used by any USB compliant devices.
====================
MECHANISM OF SHARING
====================
From a technical point of view, two different devices can share the same USB
Vendor- and Product-ID if they require the same driver on operating system
level. We make use of this fact by assigning separate IDs for various device
classes. On application layer, devices must be distinguished by their textual
name or serial number. We offer separate sets of IDs for discrimination by
textual name and for serial number.
Examples for shared use of USB IDs are included with V-USB in the "examples"
subdirectory.
======================================
IDs FOR DISCRIMINATION BY TEXTUAL NAME
======================================
If you use one of the IDs listed below, your device and host-side software
must conform to these rules:
(1) The USB device MUST provide a textual representation of the manufacturer
and product identification. The manufacturer identification MUST be available
at least in USB language 0x0409 (English/US).
(2) The textual manufacturer identification MUST contain either an Internet
domain name (e.g. "mycompany.com") registered and owned by you, or an e-mail
address under your control (e.g. "myname@gmx.net"). You can embed the domain
name or e-mail address in any string you like, e.g. "Objective Development
http://www.obdev.at/vusb/".
(3) You are responsible for retaining ownership of the domain or e-mail
address for as long as any of your products are in use.
(4) You may choose any string for the textual product identification, as long
as this string is unique within the scope of your textual manufacturer
identification.
(5) Application side device look-up MUST be based on the textual manufacturer
and product identification in addition to VID/PID matching. The driver
matching MUST be a comparison of the entire strings, NOT a sub-string match.
(6) For devices which implement a particular USB device class (e.g. HID), the
operating system's default class driver MUST be used. If an operating system
driver for Vendor Class devices is needed, this driver must be libusb or
libusb-win32 (see http://libusb.org/ and
http://libusb-win32.sourceforge.net/).
Table if IDs for discrimination by textual name:
PID dec (hex) | VID dec (hex) | Description of use
==============+===============+============================================
1500 (0x05dc) | 5824 (0x16c0) | For Vendor Class devices with libusb
--------------+---------------+--------------------------------------------
1503 (0x05df) | 5824 (0x16c0) | For generic HID class devices (which are
| | NOT mice, keyboards or joysticks)
--------------+---------------+--------------------------------------------
1505 (0x05e1) | 5824 (0x16c0) | For CDC-ACM class devices (modems)
--------------+---------------+--------------------------------------------
1508 (0x05e4) | 5824 (0x16c0) | For MIDI class devices
--------------+---------------+--------------------------------------------
Note that Windows caches the textual product- and vendor-description for
mice, keyboards and joysticks. Name-bsed discrimination is therefore not
recommended for these device classes.
=======================================
IDs FOR DISCRIMINATION BY SERIAL NUMBER
=======================================
If you use one of the IDs listed below, your device and host-side software
must conform to these rules:
(1) The USB device MUST provide a textual representation of the serial
number, unless ONLY the operating system's default class driver is used.
The serial number string MUST be available at least in USB language 0x0409
(English/US).
(2) The serial number MUST start with either an Internet domain name (e.g.
"mycompany.com") registered and owned by you, or an e-mail address under your
control (e.g. "myname@gmx.net"), both terminated with a colon (":") character.
You MAY append any string you like for further discrimination of your devices.
(3) You are responsible for retaining ownership of the domain or e-mail
address for as long as any of your products are in use.
(5) Application side device look-up MUST be based on the serial number string
in addition to VID/PID matching. The matching must start at the first
character of the serial number string and include the colon character
terminating your domain or e-mail address. It MAY stop anywhere after that.
(6) For devices which implement a particular USB device class (e.g. HID), the
operating system's default class driver MUST be used. If an operating system
driver for Vendor Class devices is needed, this driver must be libusb or
libusb-win32 (see http://libusb.org/ and
http://libusb-win32.sourceforge.net/).
(7) If ONLY the operating system's default class driver is used, e.g. for
mice, keyboards, joysticks, CDC or MIDI devices and no discrimination by an
application is needed, the serial number may be omitted.
Table if IDs for discrimination by serial number string:
PID dec (hex) | VID dec (hex) | Description of use
===============+===============+===========================================
10200 (0x27d8) | 5824 (0x16c0) | For Vendor Class devices with libusb
---------------+---------------+-------------------------------------------
10201 (0x27d9) | 5824 (0x16c0) | For generic HID class devices (which are
| | NOT mice, keyboards or joysticks)
---------------+---------------+-------------------------------------------
10202 (0x27da) | 5824 (0x16c0) | For USB Mice
---------------+---------------+-------------------------------------------
10203 (0x27db) | 5824 (0x16c0) | For USB Keyboards
---------------+---------------+-------------------------------------------
10204 (0x27dc) | 5824 (0x16c0) | For USB Joysticks
---------------+---------------+-------------------------------------------
10205 (0x27dd) | 5824 (0x16c0) | For CDC-ACM class devices (modems)
---------------+---------------+-------------------------------------------
10206 (0x27de) | 5824 (0x16c0) | For MIDI class devices
---------------+---------------+-------------------------------------------
=================
ORIGIN OF USB-IDs
=================
OBJECTIVE DEVELOPMENT Software GmbH has obtained all VID/PID pairs listed
here from Wouter van Ooijen (see www.voti.nl) for exclusive disposition.
Wouter van Ooijen has obtained the VID from the USB Implementers Forum, Inc.
(see www.usb.org). The VID is registered for the company name "Van Ooijen
Technische Informatica".
==========
DISCLAIMER
==========
OBJECTIVE DEVELOPMENT Software GmbH disclaims all liability for any
problems which are caused by the shared use of these VID/PID pairs.

View File

@ -0,0 +1,187 @@
/* Name: asmcommon.inc
* Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
* Author: Christian Starkjohann
* Creation Date: 2007-11-05
* Tabsize: 4
* Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
/* Do not link this file! Link usbdrvasm.S instead, which includes the
* appropriate implementation!
*/
/*
General Description:
This file contains assembler code which is shared among the USB driver
implementations for different CPU cocks. Since the code must be inserted
in the middle of the module, it's split out into this file and #included.
Jump destinations called from outside:
sofError: Called when no start sequence was found.
se0: Called when a package has been successfully received.
overflow: Called when receive buffer overflows.
doReturn: Called after sending data.
Outside jump destinations used by this module:
waitForJ: Called to receive an already arriving packet.
sendAckAndReti:
sendNakAndReti:
sendCntAndReti:
usbSendAndReti:
The following macros must be defined before this file is included:
.macro POP_STANDARD
.endm
.macro POP_RETI
.endm
*/
#define token x1
overflow:
ldi x2, 1<<USB_INTR_PENDING_BIT
USB_STORE_PENDING(x2) ; clear any pending interrupts
ignorePacket:
clr token
rjmp storeTokenAndReturn
;----------------------------------------------------------------------------
; Processing of received packet (numbers in brackets are cycles after center of SE0)
;----------------------------------------------------------------------------
;This is the only non-error exit point for the software receiver loop
;we don't check any CRCs here because there is no time left.
se0:
subi cnt, USB_BUFSIZE ;[5]
neg cnt ;[6]
sub YL, cnt ;[7]
sbci YH, 0 ;[8]
ldi x2, 1<<USB_INTR_PENDING_BIT ;[9]
USB_STORE_PENDING(x2) ;[10] clear pending intr and check flag later. SE0 should be over.
ld token, y ;[11]
cpi token, USBPID_DATA0 ;[13]
breq handleData ;[14]
cpi token, USBPID_DATA1 ;[15]
breq handleData ;[16]
lds shift, usbDeviceAddr;[17]
ldd x2, y+1 ;[19] ADDR and 1 bit endpoint number
lsl x2 ;[21] shift out 1 bit endpoint number
cpse x2, shift ;[22]
rjmp ignorePacket ;[23]
/* only compute endpoint number in x3 if required later */
#if USB_CFG_HAVE_INTRIN_ENDPOINT || USB_CFG_IMPLEMENT_FN_WRITEOUT
ldd x3, y+2 ;[24] endpoint number + crc
rol x3 ;[26] shift in LSB of endpoint
#endif
cpi token, USBPID_IN ;[27]
breq handleIn ;[28]
cpi token, USBPID_SETUP ;[29]
breq handleSetupOrOut ;[30]
cpi token, USBPID_OUT ;[31]
brne ignorePacket ;[32] must be ack, nak or whatever
; rjmp handleSetupOrOut ; fallthrough
;Setup and Out are followed by a data packet two bit times (16 cycles) after
;the end of SE0. The sync code allows up to 40 cycles delay from the start of
;the sync pattern until the first bit is sampled. That's a total of 56 cycles.
handleSetupOrOut: ;[32]
#if USB_CFG_IMPLEMENT_FN_WRITEOUT /* if we have data for endpoint != 0, set usbCurrentTok to address */
andi x3, 0xf ;[32]
breq storeTokenAndReturn ;[33]
mov token, x3 ;[34] indicate that this is endpoint x OUT
#endif
storeTokenAndReturn:
sts usbCurrentTok, token;[35]
doReturn:
POP_STANDARD ;[37] 12...16 cycles
USB_LOAD_PENDING(YL) ;[49]
sbrc YL, USB_INTR_PENDING_BIT;[50] check whether data is already arriving
rjmp waitForJ ;[51] save the pops and pushes -- a new interrupt is already pending
sofError:
POP_RETI ;macro call
reti
handleData:
#if USB_CFG_CHECK_CRC
CRC_CLEANUP_AND_CHECK ; jumps to ignorePacket if CRC error
#endif
lds shift, usbCurrentTok;[18]
tst shift ;[20]
breq doReturn ;[21]
lds x2, usbRxLen ;[22]
tst x2 ;[24]
brne sendNakAndReti ;[25]
; 2006-03-11: The following two lines fix a problem where the device was not
; recognized if usbPoll() was called less frequently than once every 4 ms.
cpi cnt, 4 ;[26] zero sized data packets are status phase only -- ignore and ack
brmi sendAckAndReti ;[27] keep rx buffer clean -- we must not NAK next SETUP
#if USB_CFG_CHECK_DATA_TOGGLING
sts usbCurrentDataToken, token ; store for checking by C code
#endif
sts usbRxLen, cnt ;[28] store received data, swap buffers
sts usbRxToken, shift ;[30]
lds x2, usbInputBufOffset;[32] swap buffers
ldi cnt, USB_BUFSIZE ;[34]
sub cnt, x2 ;[35]
sts usbInputBufOffset, cnt;[36] buffers now swapped
rjmp sendAckAndReti ;[38] 40 + 17 = 57 until SOP
handleIn:
;We don't send any data as long as the C code has not processed the current
;input data and potentially updated the output data. That's more efficient
;in terms of code size than clearing the tx buffers when a packet is received.
lds x1, usbRxLen ;[30]
cpi x1, 1 ;[32] negative values are flow control, 0 means "buffer free"
brge sendNakAndReti ;[33] unprocessed input packet?
ldi x1, USBPID_NAK ;[34] prepare value for usbTxLen
#if USB_CFG_HAVE_INTRIN_ENDPOINT
andi x3, 0xf ;[35] x3 contains endpoint
#if USB_CFG_SUPPRESS_INTR_CODE
brne sendNakAndReti ;[36]
#else
brne handleIn1 ;[36]
#endif
#endif
lds cnt, usbTxLen ;[37]
sbrc cnt, 4 ;[39] all handshake tokens have bit 4 set
rjmp sendCntAndReti ;[40] 42 + 16 = 58 until SOP
sts usbTxLen, x1 ;[41] x1 == USBPID_NAK from above
ldi YL, lo8(usbTxBuf) ;[43]
ldi YH, hi8(usbTxBuf) ;[44]
rjmp usbSendAndReti ;[45] 57 + 12 = 59 until SOP
; Comment about when to set usbTxLen to USBPID_NAK:
; We should set it back when we receive the ACK from the host. This would
; be simple to implement: One static variable which stores whether the last
; tx was for endpoint 0 or 1 and a compare in the receiver to distinguish the
; ACK. However, we set it back immediately when we send the package,
; assuming that no error occurs and the host sends an ACK. We save one byte
; RAM this way and avoid potential problems with endless retries. The rest of
; the driver assumes error-free transfers anyway.
#if !USB_CFG_SUPPRESS_INTR_CODE && USB_CFG_HAVE_INTRIN_ENDPOINT /* placed here due to relative jump range */
handleIn1: ;[38]
#if USB_CFG_HAVE_INTRIN_ENDPOINT3
; 2006-06-10 as suggested by O.Tamura: support second INTR IN / BULK IN endpoint
cpi x3, USB_CFG_EP3_NUMBER;[38]
breq handleIn3 ;[39]
#endif
lds cnt, usbTxLen1 ;[40]
sbrc cnt, 4 ;[42] all handshake tokens have bit 4 set
rjmp sendCntAndReti ;[43] 47 + 16 = 63 until SOP
sts usbTxLen1, x1 ;[44] x1 == USBPID_NAK from above
ldi YL, lo8(usbTxBuf1) ;[46]
ldi YH, hi8(usbTxBuf1) ;[47]
rjmp usbSendAndReti ;[48] 50 + 12 = 62 until SOP
#if USB_CFG_HAVE_INTRIN_ENDPOINT3
handleIn3:
lds cnt, usbTxLen3 ;[41]
sbrc cnt, 4 ;[43]
rjmp sendCntAndReti ;[44] 49 + 16 = 65 until SOP
sts usbTxLen3, x1 ;[45] x1 == USBPID_NAK from above
ldi YL, lo8(usbTxBuf3) ;[47]
ldi YH, hi8(usbTxBuf3) ;[48]
rjmp usbSendAndReti ;[49] 51 + 12 = 63 until SOP
#endif
#endif

View File

@ -0,0 +1,49 @@
/* Name: oddebug.c
* Project: AVR library
* Author: Christian Starkjohann
* Creation Date: 2005-01-16
* Tabsize: 4
* Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
#include "oddebug.h"
#if DEBUG_LEVEL > 0
#warning "Never compile production devices with debugging enabled"
static void uartPutc(char c)
{
while(!(ODDBG_USR & (1 << ODDBG_UDRE))); /* wait for data register empty */
ODDBG_UDR = c;
}
static uchar hexAscii(uchar h)
{
h &= 0xf;
if(h >= 10)
h += 'a' - (uchar)10 - '0';
h += '0';
return h;
}
static void printHex(uchar c)
{
uartPutc(hexAscii(c >> 4));
uartPutc(hexAscii(c));
}
void odDebug(uchar prefix, uchar *data, uchar len)
{
printHex(prefix);
uartPutc(':');
while(len--){
uartPutc(' ');
printHex(*data++);
}
uartPutc('\r');
uartPutc('\n');
}
#endif

View File

@ -0,0 +1,122 @@
/* Name: oddebug.h
* Project: AVR library
* Author: Christian Starkjohann
* Creation Date: 2005-01-16
* Tabsize: 4
* Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
#ifndef __oddebug_h_included__
#define __oddebug_h_included__
/*
General Description:
This module implements a function for debug logs on the serial line of the
AVR microcontroller. Debugging can be configured with the define
'DEBUG_LEVEL'. If this macro is not defined or defined to 0, all debugging
calls are no-ops. If it is 1, DBG1 logs will appear, but not DBG2. If it is
2, DBG1 and DBG2 logs will be printed.
A debug log consists of a label ('prefix') to indicate which debug log created
the output and a memory block to dump in hex ('data' and 'len').
*/
#ifndef F_CPU
# define F_CPU 12000000 /* 12 MHz */
#endif
/* make sure we have the UART defines: */
#include "usbportability.h"
#ifndef uchar
# define uchar unsigned char
#endif
#if DEBUG_LEVEL > 0 && !(defined TXEN || defined TXEN0) /* no UART in device */
# warning "Debugging disabled because device has no UART"
# undef DEBUG_LEVEL
#endif
#ifndef DEBUG_LEVEL
# define DEBUG_LEVEL 0
#endif
/* ------------------------------------------------------------------------- */
#if DEBUG_LEVEL > 0
# define DBG1(prefix, data, len) odDebug(prefix, data, len)
#else
# define DBG1(prefix, data, len)
#endif
#if DEBUG_LEVEL > 1
# define DBG2(prefix, data, len) odDebug(prefix, data, len)
#else
# define DBG2(prefix, data, len)
#endif
/* ------------------------------------------------------------------------- */
#if DEBUG_LEVEL > 0
extern void odDebug(uchar prefix, uchar *data, uchar len);
/* Try to find our control registers; ATMEL likes to rename these */
#if defined UBRR
# define ODDBG_UBRR UBRR
#elif defined UBRRL
# define ODDBG_UBRR UBRRL
#elif defined UBRR0
# define ODDBG_UBRR UBRR0
#elif defined UBRR0L
# define ODDBG_UBRR UBRR0L
#endif
#if defined UCR
# define ODDBG_UCR UCR
#elif defined UCSRB
# define ODDBG_UCR UCSRB
#elif defined UCSR0B
# define ODDBG_UCR UCSR0B
#endif
#if defined TXEN
# define ODDBG_TXEN TXEN
#else
# define ODDBG_TXEN TXEN0
#endif
#if defined USR
# define ODDBG_USR USR
#elif defined UCSRA
# define ODDBG_USR UCSRA
#elif defined UCSR0A
# define ODDBG_USR UCSR0A
#endif
#if defined UDRE
# define ODDBG_UDRE UDRE
#else
# define ODDBG_UDRE UDRE0
#endif
#if defined UDR
# define ODDBG_UDR UDR
#elif defined UDR0
# define ODDBG_UDR UDR0
#endif
static inline void odDebugInit(void)
{
ODDBG_UCR |= (1<<ODDBG_TXEN);
ODDBG_UBRR = F_CPU / (19200 * 16L) - 1;
}
#else
# define odDebugInit()
#endif
/* ------------------------------------------------------------------------- */
#endif /* __oddebug_h_included__ */

View File

@ -0,0 +1,384 @@
/* Name: usbconfig.h
* Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
* Author: Christian Starkjohann
* Creation Date: 2005-04-01
* Tabsize: 4
* Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
* License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
*/
#ifndef __usbconfig_h_included__
#define __usbconfig_h_included__
/*
General Description:
This file is an example configuration (with inline documentation) for the USB
driver. It configures V-USB for USB D+ connected to Port D bit 2 (which is
also hardware interrupt 0 on many devices) and USB D- to Port D bit 4. You may
wire the lines to any other port, as long as D+ is also wired to INT0 (or any
other hardware interrupt, as long as it is the highest level interrupt, see
section at the end of this file).
+ To create your own usbconfig.h file, copy this file to your project's
+ firmware source directory) and rename it to "usbconfig.h".
+ Then edit it accordingly.
*/
/* ---------------------------- Hardware Config ---------------------------- */
#define USB_CFG_IOPORTNAME D
/* This is the port where the USB bus is connected. When you configure it to
* "B", the registers PORTB, PINB and DDRB will be used.
*/
#define USB_CFG_DMINUS_BIT 4
/* This is the bit number in USB_CFG_IOPORT where the USB D- line is connected.
* This may be any bit in the port.
*/
#define USB_CFG_DPLUS_BIT 2
/* This is the bit number in USB_CFG_IOPORT where the USB D+ line is connected.
* This may be any bit in the port. Please note that D+ must also be connected
* to interrupt pin INT0! [You can also use other interrupts, see section
* "Optional MCU Description" below, or you can connect D- to the interrupt, as
* it is required if you use the USB_COUNT_SOF feature. If you use D- for the
* interrupt, the USB interrupt will also be triggered at Start-Of-Frame
* markers every millisecond.]
*/
#define USB_CFG_CLOCK_KHZ (F_CPU/1000)
/* Clock rate of the AVR in kHz. Legal values are 12000, 12800, 15000, 16000,
* 16500, 18000 and 20000. The 12.8 MHz and 16.5 MHz versions of the code
* require no crystal, they tolerate +/- 1% deviation from the nominal
* frequency. All other rates require a precision of 2000 ppm and thus a
* crystal!
* Since F_CPU should be defined to your actual clock rate anyway, you should
* not need to modify this setting.
*/
#define USB_CFG_CHECK_CRC 0
/* Define this to 1 if you want that the driver checks integrity of incoming
* data packets (CRC checks). CRC checks cost quite a bit of code size and are
* currently only available for 18 MHz crystal clock. You must choose
* USB_CFG_CLOCK_KHZ = 18000 if you enable this option.
*/
/* ----------------------- Optional Hardware Config ------------------------ */
/* #define USB_CFG_PULLUP_IOPORTNAME D */
/* If you connect the 1.5k pullup resistor from D- to a port pin instead of
* V+, you can connect and disconnect the device from firmware by calling
* the macros usbDeviceConnect() and usbDeviceDisconnect() (see usbdrv.h).
* This constant defines the port on which the pullup resistor is connected.
*/
/* #define USB_CFG_PULLUP_BIT 4 */
/* This constant defines the bit number in USB_CFG_PULLUP_IOPORT (defined
* above) where the 1.5k pullup resistor is connected. See description
* above for details.
*/
/* --------------------------- Functional Range ---------------------------- */
#define USB_CFG_HAVE_INTRIN_ENDPOINT 0
/* Define this to 1 if you want to compile a version with two endpoints: The
* default control endpoint 0 and an interrupt-in endpoint (any other endpoint
* number).
*/
#define USB_CFG_HAVE_INTRIN_ENDPOINT3 0
/* Define this to 1 if you want to compile a version with three endpoints: The
* default control endpoint 0, an interrupt-in endpoint 3 (or the number
* configured below) and a catch-all default interrupt-in endpoint as above.
* You must also define USB_CFG_HAVE_INTRIN_ENDPOINT to 1 for this feature.
*/
#define USB_CFG_EP3_NUMBER 3
/* If the so-called endpoint 3 is used, it can now be configured to any other
* endpoint number (except 0) with this macro. Default if undefined is 3.
*/
/* #define USB_INITIAL_DATATOKEN USBPID_DATA1 */
/* The above macro defines the startup condition for data toggling on the
* interrupt/bulk endpoints 1 and 3. Defaults to USBPID_DATA1.
* Since the token is toggled BEFORE sending any data, the first packet is
* sent with the oposite value of this configuration!
*/
#define USB_CFG_IMPLEMENT_HALT 0
/* Define this to 1 if you also want to implement the ENDPOINT_HALT feature
* for endpoint 1 (interrupt endpoint). Although you may not need this feature,
* it is required by the standard. We have made it a config option because it
* bloats the code considerably.
*/
#define USB_CFG_SUPPRESS_INTR_CODE 0
/* Define this to 1 if you want to declare interrupt-in endpoints, but don't
* want to send any data over them. If this macro is defined to 1, functions
* usbSetInterrupt() and usbSetInterrupt3() are omitted. This is useful if
* you need the interrupt-in endpoints in order to comply to an interface
* (e.g. HID), but never want to send any data. This option saves a couple
* of bytes in flash memory and the transmit buffers in RAM.
*/
#define USB_CFG_INTR_POLL_INTERVAL 10
/* If you compile a version with endpoint 1 (interrupt-in), this is the poll
* interval. The value is in milliseconds and must not be less than 10 ms for
* low speed devices.
*/
#define USB_CFG_IS_SELF_POWERED 0
/* Define this to 1 if the device has its own power supply. Set it to 0 if the
* device is powered from the USB bus.
*/
#define USB_CFG_MAX_BUS_POWER 100
/* Set this variable to the maximum USB bus power consumption of your device.
* The value is in milliamperes. [It will be divided by two since USB
* communicates power requirements in units of 2 mA.]
*/
#define USB_CFG_IMPLEMENT_FN_WRITE 0
/* Set this to 1 if you want usbFunctionWrite() to be called for control-out
* transfers. Set it to 0 if you don't need it and want to save a couple of
* bytes.
*/
#define USB_CFG_IMPLEMENT_FN_READ 0
/* Set this to 1 if you need to send control replies which are generated
* "on the fly" when usbFunctionRead() is called. If you only want to send
* data from a static buffer, set it to 0 and return the data from
* usbFunctionSetup(). This saves a couple of bytes.
*/
#define USB_CFG_IMPLEMENT_FN_WRITEOUT 0
/* Define this to 1 if you want to use interrupt-out (or bulk out) endpoints.
* You must implement the function usbFunctionWriteOut() which receives all
* interrupt/bulk data sent to any endpoint other than 0. The endpoint number
* can be found in 'usbRxToken'.
*/
#define USB_CFG_HAVE_FLOWCONTROL 0
/* Define this to 1 if you want flowcontrol over USB data. See the definition
* of the macros usbDisableAllRequests() and usbEnableAllRequests() in
* usbdrv.h.
*/
#define USB_CFG_DRIVER_FLASH_PAGE 0
/* If the device has more than 64 kBytes of flash, define this to the 64 k page
* where the driver's constants (descriptors) are located. Or in other words:
* Define this to 1 for boot loaders on the ATMega128.
*/
#define USB_CFG_LONG_TRANSFERS 0
/* Define this to 1 if you want to send/receive blocks of more than 254 bytes
* in a single control-in or control-out transfer. Note that the capability
* for long transfers increases the driver size.
*/
/* #define USB_RX_USER_HOOK(data, len) if(usbRxToken == (uchar)USBPID_SETUP) blinkLED(); */
/* This macro is a hook if you want to do unconventional things. If it is
* defined, it's inserted at the beginning of received message processing.
* If you eat the received message and don't want default processing to
* proceed, do a return after doing your things. One possible application
* (besides debugging) is to flash a status LED on each packet.
*/
/* #define USB_RESET_HOOK(resetStarts) if(!resetStarts){hadUsbReset();} */
/* This macro is a hook if you need to know when an USB RESET occurs. It has
* one parameter which distinguishes between the start of RESET state and its
* end.
*/
/* #define USB_SET_ADDRESS_HOOK() hadAddressAssigned(); */
/* This macro (if defined) is executed when a USB SET_ADDRESS request was
* received.
*/
#define USB_COUNT_SOF 0
/* define this macro to 1 if you need the global variable "usbSofCount" which
* counts SOF packets. This feature requires that the hardware interrupt is
* connected to D- instead of D+.
*/
/* #ifdef __ASSEMBLER__
* macro myAssemblerMacro
* in YL, TCNT0
* sts timer0Snapshot, YL
* endm
* #endif
* #define USB_SOF_HOOK myAssemblerMacro
* This macro (if defined) is executed in the assembler module when a
* Start Of Frame condition is detected. It is recommended to define it to
* the name of an assembler macro which is defined here as well so that more
* than one assembler instruction can be used. The macro may use the register
* YL and modify SREG. If it lasts longer than a couple of cycles, USB messages
* immediately after an SOF pulse may be lost and must be retried by the host.
* What can you do with this hook? Since the SOF signal occurs exactly every
* 1 ms (unless the host is in sleep mode), you can use it to tune OSCCAL in
* designs running on the internal RC oscillator.
* Please note that Start Of Frame detection works only if D- is wired to the
* interrupt, not D+. THIS IS DIFFERENT THAN MOST EXAMPLES!
*/
#define USB_CFG_CHECK_DATA_TOGGLING 0
/* define this macro to 1 if you want to filter out duplicate data packets
* sent by the host. Duplicates occur only as a consequence of communication
* errors, when the host does not receive an ACK. Please note that you need to
* implement the filtering yourself in usbFunctionWriteOut() and
* usbFunctionWrite(). Use the global usbCurrentDataToken and a static variable
* for each control- and out-endpoint to check for duplicate packets.
*/
#define USB_CFG_HAVE_MEASURE_FRAME_LENGTH 0
/* define this macro to 1 if you want the function usbMeasureFrameLength()
* compiled in. This function can be used to calibrate the AVR's RC oscillator.
*/
#define USB_USE_FAST_CRC 0
/* The assembler module has two implementations for the CRC algorithm. One is
* faster, the other is smaller. This CRC routine is only used for transmitted
* messages where timing is not critical. The faster routine needs 31 cycles
* per byte while the smaller one needs 61 to 69 cycles. The faster routine
* may be worth the 32 bytes bigger code size if you transmit lots of data and
* run the AVR close to its limit.
*/
/* -------------------------- Device Description --------------------------- */
#define USB_CFG_VENDOR_ID 0xc0, 0x16 /* = 0x16c0 = 5824 = voti.nl */
/* USB vendor ID for the device, low byte first. If you have registered your
* own Vendor ID, define it here. Otherwise you may use one of obdev's free
* shared VID/PID pairs. Be sure to read USB-IDs-for-free.txt for rules!
* *** IMPORTANT NOTE ***
* This template uses obdev's shared VID/PID pair for Vendor Class devices
* with libusb: 0x16c0/0x5dc. Use this VID/PID pair ONLY if you understand
* the implications!
*/
#define USB_CFG_DEVICE_ID 0xdc, 0x05 /* = 0x05dc = 1500 */
/* This is the ID of the product, low byte first. It is interpreted in the
* scope of the vendor ID. If you have registered your own VID with usb.org
* or if you have licensed a PID from somebody else, define it here. Otherwise
* you may use one of obdev's free shared VID/PID pairs. See the file
* USB-IDs-for-free.txt for details!
* *** IMPORTANT NOTE ***
* This template uses obdev's shared VID/PID pair for Vendor Class devices
* with libusb: 0x16c0/0x5dc. Use this VID/PID pair ONLY if you understand
* the implications!
*/
#define USB_CFG_DEVICE_VERSION 0x00, 0x01
/* Version number of the device: Minor number first, then major number.
*/
#define USB_CFG_VENDOR_NAME 'o', 'b', 'd', 'e', 'v', '.', 'a', 't'
#define USB_CFG_VENDOR_NAME_LEN 8
/* These two values define the vendor name returned by the USB device. The name
* must be given as a list of characters under single quotes. The characters
* are interpreted as Unicode (UTF-16) entities.
* If you don't want a vendor name string, undefine these macros.
* ALWAYS define a vendor name containing your Internet domain name if you use
* obdev's free shared VID/PID pair. See the file USB-IDs-for-free.txt for
* details.
*/
#define USB_CFG_DEVICE_NAME 'T', 'e', 'm', 'p', 'l', 'a', 't', 'e'
#define USB_CFG_DEVICE_NAME_LEN 8
/* Same as above for the device name. If you don't want a device name, undefine
* the macros. See the file USB-IDs-for-free.txt before you assign a name if
* you use a shared VID/PID.
*/
/*#define USB_CFG_SERIAL_NUMBER 'N', 'o', 'n', 'e' */
/*#define USB_CFG_SERIAL_NUMBER_LEN 0 */
/* Same as above for the serial number. If you don't want a serial number,
* undefine the macros.
* It may be useful to provide the serial number through other means than at
* compile time. See the section about descriptor properties below for how
* to fine tune control over USB descriptors such as the string descriptor
* for the serial number.
*/
#define USB_CFG_DEVICE_CLASS 0xff /* set to 0 if deferred to interface */
#define USB_CFG_DEVICE_SUBCLASS 0
/* See USB specification if you want to conform to an existing device class.
* Class 0xff is "vendor specific".
*/
#define USB_CFG_INTERFACE_CLASS 0 /* define class here if not at device level */
#define USB_CFG_INTERFACE_SUBCLASS 0
#define USB_CFG_INTERFACE_PROTOCOL 0
/* See USB specification if you want to conform to an existing device class or
* protocol. The following classes must be set at interface level:
* HID class is 3, no subclass and protocol required (but may be useful!)
* CDC class is 2, use subclass 2 and protocol 1 for ACM
*/
/* #define USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH 42 */
/* Define this to the length of the HID report descriptor, if you implement
* an HID device. Otherwise don't define it or define it to 0.
* If you use this define, you must add a PROGMEM character array named
* "usbHidReportDescriptor" to your code which contains the report descriptor.
* Don't forget to keep the array and this define in sync!
*/
/* #define USB_PUBLIC static */
/* Use the define above if you #include usbdrv.c instead of linking against it.
* This technique saves a couple of bytes in flash memory.
*/
/* ------------------- Fine Control over USB Descriptors ------------------- */
/* If you don't want to use the driver's default USB descriptors, you can
* provide our own. These can be provided as (1) fixed length static data in
* flash memory, (2) fixed length static data in RAM or (3) dynamically at
* runtime in the function usbFunctionDescriptor(). See usbdrv.h for more
* information about this function.
* Descriptor handling is configured through the descriptor's properties. If
* no properties are defined or if they are 0, the default descriptor is used.
* Possible properties are:
* + USB_PROP_IS_DYNAMIC: The data for the descriptor should be fetched
* at runtime via usbFunctionDescriptor(). If the usbMsgPtr mechanism is
* used, the data is in FLASH by default. Add property USB_PROP_IS_RAM if
* you want RAM pointers.
* + USB_PROP_IS_RAM: The data returned by usbFunctionDescriptor() or found
* in static memory is in RAM, not in flash memory.
* + USB_PROP_LENGTH(len): If the data is in static memory (RAM or flash),
* the driver must know the descriptor's length. The descriptor itself is
* found at the address of a well known identifier (see below).
* List of static descriptor names (must be declared PROGMEM if in flash):
* char usbDescriptorDevice[];
* char usbDescriptorConfiguration[];
* char usbDescriptorHidReport[];
* char usbDescriptorString0[];
* int usbDescriptorStringVendor[];
* int usbDescriptorStringDevice[];
* int usbDescriptorStringSerialNumber[];
* Other descriptors can't be provided statically, they must be provided
* dynamically at runtime.
*
* Descriptor properties are or-ed or added together, e.g.:
* #define USB_CFG_DESCR_PROPS_DEVICE (USB_PROP_IS_RAM | USB_PROP_LENGTH(18))
*
* The following descriptors are defined:
* USB_CFG_DESCR_PROPS_DEVICE
* USB_CFG_DESCR_PROPS_CONFIGURATION
* USB_CFG_DESCR_PROPS_STRINGS
* USB_CFG_DESCR_PROPS_STRING_0
* USB_CFG_DESCR_PROPS_STRING_VENDOR
* USB_CFG_DESCR_PROPS_STRING_PRODUCT
* USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
* USB_CFG_DESCR_PROPS_HID
* USB_CFG_DESCR_PROPS_HID_REPORT
* USB_CFG_DESCR_PROPS_UNKNOWN (for all descriptors not handled by the driver)
*
* Note about string descriptors: String descriptors are not just strings, they
* are Unicode strings prefixed with a 2 byte header. Example:
* int serialNumberDescriptor[] = {
* USB_STRING_DESCRIPTOR_HEADER(6),
* 'S', 'e', 'r', 'i', 'a', 'l'
* };
*/
#define USB_CFG_DESCR_PROPS_DEVICE 0
#define USB_CFG_DESCR_PROPS_CONFIGURATION 0
#define USB_CFG_DESCR_PROPS_STRINGS 0
#define USB_CFG_DESCR_PROPS_STRING_0 0
#define USB_CFG_DESCR_PROPS_STRING_VENDOR 0
#define USB_CFG_DESCR_PROPS_STRING_PRODUCT 0
#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER 0
#define USB_CFG_DESCR_PROPS_HID 0
#define USB_CFG_DESCR_PROPS_HID_REPORT 0
#define USB_CFG_DESCR_PROPS_UNKNOWN 0
#define usbMsgPtr_t unsigned short
/* If usbMsgPtr_t is not defined, it defaults to 'uchar *'. We define it to
* a scalar type here because gcc generates slightly shorter code for scalar
* arithmetics than for pointer arithmetics. Remove this define for backward
* type compatibility or define it to an 8 bit type if you use data in RAM only
* and all RAM is below 256 bytes (tiny memory model in IAR CC).
*/
/* ----------------------- Optional MCU Description ------------------------ */
/* The following configurations have working defaults in usbdrv.h. You
* usually don't need to set them explicitly. Only if you want to run
* the driver on a device which is not yet supported or with a compiler
* which is not fully supported (such as IAR C) or if you use a differnt
* interrupt than INT0, you may have to define some of these.
*/
/* #define USB_INTR_CFG MCUCR */
/* #define USB_INTR_CFG_SET ((1 << ISC00) | (1 << ISC01)) */
/* #define USB_INTR_CFG_CLR 0 */
/* #define USB_INTR_ENABLE GIMSK */
/* #define USB_INTR_ENABLE_BIT INT0 */
/* #define USB_INTR_PENDING GIFR */
/* #define USB_INTR_PENDING_BIT INTF0 */
/* #define USB_INTR_VECTOR INT0_vect */
#endif /* __usbconfig_h_included__ */

Some files were not shown because too many files have changed in this diff Show More