Thomas Buck 1 рік тому
коміт
cf82de8f39

+ 1
- 0
PPMDecoder

@@ -0,0 +1 @@
1
+Subproject commit 69f7151430e5ac07fa8a6526c109ff1d7b42bb24

+ 6
- 0
README.md Переглянути файл

@@ -0,0 +1,6 @@
1
+Adapted from https://github.com/normbxl/USB_PPM_Joystick
2
+Added https://github.com/VICLER/PPMDecoder to it for increased precision.
3
+
4
+// D3 / PD3 / INT1 for PPM input
5
+// D2 / PD2 / INT0 used for D+ of USB
6
+// D4 / PD4 used for D- of USB

+ 89
- 0
USBPPM.ino Переглянути файл

@@ -0,0 +1,89 @@
1
+#include "UsbJoystick.h"
2
+#include "PPM.h"
3
+
4
+#define CHANNELS 8
5
+// D3 / PD3 / INT1 for PPM input
6
+// D2 / PD2 / INT0 used for D+ of USB
7
+// D4 / PD4 used for D- of USB
8
+
9
+unsigned short a2dValue;
10
+unsigned char high;
11
+unsigned char low;
12
+unsigned char temp;
13
+unsigned char report[8];
14
+
15
+void setup(void) {
16
+  //Serial.begin(115200);
17
+  //Serial.println("Init");
18
+  
19
+  ppm.begin(CHANNELS);
20
+  usbDeviceConnect();
21
+}
22
+
23
+void loop(void) {
24
+  UsbJoystick.refresh(); // Let the AVRUSB driver do some houskeeping
25
+  calculateReport(); // Jump to our port read routine that orders the values
26
+  UsbJoystick.sendJoystick(report[0],report[1],report[2],report[3],report[4],report[5],report[6],report[7]); // send the values
27
+}
28
+
29
+void calculateReport() {  //The values read from the analog ports have to be ordered in a way the HID protocol wants it; a bit confusing.
30
+  if(!ppm.available()) {
31
+    //Serial.println("abort");
32
+    return;
33
+  }
34
+
35
+  /*
36
+  Serial.print(ppm.get(0) - MIN_PULSE);
37
+  Serial.print(' ');
38
+  Serial.print(ppm.get(1) - MIN_PULSE);
39
+  Serial.print(' ');
40
+  Serial.print(ppm.get(2) - MIN_PULSE);
41
+  Serial.println();
42
+  */
43
+  
44
+  a2dValue = ppm.get(1) - MIN_PULSE;
45
+  high = a2dValue >> 8;
46
+  low = a2dValue & 255;
47
+  report[0] = low;
48
+  temp = high;
49
+
50
+  a2dValue = ppm.get(0) - MIN_PULSE;
51
+  high = a2dValue >> 6;
52
+  low = a2dValue & 63;
53
+  report[1] = (low << 2) + temp;
54
+  temp = high;
55
+
56
+  a2dValue = ppm.get(2) - MIN_PULSE;
57
+  high = a2dValue >> 4;
58
+  low = a2dValue & 15;
59
+  report[2] = (low << 4) + temp;
60
+  temp = high;
61
+
62
+  a2dValue = ppm.get(3) - MIN_PULSE;
63
+  high = a2dValue >> 2;
64
+  low = a2dValue & 3;
65
+  report[3] = (low << 6) + temp;
66
+  temp = high;
67
+
68
+  high = 0;
69
+  low = 0;
70
+  report[4] = temp;
71
+  temp = high;
72
+
73
+  a2dValue = ppm.get(4) - MIN_PULSE;
74
+  high = a2dValue >> 8;
75
+  low = a2dValue & 255;
76
+  report[5] = low + temp;
77
+  temp = high;
78
+
79
+  a2dValue = ppm.get(5) - MIN_PULSE;
80
+  high = a2dValue >> 6;
81
+  low = a2dValue & 63;
82
+  report[6] = (low << 2) + temp;
83
+  temp = high;
84
+
85
+  // 4 buttons , tossed around
86
+
87
+  report[7] = (temp & 15);
88
+
89
+}

+ 32
- 0
UsbJoystick/ArduinoNotes.txt Переглянути файл

@@ -0,0 +1,32 @@
1
+Notes On Integrating AVRUSB with Arduino
2
+========================================
3
+
4
+* Note the license(s) under which AVRUSB is distributed.
5
+
6
+* See also: http://code.rancidbacon.com/ProjectLogArduinoUSB
7
+
8
+* Note: The pins we use on the hardware shield are:
9
+
10
+     INT0 == PD2 == IC Pin 4 == Arduino Digital Pin 2
11
+
12
+     INT1 == PD3 == IC Pin 5 == Arduino Digital Pin 3
13
+
14
+  (TODO: Change to not use PD3 so INT1 is left free?)
15
+
16
+* In order to compile a valid 'usbconfig.h' file must exit. The content of this
17
+  file will vary depending on whether the device is a generic USB device,
18
+  generic HID device or specific class of HID device for example.
19
+
20
+  The file 'usbconfig-prototype.h' can be used as a starting point, however
21
+  it might be easier to use the 'usbconfig.h' from one of the example projects.
22
+
23
+  TODO: Specify the settings that need to be changed to match the shield
24
+        design we use.
25
+
26
+* (NOTE: Initial 'usbconfig.h' used will be based on the file from
27
+ 'HIDKeys.2007-03-29'.)
28
+
29
+* At present the IDE won't compile our library so it needs to be pre-compiled
30
+  with:
31
+
32
+    avr-g++  -Wall -Os -I. -DUSB_CFG_CLOCK_KHZ=16000  -mmcu=atmega168  -c usbdrvasm.S  -c usbdrv.c

+ 216
- 0
UsbJoystick/Changelog.txt Переглянути файл

@@ -0,0 +1,216 @@
1
+This file documents changes in the firmware-only USB driver for atmel's AVR
2
+microcontrollers. New entries are always appended to the end of the file.
3
+Scroll down to the bottom to see the most recent changes.
4
+
5
+2005-04-01:
6
+  - Implemented endpoint 1 as interrupt-in endpoint.
7
+  - Moved all configuration options to usbconfig.h which is not part of the
8
+    driver.
9
+  - Changed interface for usbVendorSetup().
10
+  - Fixed compatibility with ATMega8 device.
11
+  - Various minor optimizations.
12
+
13
+2005-04-11:
14
+  - Changed interface to application: Use usbFunctionSetup(), usbFunctionRead()
15
+    and usbFunctionWrite() now. Added configuration options to choose which
16
+    of these functions to compile in.
17
+  - Assembler module delivers receive data non-inverted now.
18
+  - Made register and bit names compatible with more AVR devices.
19
+
20
+2005-05-03:
21
+  - Allow address of usbRxBuf on any memory page as long as the buffer does
22
+    not cross 256 byte page boundaries.
23
+  - Better device compatibility: works with Mega88 now.
24
+  - Code optimization in debugging module.
25
+  - Documentation updates.
26
+
27
+2006-01-02:
28
+  - Added (free) default Vendor- and Product-IDs bought from voti.nl.
29
+  - Added USBID-License.txt file which defines the rules for using the free
30
+    shared VID/PID pair.
31
+  - Added Readme.txt to the usbdrv directory which clarifies administrative
32
+    issues.
33
+
34
+2006-01-25:
35
+  - Added "configured state" to become more standards compliant.
36
+  - Added "HALT" state for interrupt endpoint.
37
+  - Driver passes the "USB Command Verifier" test from usb.org now.
38
+  - Made "serial number" a configuration option.
39
+  - Minor optimizations, we now recommend compiler option "-Os" for best
40
+    results.
41
+  - Added a version number to usbdrv.h
42
+
43
+2006-02-03:
44
+  - New configuration variable USB_BUFFER_SECTION for the memory section where
45
+    the USB rx buffer will go. This defaults to ".bss" if not defined. Since
46
+    this buffer MUST NOT cross 256 byte pages (not even touch a page at the
47
+    end), the user may want to pass a linker option similar to
48
+    "-Wl,--section-start=.mybuffer=0x800060".
49
+  - Provide structure for usbRequest_t.
50
+  - New defines for USB constants.
51
+  - Prepared for HID implementations.
52
+  - Increased data size limit for interrupt transfers to 8 bytes.
53
+  - New macro usbInterruptIsReady() to query interrupt buffer state.
54
+
55
+2006-02-18:
56
+  - Ensure that the data token which is sent as an ack to an OUT transfer is
57
+    always zero sized. This fixes a bug where the host reports an error after
58
+    sending an out transfer to the device, although all data arrived at the
59
+    device.
60
+  - Updated docs in usbdrv.h to reflect changed API in usbFunctionWrite().
61
+
62
+* Release 2006-02-20
63
+
64
+  - Give a compiler warning when compiling with debugging turned on.
65
+  - Added Oleg Semyonov's changes for IAR-cc compatibility.
66
+  - Added new (optional) functions usbDeviceConnect() and usbDeviceDisconnect()
67
+    (also thanks to Oleg!).
68
+  - Rearranged tests in usbPoll() to save a couple of instructions in the most
69
+    likely case that no actions are pending.
70
+  - We need a delay between the SET ADDRESS request until the new address
71
+    becomes active. This delay was handled in usbPoll() until now. Since the
72
+    spec says that the delay must not exceed 2ms, previous versions required
73
+    aggressive polling during the enumeration phase. We have now moved the
74
+    handling of the delay into the interrupt routine.
75
+  - We must not reply with NAK to a SETUP transaction. We can only achieve this
76
+    by making sure that the rx buffer is empty when SETUP tokens are expected.
77
+    We therefore don't pass zero sized data packets from the status phase of
78
+    a transfer to usbPoll(). This change MAY cause troubles if you rely on
79
+    receiving a less than 8 bytes long packet in usbFunctionWrite() to
80
+    identify the end of a transfer. usbFunctionWrite() will NEVER be called
81
+    with a zero length.
82
+
83
+* Release 2006-03-14
84
+
85
+  - Improved IAR C support: tiny memory model, more devices
86
+  - Added template usbconfig.h file under the name usbconfig-prototype.h
87
+
88
+* Release 2006-03-26
89
+
90
+  - Added provision for one more interrupt-in endpoint (endpoint 3).
91
+  - Added provision for one interrupt-out endpoint (endpoint 1).
92
+  - Added flowcontrol macros for USB.
93
+  - Added provision for custom configuration descriptor.
94
+  - Allow ANY two port bits for D+ and D-.
95
+  - Merged (optional) receive endpoint number into global usbRxToken variable.
96
+  - Use USB_CFG_IOPORTNAME instead of USB_CFG_IOPORT. We now construct the
97
+    variable name from the single port letter instead of computing the address
98
+    of related ports from the output-port address.
99
+
100
+* Release 2006-06-26
101
+
102
+  - Updated documentation in usbdrv.h and usbconfig-prototype.h to reflect the
103
+    new features.
104
+  - Removed "#warning" directives because IAR does not understand them. Use
105
+    unused static variables instead to generate a warning.
106
+  - Do not include <avr/io.h> when compiling with IAR.
107
+  - Introduced USB_CFG_DESCR_PROPS_* in usbconfig.h to configure how each
108
+    USB descriptor should be handled. It is now possible to provide descriptor
109
+    data in Flash, RAM or dynamically at runtime.
110
+  - STALL is now a status in usbTxLen* instead of a message. We can now conform
111
+    to the spec and leave the stall status pending until it is cleared.
112
+  - Made usbTxPacketCnt1 and usbTxPacketCnt3 public. This allows the
113
+    application code to reset data toggling on interrupt pipes.
114
+
115
+* Release 2006-07-18
116
+
117
+  - Added an #if !defined __ASSEMBLER__ to the warning in usbdrv.h. This fixes
118
+    an assembler error.
119
+  - usbDeviceDisconnect() takes pull-up resistor to high impedance now.
120
+
121
+* Release 2007-02-01
122
+
123
+  - Merged in some code size improvements from usbtiny (thanks to Dick
124
+    Streefland for these optimizations!)
125
+  - Special alignment requirement for usbRxBuf not required any more. Thanks
126
+    again to Dick Streefland for this hint!
127
+  - Reverted to "#warning" instead of unused static variables -- new versions
128
+    of IAR CC should handle this directive.
129
+  - Changed Open Source license to GNU GPL v2 in order to make linking against
130
+    other free libraries easier. We no longer require publication of the
131
+    circuit diagrams, but we STRONGLY encourage it. If you improve the driver
132
+    itself, PLEASE grant us a royalty free license to your changes for our
133
+    commercial license.
134
+
135
+* Release 2007-03-29
136
+
137
+  - New configuration option "USB_PUBLIC" in usbconfig.h.
138
+  - Set USB version number to 1.10 instead of 1.01.
139
+  - Code used USB_CFG_DESCR_PROPS_STRING_DEVICE and
140
+    USB_CFG_DESCR_PROPS_STRING_PRODUCT inconsistently. Changed all occurrences
141
+    to USB_CFG_DESCR_PROPS_STRING_PRODUCT.
142
+  - New assembler module for 16.5 MHz RC oscillator clock with PLL in receiver
143
+    code.
144
+  - New assembler module for 16 MHz crystal.
145
+  - usbdrvasm.S contains common code only, clock-specific parts have been moved
146
+    to usbdrvasm12.S, usbdrvasm16.S and usbdrvasm165.S respectively.
147
+
148
+* Release 2007-06-25
149
+
150
+  - 16 MHz module: Do SE0 check in stuffed bits as well.
151
+
152
+* Release 2007-07-07
153
+
154
+  - Define hi8(x) for IAR compiler to limit result to 8 bits. This is necessary
155
+    for negative values.
156
+  - Added 15 MHz module contributed by V. Bosch.
157
+  - Interrupt vector name can now be configured. This is useful if somebody
158
+    wants to use a different hardware interrupt than INT0.
159
+
160
+* Release 2007-08-07
161
+
162
+  - Moved handleIn3 routine in usbdrvasm16.S so that relative jump range is
163
+    not exceeded.
164
+  - More config options: USB_RX_USER_HOOK(), USB_INITIAL_DATATOKEN,
165
+    USB_COUNT_SOF
166
+  - USB_INTR_PENDING can now be a memory address, not just I/O
167
+
168
+* Release 2007-09-19
169
+
170
+  - Split out common parts of assembler modules into separate include file
171
+  - Made endpoint numbers configurable so that given interface definitions
172
+    can be matched. See USB_CFG_EP3_NUMBER in usbconfig-prototype.h.
173
+  - Store endpoint number for interrupt/bulk-out so that usbFunctionWriteOut()
174
+    can handle any number of endpoints.
175
+  - Define usbDeviceConnect() and usbDeviceDisconnect() even if no
176
+    USB_CFG_PULLUP_IOPORTNAME is defined. Directly set D+ and D- to 0 in this
177
+    case.
178
+
179
+* Release 2007-12-01
180
+
181
+  - Optimize usbDeviceConnect() and usbDeviceDisconnect() for less code size
182
+    when USB_CFG_PULLUP_IOPORTNAME is not defined.
183
+
184
+* Release 2007-12-13
185
+
186
+  - Renamed all include-only assembler modules from *.S to *.inc so that
187
+    people don't add them to their project sources.
188
+  - Distribute leap bits in tx loop more evenly for 16 MHz module.
189
+  - Use "macro" and "endm" instead of ".macro" and ".endm" for IAR
190
+  - Avoid compiler warnings for constant expr range by casting some values in
191
+    USB descriptors.
192
+
193
+* Release 2008-01-21
194
+
195
+  - Fixed bug in 15 and 16 MHz module where the new address set with
196
+    SET_ADDRESS was already accepted at the next NAK or ACK we send, not at
197
+    the next data packet we send. This caused problems when the host polled
198
+    too fast. Thanks to Alexander Neumann for his help and patience debugging
199
+    this issue!
200
+
201
+* Release 2008-02-05
202
+
203
+  - Fixed bug in 16.5 MHz module where a register was used in the interrupt
204
+    handler before it was pushed. This bug was introduced with version
205
+    2007-09-19 when common parts were moved to a separate file.
206
+  - Optimized CRC routine (thanks to Reimar Doeffinger).
207
+
208
+* Release 2008-02-16
209
+
210
+  - Removed outdated IAR compatibility stuff (code sections).
211
+  - Added hook macros for USB_RESET_HOOK() and USB_SET_ADDRESS_HOOK().
212
+  - Added optional routine usbMeasureFrameLength() for calibration of the
213
+    internal RC oscillator.
214
+
215
+* Release 2008-02-28
216
+

+ 155
- 0
UsbJoystick/CommercialLicense.txt Переглянути файл

@@ -0,0 +1,155 @@
1
+AVR-USB Driver Software License Agreement
2
+Version 2006-07-24
3
+
4
+THIS LICENSE AGREEMENT GRANTS YOU CERTAIN RIGHTS IN A SOFTWARE. YOU CAN
5
+ENTER INTO THIS AGREEMENT AND ACQUIRE THE RIGHTS OUTLINED BELOW BY PAYING
6
+THE AMOUNT ACCORDING TO SECTION 4 ("PAYMENT") TO OBJECTIVE DEVELOPMENT.
7
+
8
+
9
+1 DEFINITIONS
10
+
11
+1.1 "OBJECTIVE DEVELOPMENT" shall mean OBJECTIVE DEVELOPMENT Software GmbH,
12
+Grosse Schiffgasse 1A/7, 1020 Wien, AUSTRIA.
13
+
14
+1.2 "You" shall mean the Licensee.
15
+
16
+1.3 "AVR-USB" shall mean the firmware-only USB device implementation for
17
+Atmel AVR microcontrollers distributed by OBJECTIVE DEVELOPMENT and
18
+consisting of the files usbdrv.c, usbdrv.h, usbdrvasm.S, oddebug.c,
19
+oddebug.h, usbdrvasm.asm, iarcompat.h and usbconfig-prototype.h.
20
+
21
+
22
+2 LICENSE GRANTS
23
+
24
+2.1 Source Code. OBJECTIVE DEVELOPMENT shall furnish you with the source
25
+code of AVR-USB.
26
+
27
+2.2 Distribution and Use. OBJECTIVE DEVELOPMENT grants you the
28
+non-exclusive right to use and distribute AVR-USB with your hardware
29
+product(s), restricted by the limitations in section 3 below.
30
+
31
+2.3 Modifications. OBJECTIVE DEVELOPMENT grants you the right to modify
32
+your copy of AVR-USB according to your needs.
33
+
34
+2.4 USB IDs. OBJECTIVE DEVELOPMENT grants you the exclusive rights to use
35
+USB Product ID(s) sent to you in e-mail after receiving your payment in
36
+conjunction with USB Vendor ID 5824. OBJECTIVE DEVELOPMENT has acquired an
37
+exclusive license for this pair of USB identifiers from Wouter van Ooijen
38
+(www.voti.nl), who has licensed the VID from the USB Implementers Forum,
39
+Inc. (www.usb.org).
40
+
41
+
42
+3 LICENSE RESTRICTIONS
43
+
44
+3.1 Number of Units. Only one of the following three definitions is
45
+applicable. Which one is determined by the amount you pay to OBJECTIVE
46
+DEVELOPMENT, see section 4 ("Payment") below.
47
+
48
+Hobby License: You may use AVR-USB according to section 2 above in no more
49
+than 5 hardware units. These units must not be sold for profit.
50
+
51
+Entry Level License: You may use AVR-USB according to section 2 above in no
52
+more than 150 hardware units.
53
+
54
+Professional License: You may use AVR-USB according to section 2 above in
55
+any number of hardware units, except for large scale production ("unlimited
56
+fair use"). Quantities below 10,000 units are not considered large scale
57
+production. If your reach quantities which are obviously large scale
58
+production, you must pay a license fee of 0.10 EUR per unit for all units
59
+above 10,000.
60
+
61
+3.2 Rental. You may not rent, lease, or lend AVR-USB or otherwise encumber
62
+any copy of AVR-USB, or any of the rights granted herein.
63
+
64
+3.3 Transfer. You may not transfer your rights under this Agreement to
65
+another party without OBJECTIVE DEVELOPMENT's prior written consent. If
66
+such consent is obtained, you may permanently transfer this License to
67
+another party. The recipient of such transfer must agree to all terms and
68
+conditions of this Agreement.
69
+
70
+3.4 Reservation of Rights. OBJECTIVE DEVELOPMENT retains all rights not
71
+expressly granted.
72
+
73
+3.5 Non-Exclusive Rights. Your license rights under this Agreement are
74
+non-exclusive.
75
+
76
+3.6 Third Party Rights. This Agreement cannot grant you rights controlled
77
+by third parties. In particular, you are not allowed to use the USB logo or
78
+other trademarks owned by the USB Implementers Forum, Inc. without their
79
+consent. Since such consent depends on USB certification, it should be
80
+noted that AVR-USB will not pass certification because it does not
81
+implement checksum verification and the microcontroller ports do not meet
82
+the electrical specifications.
83
+
84
+
85
+4 PAYMENT
86
+
87
+The payment amount depends on the variation of this agreement (according to
88
+section 3.1) into which you want to enter. Concrete prices are listed on
89
+OBJECTIVE DEVELOPMENT's web site, usually at
90
+http://www.obdev.at/avrusb/license.html. You agree to pay the amount listed
91
+there to OBJECTIVE DEVELOPMENT or OBJECTIVE DEVELOPMENT's payment processor
92
+or reseller.
93
+
94
+
95
+5 COPYRIGHT AND OWNERSHIP
96
+
97
+AVR-USB is protected by copyright laws and international copyright
98
+treaties, as well as other intellectual property laws and treaties. AVR-USB
99
+is licensed, not sold.
100
+
101
+
102
+6 TERM AND TERMINATION
103
+
104
+6.1 Term. This Agreement shall continue indefinitely. However, OBJECTIVE
105
+DEVELOPMENT may terminate this Agreement and revoke the granted license and
106
+USB-IDs if you fail to comply with any of its terms and conditions.
107
+
108
+6.2 Survival of Terms. All provisions regarding secrecy, confidentiality
109
+and limitation of liability shall survive termination of this agreement.
110
+
111
+
112
+7 DISCLAIMER OF WARRANTY AND LIABILITY
113
+
114
+LIMITED WARRANTY. AVR-USB IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
115
+KIND. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, OBJECTIVE
116
+DEVELOPMENT AND ITS SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES, EITHER
117
+EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
118
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND
119
+NON-INFRINGEMENT, WITH REGARD TO AVR-USB, AND THE PROVISION OF OR FAILURE
120
+TO PROVIDE SUPPORT SERVICES. THIS LIMITED WARRANTY GIVES YOU SPECIFIC LEGAL
121
+RIGHTS. YOU MAY HAVE OTHERS, WHICH VARY FROM STATE/JURISDICTION TO
122
+STATE/JURISDICTION.
123
+
124
+LIMITATION OF LIABILITY. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW,
125
+IN NO EVENT SHALL OBJECTIVE DEVELOPMENT OR ITS SUPPLIERS BE LIABLE FOR ANY
126
+SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER
127
+(INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS,
128
+BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY
129
+LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE AVR-USB OR THE
130
+PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES, EVEN IF OBJECTIVE
131
+DEVELOPMENT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN ANY
132
+CASE, OBJECTIVE DEVELOPMENT'S ENTIRE LIABILITY UNDER ANY PROVISION OF THIS
133
+AGREEMENT SHALL BE LIMITED TO THE AMOUNT ACTUALLY PAID BY YOU FOR AVR-USB.
134
+
135
+
136
+8 MISCELLANEOUS TERMS
137
+
138
+8.1 Marketing. OBJECTIVE DEVELOPMENT has the right to mention for marketing
139
+purposes that you entered into this agreement.
140
+
141
+8.2 Entire Agreement. This document represents the entire agreement between
142
+OBJECTIVE DEVELOPMENT and you. It may only be modified in writing signed by
143
+an authorized representative of both, OBJECTIVE DEVELOPMENT and you.
144
+
145
+8.3 Severability. In case a provision of these terms and conditions should
146
+be or become partly or entirely invalid, ineffective, or not executable,
147
+the validity of all other provisions shall not be affected.
148
+
149
+8.4 Applicable Law. This agreement is governed by the laws of the Republic
150
+of Austria.
151
+
152
+8.5 Responsible Courts. The responsible courts in Vienna/Austria will have
153
+exclusive jurisdiction regarding all disputes in connection with this
154
+agreement.
155
+

+ 359
- 0
UsbJoystick/License.txt Переглянути файл

@@ -0,0 +1,359 @@
1
+OBJECTIVE DEVELOPMENT GmbH's AVR-USB driver software is distributed under the
2
+terms and conditions of the GNU GPL version 2, see the text below. In addition
3
+to the requirements in the GPL, we STRONGLY ENCOURAGE you to do the following:
4
+
5
+(1) Publish your entire project on a web site and drop us a note with the URL.
6
+Use the form at http://www.obdev.at/avrusb/feedback.html for your submission.
7
+
8
+(2) Adhere to minimum publication standards. Please include AT LEAST:
9
+    - a circuit diagram in PDF, PNG or GIF format
10
+    - full source code for the host software
11
+    - a Readme.txt file in ASCII format which describes the purpose of the
12
+      project and what can be found in which directories and which files
13
+    - a reference to http://www.obdev.at/avrusb/
14
+
15
+(3) If you improve the driver firmware itself, please give us a free license
16
+to your modifications for our commercial license offerings.
17
+
18
+
19
+
20
+                    GNU GENERAL PUBLIC LICENSE
21
+                       Version 2, June 1991
22
+
23
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
24
+                       59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
+ Everyone is permitted to copy and distribute verbatim copies
26
+ of this license document, but changing it is not allowed.
27
+
28
+                            Preamble
29
+
30
+  The licenses for most software are designed to take away your
31
+freedom to share and change it.  By contrast, the GNU General Public
32
+License is intended to guarantee your freedom to share and change free
33
+software--to make sure the software is free for all its users.  This
34
+General Public License applies to most of the Free Software
35
+Foundation's software and to any other program whose authors commit to
36
+using it.  (Some other Free Software Foundation software is covered by
37
+the GNU Library General Public License instead.)  You can apply it to
38
+your programs, too.
39
+
40
+  When we speak of free software, we are referring to freedom, not
41
+price.  Our General Public Licenses are designed to make sure that you
42
+have the freedom to distribute copies of free software (and charge for
43
+this service if you wish), that you receive source code or can get it
44
+if you want it, that you can change the software or use pieces of it
45
+in new free programs; and that you know you can do these things.
46
+
47
+  To protect your rights, we need to make restrictions that forbid
48
+anyone to deny you these rights or to ask you to surrender the rights.
49
+These restrictions translate to certain responsibilities for you if you
50
+distribute copies of the software, or if you modify it.
51
+
52
+  For example, if you distribute copies of such a program, whether
53
+gratis or for a fee, you must give the recipients all the rights that
54
+you have.  You must make sure that they, too, receive or can get the
55
+source code.  And you must show them these terms so they know their
56
+rights.
57
+
58
+  We protect your rights with two steps: (1) copyright the software, and
59
+(2) offer you this license which gives you legal permission to copy,
60
+distribute and/or modify the software.
61
+
62
+  Also, for each author's protection and ours, we want to make certain
63
+that everyone understands that there is no warranty for this free
64
+software.  If the software is modified by someone else and passed on, we
65
+want its recipients to know that what they have is not the original, so
66
+that any problems introduced by others will not reflect on the original
67
+authors' reputations.
68
+
69
+  Finally, any free program is threatened constantly by software
70
+patents.  We wish to avoid the danger that redistributors of a free
71
+program will individually obtain patent licenses, in effect making the
72
+program proprietary.  To prevent this, we have made it clear that any
73
+patent must be licensed for everyone's free use or not licensed at all.
74
+
75
+  The precise terms and conditions for copying, distribution and
76
+modification follow.
77
+
78
+                    GNU GENERAL PUBLIC LICENSE
79
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
80
+
81
+  0. This License applies to any program or other work which contains
82
+a notice placed by the copyright holder saying it may be distributed
83
+under the terms of this General Public License.  The "Program", below,
84
+refers to any such program or work, and a "work based on the Program"
85
+means either the Program or any derivative work under copyright law:
86
+that is to say, a work containing the Program or a portion of it,
87
+either verbatim or with modifications and/or translated into another
88
+language.  (Hereinafter, translation is included without limitation in
89
+the term "modification".)  Each licensee is addressed as "you".
90
+
91
+Activities other than copying, distribution and modification are not
92
+covered by this License; they are outside its scope.  The act of
93
+running the Program is not restricted, and the output from the Program
94
+is covered only if its contents constitute a work based on the
95
+Program (independent of having been made by running the Program).
96
+Whether that is true depends on what the Program does.
97
+
98
+  1. You may copy and distribute verbatim copies of the Program's
99
+source code as you receive it, in any medium, provided that you
100
+conspicuously and appropriately publish on each copy an appropriate
101
+copyright notice and disclaimer of warranty; keep intact all the
102
+notices that refer to this License and to the absence of any warranty;
103
+and give any other recipients of the Program a copy of this License
104
+along with the Program.
105
+
106
+You may charge a fee for the physical act of transferring a copy, and
107
+you may at your option offer warranty protection in exchange for a fee.
108
+
109
+  2. You may modify your copy or copies of the Program or any portion
110
+of it, thus forming a work based on the Program, and copy and
111
+distribute such modifications or work under the terms of Section 1
112
+above, provided that you also meet all of these conditions:
113
+
114
+    a) You must cause the modified files to carry prominent notices
115
+    stating that you changed the files and the date of any change.
116
+
117
+    b) You must cause any work that you distribute or publish, that in
118
+    whole or in part contains or is derived from the Program or any
119
+    part thereof, to be licensed as a whole at no charge to all third
120
+    parties under the terms of this License.
121
+
122
+    c) If the modified program normally reads commands interactively
123
+    when run, you must cause it, when started running for such
124
+    interactive use in the most ordinary way, to print or display an
125
+    announcement including an appropriate copyright notice and a
126
+    notice that there is no warranty (or else, saying that you provide
127
+    a warranty) and that users may redistribute the program under
128
+    these conditions, and telling the user how to view a copy of this
129
+    License.  (Exception: if the Program itself is interactive but
130
+    does not normally print such an announcement, your work based on
131
+    the Program is not required to print an announcement.)
132
+
133
+These requirements apply to the modified work as a whole.  If
134
+identifiable sections of that work are not derived from the Program,
135
+and can be reasonably considered independent and separate works in
136
+themselves, then this License, and its terms, do not apply to those
137
+sections when you distribute them as separate works.  But when you
138
+distribute the same sections as part of a whole which is a work based
139
+on the Program, the distribution of the whole must be on the terms of
140
+this License, whose permissions for other licensees extend to the
141
+entire whole, and thus to each and every part regardless of who wrote it.
142
+
143
+Thus, it is not the intent of this section to claim rights or contest
144
+your rights to work written entirely by you; rather, the intent is to
145
+exercise the right to control the distribution of derivative or
146
+collective works based on the Program.
147
+
148
+In addition, mere aggregation of another work not based on the Program
149
+with the Program (or with a work based on the Program) on a volume of
150
+a storage or distribution medium does not bring the other work under
151
+the scope of this License.
152
+
153
+  3. You may copy and distribute the Program (or a work based on it,
154
+under Section 2) in object code or executable form under the terms of
155
+Sections 1 and 2 above provided that you also do one of the following:
156
+
157
+    a) Accompany it with the complete corresponding machine-readable
158
+    source code, which must be distributed under the terms of Sections
159
+    1 and 2 above on a medium customarily used for software interchange; or,
160
+
161
+    b) Accompany it with a written offer, valid for at least three
162
+    years, to give any third party, for a charge no more than your
163
+    cost of physically performing source distribution, a complete
164
+    machine-readable copy of the corresponding source code, to be
165
+    distributed under the terms of Sections 1 and 2 above on a medium
166
+    customarily used for software interchange; or,
167
+
168
+    c) Accompany it with the information you received as to the offer
169
+    to distribute corresponding source code.  (This alternative is
170
+    allowed only for noncommercial distribution and only if you
171
+    received the program in object code or executable form with such
172
+    an offer, in accord with Subsection b above.)
173
+
174
+The source code for a work means the preferred form of the work for
175
+making modifications to it.  For an executable work, complete source
176
+code means all the source code for all modules it contains, plus any
177
+associated interface definition files, plus the scripts used to
178
+control compilation and installation of the executable.  However, as a
179
+special exception, the source code distributed need not include
180
+anything that is normally distributed (in either source or binary
181
+form) with the major components (compiler, kernel, and so on) of the
182
+operating system on which the executable runs, unless that component
183
+itself accompanies the executable.
184
+
185
+If distribution of executable or object code is made by offering
186
+access to copy from a designated place, then offering equivalent
187
+access to copy the source code from the same place counts as
188
+distribution of the source code, even though third parties are not
189
+compelled to copy the source along with the object code.
190
+
191
+  4. You may not copy, modify, sublicense, or distribute the Program
192
+except as expressly provided under this License.  Any attempt
193
+otherwise to copy, modify, sublicense or distribute the Program is
194
+void, and will automatically terminate your rights under this License.
195
+However, parties who have received copies, or rights, from you under
196
+this License will not have their licenses terminated so long as such
197
+parties remain in full compliance.
198
+
199
+  5. You are not required to accept this License, since you have not
200
+signed it.  However, nothing else grants you permission to modify or
201
+distribute the Program or its derivative works.  These actions are
202
+prohibited by law if you do not accept this License.  Therefore, by
203
+modifying or distributing the Program (or any work based on the
204
+Program), you indicate your acceptance of this License to do so, and
205
+all its terms and conditions for copying, distributing or modifying
206
+the Program or works based on it.
207
+
208
+  6. Each time you redistribute the Program (or any work based on the
209
+Program), the recipient automatically receives a license from the
210
+original licensor to copy, distribute or modify the Program subject to
211
+these terms and conditions.  You may not impose any further
212
+restrictions on the recipients' exercise of the rights granted herein.
213
+You are not responsible for enforcing compliance by third parties to
214
+this License.
215
+
216
+  7. If, as a consequence of a court judgment or allegation of patent
217
+infringement or for any other reason (not limited to patent issues),
218
+conditions are imposed on you (whether by court order, agreement or
219
+otherwise) that contradict the conditions of this License, they do not
220
+excuse you from the conditions of this License.  If you cannot
221
+distribute so as to satisfy simultaneously your obligations under this
222
+License and any other pertinent obligations, then as a consequence you
223
+may not distribute the Program at all.  For example, if a patent
224
+license would not permit royalty-free redistribution of the Program by
225
+all those who receive copies directly or indirectly through you, then
226
+the only way you could satisfy both it and this License would be to
227
+refrain entirely from distribution of the Program.
228
+
229
+If any portion of this section is held invalid or unenforceable under
230
+any particular circumstance, the balance of the section is intended to
231
+apply and the section as a whole is intended to apply in other
232
+circumstances.
233
+
234
+It is not the purpose of this section to induce you to infringe any
235
+patents or other property right claims or to contest validity of any
236
+such claims; this section has the sole purpose of protecting the
237
+integrity of the free software distribution system, which is
238
+implemented by public license practices.  Many people have made
239
+generous contributions to the wide range of software distributed
240
+through that system in reliance on consistent application of that
241
+system; it is up to the author/donor to decide if he or she is willing
242
+to distribute software through any other system and a licensee cannot
243
+impose that choice.
244
+
245
+This section is intended to make thoroughly clear what is believed to
246
+be a consequence of the rest of this License.
247
+
248
+  8. If the distribution and/or use of the Program is restricted in
249
+certain countries either by patents or by copyrighted interfaces, the
250
+original copyright holder who places the Program under this License
251
+may add an explicit geographical distribution limitation excluding
252
+those countries, so that distribution is permitted only in or among
253
+countries not thus excluded.  In such case, this License incorporates
254
+the limitation as if written in the body of this License.
255
+
256
+  9. The Free Software Foundation may publish revised and/or new versions
257
+of the General Public License from time to time.  Such new versions will
258
+be similar in spirit to the present version, but may differ in detail to
259
+address new problems or concerns.
260
+
261
+Each version is given a distinguishing version number.  If the Program
262
+specifies a version number of this License which applies to it and "any
263
+later version", you have the option of following the terms and conditions
264
+either of that version or of any later version published by the Free
265
+Software Foundation.  If the Program does not specify a version number of
266
+this License, you may choose any version ever published by the Free Software
267
+Foundation.
268
+
269
+  10. If you wish to incorporate parts of the Program into other free
270
+programs whose distribution conditions are different, write to the author
271
+to ask for permission.  For software which is copyrighted by the Free
272
+Software Foundation, write to the Free Software Foundation; we sometimes
273
+make exceptions for this.  Our decision will be guided by the two goals
274
+of preserving the free status of all derivatives of our free software and
275
+of promoting the sharing and reuse of software generally.
276
+
277
+                            NO WARRANTY
278
+
279
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
280
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
281
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
282
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
283
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
284
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
285
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
286
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
287
+REPAIR OR CORRECTION.
288
+
289
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
290
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
291
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
292
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
293
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
294
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
295
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
296
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
297
+POSSIBILITY OF SUCH DAMAGES.
298
+
299
+                     END OF TERMS AND CONDITIONS
300
+
301
+            How to Apply These Terms to Your New Programs
302
+
303
+  If you develop a new program, and you want it to be of the greatest
304
+possible use to the public, the best way to achieve this is to make it
305
+free software which everyone can redistribute and change under these terms.
306
+
307
+  To do so, attach the following notices to the program.  It is safest
308
+to attach them to the start of each source file to most effectively
309
+convey the exclusion of warranty; and each file should have at least
310
+the "copyright" line and a pointer to where the full notice is found.
311
+
312
+    <one line to give the program's name and a brief idea of what it does.>
313
+    Copyright (C) <year>  <name of author>
314
+
315
+    This program is free software; you can redistribute it and/or modify
316
+    it under the terms of the GNU General Public License as published by
317
+    the Free Software Foundation; either version 2 of the License, or
318
+    (at your option) any later version.
319
+
320
+    This program is distributed in the hope that it will be useful,
321
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
322
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
323
+    GNU General Public License for more details.
324
+
325
+    You should have received a copy of the GNU General Public License
326
+    along with this program; if not, write to the Free Software
327
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
328
+
329
+
330
+Also add information on how to contact you by electronic and paper mail.
331
+
332
+If the program is interactive, make it output a short notice like this
333
+when it starts in an interactive mode:
334
+
335
+    Gnomovision version 69, Copyright (C) year name of author
336
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
337
+    This is free software, and you are welcome to redistribute it
338
+    under certain conditions; type `show c' for details.
339
+
340
+The hypothetical commands `show w' and `show c' should show the appropriate
341
+parts of the General Public License.  Of course, the commands you use may
342
+be called something other than `show w' and `show c'; they could even be
343
+mouse-clicks or menu items--whatever suits your program.
344
+
345
+You should also get your employer (if you work as a programmer) or your
346
+school, if any, to sign a "copyright disclaimer" for the program, if
347
+necessary.  Here is a sample; alter the names:
348
+
349
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
350
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
351
+
352
+  <signature of Ty Coon>, 1 April 1989
353
+  Ty Coon, President of Vice
354
+
355
+This General Public License does not permit incorporating your program into
356
+proprietary programs.  If your program is a subroutine library, you may
357
+consider it more useful to permit linking proprietary applications with the
358
+library.  If this is what you want to do, use the GNU Library General
359
+Public License instead of this License.

+ 154
- 0
UsbJoystick/Readme.txt Переглянути файл

@@ -0,0 +1,154 @@
1
+This is the Readme file to Objective Development's firmware-only USB driver
2
+for Atmel AVR microcontrollers. For more information please visit
3
+http://www.obdev.at/avrusb/
4
+
5
+This directory contains the USB firmware only. Copy it as-is to your own
6
+project and add your own version of "usbconfig.h". A template for your own
7
+"usbconfig.h" can be found in "usbconfig-prototype.h" in this directory.
8
+
9
+
10
+TECHNICAL DOCUMENTATION
11
+=======================
12
+The technical documentation (API) for the firmware driver is contained in the
13
+file "usbdrv.h". Please read all of it carefully! Configuration options are
14
+documented in "usbconfig-prototype.h".
15
+
16
+The driver consists of the following files:
17
+  Readme.txt ............. The file you are currently reading.
18
+  Changelog.txt .......... Release notes for all versions of the driver.
19
+  usbdrv.h ............... Driver interface definitions and technical docs.
20
+* usbdrv.c ............... High level language part of the driver. Link this
21
+                           module to your code!
22
+* usbdrvasm.S ............ Assembler part of the driver. This module is mostly
23
+                           a stub and includes one of the usbdrvasm*.S files
24
+                           depending on processor clock. Link this module to
25
+                           your code!
26
+  usbdrvasm*.inc ......... Assembler routines for particular clock frequencies.
27
+                           Included by usbdrvasm.S, don't link it directly!
28
+  asmcommon.inc .......... Common assembler routines. Included by
29
+                           usbdrvasm*.inc, don't link it directly!
30
+  usbconfig-prototype.h .. Prototype for your own usbdrv.h file.
31
+* oddebug.c .............. Debug functions. Only used when DEBUG_LEVEL is
32
+                           defined to a value greater than 0. Link this module
33
+                           to your code!
34
+  oddebug.h .............. Interface definitions of the debug module.
35
+  iarcompat.h ............ Compatibility definitions for IAR C-compiler.
36
+  usbdrvasm.asm .......... Compatibility stub for IAR-C-compiler. Use this
37
+                           module instead of usbdrvasm.S when you assembler
38
+                           with IAR's tools.
39
+  License.txt ............ Open Source license for this driver.
40
+  CommercialLicense.txt .. Optional commercial license for this driver.
41
+  USBID-License.txt ...... Terms and conditions for using particular USB ID
42
+                           values for particular purposes.
43
+
44
+(*) ... These files should be linked to your project.
45
+
46
+
47
+CPU CORE CLOCK FREQUENCY
48
+========================
49
+We supply assembler modules for clock frequencies of 12 MHz, 15 MHz, 16 MHz and
50
+16.5 MHz. Other clock rates are not supported. The actual clock rate must be
51
+configured in usbdrv.h unless you use the default 12 MHz.
52
+
53
+12 MHz Clock
54
+This is the traditional clock rate of AVR-USB because it's the lowest clock
55
+rate where the timing constraints of the USB spec can be met.
56
+
57
+15 MHz Clock
58
+Similar to 12 MHz, but some NOPs inserted. On the other hand, the higher clock
59
+rate allows for some loops which make the resulting code size somewhat smaller
60
+than the 12 MHz version.
61
+
62
+16 MHz Clock
63
+This clock rate has been added for users of the Arduino board and other
64
+ready-made boards which come with a fixed 16 MHz crystal. It's also an option
65
+if you need the slightly higher clock rate for performance reasons. Since
66
+16 MHz is not divisible by the USB low speed bit clock of 1.5 MHz, the code
67
+is somewhat tricky and has to insert a leap cycle every third byte.
68
+
69
+16.5 MHz Clock
70
+The assembler module for this clock rate differs from the other modules because
71
+it has been built for an RC oscillator with only 1% precision. The receiver
72
+code inserts leap cycles to compensate for clock deviations. 1% is also the
73
+precision which can be achieved by calibrating the internal RC oscillator of
74
+the AVR. Please note that only AVRs with internal 64 MHz PLL oscillator can be
75
+used since the 8 MHz RC oscillator cannot be trimmed up to 16.5 MHz. This
76
+includes the very popular ATTiny25, ATTiny45, ATTiny85 series as well as the
77
+ATTiny26.
78
+
79
+We recommend that you obtain appropriate calibration values for 16.5 MHz core
80
+clock at programming time and store it in flash or EEPROM or compute the value
81
+from a reference clock at run time. Atmel's 8 MHz calibration is much more
82
+precise than the guaranteed 10% and it's therefore often possible to work with
83
+a fixed offset from this value, but it may be out of range.
84
+
85
+
86
+USB IDENTIFIERS
87
+===============
88
+Every USB device needs a vendor- and a product-identifier (VID and PID). VIDs
89
+are obtained from usb.org for a price of 1,500 USD. Once you have a VID, you
90
+can assign PIDs at will.
91
+
92
+Since an entry level cost of 1,500 USD is too high for most small companies
93
+and hobbyists, we provide a single VID/PID pair for free. If you want to use
94
+your own VID and PID instead of our's, define the macros "USB_CFG_VENDOR_ID"
95
+and "USB_CFG_DEVICE_ID" accordingly in "usbconfig.h".
96
+
97
+To use our predefined VID/PID pair, you MUST conform to a couple of
98
+requirements. See the file "USBID-License.txt" for details.
99
+
100
+Objective Development also has some offerings which include product IDs. See
101
+http://www.obdev.at/avrusb/ for details.
102
+
103
+
104
+HOST DRIVER
105
+===========
106
+You have received this driver together with an example device implementation
107
+and an example host driver. The host driver is based on libusb and compiles
108
+on various Unix flavors (Linux, BSD, Mac OS X). It also compiles natively on
109
+Windows using MinGW (see www.mingw.org) and libusb-win32 (see
110
+libusb-win32.sourceforge.net). The "Automator" project contains a native
111
+Windows host driver (not based on libusb) for Human Interface Devices.
112
+
113
+
114
+DEVELOPMENT SYSTEM
115
+==================
116
+This driver has been developed and optimized for the GNU compiler version 3
117
+(gcc 3). It does work well with gcc 4, but with bigger code size. We recommend
118
+that you use the GNU compiler suite because it is freely available. AVR-USB
119
+has also been ported to the IAR compiler and assembler. It has been tested
120
+with IAR 4.10B/W32 and 4.12A/W32 on an ATmega8 with the "small" and "tiny"
121
+memory model. Not every release is tested with IAR CC and the driver may
122
+therefore fail to compile with IAR. Please note that gcc is more efficient for
123
+usbdrv.c because this module has been deliberately optimized for gcc.
124
+
125
+
126
+USING AVR-USB FOR FREE
127
+======================
128
+The AVR firmware driver is published under the GNU General Public License
129
+Version 2 (GPL2). See the file "License.txt" for details.
130
+
131
+If you decide for the free GPL2, we STRONGLY ENCOURAGE you to do the following
132
+things IN ADDITION to the obligations from the GPL2:
133
+
134
+(1) Publish your entire project on a web site and drop us a note with the URL.
135
+Use the form at http://www.obdev.at/avrusb/feedback.html for your submission.
136
+
137
+(2) Adhere to minimum publication standards. Please include AT LEAST:
138
+    - a circuit diagram in PDF, PNG or GIF format
139
+    - full source code for the host software
140
+    - a Readme.txt file in ASCII format which describes the purpose of the
141
+      project and what can be found in which directories and which files
142
+    - a reference to http://www.obdev.at/avrusb/
143
+
144
+(3) If you improve the driver firmware itself, please give us a free license
145
+to your modifications for our commercial license offerings.
146
+
147
+
148
+COMMERCIAL LICENSES FOR AVR-USB
149
+===============================
150
+If you don't want to publish your source code under the terms of the GPL2,
151
+you can simply pay money for AVR-USB. As an additional benefit you get
152
+USB PIDs for free, licensed exclusively to you. See the file
153
+"CommercialLicense.txt" for details.
154
+

+ 143
- 0
UsbJoystick/USBID-License.txt Переглянути файл

@@ -0,0 +1,143 @@
1
+Royalty-Free Non-Exclusive License USB Product-ID
2
+=================================================
3
+
4
+Version 2006-06-19
5
+
6
+OBJECTIVE DEVELOPMENT Software GmbH hereby grants you the non-exclusive
7
+right to use three USB.org vendor-ID (VID) / product-ID (PID) pairs with
8
+products based on Objective Development's firmware-only USB driver for
9
+Atmel AVR microcontrollers:
10
+
11
+ * VID = 5824 (=0x16c0) / PID = 1500 (=0x5dc) for devices implementing no
12
+   USB device class (vendor-class devices with USB class = 0xff). Devices
13
+   using this pair will be referred to as "VENDOR CLASS" devices.
14
+
15
+ * VID = 5824 (=0x16c0) / PID = 1503 (=0x5df) for HID class devices
16
+   (excluding mice and keyboards). Devices using this pair will be referred
17
+   to as "HID CLASS" devices.
18
+
19
+ * VID = 5824 (=0x16c0) / PID = 1505 (=0x5e1) for CDC class modem devices
20
+   Devices using this pair will be referred to as "CDC-ACM CLASS" devices.
21
+
22
+Since the granted right is non-exclusive, the same VID/PID pairs may be
23
+used by many companies and individuals for different products. To avoid
24
+conflicts, your device and host driver software MUST adhere to the rules
25
+outlined below.
26
+
27
+OBJECTIVE DEVELOPMENT Software GmbH has licensed these VID/PID pairs from
28
+Wouter van Ooijen (see www.voti.nl), who has licensed the VID from the USB
29
+Implementers Forum, Inc. (see www.usb.org). The VID is registered for the
30
+company name "Van Ooijen Technische Informatica".
31
+
32
+
33
+RULES AND RESTRICTIONS
34
+======================
35
+
36
+(1) The USB device MUST provide a textual representation of the
37
+manufacturer and product identification. The manufacturer identification
38
+MUST be available at least in USB language 0x0409 (English/US).
39
+
40
+(2) The textual manufacturer identification MUST contain either an Internet
41
+domain name (e.g. "mycompany.com") registered and owned by you, or an
42
+e-mail address under your control (e.g. "myname@gmx.net"). You can embed
43
+the domain name or e-mail address in any string you like, e.g.  "Objective
44
+Development http://www.obdev.at/avrusb/".
45
+
46
+(3) You are responsible for retaining ownership of the domain or e-mail
47
+address for as long as any of your products are in use.
48
+
49
+(4) You may choose any string for the textual product identification, as
50
+long as this string is unique within the scope of your textual manufacturer
51
+identification.
52
+
53
+(5) Matching of device-specific drivers MUST be based on the textual
54
+manufacturer and product identification in addition to the usual VID/PID
55
+matching. This means that operating system features which are based on
56
+VID/PID matching only (e.g. Windows kernel level drivers, automatic actions
57
+when the device is plugged in etc) MUST NOT be used. The driver matching
58
+MUST be a comparison of the entire strings, NOT a sub-string match. For
59
+CDC-ACM CLASS devices, a generic class driver should be used and the
60
+matching is based on the USB device class.
61
+
62
+(6) The extent to which VID/PID matching is allowed for non device-specific
63
+drivers or features depends on the operating system and particular VID/PID
64
+pair used:
65
+
66
+ * Mac OS X, Linux, FreeBSD and other Unixes: No VID/PID matching is
67
+   required and hence no VID/PID-only matching is allowed at all.
68
+
69
+ * Windows: The operating system performs VID/PID matching for the kernel
70
+   level driver. You are REQUIRED to use libusb-win32 (see
71
+   http://libusb-win32.sourceforge.net/) as the kernel level driver for
72
+   VENDOR CLASS devices. HID CLASS devices all use the generic HID class
73
+   driver shipped with Windows, except mice and keyboards. You therefore
74
+   MUST NOT use any of the shared VID/PID pairs for mice or keyboards.
75
+   CDC-ACM CLASS devices require a ".inf" file which matches on the VID/PID
76
+   pair. This ".inf" file MUST load the "usbser" driver to configure the
77
+   device as modem (COM-port).
78
+
79
+(7) OBJECTIVE DEVELOPMENT Software GmbH disclaims all liability for any
80
+problems which are caused by the shared use of these VID/PID pairs. You
81
+have been warned that the sharing of VID/PID pairs may cause problems. If
82
+you want to avoid them, get your own VID/PID pair for exclusive use.
83
+
84
+
85
+HOW TO IMPLEMENT THESE RULES
86
+============================
87
+
88
+The following rules are for VENDOR CLASS and HID CLASS devices. CDC-ACM
89
+CLASS devices use the operating system's class driver and don't need a
90
+custom driver.
91
+
92
+The host driver MUST iterate over all devices with the given VID/PID
93
+numbers in their device descriptors and query the string representation for
94
+the manufacturer name in USB language 0x0409 (English/US). It MUST compare
95
+the ENTIRE string with your textual manufacturer identification chosen in
96
+(2) above. A substring search for your domain or e-mail address is NOT
97
+acceptable. The driver MUST NOT touch the device (other than querying the
98
+descriptors) unless the strings match.
99
+
100
+For all USB devices with matching VID/PID and textual manufacturer
101
+identification, the host driver must query the textual product
102
+identification and string-compare it with the name of the product it can
103
+control. It may only initialize the device if the product matches exactly.
104
+
105
+Objective Development provides examples for these matching rules with the
106
+"PowerSwitch" project (using libusb) and with the "Automator" project
107
+(using Windows calls on Windows and libusb on Unix).
108
+
109
+
110
+Technical Notes:
111
+================
112
+
113
+Sharing the same VID/PID pair among devices is possible as long as ALL
114
+drivers which match the VID/PID also perform matching on the textual
115
+identification strings. This is easy on all operating systems except
116
+Windows, since Windows establishes a static connection between the VID/PID
117
+pair and a kernel level driver. All devices with the same VID/PID pair must
118
+therefore use THE SAME kernel level driver.
119
+
120
+We therefore demand that you use libusb-win32 for VENDOR CLASS devices.
121
+This is a generic kernel level driver which allows all types of USB access
122
+for user space applications. This is only a partial solution of the
123
+problem, though, because different device drivers may come with different
124
+versions of libusb-win32 and they may not work with the libusb version of
125
+the respective other driver. You are therefore encouraged to test your
126
+driver against a broad range of libusb-win32 versions. Do not use new
127
+features in new versions, or check for their existence before you use them.
128
+When a new libusb-win32 becomes available, make sure that your driver is
129
+compatible with it.
130
+
131
+For HID CLASS devices it is necessary that all those devices bind to the
132
+same kernel driver: Microsoft's generic USB HID driver. This is true for
133
+all HID devices except those with a specialized driver. Currently, the only
134
+HIDs with specialized drivers are mice and keyboards. You therefore MUST
135
+NOT use a shared VID/PID with mouse and keyboard devices.
136
+
137
+Sharing the same VID/PID among different products is unusual and probably
138
+violates the USB specification. If you do it, you do it at your own risk.
139
+
140
+To avoid possible incompatibilities, we highly recommend that you get your
141
+own VID/PID pair if you intend to sell your product. Objective
142
+Development's commercial licenses for AVR-USB include a PID for
143
+unrestricted exclusive use.

+ 170
- 0
UsbJoystick/UsbJoystick.h Переглянути файл

@@ -0,0 +1,170 @@
1
+/*
2
+ * Based on Obdev's AVRUSB code and under the same license.
3
+ *
4
+ * UsbJoystick.h is a library for Arduino that wraps around the AVRUSB driver from ObDev
5
+ *
6
+ * Adapted from the UsbKeyboard.h library from Phil Lindsay
7
+ *
8
+ * by Michel Gutlich
9
+ *
10
+ */
11
+#ifndef __UsbJoystick_h__
12
+#define __UsbJoystick_h__
13
+
14
+#include <avr/pgmspace.h>
15
+
16
+#include "usbdrv.h"
17
+
18
+#include <avr/interrupt.h>
19
+#include <string.h>
20
+// typedef uint8_t byte; // avoid int() issue
21
+
22
+static uchar reportBuffer[8];				/* buffer for HID reports */
23
+
24
+static uchar    idleRate;           // in 4 ms units 
25
+
26
+
27
+PROGMEM const char usbHidReportDescriptor[USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH] = {  // USB report descriptor for a 6-axis, 4 button joystick
28
+0x05, 0x01,        // USAGE_PAGE (Generic Desktop)
29
+0x09, 0x04,        // USAGE (Joystick)
30
+0xa1, 0x01,        // COLLECTION (Application)
31
+
32
+0x09, 0x30,        // USAGE (X)
33
+0x15, 0x00,        // LOGICAL_MINIMUM (0)
34
+0x26, 0xff, 0x03, 	           //	  Logical Maximum (1024)
35
+0x75, 0x0a,        // REPORT_SIZE (10)
36
+0x95, 0x01,        // REPORT_COUNT (1)
37
+0x81, 0x02,        // INPUT (Data,Var,Abs)
38
+
39
+0x09, 0x31,        // USAGE (Y)
40
+0x15, 0x00,        // LOGICAL_MINIMUM (0)
41
+0x26, 0xff, 0x03, 	           //	  Logical Maximum (1024)
42
+0x75, 0x0a,        // REPORT_SIZE (10)
43
+0x95, 0x01,        // REPORT_COUNT (1)
44
+0x81, 0x02,        // INPUT (Data,Var,Abs)
45
+
46
+0x09, 0x32,        // USAGE (Z)
47
+0x15, 0x00,        // LOGICAL_MINIMUM (0)
48
+0x26, 0xff, 0x03, 	           //	  Logical Maximum (1024)
49
+0x75, 0x0a,        // REPORT_SIZE (10)
50
+0x95, 0x01,        // REPORT_COUNT (1)
51
+0x81, 0x02,        // INPUT (Data,Var,Abs)
52
+
53
+0x09, 0x33,        // USAGE (Rotate X)
54
+0x15, 0x00,        // LOGICAL_MINIMUM (0)
55
+0x26, 0xff, 0x03, 	           //	  Logical Maximum (1024)
56
+0x75, 0x0a,        // REPORT_SIZE (10)
57
+0x95, 0x01,        // REPORT_COUNT (1)
58
+0x81, 0x02,        // INPUT (Data,Var,Abs)
59
+
60
+0x09, 0x34,        // USAGE (Rotate Y)
61
+0x15, 0x00,        // LOGICAL_MINIMUM (0)
62
+0x26, 0xff, 0x03, 	           //	  Logical Maximum (1024)
63
+0x75, 0x0a,        // REPORT_SIZE (10)
64
+0x95, 0x01,        // REPORT_COUNT (1)
65
+0x81, 0x02,        // INPUT (Data,Var,Abs)
66
+
67
+0x09, 0x35,        // USAGE (Rotate Z)
68
+0x15, 0x00,        // LOGICAL_MINIMUM (0)
69
+0x26, 0xff, 0x03, 	           //	  Logical Maximum (1024)
70
+0x75, 0x0a,        // REPORT_SIZE (10)
71
+0x95, 0x01,        // REPORT_COUNT (1)
72
+0x81, 0x02,        // INPUT (Data,Var,Abs)
73
+
74
+0x05, 0x09,			   //   Usage_Page (Button)
75
+0x19, 0x01,			   //   Usage_Minimum (Button 1)
76
+0x29, 0x04,			   //   Usage_Maximum (Button 4)
77
+0x15, 0x00,			   //   Logical_Minimum (0)
78
+0x25, 0x01,			   //   Logical_Maximum (1)
79
+0x75, 0x01,			   //   Report_Size (1)
80
+0x95, 0x04,			   //   Report_Count (4)
81
+0x55, 0x00,			   //   Unit_Exponent (0)
82
+0x65, 0x00,			   //   Unit (None)
83
+0x81, 0x02,			   //   Input (Data, Const, Abs)
84
+
85
+0xc0               // END_COLLECTION
86
+};
87
+
88
+
89
+class UsbJoystickDevice {
90
+ public:
91
+  UsbJoystickDevice () {
92
+    
93
+    usbInit();
94
+      
95
+    sei();
96
+
97
+      }
98
+    
99
+  void refresh() {
100
+    usbPoll();
101
+  }
102
+    
103
+	void sendJoystick(){
104
+		sendJoystick(reportBuffer[0],reportBuffer[1],reportBuffer[2],reportBuffer[3],reportBuffer[4],reportBuffer[5],reportBuffer[6],reportBuffer[7]);
105
+	}
106
+		
107
+	
108
+  void sendJoystick(uchar val0, uchar val1, uchar val2, uchar val3, uchar val4 , uchar val5 , uchar val6, uchar val7) {
109
+      
110
+	reportBuffer[0] = val0;
111
+    reportBuffer[1] = val1;
112
+	reportBuffer[2] = val2;
113
+	reportBuffer[3] = val3;
114
+	reportBuffer[4] = val4;
115
+	reportBuffer[5] = val5;
116
+	reportBuffer[6] = val6;
117
+	reportBuffer[7] = val7;
118
+
119
+	  if(usbInterruptIsReady()) {
120
+		  usbSetInterrupt(reportBuffer, sizeof(reportBuffer));
121
+	  }
122
+  }
123
+    
124
+  //private: TODO: Make friend?
125
+  uchar    reportBuffer[8];    // buffer for HID reports
126
+
127
+};
128
+
129
+UsbJoystickDevice UsbJoystick = UsbJoystickDevice();
130
+
131
+#ifdef __cplusplus
132
+extern "C"{
133
+#endif 
134
+	
135
+  // USB_PUBLIC uchar usbFunctionSetup
136
+uchar usbFunctionSetup(uchar data[8]) 
137
+  {
138
+	usbRequest_t    *rq = (usbRequest_t *)((void *)data);
139
+	  
140
+    usbMsgPtr = UsbJoystick.reportBuffer; //
141
+    if((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS){ /* class request type */
142
+      if(rq->bRequest == USBRQ_HID_GET_REPORT){ /* wValue: ReportType (highbyte), ReportID (lowbyte) */
143
+		  reportBuffer[0]= 0;
144
+		  reportBuffer[1]= 0;
145
+		  reportBuffer[2]= 0;
146
+		  reportBuffer[3]= 0;
147
+		  reportBuffer[4]= 0;
148
+		  reportBuffer[5]= 0;
149
+		  reportBuffer[6]= 0;
150
+		  reportBuffer[7]= 0;
151
+	   
152
+	return sizeof(reportBuffer);
153
+
154
+      }else if(rq->bRequest == USBRQ_HID_GET_IDLE){
155
+		usbMsgPtr = &idleRate;
156
+		return 1;
157
+      }else if(rq->bRequest == USBRQ_HID_SET_IDLE){
158
+		idleRate = rq->wValue.bytes[1];
159
+      }else{
160
+		  /* no vendor specific requests implemented */
161
+	}
162
+    return 0;
163
+  }
164
+}
165
+#ifdef __cplusplus
166
+} // extern "C"
167
+#endif
168
+
169
+
170
+#endif // __UsbJoystick_h__

+ 178
- 0
UsbJoystick/asmcommon.inc Переглянути файл

@@ -0,0 +1,178 @@
1
+/* Name: asmcommon.inc
2
+ * Project: AVR USB driver
3
+ * Author: Christian Starkjohann
4
+ * Creation Date: 2007-11-05
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt)
8
+ * Revision: $Id$
9
+ */
10
+
11
+/* Do not link this file! Link usbdrvasm.S instead, which includes the
12
+ * appropriate implementation!
13
+ */
14
+
15
+/*
16
+General Description:
17
+This file contains assembler code which is shared among the USB driver
18
+implementations for different CPU cocks. Since the code must be inserted
19
+in the middle of the module, it's split out into this file and #included.
20
+
21
+Jump destinations called from outside:
22
+    sofError: Called when no start sequence was found.
23
+    se0: Called when a package has been successfully received.
24
+    overflow: Called when receive buffer overflows.
25
+    doReturn: Called after sending data.
26
+
27
+Outside jump destinations used by this module:
28
+    waitForJ: Called to receive an already arriving packet.
29
+    sendAckAndReti:
30
+    sendNakAndReti:
31
+    sendCntAndReti:
32
+    usbSendAndReti:
33
+
34
+The following macros must be defined before this file is included:
35
+    .macro POP_STANDARD
36
+    .endm
37
+    .macro POP_RETI
38
+    .endm
39
+*/
40
+
41
+#define token   x1
42
+
43
+overflow:
44
+    ldi     x2, 1<<USB_INTR_PENDING_BIT
45
+    USB_STORE_PENDING(x2)       ; clear any pending interrupts
46
+ignorePacket:
47
+    clr     token
48
+    rjmp    storeTokenAndReturn
49
+
50
+;----------------------------------------------------------------------------
51
+; Processing of received packet (numbers in brackets are cycles after center of SE0)
52
+;----------------------------------------------------------------------------
53
+;This is the only non-error exit point for the software receiver loop
54
+;we don't check any CRCs here because there is no time left.
55
+se0:
56
+    subi    cnt, USB_BUFSIZE    ;[5]
57
+    neg     cnt                 ;[6]
58
+    sub     YL, cnt             ;[7]
59
+    sbci    YH, 0               ;[8]
60
+    ldi     x2, 1<<USB_INTR_PENDING_BIT ;[9]
61
+    USB_STORE_PENDING(x2)       ;[10] clear pending intr and check flag later. SE0 should be over.
62
+    ld      token, y            ;[11]
63
+    cpi     token, USBPID_DATA0 ;[13]
64
+    breq    handleData          ;[14]
65
+    cpi     token, USBPID_DATA1 ;[15]
66
+    breq    handleData          ;[16]
67
+    lds     shift, usbDeviceAddr;[17]
68
+    ldd     x2, y+1             ;[19] ADDR and 1 bit endpoint number
69
+    lsl     x2                  ;[21] shift out 1 bit endpoint number
70
+    cpse    x2, shift           ;[22]
71
+    rjmp    ignorePacket        ;[23]
72
+/* only compute endpoint number in x3 if required later */
73
+#if USB_CFG_HAVE_INTRIN_ENDPOINT || USB_CFG_IMPLEMENT_FN_WRITEOUT
74
+    ldd     x3, y+2             ;[24] endpoint number + crc
75
+    rol     x3                  ;[26] shift in LSB of endpoint
76
+#endif
77
+    cpi     token, USBPID_IN    ;[27]
78
+    breq    handleIn            ;[28]
79
+    cpi     token, USBPID_SETUP ;[29]
80
+    breq    handleSetupOrOut    ;[30]
81
+    cpi     token, USBPID_OUT   ;[31]
82
+    brne    ignorePacket        ;[32] must be ack, nak or whatever
83
+;   rjmp    handleSetupOrOut    ; fallthrough
84
+
85
+;Setup and Out are followed by a data packet two bit times (16 cycles) after
86
+;the end of SE0. The sync code allows up to 40 cycles delay from the start of
87
+;the sync pattern until the first bit is sampled. That's a total of 56 cycles.
88
+handleSetupOrOut:               ;[32]
89
+#if USB_CFG_IMPLEMENT_FN_WRITEOUT   /* if we have data for endpoint != 0, set usbCurrentTok to address */
90
+    andi    x3, 0xf             ;[32]
91
+    breq    storeTokenAndReturn ;[33]
92
+    mov     token, x3           ;[34] indicate that this is endpoint x OUT
93
+#endif
94
+storeTokenAndReturn:
95
+    sts     usbCurrentTok, token;[35]
96
+doReturn:
97
+    POP_STANDARD                ;[37] 12...16 cycles
98
+    USB_LOAD_PENDING(YL)        ;[49]
99
+    sbrc    YL, USB_INTR_PENDING_BIT;[50] check whether data is already arriving
100
+    rjmp    waitForJ            ;[51] save the pops and pushes -- a new interrupt is already pending
101
+sofError:
102
+    POP_RETI                    ;macro call
103
+    reti
104
+
105
+handleData:
106
+    lds     token, usbCurrentTok;[18]
107
+    tst     token               ;[20]
108
+    breq    doReturn            ;[21]
109
+    lds     x2, usbRxLen        ;[22]
110
+    tst     x2                  ;[24]
111
+    brne    sendNakAndReti      ;[25]
112
+; 2006-03-11: The following two lines fix a problem where the device was not
113
+; recognized if usbPoll() was called less frequently than once every 4 ms.
114
+    cpi     cnt, 4              ;[26] zero sized data packets are status phase only -- ignore and ack
115
+    brmi    sendAckAndReti      ;[27] keep rx buffer clean -- we must not NAK next SETUP
116
+    sts     usbRxLen, cnt       ;[28] store received data, swap buffers
117
+    sts     usbRxToken, token   ;[30]
118
+    lds     x2, usbInputBufOffset;[32] swap buffers
119
+    ldi     cnt, USB_BUFSIZE    ;[34]
120
+    sub     cnt, x2             ;[35]
121
+    sts     usbInputBufOffset, cnt;[36] buffers now swapped
122
+    rjmp    sendAckAndReti      ;[38] 40 + 17 = 57 until SOP
123
+
124
+handleIn:
125
+;We don't send any data as long as the C code has not processed the current
126
+;input data and potentially updated the output data. That's more efficient
127
+;in terms of code size than clearing the tx buffers when a packet is received.
128
+    lds     x1, usbRxLen        ;[30]
129
+    cpi     x1, 1               ;[32] negative values are flow control, 0 means "buffer free"
130
+    brge    sendNakAndReti      ;[33] unprocessed input packet?
131
+    ldi     x1, USBPID_NAK      ;[34] prepare value for usbTxLen
132
+#if USB_CFG_HAVE_INTRIN_ENDPOINT
133
+    andi    x3, 0xf             ;[35] x3 contains endpoint
134
+    brne    handleIn1           ;[36]
135
+#endif
136
+    lds     cnt, usbTxLen       ;[37]
137
+    sbrc    cnt, 4              ;[39] all handshake tokens have bit 4 set
138
+    rjmp    sendCntAndReti      ;[40] 42 + 16 = 58 until SOP
139
+    sts     usbTxLen, x1        ;[41] x1 == USBPID_NAK from above
140
+    ldi     YL, lo8(usbTxBuf)   ;[43]
141
+    ldi     YH, hi8(usbTxBuf)   ;[44]
142
+    rjmp    usbSendAndReti      ;[45] 57 + 12 = 59 until SOP
143
+
144
+; Comment about when to set usbTxLen to USBPID_NAK:
145
+; We should set it back when we receive the ACK from the host. This would
146
+; be simple to implement: One static variable which stores whether the last
147
+; tx was for endpoint 0 or 1 and a compare in the receiver to distinguish the
148
+; ACK. However, we set it back immediately when we send the package,
149
+; assuming that no error occurs and the host sends an ACK. We save one byte
150
+; RAM this way and avoid potential problems with endless retries. The rest of
151
+; the driver assumes error-free transfers anyway.
152
+
153
+#if USB_CFG_HAVE_INTRIN_ENDPOINT    /* placed here due to relative jump range */
154
+handleIn1:                      ;[38]
155
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
156
+; 2006-06-10 as suggested by O.Tamura: support second INTR IN / BULK IN endpoint
157
+    cpi     x3, USB_CFG_EP3_NUMBER;[38]
158
+    breq    handleIn3           ;[39]
159
+#endif
160
+    lds     cnt, usbTxLen1      ;[40]
161
+    sbrc    cnt, 4              ;[42] all handshake tokens have bit 4 set
162
+    rjmp    sendCntAndReti      ;[43] 47 + 16 = 63 until SOP
163
+    sts     usbTxLen1, x1       ;[44] x1 == USBPID_NAK from above
164
+    ldi     YL, lo8(usbTxBuf1)  ;[46]
165
+    ldi     YH, hi8(usbTxBuf1)  ;[47]
166
+    rjmp    usbSendAndReti      ;[48] 50 + 12 = 62 until SOP
167
+#endif
168
+
169
+#if USB_CFG_HAVE_INTRIN_ENDPOINT && USB_CFG_HAVE_INTRIN_ENDPOINT3
170
+handleIn3:
171
+    lds     cnt, usbTxLen3      ;[41]
172
+    sbrc    cnt, 4              ;[43]
173
+    rjmp    sendCntAndReti      ;[44] 49 + 16 = 65 until SOP
174
+    sts     usbTxLen3, x1       ;[45] x1 == USBPID_NAK from above
175
+    ldi     YL, lo8(usbTxBuf3)  ;[47]
176
+    ldi     YH, hi8(usbTxBuf3)  ;[48]
177
+    rjmp    usbSendAndReti      ;[49] 51 + 12 = 63 until SOP
178
+#endif

+ 80
- 0
UsbJoystick/examples/UsbJoystickDemo/UsbJoystickDemo.pde Переглянути файл

@@ -0,0 +1,80 @@
1
+/* This demo uses the UsbJoystick.h library, a library based on AVRUSB from ObDev
2
+ * It demonstrates a 6-axis joystick with 4 buttons by reading all the analog ports and
3
+ * digtal pins 9,10,11,and 12
4
+ * Adapted from the UsbKeyboard.h library from Phil Lindsay
5
+ *
6
+ * by Michel Gutlich   19-8-2008
7
+ */
8
+
9
+#include <USBJoystick.h>
10
+
11
+unsigned short a2dValue;
12
+unsigned char high;
13
+unsigned char low;
14
+unsigned char temp;
15
+unsigned char report[8];
16
+
17
+
18
+void setup() {
19
+  
20
+  pinMode (9,INPUT);
21
+  pinMode (10,INPUT);
22
+  pinMode (11,INPUT);
23
+  pinMode (12,INPUT);
24
+  
25
+}
26
+
27
+void loop () {
28
+  UsbJoystick.refresh(); // Let the AVRUSB driver do some houskeeping
29
+  calculateReport(); // Jump to our port read routine that orders the values
30
+  UsbJoystick.sendJoystick(report[0],report[1],reportBuffer[2],report[3],report[4],report[5],report[6],report[7]); // send the values
31
+}
32
+
33
+void calculateReport() {  //The values read from the analog ports have to be ordered in a way the HID protocol wants it; a bit confusing.
34
+
35
+  a2dValue = analogRead(0);
36
+  high = a2dValue >> 8;
37
+  low = a2dValue & 255;
38
+  report[0] = low;
39
+  temp = high;
40
+
41
+  a2dValue = analogRead(1);
42
+  high = a2dValue >> 6;
43
+  low = a2dValue & 63;
44
+  report[1] = (low << 2) + temp;
45
+  temp = high;
46
+
47
+  a2dValue =analogRead(2);
48
+  high = a2dValue >> 4;
49
+  low = a2dValue & 15;
50
+  report[2] = (low << 4) + temp;
51
+  temp = high;
52
+
53
+  a2dValue = analogRead(3);
54
+  high = a2dValue >> 2;
55
+  low = a2dValue & 3;
56
+  report[3] = (low << 6) + temp;
57
+  temp = high;
58
+
59
+  high = 0;
60
+  low = 0;
61
+  report[4] = temp;
62
+  temp = high;
63
+
64
+  a2dValue = analogRead(4);
65
+  high = a2dValue >> 8;
66
+  low = a2dValue & 255;
67
+  report[5] = low + temp;
68
+  temp = high;
69
+
70
+  a2dValue = analogRead(5);
71
+  high = a2dValue >> 6;
72
+  low = a2dValue & 63;
73
+  report[6] = (low << 2) + temp;
74
+  temp = high;
75
+
76
+  // 4 buttons , tossed around
77
+
78
+  report[7] = (temp & 15) + (digitalRead(9) << 4) +  (digitalRead(10) << 5) +  (digitalRead(11) << 6) +  (digitalRead(12) << 7);
79
+
80
+}

+ 65
- 0
UsbJoystick/iarcompat.h Переглянути файл

@@ -0,0 +1,65 @@
1
+/* Name: iarcompat.h
2
+ * Project: AVR USB driver
3
+ * Author: Christian Starkjohann
4
+ * Creation Date: 2006-03-01
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2006 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: iarcompat.h 533 2008-02-28 15:35:25Z cs $
9
+ */
10
+
11
+/*
12
+General Description:
13
+This header is included when we compile with the IAR C-compiler and assembler.
14
+It defines macros for cross compatibility between gcc and IAR-cc.
15
+
16
+Thanks to Oleg Semyonov for his help with the IAR tools port!
17
+*/
18
+
19
+#ifndef __iarcompat_h_INCLUDED__
20
+#define __iarcompat_h_INCLUDED__
21
+
22
+#if defined __IAR_SYSTEMS_ICC__ || defined __IAR_SYSTEMS_ASM__
23
+
24
+/* Enable bit definitions */
25
+#ifndef ENABLE_BIT_DEFINITIONS
26
+#   define ENABLE_BIT_DEFINITIONS	1
27
+#endif
28
+
29
+/* Include IAR headers */
30
+#include <ioavr.h>
31
+#ifndef __IAR_SYSTEMS_ASM__
32
+#   include <inavr.h>
33
+#endif
34
+
35
+#define __attribute__(arg)
36
+
37
+#ifdef __IAR_SYSTEMS_ASM__
38
+#   define __ASSEMBLER__
39
+#endif
40
+
41
+#ifdef __HAS_ELPM__
42
+#   define PROGMEM __farflash
43
+#else
44
+#   define PROGMEM __flash
45
+#endif
46
+
47
+#define PRG_RDB(addr)   (*(PROGMEM char *)(addr))
48
+
49
+/* The following definitions are not needed by the driver, but may be of some
50
+ * help if you port a gcc based project to IAR.
51
+ */
52
+#define cli()       __disable_interrupt()
53
+#define sei()       __enable_interrupt()
54
+#define wdt_reset() __watchdog_reset()
55
+
56
+/* Depending on the device you use, you may get problems with the way usbdrv.h
57
+ * handles the differences between devices. Since IAR does not use #defines
58
+ * for MCU registers, we can't check for the existence of a particular
59
+ * register with an #ifdef. If the autodetection mechanism fails, include
60
+ * definitions for the required USB_INTR_* macros in your usbconfig.h. See
61
+ * usbconfig-prototype.h and usbdrv.h for details.
62
+ */
63
+
64
+#endif  /* defined __IAR_SYSTEMS_ICC__ || defined __IAR_SYSTEMS_ASM__ */
65
+#endif  /* __iarcompat_h_INCLUDED__ */

+ 50
- 0
UsbJoystick/oddebug.c Переглянути файл

@@ -0,0 +1,50 @@
1
+/* Name: oddebug.c
2
+ * Project: AVR library
3
+ * Author: Christian Starkjohann
4
+ * Creation Date: 2005-01-16
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: oddebug.c 275 2007-03-20 09:58:28Z cs $
9
+ */
10
+
11
+#include "oddebug.h"
12
+
13
+#if DEBUG_LEVEL > 0
14
+
15
+#warning "Never compile production devices with debugging enabled"
16
+
17
+static void uartPutc(char c)
18
+{
19
+    while(!(ODDBG_USR & (1 << ODDBG_UDRE)));    /* wait for data register empty */
20
+    ODDBG_UDR = c;
21
+}
22
+
23
+static uchar    hexAscii(uchar h)
24
+{
25
+    h &= 0xf;
26
+    if(h >= 10)
27
+        h += 'a' - (uchar)10 - '0';
28
+    h += '0';
29
+    return h;
30
+}
31
+
32
+static void printHex(uchar c)
33
+{
34
+    uartPutc(hexAscii(c >> 4));
35
+    uartPutc(hexAscii(c));
36
+}
37
+
38
+void    odDebug(uchar prefix, uchar *data, uchar len)
39
+{
40
+    printHex(prefix);
41
+    uartPutc(':');
42
+    while(len--){
43
+        uartPutc(' ');
44
+        printHex(*data++);
45
+    }
46
+    uartPutc('\r');
47
+    uartPutc('\n');
48
+}
49
+
50
+#endif

+ 126
- 0
UsbJoystick/oddebug.h Переглянути файл

@@ -0,0 +1,126 @@
1
+/* Name: oddebug.h
2
+ * Project: AVR library
3
+ * Author: Christian Starkjohann
4
+ * Creation Date: 2005-01-16
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: oddebug.h 275 2007-03-20 09:58:28Z cs $
9
+ */
10
+
11
+#ifndef __oddebug_h_included__
12
+#define __oddebug_h_included__
13
+
14
+/*
15
+General Description:
16
+This module implements a function for debug logs on the serial line of the
17
+AVR microcontroller. Debugging can be configured with the define
18
+'DEBUG_LEVEL'. If this macro is not defined or defined to 0, all debugging
19
+calls are no-ops. If it is 1, DBG1 logs will appear, but not DBG2. If it is
20
+2, DBG1 and DBG2 logs will be printed.
21
+
22
+A debug log consists of a label ('prefix') to indicate which debug log created
23
+the output and a memory block to dump in hex ('data' and 'len').
24
+*/
25
+
26
+
27
+#ifndef F_CPU
28
+#   define  F_CPU   12000000    /* 12 MHz */
29
+#endif
30
+
31
+/* make sure we have the UART defines: */
32
+#include "iarcompat.h"
33
+#ifndef __IAR_SYSTEMS_ICC__
34
+#   include <avr/io.h>
35
+#endif
36
+
37
+#ifndef uchar
38
+#   define  uchar   unsigned char
39
+#endif
40
+
41
+#if DEBUG_LEVEL > 0 && !(defined TXEN || defined TXEN0) /* no UART in device */
42
+#   warning "Debugging disabled because device has no UART"
43
+#   undef   DEBUG_LEVEL
44
+#endif
45
+
46
+#ifndef DEBUG_LEVEL
47
+#   define  DEBUG_LEVEL 0
48
+#endif
49
+
50
+/* ------------------------------------------------------------------------- */
51
+
52
+#if DEBUG_LEVEL > 0
53
+#   define  DBG1(prefix, data, len) odDebug(prefix, data, len)
54
+#else
55
+#   define  DBG1(prefix, data, len)
56
+#endif
57
+
58
+#if DEBUG_LEVEL > 1
59
+#   define  DBG2(prefix, data, len) odDebug(prefix, data, len)
60
+#else
61
+#   define  DBG2(prefix, data, len)
62
+#endif
63
+
64
+/* ------------------------------------------------------------------------- */
65
+
66
+#if DEBUG_LEVEL > 0
67
+extern void odDebug(uchar prefix, uchar *data, uchar len);
68
+
69
+/* Try to find our control registers; ATMEL likes to rename these */
70
+
71
+#if defined UBRR
72
+#   define  ODDBG_UBRR  UBRR
73
+#elif defined UBRRL
74
+#   define  ODDBG_UBRR  UBRRL
75
+#elif defined UBRR0
76
+#   define  ODDBG_UBRR  UBRR0
77
+#elif defined UBRR0L
78
+#   define  ODDBG_UBRR  UBRR0L
79
+#endif
80
+
81
+#if defined UCR
82
+#   define  ODDBG_UCR   UCR
83
+#elif defined UCSRB
84
+#   define  ODDBG_UCR   UCSRB
85
+#elif defined UCSR0B
86
+#   define  ODDBG_UCR   UCSR0B
87
+#endif
88
+
89
+#if defined TXEN
90
+#   define  ODDBG_TXEN  TXEN
91
+#else
92
+#   define  ODDBG_TXEN  TXEN0
93
+#endif
94
+
95
+#if defined USR
96
+#   define  ODDBG_USR   USR
97
+#elif defined UCSRA
98
+#   define  ODDBG_USR   UCSRA
99
+#elif defined UCSR0A
100
+#   define  ODDBG_USR   UCSR0A
101
+#endif
102
+
103
+#if defined UDRE
104
+#   define  ODDBG_UDRE  UDRE
105
+#else
106
+#   define  ODDBG_UDRE  UDRE0
107
+#endif
108
+
109
+#if defined UDR
110
+#   define  ODDBG_UDR   UDR
111
+#elif defined UDR0
112
+#   define  ODDBG_UDR   UDR0
113
+#endif
114
+
115
+static inline void  odDebugInit(void)
116
+{
117
+    ODDBG_UCR |= (1<<ODDBG_TXEN);
118
+    ODDBG_UBRR = F_CPU / (19200 * 16L) - 1;
119
+}
120
+#else
121
+#   define odDebugInit()
122
+#endif
123
+
124
+/* ------------------------------------------------------------------------- */
125
+
126
+#endif /* __oddebug_h_included__ */

+ 299
- 0
UsbJoystick/usbconfig-prototype.h Переглянути файл

@@ -0,0 +1,299 @@
1
+/* Name: usbconfig.h
2
+ * Project: AVR USB driver
3
+ * Author: Christian Starkjohann
4
+ * Creation Date: 2005-04-01
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: usbconfig-prototype.h 532 2008-02-28 15:35:05Z cs $
9
+ */
10
+
11
+#ifndef __usbconfig_h_included__
12
+#define __usbconfig_h_included__
13
+
14
+/*
15
+General Description:
16
+This file is an example configuration (with inline documentation) for the USB
17
+driver. It configures AVR-USB for an ATMega8 with USB D+ connected to Port D
18
+bit 2 (which is also hardware interrupt 0) and USB D- to Port D bit 0. You may
19
+wire the lines to any other port, as long as D+ is also wired to INT0.
20
+To create your own usbconfig.h file, copy this file to the directory
21
+containing "usbdrv" (that is your project firmware source directory) and
22
+rename it to "usbconfig.h". Then edit it accordingly.
23
+*/
24
+
25
+/* ---------------------------- Hardware Config ---------------------------- */
26
+
27
+#define USB_CFG_IOPORTNAME      D
28
+/* This is the port where the USB bus is connected. When you configure it to
29
+ * "B", the registers PORTB, PINB and DDRB will be used.
30
+ */
31
+#define USB_CFG_DMINUS_BIT      0
32
+/* This is the bit number in USB_CFG_IOPORT where the USB D- line is connected.
33
+ * This may be any bit in the port.
34
+ */
35
+#define USB_CFG_DPLUS_BIT       2
36
+/* This is the bit number in USB_CFG_IOPORT where the USB D+ line is connected.
37
+ * This may be any bit in the port. Please note that D+ must also be connected
38
+ * to interrupt pin INT0! [You can also use other interrupts, see section
39
+ * "Optional MCU Description" below, or you can connect D- to the interrupt, as
40
+ * it is required if you use the USB_COUNT_SOF feature. If you use D- for the
41
+ * interrupt, the USB interrupt will also be triggered at Start-Of-Frame
42
+ * markers every millisecond.]
43
+ */
44
+/* #define USB_CFG_CLOCK_KHZ       (F_CPU/1000) */
45
+/* Clock rate of the AVR in MHz. Legal values are 12000, 15000, 16000 or 16500.
46
+ * The 16.5 MHz version of the code requires no crystal, it tolerates +/- 1%
47
+ * deviation from the nominal frequency. All other rates require a precision
48
+ * of 2000 ppm and thus a crystal!
49
+ * Default if not specified: 12 MHz
50
+ */
51
+
52
+/* ----------------------- Optional Hardware Config ------------------------ */
53
+
54
+/* #define USB_CFG_PULLUP_IOPORTNAME   D */
55
+/* If you connect the 1.5k pullup resistor from D- to a port pin instead of
56
+ * V+, you can connect and disconnect the device from firmware by calling
57
+ * the macros usbDeviceConnect() and usbDeviceDisconnect() (see usbdrv.h).
58
+ * This constant defines the port on which the pullup resistor is connected.
59
+ */
60
+/* #define USB_CFG_PULLUP_BIT          4 */
61
+/* This constant defines the bit number in USB_CFG_PULLUP_IOPORT (defined
62
+ * above) where the 1.5k pullup resistor is connected. See description
63
+ * above for details.
64
+ */
65
+
66
+/* --------------------------- Functional Range ---------------------------- */
67
+
68
+#define USB_CFG_HAVE_INTRIN_ENDPOINT    1
69
+/* Define this to 1 if you want to compile a version with two endpoints: The
70
+ * default control endpoint 0 and an interrupt-in endpoint (any other endpoint
71
+ * number).
72
+ */
73
+#define USB_CFG_HAVE_INTRIN_ENDPOINT3   0
74
+/* Define this to 1 if you want to compile a version with three endpoints: The
75
+ * default control endpoint 0, an interrupt-in endpoint 3 (or the number
76
+ * configured below) and a catch-all default interrupt-in endpoint as above.
77
+ * You must also define USB_CFG_HAVE_INTRIN_ENDPOINT to 1 for this feature.
78
+ */
79
+#define USB_CFG_EP3_NUMBER              3
80
+/* If the so-called endpoint 3 is used, it can now be configured to any other
81
+ * endpoint number (except 0) with this macro. Default if undefined is 3.
82
+ */
83
+/* #define USB_INITIAL_DATATOKEN           USBPID_DATA0 */
84
+/* The above macro defines the startup condition for data toggling on the
85
+ * interrupt/bulk endpoints 1 and 3. Defaults to USBPID_DATA0.
86
+ */
87
+#define USB_CFG_IMPLEMENT_HALT          0
88
+/* Define this to 1 if you also want to implement the ENDPOINT_HALT feature
89
+ * for endpoint 1 (interrupt endpoint). Although you may not need this feature,
90
+ * it is required by the standard. We have made it a config option because it
91
+ * bloats the code considerably.
92
+ */
93
+#define USB_CFG_INTR_POLL_INTERVAL      20
94
+/* If you compile a version with endpoint 1 (interrupt-in), this is the poll
95
+ * interval. The value is in milliseconds and must not be less than 10 ms for
96
+ * low speed devices.
97
+ */
98
+#define USB_CFG_IS_SELF_POWERED         0
99
+/* Define this to 1 if the device has its own power supply. Set it to 0 if the
100
+ * device is powered from the USB bus.
101
+ */
102
+#define USB_CFG_MAX_BUS_POWER           100
103
+/* Set this variable to the maximum USB bus power consumption of your device.
104
+ * The value is in milliamperes. [It will be divided by two since USB
105
+ * communicates power requirements in units of 2 mA.]
106
+ */
107
+#define USB_CFG_IMPLEMENT_FN_WRITE      0
108
+/* Set this to 1 if you want usbFunctionWrite() to be called for control-out
109
+ * transfers. Set it to 0 if you don't need it and want to save a couple of
110
+ * bytes.
111
+ */
112
+#define USB_CFG_IMPLEMENT_FN_READ       0
113
+/* Set this to 1 if you need to send control replies which are generated
114
+ * "on the fly" when usbFunctionRead() is called. If you only want to send
115
+ * data from a static buffer, set it to 0 and return the data from
116
+ * usbFunctionSetup(). This saves a couple of bytes.
117
+ */
118
+#define USB_CFG_IMPLEMENT_FN_WRITEOUT   0
119
+/* Define this to 1 if you want to use interrupt-out (or bulk out) endpoints.
120
+ * You must implement the function usbFunctionWriteOut() which receives all
121
+ * interrupt/bulk data sent to any endpoint other than 0. The endpoint number
122
+ * can be found in 'usbRxToken'.
123
+ */
124
+#define USB_CFG_HAVE_FLOWCONTROL        0
125
+/* Define this to 1 if you want flowcontrol over USB data. See the definition
126
+ * of the macros usbDisableAllRequests() and usbEnableAllRequests() in
127
+ * usbdrv.h.
128
+ */
129
+/* #define USB_RX_USER_HOOK(data, len)     if(usbRxToken == (uchar)USBPID_SETUP) blinkLED(); */
130
+/* This macro is a hook if you want to do unconventional things. If it is
131
+ * defined, it's inserted at the beginning of received message processing.
132
+ * If you eat the received message and don't want default processing to
133
+ * proceed, do a return after doing your things. One possible application
134
+ * (besides debugging) is to flash a status LED on each packet.
135
+ */
136
+/* #define USB_RESET_HOOK(resetStarts)     if(!resetStarts){hadUsbReset();} */
137
+/* This macro is a hook if you need to know when an USB RESET occurs. It has
138
+ * one parameter which distinguishes between the start of RESET state and its
139
+ * end.
140
+ */
141
+/* #define USB_SET_ADDRESS_HOOK()              hadAddressAssigned(); */
142
+/* This macro (if defined) is executed when a USB SET_ADDRESS request was
143
+ * received.
144
+ */
145
+#define USB_COUNT_SOF                   0
146
+/* define this macro to 1 if you need the global variable "usbSofCount" which
147
+ * counts SOF packets. This feature requires that the hardware interrupt is
148
+ * connected to D- instead of D+.
149
+ */
150
+#define USB_CFG_HAVE_MEASURE_FRAME_LENGTH   0
151
+/* define this macro to 1 if you want the function usbMeasureFrameLength()
152
+ * compiled in. This function can be used to calibrate the AVR's RC oscillator.
153
+ */
154
+
155
+/* -------------------------- Device Description --------------------------- */
156
+
157
+#define  USB_CFG_VENDOR_ID       0xc0, 0x16
158
+/* USB vendor ID for the device, low byte first. If you have registered your
159
+ * own Vendor ID, define it here. Otherwise you use obdev's free shared
160
+ * VID/PID pair. Be sure to read USBID-License.txt for rules!
161
+ * This template uses obdev's shared VID/PID pair for HIDs: 0x16c0/0x5df.
162
+ * Use this VID/PID pair ONLY if you understand the implications!
163
+ */
164
+#define  USB_CFG_DEVICE_ID       0xdf, 0x05
165
+/* This is the ID of the product, low byte first. It is interpreted in the
166
+ * scope of the vendor ID. If you have registered your own VID with usb.org
167
+ * or if you have licensed a PID from somebody else, define it here. Otherwise
168
+ * you use obdev's free shared VID/PID pair. Be sure to read the rules in
169
+ * USBID-License.txt!
170
+ * This template uses obdev's shared VID/PID pair for HIDs: 0x16c0/0x5df.
171
+ * Use this VID/PID pair ONLY if you understand the implications!
172
+ */
173
+#define USB_CFG_DEVICE_VERSION  0x00, 0x01
174
+/* Version number of the device: Minor number first, then major number.
175
+ */
176
+#define USB_CFG_VENDOR_NAME     'w', 'w', 'w', '.', 'o', 'b', 'd', 'e', 'v', '.', 'a', 't'
177
+#define USB_CFG_VENDOR_NAME_LEN 12
178
+/* These two values define the vendor name returned by the USB device. The name
179
+ * must be given as a list of characters under single quotes. The characters
180
+ * are interpreted as Unicode (UTF-16) entities.
181
+ * If you don't want a vendor name string, undefine these macros.
182
+ * ALWAYS define a vendor name containing your Internet domain name if you use
183
+ * obdev's free shared VID/PID pair. See the file USBID-License.txt for
184
+ * details.
185
+ */
186
+#define USB_CFG_DEVICE_NAME     'T', 'e', 'm', 'p', 'l', 'a', 't', 'e'
187
+#define USB_CFG_DEVICE_NAME_LEN 8
188
+/* Same as above for the device name. If you don't want a device name, undefine
189
+ * the macros. See the file USBID-License.txt before you assign a name if you
190
+ * use a shared VID/PID.
191
+ */
192
+/*#define USB_CFG_SERIAL_NUMBER   'N', 'o', 'n', 'e' */
193
+/*#define USB_CFG_SERIAL_NUMBER_LEN   0 */
194
+/* Same as above for the serial number. If you don't want a serial number,
195
+ * undefine the macros.
196
+ * It may be useful to provide the serial number through other means than at
197
+ * compile time. See the section about descriptor properties below for how
198
+ * to fine tune control over USB descriptors such as the string descriptor
199
+ * for the serial number.
200
+ */
201
+#define USB_CFG_DEVICE_CLASS        0
202
+#define USB_CFG_DEVICE_SUBCLASS     0
203
+/* See USB specification if you want to conform to an existing device class.
204
+ */
205
+#define USB_CFG_INTERFACE_CLASS     3   /* HID */
206
+#define USB_CFG_INTERFACE_SUBCLASS  0
207
+#define USB_CFG_INTERFACE_PROTOCOL  0
208
+/* See USB specification if you want to conform to an existing device class or
209
+ * protocol.
210
+ * This template defines a HID class device. If you implement a vendor class
211
+ * device, set USB_CFG_INTERFACE_CLASS to 0 and USB_CFG_DEVICE_CLASS to 0xff.
212
+ */
213
+#define USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH    42  /* total length of report descriptor */
214
+/* Define this to the length of the HID report descriptor, if you implement
215
+ * an HID device. Otherwise don't define it or define it to 0.
216
+ * Since this template defines a HID device, it must also specify a HID
217
+ * report descriptor length. You must add a PROGMEM character array named
218
+ * "usbHidReportDescriptor" to your code which contains the report descriptor.
219
+ * Don't forget to keep the array and this define in sync!
220
+ */
221
+
222
+/* #define USB_PUBLIC static */
223
+/* Use the define above if you #include usbdrv.c instead of linking against it.
224
+ * This technique saves a couple of bytes in flash memory.
225
+ */
226
+
227
+/* ------------------- Fine Control over USB Descriptors ------------------- */
228
+/* If you don't want to use the driver's default USB descriptors, you can
229
+ * provide our own. These can be provided as (1) fixed length static data in
230
+ * flash memory, (2) fixed length static data in RAM or (3) dynamically at
231
+ * runtime in the function usbFunctionDescriptor(). See usbdrv.h for more
232
+ * information about this function.
233
+ * Descriptor handling is configured through the descriptor's properties. If
234
+ * no properties are defined or if they are 0, the default descriptor is used.
235
+ * Possible properties are:
236
+ *   + USB_PROP_IS_DYNAMIC: The data for the descriptor should be fetched
237
+ *     at runtime via usbFunctionDescriptor().
238
+ *   + USB_PROP_IS_RAM: The data returned by usbFunctionDescriptor() or found
239
+ *     in static memory is in RAM, not in flash memory.
240
+ *   + USB_PROP_LENGTH(len): If the data is in static memory (RAM or flash),
241
+ *     the driver must know the descriptor's length. The descriptor itself is
242
+ *     found at the address of a well known identifier (see below).
243
+ * List of static descriptor names (must be declared PROGMEM if in flash):
244
+ *   char usbDescriptorDevice[];
245
+ *   char usbDescriptorConfiguration[];
246
+ *   char usbDescriptorHidReport[];
247
+ *   char usbDescriptorString0[];
248
+ *   int usbDescriptorStringVendor[];
249
+ *   int usbDescriptorStringDevice[];
250
+ *   int usbDescriptorStringSerialNumber[];
251
+ * Other descriptors can't be provided statically, they must be provided
252
+ * dynamically at runtime.
253
+ *
254
+ * Descriptor properties are or-ed or added together, e.g.:
255
+ * #define USB_CFG_DESCR_PROPS_DEVICE   (USB_PROP_IS_RAM | USB_PROP_LENGTH(18))
256
+ *
257
+ * The following descriptors are defined:
258
+ *   USB_CFG_DESCR_PROPS_DEVICE
259
+ *   USB_CFG_DESCR_PROPS_CONFIGURATION
260
+ *   USB_CFG_DESCR_PROPS_STRINGS
261
+ *   USB_CFG_DESCR_PROPS_STRING_0
262
+ *   USB_CFG_DESCR_PROPS_STRING_VENDOR
263
+ *   USB_CFG_DESCR_PROPS_STRING_PRODUCT
264
+ *   USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
265
+ *   USB_CFG_DESCR_PROPS_HID
266
+ *   USB_CFG_DESCR_PROPS_HID_REPORT
267
+ *   USB_CFG_DESCR_PROPS_UNKNOWN (for all descriptors not handled by the driver)
268
+ *
269
+ */
270
+
271
+#define USB_CFG_DESCR_PROPS_DEVICE                  0
272
+#define USB_CFG_DESCR_PROPS_CONFIGURATION           0
273
+#define USB_CFG_DESCR_PROPS_STRINGS                 0
274
+#define USB_CFG_DESCR_PROPS_STRING_0                0
275
+#define USB_CFG_DESCR_PROPS_STRING_VENDOR           0
276
+#define USB_CFG_DESCR_PROPS_STRING_PRODUCT          0
277
+#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER    0
278
+#define USB_CFG_DESCR_PROPS_HID                     0
279
+#define USB_CFG_DESCR_PROPS_HID_REPORT              0
280
+#define USB_CFG_DESCR_PROPS_UNKNOWN                 0
281
+
282
+/* ----------------------- Optional MCU Description ------------------------ */
283
+
284
+/* The following configurations have working defaults in usbdrv.h. You
285
+ * usually don't need to set them explicitly. Only if you want to run
286
+ * the driver on a device which is not yet supported or with a compiler
287
+ * which is not fully supported (such as IAR C) or if you use a differnt
288
+ * interrupt than INT0, you may have to define some of these.
289
+ */
290
+/* #define USB_INTR_CFG            MCUCR */
291
+/* #define USB_INTR_CFG_SET        ((1 << ISC00) | (1 << ISC01)) */
292
+/* #define USB_INTR_CFG_CLR        0 */
293
+/* #define USB_INTR_ENABLE         GIMSK */
294
+/* #define USB_INTR_ENABLE_BIT     INT0 */
295
+/* #define USB_INTR_PENDING        GIFR */
296
+/* #define USB_INTR_PENDING_BIT    INTF0 */
297
+/* #define USB_INTR_VECTOR         SIG_INTERRUPT0 */
298
+
299
+#endif /* __usbconfig_h_included__ */

+ 245
- 0
UsbJoystick/usbconfig.h Переглянути файл

@@ -0,0 +1,245 @@
1
+/* Name: usbconfig.h
2
+ * Project: AVR USB driver
3
+ * Author: Christian Starkjohann
4
+ * Creation Date: 2007-06-23
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: usbconfig.h 362 2007-06-25 14:38:21Z cs $
9
+ */
10
+
11
+#ifndef __usbconfig_h_included__
12
+#define __usbconfig_h_included__
13
+
14
+/* ---------------------------- Hardware Config ---------------------------- */
15
+
16
+#define USB_CFG_IOPORTNAME      D
17
+/* This is the port where the USB bus is connected. When you configure it to
18
+ * "B", the registers PORTB, PINB and DDRB will be used.
19
+ */
20
+#define USB_CFG_DMINUS_BIT      4
21
+/* This is the bit number in USB_CFG_IOPORT where the USB D- line is connected.
22
+ * This may be any bit in the port.
23
+ */
24
+#define USB_CFG_DPLUS_BIT       2
25
+/* This is the bit number in USB_CFG_IOPORT where the USB D+ line is connected.
26
+ * This may be any bit in the port. Please note that D+ must also be connected
27
+ * to interrupt pin INT0!
28
+ */
29
+#define USB_CFG_CLOCK_KHZ       (F_CPU/1000)
30
+/* Clock rate of the AVR in MHz. Legal values are 12000, 16000 or 16500.
31
+ * The 16.5 MHz version of the code requires no crystal, it tolerates +/- 1%
32
+ * deviation from the nominal frequency. All other rates require a precision
33
+ * of 2000 ppm and thus a crystal!
34
+ * Default if not specified: 12 MHz
35
+ */
36
+
37
+/* ----------------------- Optional Hardware Config ------------------------ */
38
+
39
+#define USB_CFG_PULLUP_IOPORTNAME   D
40
+/* If you connect the 1.5k pullup resistor from D- to a port pin instead of
41
+ * V+, you can connect and disconnect the device from firmware by calling
42
+ * the macros usbDeviceConnect() and usbDeviceDisconnect() (see usbdrv.h).
43
+ * This constant defines the port on which the pullup resistor is connected.
44
+ */
45
+#define USB_CFG_PULLUP_BIT          5
46
+/* This constant defines the bit number in USB_CFG_PULLUP_IOPORT (defined
47
+ * above) where the 1.5k pullup resistor is connected. See description
48
+ * above for details.
49
+ */
50
+
51
+/* --------------------------- Functional Range ---------------------------- */
52
+
53
+#define USB_CFG_HAVE_INTRIN_ENDPOINT    1
54
+/* Define this to 1 if you want to compile a version with two endpoints: The
55
+ * default control endpoint 0 and an interrupt-in endpoint 1.
56
+ */
57
+#define USB_CFG_HAVE_INTRIN_ENDPOINT3   0
58
+/* Define this to 1 if you want to compile a version with three endpoints: The
59
+ * default control endpoint 0, an interrupt-in endpoint 1 and an interrupt-in
60
+ * endpoint 3. You must also enable endpoint 1 above.
61
+ */
62
+#define USB_CFG_IMPLEMENT_HALT          0
63
+/* Define this to 1 if you also want to implement the ENDPOINT_HALT feature
64
+ * for endpoint 1 (interrupt endpoint). Although you may not need this feature,
65
+ * it is required by the standard. We have made it a config option because it
66
+ * bloats the code considerably.
67
+ */
68
+#define USB_CFG_INTR_POLL_INTERVAL      10
69
+/* If you compile a version with endpoint 1 (interrupt-in), this is the poll
70
+ * interval. The value is in milliseconds and must not be less than 10 ms for
71
+ * low speed devices.
72
+ */
73
+#define USB_CFG_IS_SELF_POWERED         0
74
+/* Define this to 1 if the device has its own power supply. Set it to 0 if the
75
+ * device is powered from the USB bus.
76
+ */
77
+#define USB_CFG_MAX_BUS_POWER           100
78
+/* Set this variable to the maximum USB bus power consumption of your device.
79
+ * The value is in milliamperes. [It will be divided by two since USB
80
+ * communicates power requirements in units of 2 mA.]
81
+ */
82
+#define USB_CFG_IMPLEMENT_FN_WRITE      0
83
+/* Set this to 1 if you want usbFunctionWrite() to be called for control-out
84
+ * transfers. Set it to 0 if you don't need it and want to save a couple of
85
+ * bytes.
86
+ */
87
+#define USB_CFG_IMPLEMENT_FN_READ       0
88
+/* Set this to 1 if you need to send control replies which are generated
89
+ * "on the fly" when usbFunctionRead() is called. If you only want to send
90
+ * data from a static buffer, set it to 0 and return the data from
91
+ * usbFunctionSetup(). This saves a couple of bytes.
92
+ */
93
+#define USB_CFG_IMPLEMENT_FN_WRITEOUT   0
94
+/* Define this to 1 if you want to use interrupt-out (or bulk out) endpoint 1.
95
+ * You must implement the function usbFunctionWriteOut() which receives all
96
+ * interrupt/bulk data sent to endpoint 1.
97
+ */
98
+#define USB_CFG_HAVE_FLOWCONTROL        0
99
+/* Define this to 1 if you want flowcontrol over USB data. See the definition
100
+ * of the macros usbDisableAllRequests() and usbEnableAllRequests() in
101
+ * usbdrv.h.
102
+ */
103
+
104
+/* -------------------------- Device Description --------------------------- */
105
+
106
+#define  USB_CFG_VENDOR_ID       0x42, 0x42
107
+/* USB vendor ID for the device, low byte first. If you have registered your
108
+ * own Vendor ID, define it here. Otherwise you use obdev's free shared
109
+ * VID/PID pair. Be sure to read USBID-License.txt for rules!
110
+ * This template uses obdev's shared VID/PID pair for HIDs: 0x16c0/0x5df.
111
+ * Use this VID/PID pair ONLY if you understand the implications!
112
+ */
113
+#define  USB_CFG_DEVICE_ID       0x31, 0xe1
114
+/* This is the ID of the product, low byte first. It is interpreted in the
115
+ * scope of the vendor ID. If you have registered your own VID with usb.org
116
+ * or if you have licensed a PID from somebody else, define it here. Otherwise
117
+ * you use obdev's free shared VID/PID pair. Be sure to read the rules in
118
+ * USBID-License.txt!
119
+ * This template uses obdev's shared VID/PID pair for HIDs: 0x16c0/0x5df.
120
+ * Use this VID/PID pair ONLY if you understand the implications!
121
+ */
122
+#define USB_CFG_DEVICE_VERSION  0x00, 0x01
123
+/* Version number of the device: Minor number first, then major number.
124
+ */
125
+#define USB_CFG_VENDOR_NAME     'A', 'r', 'd', 'u', 'i','n','o'
126
+#define USB_CFG_VENDOR_NAME_LEN 7
127
+/* These two values define the vendor name returned by the USB device. The name
128
+ * must be given as a list of characters under single quotes. The characters
129
+ * are interpreted as Unicode (UTF-16) entities.
130
+ * If you don't want a vendor name string, undefine these macros.
131
+ * ALWAYS define a vendor name containing your Internet domain name if you use
132
+ * obdev's free shared VID/PID pair. See the file USBID-License.txt for
133
+ * details.
134
+ */
135
+#define USB_CFG_DEVICE_NAME     'U', 's', 'b', 'J', 'o', 'y', 's', 't', 'i','c','k'
136
+#define USB_CFG_DEVICE_NAME_LEN 11
137
+/* Same as above for the device name. If you don't want a device name, undefine
138
+ * the macros. See the file USBID-License.txt before you assign a name if you
139
+ * use a shared VID/PID.
140
+ */
141
+/*#define USB_CFG_SERIAL_NUMBER   'N', 'o', 'n', 'e' */
142
+/*#define USB_CFG_SERIAL_NUMBER_LEN   0 */
143
+/* Same as above for the serial number. If you don't want a serial number,
144
+ * undefine the macros.
145
+ * It may be useful to provide the serial number through other means than at
146
+ * compile time. See the section about descriptor properties below for how
147
+ * to fine tune control over USB descriptors such as the string descriptor
148
+ * for the serial number.
149
+ */
150
+#define USB_CFG_DEVICE_CLASS        0
151
+#define USB_CFG_DEVICE_SUBCLASS     0
152
+/* See USB specification if you want to conform to an existing device class.
153
+ */
154
+#define USB_CFG_INTERFACE_CLASS     3   /* HID */
155
+#define USB_CFG_INTERFACE_SUBCLASS  0   /* no boot interface */
156
+#define USB_CFG_INTERFACE_PROTOCOL  0   /* no protocol */
157
+/* See USB specification if you want to conform to an existing device class or
158
+ * protocol.
159
+ */
160
+#define USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH    105  /* total length of report descriptor */
161
+/* Define this to the length of the HID report descriptor, if you implement
162
+ * an HID device. Otherwise don't define it or define it to 0.
163
+ * Since this template defines a HID device, it must also specify a HID
164
+ * report descriptor length. You must add a PROGMEM character array named
165
+ * "usbHidReportDescriptor" to your code which contains the report descriptor.
166
+ * Don't forget to keep the array and this define in sync!
167
+ */
168
+
169
+/* #define USB_PUBLIC static */
170
+/* Use the define above if you #include usbdrv.c instead of linking against it.
171
+ * This technique saves a couple of bytes in flash memory.
172
+ */
173
+
174
+/* ------------------- Fine Control over USB Descriptors ------------------- */
175
+/* If you don't want to use the driver's default USB descriptors, you can
176
+ * provide our own. These can be provided as (1) fixed length static data in
177
+ * flash memory, (2) fixed length static data in RAM or (3) dynamically at
178
+ * runtime in the function usbFunctionDescriptor(). See usbdrv.h for more
179
+ * information about this function.
180
+ * Descriptor handling is configured through the descriptor's properties. If
181
+ * no properties are defined or if they are 0, the default descriptor is used.
182
+ * Possible properties are:
183
+ *   + USB_PROP_IS_DYNAMIC: The data for the descriptor should be fetched
184
+ *     at runtime via usbFunctionDescriptor().
185
+ *   + USB_PROP_IS_RAM: The data returned by usbFunctionDescriptor() or found
186
+ *     in static memory is in RAM, not in flash memory.
187
+ *   + USB_PROP_LENGTH(len): If the data is in static memory (RAM or flash),
188
+ *     the driver must know the descriptor's length. The descriptor itself is
189
+ *     found at the address of a well known identifier (see below).
190
+ * List of static descriptor names (must be declared PROGMEM if in flash):
191
+ *   char usbDescriptorDevice[];
192
+ *   char usbDescriptorConfiguration[];
193
+ *   char usbDescriptorHidReport[];
194
+ *   char usbDescriptorString0[];
195
+ *   int usbDescriptorStringVendor[];
196
+ *   int usbDescriptorStringDevice[];
197
+ *   int usbDescriptorStringSerialNumber[];
198
+ * Other descriptors can't be provided statically, they must be provided
199
+ * dynamically at runtime.
200
+ *
201
+ * Descriptor properties are or-ed or added together, e.g.:
202
+ * #define USB_CFG_DESCR_PROPS_DEVICE   (USB_PROP_IS_RAM | USB_PROP_LENGTH(18))
203
+ *
204
+ * The following descriptors are defined:
205
+ *   USB_CFG_DESCR_PROPS_DEVICE
206
+ *   USB_CFG_DESCR_PROPS_CONFIGURATION
207
+ *   USB_CFG_DESCR_PROPS_STRINGS
208
+ *   USB_CFG_DESCR_PROPS_STRING_0
209
+ *   USB_CFG_DESCR_PROPS_STRING_VENDOR
210
+ *   USB_CFG_DESCR_PROPS_STRING_PRODUCT
211
+ *   USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
212
+ *   USB_CFG_DESCR_PROPS_HID
213
+ *   USB_CFG_DESCR_PROPS_HID_REPORT
214
+ *   USB_CFG_DESCR_PROPS_UNKNOWN (for all descriptors not handled by the driver)
215
+ *
216
+ */
217
+
218
+#define USB_CFG_DESCR_PROPS_DEVICE                  0
219
+#define USB_CFG_DESCR_PROPS_CONFIGURATION           0
220
+#define USB_CFG_DESCR_PROPS_STRINGS                 0
221
+#define USB_CFG_DESCR_PROPS_STRING_0                0
222
+#define USB_CFG_DESCR_PROPS_STRING_VENDOR           0
223
+#define USB_CFG_DESCR_PROPS_STRING_PRODUCT          0
224
+#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER    0
225
+#define USB_CFG_DESCR_PROPS_HID                     0
226
+#define USB_CFG_DESCR_PROPS_HID_REPORT              0
227
+#define USB_CFG_DESCR_PROPS_UNKNOWN                 0
228
+
229
+/* ----------------------- Optional MCU Description ------------------------ */
230
+
231
+/* The following configurations have working defaults in usbdrv.h. You
232
+ * usually don't need to set them explicitly. Only if you want to run
233
+ * the driver on a device which is not yet supported or with a compiler
234
+ * which is not fully supported (such as IAR C) or if you use a differnt
235
+ * interrupt than INT0, you may have to define some of these.
236
+ */
237
+/* #define USB_INTR_CFG            MCUCR */
238
+/* #define USB_INTR_CFG_SET        ((1 << ISC00) | (1 << ISC01)) */
239
+/* #define USB_INTR_CFG_CLR        0 */
240
+/* #define USB_INTR_ENABLE         GIMSK */
241
+/* #define USB_INTR_ENABLE_BIT     INT0 */
242
+/* #define USB_INTR_PENDING        GIFR */
243
+/* #define USB_INTR_PENDING_BIT    INTF0 */
244
+
245
+#endif /* __usbconfig_h_included__ */

+ 578
- 0
UsbJoystick/usbdrv.c Переглянути файл

@@ -0,0 +1,578 @@
1
+/* Name: usbdrv.c
2
+ * Project: AVR USB driver
3
+ * Author: Christian Starkjohann
4
+ * Creation Date: 2004-12-29
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: usbdrv.c 530 2008-02-28 15:34:04Z cs $
9
+ */
10
+
11
+#include "iarcompat.h"
12
+#ifndef __IAR_SYSTEMS_ICC__
13
+#   include <avr/io.h>
14
+#   include <avr/pgmspace.h>
15
+#endif
16
+#include "usbdrv.h"
17
+#include "oddebug.h"
18
+
19
+/*
20
+General Description:
21
+This module implements the C-part of the USB driver. See usbdrv.h for a
22
+documentation of the entire driver.
23
+*/
24
+
25
+/* ------------------------------------------------------------------------- */
26
+
27
+/* raw USB registers / interface to assembler code: */
28
+uchar usbRxBuf[2*USB_BUFSIZE];  /* raw RX buffer: PID, 8 bytes data, 2 bytes CRC */
29
+uchar       usbInputBufOffset;  /* offset in usbRxBuf used for low level receiving */
30
+uchar       usbDeviceAddr;      /* assigned during enumeration, defaults to 0 */
31
+uchar       usbNewDeviceAddr;   /* device ID which should be set after status phase */
32
+uchar       usbConfiguration;   /* currently selected configuration. Administered by driver, but not used */
33
+volatile schar usbRxLen;        /* = 0; number of bytes in usbRxBuf; 0 means free, -1 for flow control */
34
+uchar       usbCurrentTok;      /* last token received or endpoint number for last OUT token if != 0 */
35
+uchar       usbRxToken;         /* token for data we received; or endpont number for last OUT */
36
+uchar       usbMsgLen = 0xff;   /* remaining number of bytes, no msg to send if -1 (see usbMsgPtr) */
37
+volatile uchar usbTxLen = USBPID_NAK;   /* number of bytes to transmit with next IN token or handshake token */
38
+uchar       usbTxBuf[USB_BUFSIZE];/* data to transmit with next IN, free if usbTxLen contains handshake token */
39
+#if USB_COUNT_SOF
40
+volatile uchar  usbSofCount;    /* incremented by assembler module every SOF */
41
+#endif
42
+#if USB_CFG_HAVE_INTRIN_ENDPOINT
43
+volatile uchar usbTxLen1 = USBPID_NAK;  /* TX count for endpoint 1 */
44
+uchar       usbTxBuf1[USB_BUFSIZE];     /* TX data for endpoint 1 */
45
+#   if USB_CFG_HAVE_INTRIN_ENDPOINT3
46
+volatile uchar usbTxLen3 = USBPID_NAK;  /* TX count for endpoint 3 */
47
+uchar       usbTxBuf3[USB_BUFSIZE];     /* TX data for endpoint 3 */
48
+#   endif
49
+#endif
50
+
51
+/* USB status registers / not shared with asm code */
52
+uchar           *usbMsgPtr;     /* data to transmit next -- ROM or RAM address */
53
+static uchar    usbMsgFlags;    /* flag values see below */
54
+
55
+#define USB_FLG_TX_PACKET       (1<<0)
56
+/* Leave free 6 bits after TX_PACKET. This way we can increment usbMsgFlags to toggle TX_PACKET */
57
+#define USB_FLG_MSGPTR_IS_ROM   (1<<6)
58
+#define USB_FLG_USE_DEFAULT_RW  (1<<7)
59
+
60
+/*
61
+optimizing hints:
62
+- do not post/pre inc/dec integer values in operations
63
+- assign value of PRG_RDB() to register variables and don't use side effects in arg
64
+- use narrow scope for variables which should be in X/Y/Z register
65
+- assign char sized expressions to variables to force 8 bit arithmetics
66
+*/
67
+
68
+/* ------------------------------------------------------------------------- */
69
+
70
+#if USB_CFG_DESCR_PROPS_STRINGS == 0
71
+
72
+#if USB_CFG_DESCR_PROPS_STRING_0 == 0
73
+#undef USB_CFG_DESCR_PROPS_STRING_0
74
+#define USB_CFG_DESCR_PROPS_STRING_0    sizeof(usbDescriptorString0)
75
+PROGMEM const char usbDescriptorString0[] = { /* language descriptor */
76
+    4,          /* sizeof(usbDescriptorString0): length of descriptor in bytes */
77
+    3,          /* descriptor type */
78
+    0x09, 0x04, /* language index (0x0409 = US-English) */
79
+};
80
+#endif
81
+
82
+#if USB_CFG_DESCR_PROPS_STRING_VENDOR == 0 && USB_CFG_VENDOR_NAME_LEN
83
+#undef USB_CFG_DESCR_PROPS_STRING_VENDOR
84
+#define USB_CFG_DESCR_PROPS_STRING_VENDOR   sizeof(usbDescriptorStringVendor)
85
+PROGMEM const int  usbDescriptorStringVendor[] = {
86
+    USB_STRING_DESCRIPTOR_HEADER(USB_CFG_VENDOR_NAME_LEN),
87
+    USB_CFG_VENDOR_NAME
88
+};
89
+#endif
90
+
91
+#if USB_CFG_DESCR_PROPS_STRING_PRODUCT == 0 && USB_CFG_DEVICE_NAME_LEN
92
+#undef USB_CFG_DESCR_PROPS_STRING_PRODUCT
93
+#define USB_CFG_DESCR_PROPS_STRING_PRODUCT   sizeof(usbDescriptorStringDevice)
94
+PROGMEM const int  usbDescriptorStringDevice[] = {
95
+    USB_STRING_DESCRIPTOR_HEADER(USB_CFG_DEVICE_NAME_LEN),
96
+    USB_CFG_DEVICE_NAME
97
+};
98
+#endif
99
+
100
+#if USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER == 0 && USB_CFG_SERIAL_NUMBER_LEN
101
+#undef USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
102
+#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER    sizeof(usbDescriptorStringSerialNumber)
103
+PROGMEM const int usbDescriptorStringSerialNumber[] = {
104
+    USB_STRING_DESCRIPTOR_HEADER(USB_CFG_SERIAL_NUMBER_LEN),
105
+    USB_CFG_SERIAL_NUMBER
106
+};
107
+#endif
108
+
109
+#endif  /* USB_CFG_DESCR_PROPS_STRINGS == 0 */
110
+
111
+#if USB_CFG_DESCR_PROPS_DEVICE == 0
112
+#undef USB_CFG_DESCR_PROPS_DEVICE
113
+#define USB_CFG_DESCR_PROPS_DEVICE  sizeof(usbDescriptorDevice)
114
+PROGMEM const char usbDescriptorDevice[] = {    /* USB device descriptor */
115
+    18,         /* sizeof(usbDescriptorDevice): length of descriptor in bytes */
116
+    USBDESCR_DEVICE,        /* descriptor type */
117
+    0x10, 0x01,             /* USB version supported */
118
+    USB_CFG_DEVICE_CLASS,
119
+    USB_CFG_DEVICE_SUBCLASS,
120
+    0,                      /* protocol */
121
+    8,                      /* max packet size */
122
+    /* the following two casts affect the first byte of the constant only, but
123
+     * that's sufficient to avoid a warning with the default values.
124
+     */
125
+    (char)USB_CFG_VENDOR_ID,/* 2 bytes */
126
+    (char)USB_CFG_DEVICE_ID,/* 2 bytes */
127
+    USB_CFG_DEVICE_VERSION, /* 2 bytes */
128
+    USB_CFG_DESCR_PROPS_STRING_VENDOR != 0 ? 1 : 0,         /* manufacturer string index */
129
+    USB_CFG_DESCR_PROPS_STRING_PRODUCT != 0 ? 2 : 0,        /* product string index */
130
+    USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER != 0 ? 3 : 0,  /* serial number string index */
131
+    1,          /* number of configurations */
132
+};
133
+#endif
134
+
135
+#if USB_CFG_DESCR_PROPS_HID_REPORT != 0 && USB_CFG_DESCR_PROPS_HID == 0
136
+#undef USB_CFG_DESCR_PROPS_HID
137
+#define USB_CFG_DESCR_PROPS_HID     9   /* length of HID descriptor in config descriptor below */
138
+#endif
139
+
140
+#if USB_CFG_DESCR_PROPS_CONFIGURATION == 0
141
+#undef USB_CFG_DESCR_PROPS_CONFIGURATION
142
+#define USB_CFG_DESCR_PROPS_CONFIGURATION   sizeof(usbDescriptorConfiguration)
143
+PROGMEM const char usbDescriptorConfiguration[] = {    /* USB configuration descriptor */
144
+    9,          /* sizeof(usbDescriptorConfiguration): length of descriptor in bytes */
145
+    USBDESCR_CONFIG,    /* descriptor type */
146
+    18 + 7 * USB_CFG_HAVE_INTRIN_ENDPOINT + (USB_CFG_DESCR_PROPS_HID & 0xff), 0,
147
+                /* total length of data returned (including inlined descriptors) */
148
+    1,          /* number of interfaces in this configuration */
149
+    1,          /* index of this configuration */
150
+    0,          /* configuration name string index */
151
+#if USB_CFG_IS_SELF_POWERED
152
+    USBATTR_SELFPOWER,      /* attributes */
153
+#else
154
+    (char)USBATTR_BUSPOWER, /* attributes */
155
+#endif
156
+    USB_CFG_MAX_BUS_POWER/2,            /* max USB current in 2mA units */
157
+/* interface descriptor follows inline: */
158
+    9,          /* sizeof(usbDescrInterface): length of descriptor in bytes */
159
+    USBDESCR_INTERFACE, /* descriptor type */
160
+    0,          /* index of this interface */
161
+    0,          /* alternate setting for this interface */
162
+    USB_CFG_HAVE_INTRIN_ENDPOINT,   /* endpoints excl 0: number of endpoint descriptors to follow */
163
+    USB_CFG_INTERFACE_CLASS,
164
+    USB_CFG_INTERFACE_SUBCLASS,
165
+    USB_CFG_INTERFACE_PROTOCOL,
166
+    0,          /* string index for interface */
167
+#if (USB_CFG_DESCR_PROPS_HID & 0xff)    /* HID descriptor */
168
+    9,          /* sizeof(usbDescrHID): length of descriptor in bytes */
169
+    USBDESCR_HID,   /* descriptor type: HID */
170
+    0x01, 0x01, /* BCD representation of HID version */
171
+    0x00,       /* target country code */
172
+    0x01,       /* number of HID Report (or other HID class) Descriptor infos to follow */
173
+    0x22,       /* descriptor type: report */
174
+    USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH, 0,  /* total length of report descriptor */
175
+#endif
176
+#if USB_CFG_HAVE_INTRIN_ENDPOINT    /* endpoint descriptor for endpoint 1 */
177
+    7,          /* sizeof(usbDescrEndpoint) */
178
+    USBDESCR_ENDPOINT,  /* descriptor type = endpoint */
179
+    (char)0x81, /* IN endpoint number 1 */
180
+    0x03,       /* attrib: Interrupt endpoint */
181
+    8, 0,       /* maximum packet size */
182
+    USB_CFG_INTR_POLL_INTERVAL, /* in ms */
183
+#endif
184
+};
185
+#endif
186
+
187
+/* We don't use prog_int or prog_int16_t for compatibility with various libc
188
+ * versions. Here's an other compatibility hack:
189
+ */
190
+#ifndef PRG_RDB
191
+#define PRG_RDB(addr)   pgm_read_byte(addr)
192
+#endif
193
+
194
+typedef union{
195
+    unsigned    word;
196
+    uchar       *ptr;
197
+    uchar       bytes[2];
198
+}converter_t;
199
+/* We use this union to do type conversions. This is better optimized than
200
+ * type casts in gcc 3.4.3 and much better than using bit shifts to build
201
+ * ints from chars. Byte ordering is not a problem on an 8 bit platform.
202
+ */
203
+
204
+/* ------------------------------------------------------------------------- */
205
+
206
+static inline void  usbResetDataToggling(void)
207
+{
208
+#if USB_CFG_HAVE_INTRIN_ENDPOINT
209
+    USB_SET_DATATOKEN1(USB_INITIAL_DATATOKEN);  /* reset data toggling for interrupt endpoint */
210
+#   if USB_CFG_HAVE_INTRIN_ENDPOINT3
211
+    USB_SET_DATATOKEN3(USB_INITIAL_DATATOKEN);  /* reset data toggling for interrupt endpoint */
212
+#   endif
213
+#endif
214
+}
215
+
216
+static inline void  usbResetStall(void)
217
+{
218
+#if USB_CFG_IMPLEMENT_HALT && USB_CFG_HAVE_INTRIN_ENDPOINT
219
+        usbTxLen1 = USBPID_NAK;
220
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
221
+        usbTxLen3 = USBPID_NAK;
222
+#endif
223
+#endif
224
+}
225
+
226
+/* ------------------------------------------------------------------------- */
227
+
228
+#if USB_CFG_HAVE_INTRIN_ENDPOINT
229
+USB_PUBLIC void usbSetInterrupt(uchar *data, uchar len)
230
+{
231
+uchar       *p, i;
232
+
233
+#if USB_CFG_IMPLEMENT_HALT
234
+    if(usbTxLen1 == USBPID_STALL)
235
+        return;
236
+#endif
237
+#if 0   /* No runtime checks! Caller is responsible for valid data! */
238
+    if(len > 8) /* interrupt transfers are limited to 8 bytes */
239
+        len = 8;
240
+#endif
241
+    if(usbTxLen1 & 0x10){   /* packet buffer was empty */
242
+        usbTxBuf1[0] ^= USBPID_DATA0 ^ USBPID_DATA1;    /* toggle token */
243
+    }else{
244
+        usbTxLen1 = USBPID_NAK; /* avoid sending outdated (overwritten) interrupt data */
245
+    }
246
+    p = usbTxBuf1 + 1;
247
+    for(i=len;i--;)
248
+        *p++ = *data++;
249
+    usbCrc16Append(&usbTxBuf1[1], len);
250
+    usbTxLen1 = len + 4;    /* len must be given including sync byte */
251
+    DBG2(0x21, usbTxBuf1, len + 3);
252
+}
253
+#endif
254
+
255
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
256
+USB_PUBLIC void usbSetInterrupt3(uchar *data, uchar len)
257
+{
258
+uchar       *p, i;
259
+
260
+    if(usbTxLen3 & 0x10){   /* packet buffer was empty */
261
+        usbTxBuf3[0] ^= USBPID_DATA0 ^ USBPID_DATA1;    /* toggle token */
262
+    }else{
263
+        usbTxLen3 = USBPID_NAK; /* avoid sending outdated (overwritten) interrupt data */
264
+    }
265
+    p = usbTxBuf3 + 1;
266
+    for(i=len;i--;)
267
+        *p++ = *data++;
268
+    usbCrc16Append(&usbTxBuf3[1], len);
269
+    usbTxLen3 = len + 4;    /* len must be given including sync byte */
270
+    DBG2(0x23, usbTxBuf3, len + 3);
271
+}
272
+#endif
273
+
274
+
275
+static uchar usbRead(uchar *data, uchar len)
276
+{
277
+#if USB_CFG_IMPLEMENT_FN_READ
278
+    if(usbMsgFlags & USB_FLG_USE_DEFAULT_RW){
279
+#endif
280
+        uchar i = len, *r = usbMsgPtr;
281
+        if(usbMsgFlags & USB_FLG_MSGPTR_IS_ROM){    /* ROM data */
282
+            while(i--){
283
+                uchar c = PRG_RDB(r);    /* assign to char size variable to enforce byte ops */
284
+                *data++ = c;
285
+                r++;
286
+            }
287
+        }else{                  /* RAM data */
288
+            while(i--)
289
+                *data++ = *r++;
290
+        }
291
+        usbMsgPtr = r;
292
+        return len;
293
+#if USB_CFG_IMPLEMENT_FN_READ
294
+    }else{
295
+        if(len != 0)    /* don't bother app with 0 sized reads */
296
+            return usbFunctionRead(data, len);
297
+        return 0;
298
+    }
299
+#endif
300
+}
301
+
302
+
303
+#define GET_DESCRIPTOR(cfgProp, staticName)         \
304
+    if(cfgProp){                                    \
305
+        if((cfgProp) & USB_PROP_IS_RAM)             \
306
+            flags &= ~USB_FLG_MSGPTR_IS_ROM;        \
307
+        if((cfgProp) & USB_PROP_IS_DYNAMIC){        \
308
+            replyLen = usbFunctionDescriptor(rq);   \
309
+        }else{                                      \
310
+            replyData = (uchar *)(staticName);      \
311
+            SET_REPLY_LEN((cfgProp) & 0xff);        \
312
+        }                                           \
313
+    }
314
+/* We use if() instead of #if in the macro above because #if can't be used
315
+ * in macros and the compiler optimizes constant conditions anyway.
316
+ */
317
+
318
+
319
+/* Don't make this function static to avoid inlining.
320
+ * The entire function would become too large and exceed the range of
321
+ * relative jumps.
322
+ * 2006-02-25: Either gcc 3.4.3 is better than the gcc used when the comment
323
+ * above was written, or other parts of the code have changed. We now get
324
+ * better results with an inlined function. Test condition: PowerSwitch code.
325
+ */
326
+static void usbProcessRx(uchar *data, uchar len)
327
+{
328
+usbRequest_t    *rq = (usbRequest_t *)((void *)data);
329
+uchar           replyLen = 0, flags = USB_FLG_USE_DEFAULT_RW;
330
+/* We use if() cascades because the compare is done byte-wise while switch()
331
+ * is int-based. The if() cascades are therefore more efficient.
332
+ */
333
+/* usbRxToken can be:
334
+ * 0x2d 00101101 (USBPID_SETUP for endpoint 0)
335
+ * 0xe1 11100001 (USBPID_OUT for endpoint 0)
336
+ * 0xff 11111111 (USBPID_OUT for endpoint 1)
337
+ */
338
+    DBG2(0x10 + ((usbRxToken >> 1) & 3), data, len);    /* SETUP0=12; OUT0=10; OUT1=13 */
339
+#ifdef USB_RX_USER_HOOK
340
+    USB_RX_USER_HOOK(data, len)
341
+#endif
342
+#if USB_CFG_IMPLEMENT_FN_WRITEOUT
343
+    if(usbRxToken < 0x10){  /* endpoint number in usbRxToken */
344
+        usbFunctionWriteOut(data, len);
345
+        return; /* no reply expected, hence no usbMsgPtr, usbMsgFlags, usbMsgLen set */
346
+    }
347
+#endif
348
+    if(usbRxToken == (uchar)USBPID_SETUP){
349
+        usbTxLen = USBPID_NAK;  /* abort pending transmit */
350
+        if(len == 8){   /* Setup size must be always 8 bytes. Ignore otherwise. */
351
+            uchar type = rq->bmRequestType & USBRQ_TYPE_MASK;
352
+            if(type == USBRQ_TYPE_STANDARD){
353
+                #define SET_REPLY_LEN(len)  replyLen = (len); usbMsgPtr = replyData
354
+                /* This macro ensures that replyLen and usbMsgPtr are always set in the same way.
355
+                 * That allows optimization of common code in if() branches */
356
+                uchar *replyData = usbTxBuf + 9; /* there is 3 bytes free space at the end of the buffer */
357
+                replyData[0] = 0;   /* common to USBRQ_GET_STATUS and USBRQ_GET_INTERFACE */
358
+                if(rq->bRequest == USBRQ_GET_STATUS){           /* 0 */
359
+                    uchar __attribute__((__unused__)) recipient = rq->bmRequestType & USBRQ_RCPT_MASK;  /* assign arith ops to variables to enforce byte size */
360
+#if USB_CFG_IS_SELF_POWERED
361
+                    if(recipient == USBRQ_RCPT_DEVICE)
362
+                        replyData[0] =  USB_CFG_IS_SELF_POWERED;
363
+#endif
364
+#if USB_CFG_HAVE_INTRIN_ENDPOINT && USB_CFG_IMPLEMENT_HALT
365
+                    if(recipient == USBRQ_RCPT_ENDPOINT && rq->wIndex.bytes[0] == 0x81)   /* request status for endpoint 1 */
366
+                        replyData[0] = usbTxLen1 == USBPID_STALL;
367
+#endif
368
+                    replyData[1] = 0;
369
+                    SET_REPLY_LEN(2);
370
+                }else if(rq->bRequest == USBRQ_SET_ADDRESS){    /* 5 */
371
+                    usbNewDeviceAddr = rq->wValue.bytes[0];
372
+#ifdef USB_SET_ADDRESS_HOOK
373
+                    USB_SET_ADDRESS_HOOK();
374
+#endif
375
+                }else if(rq->bRequest == USBRQ_GET_DESCRIPTOR){ /* 6 */
376
+                    flags = USB_FLG_MSGPTR_IS_ROM | USB_FLG_USE_DEFAULT_RW;
377
+                    if(rq->wValue.bytes[1] == USBDESCR_DEVICE){ /* 1 */
378
+                        GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_DEVICE, usbDescriptorDevice)
379
+                    }else if(rq->wValue.bytes[1] == USBDESCR_CONFIG){   /* 2 */
380
+                        GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_CONFIGURATION, usbDescriptorConfiguration)
381
+                    }else if(rq->wValue.bytes[1] == USBDESCR_STRING){   /* 3 */
382
+#if USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC
383
+                        if(USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_RAM)
384
+                            flags &= ~USB_FLG_MSGPTR_IS_ROM;
385
+                        replyLen = usbFunctionDescriptor(rq);
386
+#else   /* USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC */
387
+                        if(rq->wValue.bytes[0] == 0){   /* descriptor index */
388
+                            GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_0, usbDescriptorString0)
389
+                        }else if(rq->wValue.bytes[0] == 1){
390
+                            GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_VENDOR, usbDescriptorStringVendor)
391
+                        }else if(rq->wValue.bytes[0] == 2){
392
+                            GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_PRODUCT, usbDescriptorStringDevice)
393
+                        }else if(rq->wValue.bytes[0] == 3){
394
+                            GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER, usbDescriptorStringSerialNumber)
395
+                        }else if(USB_CFG_DESCR_PROPS_UNKNOWN & USB_PROP_IS_DYNAMIC){
396
+                            replyLen = usbFunctionDescriptor(rq);
397
+                        }
398
+#endif  /* USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC */
399
+#if USB_CFG_DESCR_PROPS_HID_REPORT  /* only support HID descriptors if enabled */
400
+                    }else if(rq->wValue.bytes[1] == USBDESCR_HID){          /* 0x21 */
401
+                        GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_HID, usbDescriptorConfiguration + 18)
402
+                    }else if(rq->wValue.bytes[1] == USBDESCR_HID_REPORT){   /* 0x22 */
403
+                        GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_HID_REPORT, usbDescriptorHidReport)
404
+#endif  /* USB_CFG_DESCR_PROPS_HID_REPORT */
405
+                    }else if(USB_CFG_DESCR_PROPS_UNKNOWN & USB_PROP_IS_DYNAMIC){
406
+                        replyLen = usbFunctionDescriptor(rq);
407
+                    }
408
+                }else if(rq->bRequest == USBRQ_GET_CONFIGURATION){  /* 8 */
409
+                    replyData = &usbConfiguration;  /* send current configuration value */
410
+                    SET_REPLY_LEN(1);
411
+                }else if(rq->bRequest == USBRQ_SET_CONFIGURATION){  /* 9 */
412
+                    usbConfiguration = rq->wValue.bytes[0];
413
+                    usbResetStall();
414
+                }else if(rq->bRequest == USBRQ_GET_INTERFACE){      /* 10 */
415
+                    SET_REPLY_LEN(1);
416
+#if USB_CFG_HAVE_INTRIN_ENDPOINT
417
+                }else if(rq->bRequest == USBRQ_SET_INTERFACE){      /* 11 */
418
+                    usbResetDataToggling();
419
+                    usbResetStall();
420
+#   if USB_CFG_IMPLEMENT_HALT
421
+                }else if(rq->bRequest == USBRQ_CLEAR_FEATURE || rq->bRequest == USBRQ_SET_FEATURE){   /* 1|3 */
422
+                    if(rq->wValue.bytes[0] == 0 && rq->wIndex.bytes[0] == 0x81){   /* feature 0 == HALT for endpoint == 1 */
423
+                        usbTxLen1 = rq->bRequest == USBRQ_CLEAR_FEATURE ? USBPID_NAK : USBPID_STALL;
424
+                        usbResetDataToggling();
425
+                    }
426
+#   endif
427
+#endif
428
+                }else{
429
+                    /* the following requests can be ignored, send default reply */
430
+                    /* 1: CLEAR_FEATURE, 3: SET_FEATURE, 7: SET_DESCRIPTOR */
431
+                    /* 12: SYNCH_FRAME */
432
+                }
433
+                #undef SET_REPLY_LEN
434
+            }else{  /* not a standard request -- must be vendor or class request */
435
+                replyLen = usbFunctionSetup(data);
436
+            }
437
+#if USB_CFG_IMPLEMENT_FN_READ || USB_CFG_IMPLEMENT_FN_WRITE
438
+            if(replyLen == 0xff){   /* use user-supplied read/write function */
439
+                if((rq->bmRequestType & USBRQ_DIR_MASK) == USBRQ_DIR_DEVICE_TO_HOST){
440
+                    replyLen = rq->wLength.bytes[0];    /* IN transfers only */
441
+                }
442
+                flags &= ~USB_FLG_USE_DEFAULT_RW;  /* we have no valid msg, use user supplied read/write functions */
443
+            }else   /* The 'else' prevents that we limit a replyLen of 0xff to the maximum transfer len. */
444
+#endif
445
+            if(!rq->wLength.bytes[1] && replyLen > rq->wLength.bytes[0])  /* limit length to max */
446
+                replyLen = rq->wLength.bytes[0];
447
+        }
448
+        /* make sure that data packets which are sent as ACK to an OUT transfer are always zero sized */
449
+    }else{  /* DATA packet from out request */
450
+#if USB_CFG_IMPLEMENT_FN_WRITE
451
+        if(!(usbMsgFlags & USB_FLG_USE_DEFAULT_RW)){
452
+            uchar rval = usbFunctionWrite(data, len);
453
+            replyLen = 0xff;
454
+            if(rval == 0xff){       /* an error occurred */
455
+                usbMsgLen = 0xff;   /* cancel potentially pending data packet for ACK */
456
+                usbTxLen = USBPID_STALL;
457
+            }else if(rval != 0){    /* This was the final package */
458
+                replyLen = 0;       /* answer with a zero-sized data packet */
459
+            }
460
+            flags = 0;    /* start with a DATA1 package, stay with user supplied write() function */
461
+        }
462
+#endif
463
+    }
464
+    usbMsgFlags = flags;
465
+    usbMsgLen = replyLen;
466
+}
467
+
468
+/* ------------------------------------------------------------------------- */
469
+
470
+static void usbBuildTxBlock(void)
471
+{
472
+uchar   wantLen, len, txLen, token;
473
+
474
+    wantLen = usbMsgLen;
475
+    if(wantLen > 8)
476
+        wantLen = 8;
477
+    usbMsgLen -= wantLen;
478
+    token = USBPID_DATA1;
479
+    if(usbMsgFlags & USB_FLG_TX_PACKET)
480
+        token = USBPID_DATA0;
481
+    usbMsgFlags++;
482
+    len = usbRead(usbTxBuf + 1, wantLen);
483
+    if(len <= 8){           /* valid data packet */
484
+        usbCrc16Append(&usbTxBuf[1], len);
485
+        txLen = len + 4;    /* length including sync byte */
486
+        if(len < 8)         /* a partial package identifies end of message */
487
+            usbMsgLen = 0xff;
488
+    }else{
489
+        txLen = USBPID_STALL;   /* stall the endpoint */
490
+        usbMsgLen = 0xff;
491
+    }
492
+    usbTxBuf[0] = token;
493
+    usbTxLen = txLen;
494
+    DBG2(0x20, usbTxBuf, txLen-1);
495
+}
496
+
497
+/* ------------------------------------------------------------------------- */
498
+
499
+static inline uchar isNotSE0(void)
500
+{
501
+uchar   rval;
502
+/* We want to do
503
+ *     return (USBIN & USBMASK);
504
+ * here, but the compiler does int-expansion acrobatics.
505
+ * We can avoid this by assigning to a char-sized variable.
506
+ */
507
+    rval = USBIN & USBMASK;
508
+    return rval;
509
+}
510
+
511
+static inline void usbHandleResetHook(uchar notResetState)
512
+{
513
+#ifdef USB_RESET_HOOK
514
+static uchar    wasReset;
515
+uchar           isReset = !notResetState;
516
+
517
+    if(wasReset != isReset){
518
+        USB_RESET_HOOK(isReset);
519
+        wasReset = isReset;
520
+    }
521
+#endif
522
+}
523
+
524
+/* ------------------------------------------------------------------------- */
525
+
526
+USB_PUBLIC void usbPoll(void)
527
+{
528
+schar   len;
529
+uchar   i;
530
+
531
+    if((len = usbRxLen) > 0){
532
+/* We could check CRC16 here -- but ACK has already been sent anyway. If you
533
+ * need data integrity checks with this driver, check the CRC in your app
534
+ * code and report errors back to the host. Since the ACK was already sent,
535
+ * retries must be handled on application level.
536
+ * unsigned crc = usbCrc16(buffer + 1, usbRxLen - 3);
537
+ */
538
+        usbProcessRx(usbRxBuf + USB_BUFSIZE + 1 - usbInputBufOffset, len - 3);
539
+#if USB_CFG_HAVE_FLOWCONTROL
540
+        if(usbRxLen > 0)    /* only mark as available if not inactivated */
541
+            usbRxLen = 0;
542
+#else
543
+        usbRxLen = 0;       /* mark rx buffer as available */
544
+#endif
545
+    }
546
+    if(usbTxLen & 0x10){ /* transmit system idle */
547
+        if(usbMsgLen != 0xff){  /* transmit data pending? */
548
+            usbBuildTxBlock();
549
+        }
550
+    }
551
+    for(i = 10; i > 0; i--){
552
+        if(isNotSE0())
553
+            break;
554
+    }
555
+    if(i == 0){ /* RESET condition, called multiple times during reset */
556
+        usbNewDeviceAddr = 0;
557
+        usbDeviceAddr = 0;
558
+        usbResetStall();
559
+        DBG1(0xff, 0, 0);
560
+    }
561
+    usbHandleResetHook(i);
562
+}
563
+
564
+/* ------------------------------------------------------------------------- */
565
+
566
+USB_PUBLIC void usbInit(void)
567
+{
568
+#if USB_INTR_CFG_SET != 0
569
+    USB_INTR_CFG |= USB_INTR_CFG_SET;
570
+#endif
571
+#if USB_INTR_CFG_CLR != 0
572
+    USB_INTR_CFG &= ~(USB_INTR_CFG_CLR);
573
+#endif
574
+    USB_INTR_ENABLE |= (1 << USB_INTR_ENABLE_BIT);
575
+    usbResetDataToggling();
576
+}
577
+
578
+/* ------------------------------------------------------------------------- */

+ 706
- 0
UsbJoystick/usbdrv.h Переглянути файл

@@ -0,0 +1,706 @@
1
+/* Name: usbdrv.h
2
+ * Project: AVR USB driver
3
+ * Author: Christian Starkjohann
4
+ * Creation Date: 2004-12-29
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: usbdrv.h 536 2008-02-28 21:11:35Z cs $
9
+ */
10
+
11
+#ifndef __usbdrv_h_included__
12
+#define __usbdrv_h_included__
13
+#include "usbconfig.h"
14
+#include "iarcompat.h"
15
+
16
+/*
17
+Hardware Prerequisites:
18
+=======================
19
+USB lines D+ and D- MUST be wired to the same I/O port. We recommend that D+
20
+triggers the interrupt (best achieved by using INT0 for D+), but it is also
21
+possible to trigger the interrupt from D-. If D- is used, interrupts are also
22
+triggered by SOF packets. D- requires a pull-up of 1.5k to +3.5V (and the
23
+device must be powered at 3.5V) to identify as low-speed USB device. A
24
+pull-down or pull-up of 1M SHOULD be connected from D+ to +3.5V to prevent
25
+interference when no USB master is connected. If you use Zener diodes to limit
26
+the voltage on D+ and D-, you MUST use a pull-down resistor, not a pull-up.
27
+We use D+ as interrupt source and not D- because it does not trigger on
28
+keep-alive and RESET states. If you want to count keep-alive events with
29
+USB_COUNT_SOF, you MUST use D- as an interrupt source.
30
+
31
+As a compile time option, the 1.5k pull-up resistor on D- can be made
32
+switchable to allow the device to disconnect at will. See the definition of
33
+usbDeviceConnect() and usbDeviceDisconnect() further down in this file.
34
+
35
+Please adapt the values in usbconfig.h according to your hardware!
36
+
37
+The device MUST be clocked at exactly 12 MHz, 15 MHz or 16 MHz
38
+or at 16.5 MHz +/- 1%. See usbconfig-prototype.h for details.
39
+
40
+
41
+Limitations:
42
+============
43
+Robustness with respect to communication errors:
44
+The driver assumes error-free communication. It DOES check for errors in
45
+the PID, but does NOT check bit stuffing errors, SE0 in middle of a byte,
46
+token CRC (5 bit) and data CRC (16 bit). CRC checks can not be performed due
47
+to timing constraints: We must start sending a reply within 7 bit times.
48
+Bit stuffing and misplaced SE0 would have to be checked in real-time, but CPU
49
+performance does not permit that. The driver does not check Data0/Data1
50
+toggling, but application software can implement the check.
51
+
52
+Input characteristics:
53
+Since no differential receiver circuit is used, electrical interference
54
+robustness may suffer. The driver samples only one of the data lines with
55
+an ordinary I/O pin's input characteristics. However, since this is only a
56
+low speed USB implementation and the specification allows for 8 times the
57
+bit rate over the same hardware, we should be on the safe side. Even the spec
58
+requires detection of asymmetric states at high bit rate for SE0 detection.
59
+
60
+Number of endpoints:
61
+The driver supports the following endpoints:
62
+
63
+- Endpoint 0, the default control endpoint.
64
+- Any number of interrupt- or bulk-out endpoints. The data is sent to
65
+  usbFunctionWriteOut() and USB_CFG_IMPLEMENT_FN_WRITEOUT must be defined
66
+  to 1 to activate this feature. The endpoint number can be found in the
67
+  global variable 'usbRxToken'.
68
+- One default interrupt- or bulk-in endpoint. This endpoint is used for
69
+  interrupt- or bulk-in transfers which are not handled by any other endpoint.
70
+  You must define USB_CFG_HAVE_INTRIN_ENDPOINT in order to activate this
71
+  feature and call usbSetInterrupt() to send interrupt/bulk data.
72
+- One additional interrupt- or bulk-in endpoint. This was endpoint 3 in
73
+  previous versions of this driver but can now be configured to any endpoint
74
+  number. You must define USB_CFG_HAVE_INTRIN_ENDPOINT3 in order to activate
75
+  this feature and call usbSetInterrupt3() to send interrupt/bulk data. The
76
+  endpoint number can be set with USB_CFG_EP3_NUMBER.
77
+
78
+Please note that the USB standard forbids bulk endpoints for low speed devices!
79
+Most operating systems allow them anyway, but the AVR will spend 90% of the CPU
80
+time in the USB interrupt polling for bulk data.
81
+
82
+Maximum data payload:
83
+Data payload of control in and out transfers may be up to 254 bytes. In order
84
+to accept payload data of out transfers, you need to implement
85
+'usbFunctionWrite()'.
86
+
87
+USB Suspend Mode supply current:
88
+The USB standard limits power consumption to 500uA when the bus is in suspend
89
+mode. This is not a problem for self-powered devices since they don't need
90
+bus power anyway. Bus-powered devices can achieve this only by putting the
91
+CPU in sleep mode. The driver does not implement suspend handling by itself.
92
+However, the application may implement activity monitoring and wakeup from
93
+sleep. The host sends regular SE0 states on the bus to keep it active. These
94
+SE0 states can be detected by using D- as the interrupt source. Define
95
+USB_COUNT_SOF to 1 and use the global variable usbSofCount to check for bus
96
+activity.
97
+
98
+Operation without an USB master:
99
+The driver behaves neutral without connection to an USB master if D- reads
100
+as 1. To avoid spurious interrupts, we recommend a high impedance (e.g. 1M)
101
+pull-down or pull-up resistor on D+ (interrupt). If Zener diodes are used,
102
+use a pull-down. If D- becomes statically 0, the driver may block in the
103
+interrupt routine.
104
+
105
+Interrupt latency:
106
+The application must ensure that the USB interrupt is not disabled for more
107
+than 25 cycles (this is for 12 MHz, faster clocks allow longer latency).
108
+This implies that all interrupt routines must either be declared as "INTERRUPT"
109
+instead of "SIGNAL" (see "avr/signal.h") or that they are written in assembler
110
+with "sei" as the first instruction.
111
+
112
+Maximum interrupt duration / CPU cycle consumption:
113
+The driver handles all USB communication during the interrupt service
114
+routine. The routine will not return before an entire USB message is received
115
+and the reply is sent. This may be up to ca. 1200 cycles @ 12 MHz (= 100us) if
116
+the host conforms to the standard. The driver will consume CPU cycles for all
117
+USB messages, even if they address another (low-speed) device on the same bus.
118
+
119
+*/
120
+
121
+/* ------------------------------------------------------------------------- */
122
+/* --------------------------- Module Interface ---------------------------- */
123
+/* ------------------------------------------------------------------------- */
124
+
125
+#define USBDRV_VERSION  20080228
126
+/* This define uniquely identifies a driver version. It is a decimal number
127
+ * constructed from the driver's release date in the form YYYYMMDD. If the
128
+ * driver's behavior or interface changes, you can use this constant to
129
+ * distinguish versions. If it is not defined, the driver's release date is
130
+ * older than 2006-01-25.
131
+ */
132
+
133
+
134
+#ifndef USB_PUBLIC
135
+#define USB_PUBLIC
136
+#endif
137
+/* USB_PUBLIC is used as declaration attribute for all functions exported by
138
+ * the USB driver. The default is no attribute (see above). You may define it
139
+ * to static either in usbconfig.h or from the command line if you include
140
+ * usbdrv.c instead of linking against it. Including the C module of the driver
141
+ * directly in your code saves a couple of bytes in flash memory.
142
+ */
143
+
144
+#ifndef __ASSEMBLER__
145
+#ifndef uchar
146
+#define uchar   unsigned char
147
+#endif
148
+#ifndef schar
149
+#define schar   signed char
150
+#endif
151
+/* shortcuts for well defined 8 bit integer types */
152
+
153
+struct usbRequest;  /* forward declaration */
154
+
155
+#ifdef __cplusplus
156
+extern "C"{
157
+#endif
158
+USB_PUBLIC void usbInit(void);
159
+/* This function must be called before interrupts are enabled and the main
160
+ * loop is entered.
161
+ */
162
+USB_PUBLIC void usbPoll(void);
163
+/* This function must be called at regular intervals from the main loop.
164
+ * Maximum delay between calls is somewhat less than 50ms (USB timeout for
165
+ * accepting a Setup message). Otherwise the device will not be recognized.
166
+ * Please note that debug outputs through the UART take ~ 0.5ms per byte
167
+ * at 19200 bps.
168
+ */
169
+extern uchar *usbMsgPtr;
170
+/* This variable may be used to pass transmit data to the driver from the
171
+ * implementation of usbFunctionWrite(). It is also used internally by the
172
+ * driver for standard control requests.
173
+ */
174
+USB_PUBLIC uchar usbFunctionSetup(uchar data[8]);
175
+/* This function is called when the driver receives a SETUP transaction from
176
+ * the host which is not answered by the driver itself (in practice: class and
177
+ * vendor requests). All control transfers start with a SETUP transaction where
178
+ * the host communicates the parameters of the following (optional) data
179
+ * transfer. The SETUP data is available in the 'data' parameter which can
180
+ * (and should) be casted to 'usbRequest_t *' for a more user-friendly access
181
+ * to parameters.
182
+ *
183
+ * If the SETUP indicates a control-in transfer, you should provide the
184
+ * requested data to the driver. There are two ways to transfer this data:
185
+ * (1) Set the global pointer 'usbMsgPtr' to the base of the static RAM data
186
+ * block and return the length of the data in 'usbFunctionSetup()'. The driver
187
+ * will handle the rest. Or (2) return 0xff in 'usbFunctionSetup()'. The driver
188
+ * will then call 'usbFunctionRead()' when data is needed. See the
189
+ * documentation for usbFunctionRead() for details.
190
+ *
191
+ * If the SETUP indicates a control-out transfer, the only way to receive the
192
+ * data from the host is through the 'usbFunctionWrite()' call. If you
193
+ * implement this function, you must return 0xff in 'usbFunctionSetup()' to
194
+ * indicate that 'usbFunctionWrite()' should be used. See the documentation of
195
+ * this function for more information. If you just want to ignore the data sent
196
+ * by the host, return 0 in 'usbFunctionSetup()'.
197
+ *
198
+ * Note that calls to the functions usbFunctionRead() and usbFunctionWrite()
199
+ * are only done if enabled by the configuration in usbconfig.h.
200
+ */
201
+#ifdef __cplusplus
202
+} // extern "C"
203
+#endif
204
+USB_PUBLIC uchar usbFunctionDescriptor(struct usbRequest *rq);
205
+/* You need to implement this function ONLY if you provide USB descriptors at
206
+ * runtime (which is an expert feature). It is very similar to
207
+ * usbFunctionSetup() above, but it is called only to request USB descriptor
208
+ * data. See the documentation of usbFunctionSetup() above for more info.
209
+ */
210
+#if USB_CFG_HAVE_INTRIN_ENDPOINT
211
+#ifdef __cplusplus
212
+extern "C"{
213
+#endif
214
+USB_PUBLIC void usbSetInterrupt(uchar *data, uchar len);
215
+/* This function sets the message which will be sent during the next interrupt
216
+ * IN transfer. The message is copied to an internal buffer and must not exceed
217
+ * a length of 8 bytes. The message may be 0 bytes long just to indicate the
218
+ * interrupt status to the host.
219
+ * If you need to transfer more bytes, use a control read after the interrupt.
220
+ */
221
+extern volatile uchar usbTxLen1;
222
+#define usbInterruptIsReady()   (usbTxLen1 & 0x10)
223
+/* This macro indicates whether the last interrupt message has already been
224
+ * sent. If you set a new interrupt message before the old was sent, the
225
+ * message already buffered will be lost.
226
+ */
227
+#ifdef __cplusplus
228
+} // extern "C"
229
+#endif
230
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
231
+USB_PUBLIC void usbSetInterrupt3(uchar *data, uchar len);
232
+extern volatile uchar usbTxLen3;
233
+#define usbInterruptIsReady3()   (usbTxLen3 & 0x10)
234
+/* Same as above for endpoint 3 */
235
+#endif
236
+#endif /* USB_CFG_HAVE_INTRIN_ENDPOINT */
237
+#if USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH    /* simplified interface for backward compatibility */
238
+#define usbHidReportDescriptor  usbDescriptorHidReport
239
+/* should be declared as: PROGMEM char usbHidReportDescriptor[]; */
240
+/* If you implement an HID device, you need to provide a report descriptor.
241
+ * The HID report descriptor syntax is a bit complex. If you understand how
242
+ * report descriptors are constructed, we recommend that you use the HID
243
+ * Descriptor Tool from usb.org, see http://www.usb.org/developers/hidpage/.
244
+ * Otherwise you should probably start with a working example.
245
+ */
246
+#endif  /* USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH */
247
+#if USB_CFG_IMPLEMENT_FN_WRITE
248
+USB_PUBLIC uchar usbFunctionWrite(uchar *data, uchar len);
249
+/* This function is called by the driver to provide a control transfer's
250
+ * payload data (control-out). It is called in chunks of up to 8 bytes. The
251
+ * total count provided in the current control transfer can be obtained from
252
+ * the 'length' property in the setup data. If an error occurred during
253
+ * processing, return 0xff (== -1). The driver will answer the entire transfer
254
+ * with a STALL token in this case. If you have received the entire payload
255
+ * successfully, return 1. If you expect more data, return 0. If you don't
256
+ * know whether the host will send more data (you should know, the total is
257
+ * provided in the usbFunctionSetup() call!), return 1.
258
+ * NOTE: If you return 0xff for STALL, 'usbFunctionWrite()' may still be called
259
+ * for the remaining data. You must continue to return 0xff for STALL in these
260
+ * calls.
261
+ * In order to get usbFunctionWrite() called, define USB_CFG_IMPLEMENT_FN_WRITE
262
+ * to 1 in usbconfig.h and return 0xff in usbFunctionSetup()..
263
+ */
264
+#endif /* USB_CFG_IMPLEMENT_FN_WRITE */
265
+#if USB_CFG_IMPLEMENT_FN_READ
266
+USB_PUBLIC uchar usbFunctionRead(uchar *data, uchar len);
267
+/* This function is called by the driver to ask the application for a control
268
+ * transfer's payload data (control-in). It is called in chunks of up to 8
269
+ * bytes each. You should copy the data to the location given by 'data' and
270
+ * return the actual number of bytes copied. If you return less than requested,
271
+ * the control-in transfer is terminated. If you return 0xff, the driver aborts
272
+ * the transfer with a STALL token.
273
+ * In order to get usbFunctionRead() called, define USB_CFG_IMPLEMENT_FN_READ
274
+ * to 1 in usbconfig.h and return 0xff in usbFunctionSetup()..
275
+ */
276
+#endif /* USB_CFG_IMPLEMENT_FN_READ */
277
+#if USB_CFG_IMPLEMENT_FN_WRITEOUT
278
+USB_PUBLIC void usbFunctionWriteOut(uchar *data, uchar len);
279
+/* This function is called by the driver when data on interrupt-out or bulk-
280
+ * out endpoint 1 is received. You must define USB_CFG_IMPLEMENT_FN_WRITEOUT
281
+ * to 1 in usbconfig.h to get this function called.
282
+ */
283
+#endif /* USB_CFG_IMPLEMENT_FN_WRITEOUT */
284
+#ifdef USB_CFG_PULLUP_IOPORTNAME
285
+#define usbDeviceConnect()      ((USB_PULLUP_DDR |= (1<<USB_CFG_PULLUP_BIT)), \
286
+                                  (USB_PULLUP_OUT |= (1<<USB_CFG_PULLUP_BIT)))
287
+#define usbDeviceDisconnect()   ((USB_PULLUP_DDR &= ~(1<<USB_CFG_PULLUP_BIT)), \
288
+                                  (USB_PULLUP_OUT &= ~(1<<USB_CFG_PULLUP_BIT)))
289
+#else /* USB_CFG_PULLUP_IOPORTNAME */
290
+#define usbDeviceConnect()      (USBDDR &= ~(1<<USBMINUS))
291
+#define usbDeviceDisconnect()   (USBDDR |= (1<<USBMINUS))
292
+#endif /* USB_CFG_PULLUP_IOPORTNAME */
293
+/* The macros usbDeviceConnect() and usbDeviceDisconnect() (intended to look
294
+ * like a function) connect resp. disconnect the device from the host's USB.
295
+ * If the constants USB_CFG_PULLUP_IOPORT and USB_CFG_PULLUP_BIT are defined
296
+ * in usbconfig.h, a disconnect consists of removing the pull-up resisitor
297
+ * from D-, otherwise the disconnect is done by brute-force pulling D- to GND.
298
+ * This does not conform to the spec, but it works.
299
+ * Please note that the USB interrupt must be disabled while the device is
300
+ * in disconnected state, or the interrupt handler will hang! You can either
301
+ * turn off the USB interrupt selectively with
302
+ *     USB_INTR_ENABLE &= ~(1 << USB_INTR_ENABLE_BIT)
303
+ * or use cli() to disable interrupts globally.
304
+ */
305
+#ifdef __cplusplus
306
+extern "C"{
307
+#endif
308
+extern unsigned usbCrc16(unsigned data, uchar len);
309
+#define usbCrc16(data, len) usbCrc16((unsigned)(data), len)
310
+/* This function calculates the binary complement of the data CRC used in
311
+ * USB data packets. The value is used to build raw transmit packets.
312
+ * You may want to use this function for data checksums or to verify received
313
+ * data. We enforce 16 bit calling conventions for compatibility with IAR's
314
+ * tiny memory model.
315
+ */
316
+extern unsigned usbCrc16Append(unsigned data, uchar len);
317
+#define usbCrc16Append(data, len)    usbCrc16Append((unsigned)(data), len)
318
+/* This function is equivalent to usbCrc16() above, except that it appends
319
+ * the 2 bytes CRC (lowbyte first) in the 'data' buffer after reading 'len'
320
+ * bytes.
321
+ */
322
+#ifdef __cplusplus
323
+} // extern "C"
324
+#endif
325
+#if USB_CFG_HAVE_MEASURE_FRAME_LENGTH
326
+extern unsigned usbMeasureFrameLength(void);
327
+/* This function MUST be called IMMEDIATELY AFTER USB reset and measures 1/7 of
328
+ * the number of CPU cycles during one USB frame minus one low speed bit
329
+ * length. In other words: return value = 1499 * (F_CPU / 10.5 MHz)
330
+ * Since this is a busy wait, you MUST disable all interrupts with cli() before
331
+ * calling this function.
332
+ * This can be used to calibrate the AVR's RC oscillator.
333
+ */
334
+#endif
335
+extern uchar    usbConfiguration;
336
+/* This value contains the current configuration set by the host. The driver
337
+ * allows setting and querying of this variable with the USB SET_CONFIGURATION
338
+ * and GET_CONFIGURATION requests, but does not use it otherwise.
339
+ * You may want to reflect the "configured" status with a LED on the device or
340
+ * switch on high power parts of the circuit only if the device is configured.
341
+ */
342
+#if USB_COUNT_SOF
343
+extern volatile uchar   usbSofCount;
344
+/* This variable is incremented on every SOF packet. It is only available if
345
+ * the macro USB_COUNT_SOF is defined to a value != 0.
346
+ */
347
+#endif
348
+
349
+#define USB_STRING_DESCRIPTOR_HEADER(stringLength) ((2*(stringLength)+2) | (3<<8))
350
+/* This macro builds a descriptor header for a string descriptor given the
351
+ * string's length. See usbdrv.c for an example how to use it.
352
+ */
353
+#if USB_CFG_HAVE_FLOWCONTROL
354
+extern volatile schar   usbRxLen;
355
+#define usbDisableAllRequests()     usbRxLen = -1
356
+/* Must be called from usbFunctionWrite(). This macro disables all data input
357
+ * from the USB interface. Requests from the host are answered with a NAK
358
+ * while they are disabled.
359
+ */
360
+#define usbEnableAllRequests()      usbRxLen = 0
361
+/* May only be called if requests are disabled. This macro enables input from
362
+ * the USB interface after it has been disabled with usbDisableAllRequests().
363
+ */
364
+#define usbAllRequestsAreDisabled() (usbRxLen < 0)
365
+/* Use this macro to find out whether requests are disabled. It may be needed
366
+ * to ensure that usbEnableAllRequests() is never called when requests are
367
+ * enabled.
368
+ */
369
+#endif
370
+
371
+#define USB_SET_DATATOKEN1(token)   usbTxBuf1[0] = token
372
+#define USB_SET_DATATOKEN3(token)   usbTxBuf3[0] = token
373
+/* These two macros can be used by application software to reset data toggling
374
+ * for interrupt-in endpoints 1 and 3.
375
+ */
376
+
377
+#endif  /* __ASSEMBLER__ */
378
+
379
+
380
+/* ------------------------------------------------------------------------- */
381
+/* ----------------- Definitions for Descriptor Properties ----------------- */
382
+/* ------------------------------------------------------------------------- */
383
+/* This is advanced stuff. See usbconfig-prototype.h for more information
384
+ * about the various methods to define USB descriptors. If you do nothing,
385
+ * the default descriptors will be used.
386
+ */
387
+#define USB_PROP_IS_DYNAMIC     (1 << 8)
388
+/* If this property is set for a descriptor, usbFunctionDescriptor() will be
389
+ * used to obtain the particular descriptor.
390
+ */
391
+#define USB_PROP_IS_RAM         (1 << 9)
392
+/* If this property is set for a descriptor, the data is read from RAM
393
+ * memory instead of Flash. The property is used for all methods to provide
394
+ * external descriptors.
395
+ */
396
+#define USB_PROP_LENGTH(len)    ((len) & 0xff)
397
+/* If a static external descriptor is used, this is the total length of the
398
+ * descriptor in bytes.
399
+ */
400
+
401
+/* all descriptors which may have properties: */
402
+#ifndef USB_CFG_DESCR_PROPS_DEVICE
403
+#define USB_CFG_DESCR_PROPS_DEVICE                  0
404
+#endif
405
+#ifndef USB_CFG_DESCR_PROPS_CONFIGURATION
406
+#define USB_CFG_DESCR_PROPS_CONFIGURATION           0
407
+#endif
408
+#ifndef USB_CFG_DESCR_PROPS_STRINGS
409
+#define USB_CFG_DESCR_PROPS_STRINGS                 0
410
+#endif
411
+#ifndef USB_CFG_DESCR_PROPS_STRING_0
412
+#define USB_CFG_DESCR_PROPS_STRING_0                0
413
+#endif
414
+#ifndef USB_CFG_DESCR_PROPS_STRING_VENDOR
415
+#define USB_CFG_DESCR_PROPS_STRING_VENDOR           0
416
+#endif
417
+#ifndef USB_CFG_DESCR_PROPS_STRING_PRODUCT
418
+#define USB_CFG_DESCR_PROPS_STRING_PRODUCT          0
419
+#endif
420
+#ifndef USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
421
+#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER    0
422
+#endif
423
+#ifndef USB_CFG_DESCR_PROPS_HID
424
+#define USB_CFG_DESCR_PROPS_HID                     0
425
+#endif
426
+#if !(USB_CFG_DESCR_PROPS_HID_REPORT)
427
+#   undef USB_CFG_DESCR_PROPS_HID_REPORT
428
+#   if USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH /* do some backward compatibility tricks */
429
+#       define USB_CFG_DESCR_PROPS_HID_REPORT       USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH
430
+#   else
431
+#       define USB_CFG_DESCR_PROPS_HID_REPORT       0
432
+#   endif
433
+#endif
434
+#ifndef USB_CFG_DESCR_PROPS_UNKNOWN
435
+#define USB_CFG_DESCR_PROPS_UNKNOWN                 0
436
+#endif
437
+
438
+/* ------------------ forward declaration of descriptors ------------------- */
439
+/* If you use external static descriptors, they must be stored in global
440
+ * arrays as declared below:
441
+ */
442
+#ifndef __ASSEMBLER__
443
+extern
444
+#if !(USB_CFG_DESCR_PROPS_DEVICE & USB_PROP_IS_RAM)
445
+PROGMEM
446
+#endif
447
+const char usbDescriptorDevice[];
448
+
449
+extern
450
+#if !(USB_CFG_DESCR_PROPS_CONFIGURATION & USB_PROP_IS_RAM)
451
+PROGMEM
452
+#endif
453
+const char usbDescriptorConfiguration[];
454
+
455
+extern
456
+#if !(USB_CFG_DESCR_PROPS_HID_REPORT & USB_PROP_IS_RAM)
457
+PROGMEM
458
+#endif
459
+const char usbDescriptorHidReport[];
460
+
461
+extern
462
+#if !(USB_CFG_DESCR_PROPS_STRING_0 & USB_PROP_IS_RAM)
463
+PROGMEM
464
+#endif
465
+const char usbDescriptorString0[];
466
+
467
+extern
468
+#if !(USB_CFG_DESCR_PROPS_STRING_VENDOR & USB_PROP_IS_RAM)
469
+PROGMEM
470
+#endif
471
+const int usbDescriptorStringVendor[];
472
+
473
+extern
474
+#if !(USB_CFG_DESCR_PROPS_STRING_PRODUCT & USB_PROP_IS_RAM)
475
+PROGMEM
476
+#endif
477
+const int usbDescriptorStringDevice[];
478
+
479
+extern
480
+#if !(USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER & USB_PROP_IS_RAM)
481
+PROGMEM
482
+#endif
483
+const int usbDescriptorStringSerialNumber[];
484
+
485
+#endif /* __ASSEMBLER__ */
486
+
487
+/* ------------------------------------------------------------------------- */
488
+/* ------------------------ General Purpose Macros ------------------------- */
489
+/* ------------------------------------------------------------------------- */
490
+
491
+#define USB_CONCAT(a, b)            a ## b
492
+#define USB_CONCAT_EXPANDED(a, b)   USB_CONCAT(a, b)
493
+
494
+#define USB_OUTPORT(name)           USB_CONCAT(PORT, name)
495
+#define USB_INPORT(name)            USB_CONCAT(PIN, name)
496
+#define USB_DDRPORT(name)           USB_CONCAT(DDR, name)
497
+/* The double-define trick above lets us concatenate strings which are
498
+ * defined by macros.
499
+ */
500
+
501
+/* ------------------------------------------------------------------------- */
502
+/* ------------------------- Constant definitions -------------------------- */
503
+/* ------------------------------------------------------------------------- */
504
+
505
+#if !defined __ASSEMBLER__ && (!defined USB_CFG_VENDOR_ID || !defined USB_CFG_DEVICE_ID)
506
+#warning "You should define USB_CFG_VENDOR_ID and USB_CFG_DEVICE_ID in usbconfig.h"
507
+/* If the user has not defined IDs, we default to obdev's free IDs.
508
+ * See USBID-License.txt for details.
509
+ */
510
+#endif
511
+
512
+/* make sure we have a VID and PID defined, byte order is lowbyte, highbyte */
513
+#ifndef USB_CFG_VENDOR_ID
514
+#   define  USB_CFG_VENDOR_ID   0xc0, 0x16  /* 5824 in dec, stands for VOTI */
515
+#endif
516
+
517
+#ifndef USB_CFG_DEVICE_ID
518
+#   if USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH
519
+#       define USB_CFG_DEVICE_ID    0xdf, 0x05  /* 1503 in dec, shared PID for HIDs */
520
+#   elif USB_CFG_INTERFACE_CLASS == 2
521
+#       define USB_CFG_DEVICE_ID    0xe1, 0x05  /* 1505 in dec, shared PID for CDC Modems */
522
+#   else
523
+#       define USB_CFG_DEVICE_ID    0xdc, 0x05  /* 1500 in dec, obdev's free PID */
524
+#   endif
525
+#endif
526
+
527
+/* Derive Output, Input and DataDirection ports from port names */
528
+#ifndef USB_CFG_IOPORTNAME
529
+#error "You must define USB_CFG_IOPORTNAME in usbconfig.h, see usbconfig-prototype.h"
530
+#endif
531
+
532
+#define USBOUT          USB_OUTPORT(USB_CFG_IOPORTNAME)
533
+#define USB_PULLUP_OUT  USB_OUTPORT(USB_CFG_PULLUP_IOPORTNAME)
534
+#define USBIN           USB_INPORT(USB_CFG_IOPORTNAME)
535
+#define USBDDR          USB_DDRPORT(USB_CFG_IOPORTNAME)
536
+#define USB_PULLUP_DDR  USB_DDRPORT(USB_CFG_PULLUP_IOPORTNAME)
537
+
538
+#define USBMINUS    USB_CFG_DMINUS_BIT
539
+#define USBPLUS     USB_CFG_DPLUS_BIT
540
+#define USBIDLE     (1<<USB_CFG_DMINUS_BIT) /* value representing J state */
541
+#define USBMASK     ((1<<USB_CFG_DPLUS_BIT) | (1<<USB_CFG_DMINUS_BIT))  /* mask for USB I/O bits */
542
+
543
+/* defines for backward compatibility with older driver versions: */
544
+#define USB_CFG_IOPORT          USB_OUTPORT(USB_CFG_IOPORTNAME)
545
+#ifdef USB_CFG_PULLUP_IOPORTNAME
546
+#define USB_CFG_PULLUP_IOPORT   USB_OUTPORT(USB_CFG_PULLUP_IOPORTNAME)
547
+#endif
548
+
549
+#ifndef USB_CFG_EP3_NUMBER  /* if not defined in usbconfig.h */
550
+#define USB_CFG_EP3_NUMBER  3
551
+#endif
552
+
553
+#define USB_BUFSIZE     11  /* PID, 8 bytes data, 2 bytes CRC */
554
+
555
+/* ----- Try to find registers and bits responsible for ext interrupt 0 ----- */
556
+
557
+#ifndef USB_INTR_CFG    /* allow user to override our default */
558
+#   if defined  EICRA
559
+#       define USB_INTR_CFG EICRA
560
+#   else
561
+#       define USB_INTR_CFG MCUCR
562
+#   endif
563
+#endif
564
+#ifndef USB_INTR_CFG_SET    /* allow user to override our default */
565
+#   define USB_INTR_CFG_SET ((1 << ISC00) | (1 << ISC01))    /* cfg for rising edge */
566
+#endif
567
+#ifndef USB_INTR_CFG_CLR    /* allow user to override our default */
568
+#   define USB_INTR_CFG_CLR 0    /* no bits to clear */
569
+#endif
570
+
571
+#ifndef USB_INTR_ENABLE     /* allow user to override our default */
572
+#   if defined GIMSK
573
+#       define USB_INTR_ENABLE  GIMSK
574
+#   elif defined EIMSK
575
+#       define USB_INTR_ENABLE  EIMSK
576
+#   else
577
+#       define USB_INTR_ENABLE  GICR
578
+#   endif
579
+#endif
580
+#ifndef USB_INTR_ENABLE_BIT /* allow user to override our default */
581
+#   define USB_INTR_ENABLE_BIT  INT0
582
+#endif
583
+
584
+#ifndef USB_INTR_PENDING    /* allow user to override our default */
585
+#   if defined  EIFR
586
+#       define USB_INTR_PENDING EIFR
587
+#   else
588
+#       define USB_INTR_PENDING GIFR
589
+#   endif
590
+#endif
591
+#ifndef USB_INTR_PENDING_BIT    /* allow user to override our default */
592
+#   define USB_INTR_PENDING_BIT INTF0
593
+#endif
594
+
595
+/*
596
+The defines above don't work for the following chips
597
+at90c8534: no ISC0?, no PORTB, can't find a data sheet
598
+at86rf401: no PORTB, no MCUCR etc, low clock rate
599
+atmega103: no ISC0? (maybe omission in header, can't find data sheet)
600
+atmega603: not defined in avr-libc
601
+at43usb320, at43usb355, at76c711: have USB anyway
602
+at94k: is different...
603
+
604
+at90s1200, attiny11, attiny12, attiny15, attiny28: these have no RAM
605
+*/
606
+
607
+/* ------------------------------------------------------------------------- */
608
+/* ----------------- USB Specification Constants and Types ----------------- */
609
+/* ------------------------------------------------------------------------- */
610
+
611
+/* USB Token values */
612
+#define USBPID_SETUP    0x2d
613
+#define USBPID_OUT      0xe1
614
+#define USBPID_IN       0x69
615
+#define USBPID_DATA0    0xc3
616
+#define USBPID_DATA1    0x4b
617
+
618
+#define USBPID_ACK      0xd2
619
+#define USBPID_NAK      0x5a
620
+#define USBPID_STALL    0x1e
621
+
622
+#ifndef USB_INITIAL_DATATOKEN
623
+#define USB_INITIAL_DATATOKEN   USBPID_DATA0
624
+#endif
625
+
626
+#ifndef __ASSEMBLER__
627
+
628
+extern uchar    usbTxBuf1[USB_BUFSIZE], usbTxBuf3[USB_BUFSIZE];
629
+
630
+typedef union usbWord{
631
+    unsigned    word;
632
+    uchar       bytes[2];
633
+}usbWord_t;
634
+
635
+typedef struct usbRequest{
636
+    uchar       bmRequestType;
637
+    uchar       bRequest;
638
+    usbWord_t   wValue;
639
+    usbWord_t   wIndex;
640
+    usbWord_t   wLength;
641
+}usbRequest_t;
642
+/* This structure matches the 8 byte setup request */
643
+#endif
644
+
645
+/* bmRequestType field in USB setup:
646
+ * d t t r r r r r, where
647
+ * d ..... direction: 0=host->device, 1=device->host
648
+ * t ..... type: 0=standard, 1=class, 2=vendor, 3=reserved
649
+ * r ..... recipient: 0=device, 1=interface, 2=endpoint, 3=other
650
+ */
651
+
652
+/* USB setup recipient values */
653
+#define USBRQ_RCPT_MASK         0x1f
654
+#define USBRQ_RCPT_DEVICE       0
655
+#define USBRQ_RCPT_INTERFACE    1
656
+#define USBRQ_RCPT_ENDPOINT     2
657
+
658
+/* USB request type values */
659
+#define USBRQ_TYPE_MASK         0x60
660
+#define USBRQ_TYPE_STANDARD     (0<<5)
661
+#define USBRQ_TYPE_CLASS        (1<<5)
662
+#define USBRQ_TYPE_VENDOR       (2<<5)
663
+
664
+/* USB direction values: */
665
+#define USBRQ_DIR_MASK              0x80
666
+#define USBRQ_DIR_HOST_TO_DEVICE    (0<<7)
667
+#define USBRQ_DIR_DEVICE_TO_HOST    (1<<7)
668
+
669
+/* USB Standard Requests */
670
+#define USBRQ_GET_STATUS        0
671
+#define USBRQ_CLEAR_FEATURE     1
672
+#define USBRQ_SET_FEATURE       3
673
+#define USBRQ_SET_ADDRESS       5
674
+#define USBRQ_GET_DESCRIPTOR    6
675
+#define USBRQ_SET_DESCRIPTOR    7
676
+#define USBRQ_GET_CONFIGURATION 8
677
+#define USBRQ_SET_CONFIGURATION 9
678
+#define USBRQ_GET_INTERFACE     10
679
+#define USBRQ_SET_INTERFACE     11
680
+#define USBRQ_SYNCH_FRAME       12
681
+
682
+/* USB descriptor constants */
683
+#define USBDESCR_DEVICE         1
684
+#define USBDESCR_CONFIG         2
685
+#define USBDESCR_STRING         3
686
+#define USBDESCR_INTERFACE      4
687
+#define USBDESCR_ENDPOINT       5
688
+#define USBDESCR_HID            0x21
689
+#define USBDESCR_HID_REPORT     0x22
690
+#define USBDESCR_HID_PHYS       0x23
691
+
692
+#define USBATTR_BUSPOWER        0x80
693
+#define USBATTR_SELFPOWER       0x40
694
+#define USBATTR_REMOTEWAKE      0x20
695
+
696
+/* USB HID Requests */
697
+#define USBRQ_HID_GET_REPORT    0x01
698
+#define USBRQ_HID_GET_IDLE      0x02
699
+#define USBRQ_HID_GET_PROTOCOL  0x03
700
+#define USBRQ_HID_SET_REPORT    0x09
701
+#define USBRQ_HID_SET_IDLE      0x0a
702
+#define USBRQ_HID_SET_PROTOCOL  0x0b
703
+
704
+/* ------------------------------------------------------------------------- */
705
+
706
+#endif /* __usbdrv_h_included__ */

+ 307
- 0
UsbJoystick/usbdrvasm.S Переглянути файл

@@ -0,0 +1,307 @@
1
+/* Name: usbdrvasm.S
2
+ * Project: AVR USB driver
3
+ * Author: Christian Starkjohann
4
+ * Creation Date: 2007-06-13
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt)
8
+ * Revision: $Id$
9
+ */
10
+
11
+/*
12
+General Description:
13
+This module is the assembler part of the USB driver. This file contains
14
+general code (preprocessor acrobatics and CRC computation) and then includes
15
+the file appropriate for the given clock rate.
16
+*/
17
+
18
+#include "iarcompat.h"
19
+#ifndef __IAR_SYSTEMS_ASM__
20
+    /* configs for io.h */
21
+#   define __SFR_OFFSET 0
22
+#   define _VECTOR(N)   __vector_ ## N   /* io.h does not define this for asm */
23
+#   include <avr/io.h> /* for CPU I/O register definitions and vectors */
24
+#   define macro    .macro  /* GNU Assembler macro definition */
25
+#   define endm     .endm   /* End of GNU Assembler macro definition */
26
+#endif  /* __IAR_SYSTEMS_ASM__ */
27
+#include "usbdrv.h" /* for common defs */
28
+
29
+/* register names */
30
+#define x1      r16
31
+#define x2      r17
32
+#define shift   r18
33
+#define cnt     r19
34
+#define x3      r20
35
+#define x4      r21
36
+#define bitcnt  r22
37
+#define phase   x4
38
+#define leap    x4
39
+
40
+/* Some assembler dependent definitions and declarations: */
41
+
42
+#ifdef __IAR_SYSTEMS_ASM__
43
+
44
+#   define nop2     rjmp    $+2 /* jump to next instruction */
45
+#   define XL       r26
46
+#   define XH       r27
47
+#   define YL       r28
48
+#   define YH       r29
49
+#   define ZL       r30
50
+#   define ZH       r31
51
+#   define lo8(x)   LOW(x)
52
+#   define hi8(x)   (((x)>>8) & 0xff)   /* not HIGH to allow XLINK to make a proper range check */
53
+
54
+    extern  usbRxBuf, usbDeviceAddr, usbNewDeviceAddr, usbInputBufOffset
55
+    extern  usbCurrentTok, usbRxLen, usbRxToken, usbTxLen
56
+    extern  usbTxBuf, usbMsgLen, usbTxLen1, usbTxBuf1, usbTxLen3, usbTxBuf3
57
+#   if USB_COUNT_SOF
58
+        extern usbSofCount
59
+#   endif
60
+    public  usbCrc16
61
+    public  usbCrc16Append
62
+
63
+    COMMON  INTVEC
64
+#   ifndef USB_INTR_VECTOR
65
+        ORG     INT0_vect
66
+#   else /* USB_INTR_VECTOR */
67
+        ORG     USB_INTR_VECTOR
68
+#       undef   USB_INTR_VECTOR
69
+#   endif /* USB_INTR_VECTOR */
70
+#   define  USB_INTR_VECTOR usbInterruptHandler
71
+    rjmp    USB_INTR_VECTOR
72
+    RSEG    CODE
73
+
74
+#else /* __IAR_SYSTEMS_ASM__ */
75
+
76
+#   define nop2     rjmp    .+0 /* jump to next instruction */
77
+
78
+#   ifndef USB_INTR_VECTOR /* default to hardware interrupt INT0 */
79
+#       define USB_INTR_VECTOR  INT0_vect
80
+#   endif
81
+    .text
82
+    .global USB_INTR_VECTOR
83
+    .type   USB_INTR_VECTOR, @function
84
+    .global usbCrc16
85
+    .global usbCrc16Append
86
+#endif /* __IAR_SYSTEMS_ASM__ */
87
+
88
+
89
+#if USB_INTR_PENDING < 0x40 /* This is an I/O address, use in and out */
90
+#   define  USB_LOAD_PENDING(reg)   in reg, USB_INTR_PENDING
91
+#   define  USB_STORE_PENDING(reg)  out USB_INTR_PENDING, reg
92
+#else   /* It's a memory address, use lds and sts */
93
+#   define  USB_LOAD_PENDING(reg)   lds reg, USB_INTR_PENDING
94
+#   define  USB_STORE_PENDING(reg)  sts USB_INTR_PENDING, reg
95
+#endif
96
+
97
+
98
+;----------------------------------------------------------------------------
99
+; Utility functions
100
+;----------------------------------------------------------------------------
101
+
102
+#ifdef __IAR_SYSTEMS_ASM__
103
+/* Register assignments for usbCrc16 on IAR cc */
104
+/* Calling conventions on IAR:
105
+ * First parameter passed in r16/r17, second in r18/r19 and so on.
106
+ * Callee must preserve r4-r15, r24-r29 (r28/r29 is frame pointer)
107
+ * Result is passed in r16/r17
108
+ * In case of the "tiny" memory model, pointers are only 8 bit with no
109
+ * padding. We therefore pass argument 1 as "16 bit unsigned".
110
+ */
111
+RTMODEL "__rt_version", "3"
112
+/* The line above will generate an error if cc calling conventions change.
113
+ * The value "3" above is valid for IAR 4.10B/W32
114
+ */
115
+#   define argLen   r18 /* argument 2 */
116
+#   define argPtrL  r16 /* argument 1 */
117
+#   define argPtrH  r17 /* argument 1 */
118
+
119
+#   define resCrcL  r16 /* result */
120
+#   define resCrcH  r17 /* result */
121
+
122
+#   define ptrL     ZL
123
+#   define ptrH     ZH
124
+#   define ptr      Z
125
+#   define byte     r22
126
+#   define bitCnt   r19
127
+#   define polyL    r20
128
+#   define polyH    r21
129
+#   define scratch  r23
130
+
131
+#else  /* __IAR_SYSTEMS_ASM__ */ 
132
+/* Register assignments for usbCrc16 on gcc */
133
+/* Calling conventions on gcc:
134
+ * First parameter passed in r24/r25, second in r22/23 and so on.
135
+ * Callee must preserve r1-r17, r28/r29
136
+ * Result is passed in r24/r25
137
+ */
138
+#   define argLen   r22 /* argument 2 */
139
+#   define argPtrL  r24 /* argument 1 */
140
+#   define argPtrH  r25 /* argument 1 */
141
+
142
+#   define resCrcL  r24 /* result */
143
+#   define resCrcH  r25 /* result */
144
+
145
+#   define ptrL     XL
146
+#   define ptrH     XH
147
+#   define ptr      x
148
+#   define byte     r18
149
+#   define bitCnt   r19
150
+#   define polyL    r20
151
+#   define polyH    r21
152
+#   define scratch  r23
153
+
154
+#endif
155
+
156
+; extern unsigned usbCrc16(unsigned char *data, unsigned char len);
157
+; data: r24/25
158
+; len: r22
159
+; temp variables:
160
+;   r18: data byte
161
+;   r19: bit counter
162
+;   r20/21: polynomial
163
+;   r23: scratch
164
+;   r24/25: crc-sum
165
+;   r26/27=X: ptr
166
+usbCrc16:
167
+    mov     ptrL, argPtrL
168
+    mov     ptrH, argPtrH
169
+    ldi     resCrcL, 0
170
+    ldi     resCrcH, 0
171
+    ldi     polyL, lo8(0xa001)
172
+    ldi     polyH, hi8(0xa001)
173
+    com     argLen      ; argLen = -argLen - 1
174
+crcByteLoop:
175
+    subi    argLen, -1
176
+    brcc    crcReady    ; modified loop to ensure that carry is set below
177
+    ld      byte, ptr+
178
+    ldi     bitCnt, -8  ; strange loop counter to ensure that carry is set where we need it
179
+    eor     resCrcL, byte
180
+crcBitLoop:
181
+    ror     resCrcH     ; carry is always set here
182
+    ror     resCrcL
183
+    brcs    crcNoXor
184
+    eor     resCrcL, polyL
185
+    eor     resCrcH, polyH
186
+crcNoXor:
187
+    subi    bitCnt, -1
188
+    brcs    crcBitLoop
189
+    rjmp    crcByteLoop
190
+crcReady:
191
+    ret
192
+; Thanks to Reimar Doeffinger for optimizing this CRC routine!
193
+
194
+; extern unsigned usbCrc16Append(unsigned char *data, unsigned char len);
195
+usbCrc16Append:
196
+    rcall   usbCrc16
197
+    st      ptr+, resCrcL
198
+    st      ptr+, resCrcH
199
+    ret
200
+
201
+#undef argLen
202
+#undef argPtrL
203
+#undef argPtrH
204
+#undef resCrcL
205
+#undef resCrcH
206
+#undef ptrL
207
+#undef ptrH
208
+#undef ptr
209
+#undef byte
210
+#undef bitCnt
211
+#undef polyL
212
+#undef polyH
213
+#undef scratch
214
+
215
+
216
+#if USB_CFG_HAVE_MEASURE_FRAME_LENGTH
217
+#ifdef __IAR_SYSTEMS_ASM__
218
+/* Register assignments for usbMeasureFrameLength on IAR cc */
219
+/* Calling conventions on IAR:
220
+ * First parameter passed in r16/r17, second in r18/r19 and so on.
221
+ * Callee must preserve r4-r15, r24-r29 (r28/r29 is frame pointer)
222
+ * Result is passed in r16/r17
223
+ * In case of the "tiny" memory model, pointers are only 8 bit with no
224
+ * padding. We therefore pass argument 1 as "16 bit unsigned".
225
+ */
226
+#   define resL     r16
227
+#   define resH     r17
228
+#   define cnt16L   r30
229
+#   define cnt16H   r31
230
+#   define cntH     r18
231
+
232
+#else  /* __IAR_SYSTEMS_ASM__ */ 
233
+/* Register assignments for usbMeasureFrameLength on gcc */
234
+/* Calling conventions on gcc:
235
+ * First parameter passed in r24/r25, second in r22/23 and so on.
236
+ * Callee must preserve r1-r17, r28/r29
237
+ * Result is passed in r24/r25
238
+ */
239
+#   define resL     r24
240
+#   define resH     r25
241
+#   define cnt16L   r24
242
+#   define cnt16H   r25
243
+#   define cntH     r26
244
+#endif
245
+#   define cnt16    cnt16L
246
+
247
+; extern unsigned usbMeasurePacketLength(void);
248
+; returns time between two idle strobes in multiples of 7 CPU clocks
249
+.global usbMeasureFrameLength
250
+usbMeasureFrameLength:
251
+    ldi     cntH, 6         ; wait ~ 10 ms for D- == 0
252
+    clr     cnt16L
253
+    clr     cnt16H
254
+usbMFTime16:
255
+    dec     cntH
256
+    breq    usbMFTimeout
257
+usbMFWaitStrobe:            ; first wait for D- == 0 (idle strobe)
258
+    sbiw    cnt16, 1        ;[0] [6]
259
+    breq    usbMFTime16     ;[2]
260
+    sbic    USBIN, USBMINUS ;[3]
261
+    rjmp    usbMFWaitStrobe ;[4]
262
+usbMFWaitIdle:              ; then wait until idle again
263
+    sbis    USBIN, USBMINUS ;1 wait for D- == 1
264
+    rjmp    usbMFWaitIdle   ;2
265
+    ldi     cnt16L, 1       ;1 represents cycles so far
266
+    clr     cnt16H          ;1
267
+usbMFWaitLoop:
268
+    in      cntH, USBIN     ;[0] [7]
269
+    adiw    cnt16, 1        ;[1]
270
+    breq    usbMFTimeout    ;[3]
271
+    andi    cntH, USBMASK   ;[4]
272
+    brne    usbMFWaitLoop   ;[5]
273
+usbMFTimeout:
274
+#if resL != cnt16L
275
+    mov     resL, cnt16L
276
+    mov     resH, cnt16H
277
+#endif
278
+    ret
279
+
280
+#undef resL
281
+#undef resH
282
+#undef cnt16
283
+#undef cnt16L
284
+#undef cnt16H
285
+#undef cntH
286
+
287
+#endif  /* USB_CFG_HAVE_MEASURE_FRAME_LENGTH */
288
+
289
+;----------------------------------------------------------------------------
290
+; Now include the clock rate specific code
291
+;----------------------------------------------------------------------------
292
+
293
+#ifndef USB_CFG_CLOCK_KHZ
294
+#   define USB_CFG_CLOCK_KHZ 12000
295
+#endif
296
+
297
+#if USB_CFG_CLOCK_KHZ == 12000
298
+#   include "usbdrvasm12.inc"
299
+#elif USB_CFG_CLOCK_KHZ == 15000
300
+#   include "usbdrvasm15.inc"
301
+#elif USB_CFG_CLOCK_KHZ == 16000
302
+#   include "usbdrvasm16.inc"
303
+#elif USB_CFG_CLOCK_KHZ == 16500
304
+#   include "usbdrvasm165.inc"
305
+#else
306
+#   error "USB_CFG_CLOCK_KHZ is not one of the supported rates!"
307
+#endif

+ 21
- 0
UsbJoystick/usbdrvasm.asm Переглянути файл

@@ -0,0 +1,21 @@
1
+/* Name: usbdrvasm.asm
2
+ * Project: AVR USB driver
3
+ * Author: Christian Starkjohann
4
+ * Creation Date: 2006-03-01
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2006 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id$
9
+ */
10
+
11
+/*
12
+General Description:
13
+The IAR compiler/assembler system prefers assembler files with file extension
14
+".asm". We simply provide this file as an alias for usbdrvasm.S.
15
+
16
+Thanks to Oleg Semyonov for his help with the IAR tools port!
17
+*/
18
+
19
+#include "usbdrvasm.S"
20
+
21
+end

+ 427
- 0
UsbJoystick/usbdrvasm12.inc Переглянути файл

@@ -0,0 +1,427 @@
1
+/* Name: usbdrvasm12.inc
2
+ * Project: AVR USB driver
3
+ * Author: Christian Starkjohann
4
+ * Creation Date: 2004-12-29
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: usbdrvasm12.inc 483 2008-02-05 15:05:32Z cs $
9
+ */
10
+
11
+/* Do not link this file! Link usbdrvasm.S instead, which includes the
12
+ * appropriate implementation!
13
+ */
14
+
15
+/*
16
+General Description:
17
+This file is the 12 MHz version of the asssembler part of the USB driver. It
18
+requires a 12 MHz crystal (not a ceramic resonator and not a calibrated RC
19
+oscillator).
20
+
21
+See usbdrv.h for a description of the entire driver.
22
+
23
+Since almost all of this code is timing critical, don't change unless you
24
+really know what you are doing! Many parts require not only a maximum number
25
+of CPU cycles, but even an exact number of cycles!
26
+
27
+
28
+Timing constraints according to spec (in bit times):
29
+timing subject                                      min max    CPUcycles
30
+---------------------------------------------------------------------------
31
+EOP of OUT/SETUP to sync pattern of DATA0 (both rx) 2   16     16-128
32
+EOP of IN to sync pattern of DATA0 (rx, then tx)    2   7.5    16-60
33
+DATAx (rx) to ACK/NAK/STALL (tx)                    2   7.5    16-60
34
+*/
35
+
36
+;Software-receiver engine. Strict timing! Don't change unless you can preserve timing!
37
+;interrupt response time: 4 cycles + insn running = 7 max if interrupts always enabled
38
+;max allowable interrupt latency: 34 cycles -> max 25 cycles interrupt disable
39
+;max stack usage: [ret(2), YL, SREG, YH, shift, x1, x2, x3, cnt, x4] = 11 bytes
40
+;Numbers in brackets are maximum cycles since SOF.
41
+USB_INTR_VECTOR:
42
+;order of registers pushed: YL, SREG [sofError], YH, shift, x1, x2, x3, cnt
43
+    push    YL              ;2 [35] push only what is necessary to sync with edge ASAP
44
+    in      YL, SREG        ;1 [37]
45
+    push    YL              ;2 [39]
46
+;----------------------------------------------------------------------------
47
+; Synchronize with sync pattern:
48
+;----------------------------------------------------------------------------
49
+;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K]
50
+;sync up with J to K edge during sync pattern -- use fastest possible loops
51
+;first part has no timeout because it waits for IDLE or SE1 (== disconnected)
52
+waitForJ:
53
+    sbis    USBIN, USBMINUS ;1 [40] wait for D- == 1
54
+    rjmp    waitForJ        ;2
55
+waitForK:
56
+;The following code results in a sampling window of 1/4 bit which meets the spec.
57
+    sbis    USBIN, USBMINUS
58
+    rjmp    foundK
59
+    sbis    USBIN, USBMINUS
60
+    rjmp    foundK
61
+    sbis    USBIN, USBMINUS
62
+    rjmp    foundK
63
+    sbis    USBIN, USBMINUS
64
+    rjmp    foundK
65
+    sbis    USBIN, USBMINUS
66
+    rjmp    foundK
67
+#if USB_COUNT_SOF
68
+    lds     YL, usbSofCount
69
+    inc     YL
70
+    sts     usbSofCount, YL
71
+#endif  /* USB_COUNT_SOF */
72
+    rjmp    sofError
73
+foundK:
74
+;{3, 5} after falling D- edge, average delay: 4 cycles [we want 4 for center sampling]
75
+;we have 1 bit time for setup purposes, then sample again. Numbers in brackets
76
+;are cycles from center of first sync (double K) bit after the instruction
77
+    push    YH                  ;2 [2]
78
+    lds     YL, usbInputBufOffset;2 [4]
79
+    clr     YH                  ;1 [5]
80
+    subi    YL, lo8(-(usbRxBuf));1 [6]
81
+    sbci    YH, hi8(-(usbRxBuf));1 [7]
82
+
83
+    sbis    USBIN, USBMINUS ;1 [8] we want two bits K [sample 1 cycle too early]
84
+    rjmp    haveTwoBitsK    ;2 [10]
85
+    pop     YH              ;2 [11] undo the push from before
86
+    rjmp    waitForK        ;2 [13] this was not the end of sync, retry
87
+haveTwoBitsK:
88
+;----------------------------------------------------------------------------
89
+; push more registers and initialize values while we sample the first bits:
90
+;----------------------------------------------------------------------------
91
+    push    shift           ;2 [16]
92
+    push    x1              ;2 [12]
93
+    push    x2              ;2 [14]
94
+
95
+    in      x1, USBIN       ;1 [17] <-- sample bit 0
96
+    ldi     shift, 0xff     ;1 [18]
97
+    bst     x1, USBMINUS    ;1 [19]
98
+    bld     shift, 0        ;1 [20]
99
+    push    x3              ;2 [22]
100
+    push    cnt             ;2 [24]
101
+    
102
+    in      x2, USBIN       ;1 [25] <-- sample bit 1
103
+    ser     x3              ;1 [26] [inserted init instruction]
104
+    eor     x1, x2          ;1 [27]
105
+    bst     x1, USBMINUS    ;1 [28]
106
+    bld     shift, 1        ;1 [29]
107
+    ldi     cnt, USB_BUFSIZE;1 [30] [inserted init instruction]
108
+    rjmp    rxbit2          ;2 [32]
109
+
110
+;----------------------------------------------------------------------------
111
+; Receiver loop (numbers in brackets are cycles within byte after instr)
112
+;----------------------------------------------------------------------------
113
+
114
+unstuff0:               ;1 (branch taken)
115
+    andi    x3, ~0x01   ;1 [15]
116
+    mov     x1, x2      ;1 [16] x2 contains last sampled (stuffed) bit
117
+    in      x2, USBIN   ;1 [17] <-- sample bit 1 again
118
+    ori     shift, 0x01 ;1 [18]
119
+    rjmp    didUnstuff0 ;2 [20]
120
+
121
+unstuff1:               ;1 (branch taken)
122
+    mov     x2, x1      ;1 [21] x1 contains last sampled (stuffed) bit
123
+    andi    x3, ~0x02   ;1 [22]
124
+    ori     shift, 0x02 ;1 [23]
125
+    nop                 ;1 [24]
126
+    in      x1, USBIN   ;1 [25] <-- sample bit 2 again
127
+    rjmp    didUnstuff1 ;2 [27]
128
+
129
+unstuff2:               ;1 (branch taken)
130
+    andi    x3, ~0x04   ;1 [29]
131
+    ori     shift, 0x04 ;1 [30]
132
+    mov     x1, x2      ;1 [31] x2 contains last sampled (stuffed) bit
133
+    nop                 ;1 [32]
134
+    in      x2, USBIN   ;1 [33] <-- sample bit 3
135
+    rjmp    didUnstuff2 ;2 [35]
136
+
137
+unstuff3:               ;1 (branch taken)
138
+    in      x2, USBIN   ;1 [34] <-- sample stuffed bit 3 [one cycle too late]
139
+    andi    x3, ~0x08   ;1 [35]
140
+    ori     shift, 0x08 ;1 [36]
141
+    rjmp    didUnstuff3 ;2 [38]
142
+
143
+unstuff4:               ;1 (branch taken)
144
+    andi    x3, ~0x10   ;1 [40]
145
+    in      x1, USBIN   ;1 [41] <-- sample stuffed bit 4
146
+    ori     shift, 0x10 ;1 [42]
147
+    rjmp    didUnstuff4 ;2 [44]
148
+
149
+unstuff5:               ;1 (branch taken)
150
+    andi    x3, ~0x20   ;1 [48]
151
+    in      x2, USBIN   ;1 [49] <-- sample stuffed bit 5
152
+    ori     shift, 0x20 ;1 [50]
153
+    rjmp    didUnstuff5 ;2 [52]
154
+
155
+unstuff6:               ;1 (branch taken)
156
+    andi    x3, ~0x40   ;1 [56]
157
+    in      x1, USBIN   ;1 [57] <-- sample stuffed bit 6
158
+    ori     shift, 0x40 ;1 [58]
159
+    rjmp    didUnstuff6 ;2 [60]
160
+
161
+; extra jobs done during bit interval:
162
+; bit 0:    store, clear [SE0 is unreliable here due to bit dribbling in hubs]
163
+; bit 1:    se0 check
164
+; bit 2:    overflow check
165
+; bit 3:    recovery from delay [bit 0 tasks took too long]
166
+; bit 4:    none
167
+; bit 5:    none
168
+; bit 6:    none
169
+; bit 7:    jump, eor
170
+rxLoop:
171
+    eor     x3, shift   ;1 [0] reconstruct: x3 is 0 at bit locations we changed, 1 at others
172
+    in      x1, USBIN   ;1 [1] <-- sample bit 0
173
+    st      y+, x3      ;2 [3] store data
174
+    ser     x3          ;1 [4]
175
+    nop                 ;1 [5]
176
+    eor     x2, x1      ;1 [6]
177
+    bst     x2, USBMINUS;1 [7]
178
+    bld     shift, 0    ;1 [8]
179
+    in      x2, USBIN   ;1 [9] <-- sample bit 1 (or possibly bit 0 stuffed)
180
+    andi    x2, USBMASK ;1 [10]
181
+    breq    se0         ;1 [11] SE0 check for bit 1
182
+    andi    shift, 0xf9 ;1 [12]
183
+didUnstuff0:
184
+    breq    unstuff0    ;1 [13]
185
+    eor     x1, x2      ;1 [14]
186
+    bst     x1, USBMINUS;1 [15]
187
+    bld     shift, 1    ;1 [16]
188
+rxbit2:
189
+    in      x1, USBIN   ;1 [17] <-- sample bit 2 (or possibly bit 1 stuffed)
190
+    andi    shift, 0xf3 ;1 [18]
191
+    breq    unstuff1    ;1 [19] do remaining work for bit 1
192
+didUnstuff1:
193
+    subi    cnt, 1      ;1 [20]
194
+    brcs    overflow    ;1 [21] loop control
195
+    eor     x2, x1      ;1 [22]
196
+    bst     x2, USBMINUS;1 [23]
197
+    bld     shift, 2    ;1 [24]
198
+    in      x2, USBIN   ;1 [25] <-- sample bit 3 (or possibly bit 2 stuffed)
199
+    andi    shift, 0xe7 ;1 [26]
200
+    breq    unstuff2    ;1 [27]
201
+didUnstuff2:
202
+    eor     x1, x2      ;1 [28]
203
+    bst     x1, USBMINUS;1 [29]
204
+    bld     shift, 3    ;1 [30]
205
+didUnstuff3:
206
+    andi    shift, 0xcf ;1 [31]
207
+    breq    unstuff3    ;1 [32]
208
+    in      x1, USBIN   ;1 [33] <-- sample bit 4
209
+    eor     x2, x1      ;1 [34]
210
+    bst     x2, USBMINUS;1 [35]
211
+    bld     shift, 4    ;1 [36]
212
+didUnstuff4:
213
+    andi    shift, 0x9f ;1 [37]
214
+    breq    unstuff4    ;1 [38]
215
+    nop2                ;2 [40]
216
+    in      x2, USBIN   ;1 [41] <-- sample bit 5
217
+    eor     x1, x2      ;1 [42]
218
+    bst     x1, USBMINUS;1 [43]
219
+    bld     shift, 5    ;1 [44]
220
+didUnstuff5:
221
+    andi    shift, 0x3f ;1 [45]
222
+    breq    unstuff5    ;1 [46]
223
+    nop2                ;2 [48]
224
+    in      x1, USBIN   ;1 [49] <-- sample bit 6
225
+    eor     x2, x1      ;1 [50]
226
+    bst     x2, USBMINUS;1 [51]
227
+    bld     shift, 6    ;1 [52]
228
+didUnstuff6:
229
+    cpi     shift, 0x02 ;1 [53]
230
+    brlo    unstuff6    ;1 [54]
231
+    nop2                ;2 [56]
232
+    in      x2, USBIN   ;1 [57] <-- sample bit 7
233
+    eor     x1, x2      ;1 [58]
234
+    bst     x1, USBMINUS;1 [59]
235
+    bld     shift, 7    ;1 [60]
236
+didUnstuff7:
237
+    cpi     shift, 0x04 ;1 [61]
238
+    brsh    rxLoop      ;2 [63] loop control
239
+unstuff7:
240
+    andi    x3, ~0x80   ;1 [63]
241
+    ori     shift, 0x80 ;1 [64]
242
+    in      x2, USBIN   ;1 [65] <-- sample stuffed bit 7
243
+    nop                 ;1 [66]
244
+    rjmp    didUnstuff7 ;2 [68]
245
+
246
+macro POP_STANDARD ; 12 cycles
247
+    pop     cnt
248
+    pop     x3
249
+    pop     x2
250
+    pop     x1
251
+    pop     shift
252
+    pop     YH
253
+endm
254
+macro POP_RETI     ; 5 cycles
255
+    pop     YL
256
+    out     SREG, YL
257
+    pop     YL
258
+endm
259
+
260
+#include "asmcommon.inc"
261
+
262
+;----------------------------------------------------------------------------
263
+; Transmitting data
264
+;----------------------------------------------------------------------------
265
+
266
+bitstuff0:                  ;1 (for branch taken)
267
+    eor     x1, x4          ;1
268
+    ldi     x2, 0           ;1
269
+    out     USBOUT, x1      ;1 <-- out
270
+    rjmp    didStuff0       ;2 branch back 2 cycles earlier
271
+bitstuff1:                  ;1 (for branch taken)
272
+    eor     x1, x4          ;1
273
+    rjmp    didStuff1       ;2 we know that C is clear, jump back to do OUT and ror 0 into x2
274
+bitstuff2:                  ;1 (for branch taken)
275
+    eor     x1, x4          ;1
276
+    rjmp    didStuff2       ;2 jump back 4 cycles earlier and do out and ror 0 into x2
277
+bitstuff3:                  ;1 (for branch taken)
278
+    eor     x1, x4          ;1
279
+    rjmp    didStuff3       ;2 jump back earlier and ror 0 into x2
280
+bitstuff4:                  ;1 (for branch taken)
281
+    eor     x1, x4          ;1
282
+    ldi     x2, 0           ;1
283
+    out     USBOUT, x1      ;1 <-- out
284
+    rjmp    didStuff4       ;2 jump back 2 cycles earlier
285
+
286
+sendNakAndReti:                 ;0 [-19] 19 cycles until SOP
287
+    ldi     x3, USBPID_NAK      ;1 [-18]
288
+    rjmp    usbSendX3           ;2 [-16]
289
+sendAckAndReti:                 ;0 [-19] 19 cycles until SOP
290
+    ldi     x3, USBPID_ACK      ;1 [-18]
291
+    rjmp    usbSendX3           ;2 [-16]
292
+sendCntAndReti:                 ;0 [-17] 17 cycles until SOP
293
+    mov     x3, cnt             ;1 [-16]
294
+usbSendX3:                      ;0 [-16]
295
+    ldi     YL, 20              ;1 [-15] 'x3' is R20
296
+    ldi     YH, 0               ;1 [-14]
297
+    ldi     cnt, 2              ;1 [-13]
298
+;   rjmp    usbSendAndReti      fallthrough
299
+
300
+; USB spec says:
301
+; idle = J
302
+; J = (D+ = 0), (D- = 1) or USBOUT = 0x01
303
+; K = (D+ = 1), (D- = 0) or USBOUT = 0x02
304
+; Spec allows 7.5 bit times from EOP to SOP for replies (= 60 cycles)
305
+
306
+;usbSend:
307
+;pointer to data in 'Y'
308
+;number of bytes in 'cnt' -- including sync byte
309
+;uses: x1...x4, shift, cnt, Y
310
+;Numbers in brackets are time since first bit of sync pattern is sent
311
+usbSendAndReti:             ;0 [-13] timing: 13 cycles until SOP
312
+    in      x2, USBDDR      ;1 [-12]
313
+    ori     x2, USBMASK     ;1 [-11]
314
+    sbi     USBOUT, USBMINUS;2 [-9] prepare idle state; D+ and D- must have been 0 (no pullups)
315
+    in      x1, USBOUT      ;1 [-8] port mirror for tx loop
316
+    out     USBDDR, x2      ;1 [-7] <- acquire bus
317
+; need not init x2 (bitstuff history) because sync starts with 0
318
+    push    x4              ;2 [-5]
319
+    ldi     x4, USBMASK     ;1 [-4] exor mask
320
+    ldi     shift, 0x80     ;1 [-3] sync byte is first byte sent
321
+txLoop:                     ;       [62]
322
+    sbrs    shift, 0        ;1 [-2] [62]
323
+    eor     x1, x4          ;1 [-1] [63]
324
+    out     USBOUT, x1      ;1 [0] <-- out bit 0
325
+    ror     shift           ;1 [1]
326
+    ror     x2              ;1 [2]
327
+didStuff0:
328
+    cpi     x2, 0xfc        ;1 [3]
329
+    brsh    bitstuff0       ;1 [4]
330
+    sbrs    shift, 0        ;1 [5]
331
+    eor     x1, x4          ;1 [6]
332
+    ror     shift           ;1 [7]
333
+didStuff1:
334
+    out     USBOUT, x1      ;1 [8] <-- out bit 1
335
+    ror     x2              ;1 [9]
336
+    cpi     x2, 0xfc        ;1 [10]
337
+    brsh    bitstuff1       ;1 [11]
338
+    sbrs    shift, 0        ;1 [12]
339
+    eor     x1, x4          ;1 [13]
340
+    ror     shift           ;1 [14]
341
+didStuff2:
342
+    ror     x2              ;1 [15]
343
+    out     USBOUT, x1      ;1 [16] <-- out bit 2
344
+    cpi     x2, 0xfc        ;1 [17]
345
+    brsh    bitstuff2       ;1 [18]
346
+    sbrs    shift, 0        ;1 [19]
347
+    eor     x1, x4          ;1 [20]
348
+    ror     shift           ;1 [21]
349
+didStuff3:
350
+    ror     x2              ;1 [22]
351
+    cpi     x2, 0xfc        ;1 [23]
352
+    out     USBOUT, x1      ;1 [24] <-- out bit 3
353
+    brsh    bitstuff3       ;1 [25]
354
+    nop2                    ;2 [27]
355
+    ld      x3, y+          ;2 [29]
356
+    sbrs    shift, 0        ;1 [30]
357
+    eor     x1, x4          ;1 [31]
358
+    out     USBOUT, x1      ;1 [32] <-- out bit 4
359
+    ror     shift           ;1 [33]
360
+    ror     x2              ;1 [34]
361
+didStuff4:
362
+    cpi     x2, 0xfc        ;1 [35]
363
+    brsh    bitstuff4       ;1 [36]
364
+    sbrs    shift, 0        ;1 [37]
365
+    eor     x1, x4          ;1 [38]
366
+    ror     shift           ;1 [39]
367
+didStuff5:
368
+    out     USBOUT, x1      ;1 [40] <-- out bit 5
369
+    ror     x2              ;1 [41]
370
+    cpi     x2, 0xfc        ;1 [42]
371
+    brsh    bitstuff5       ;1 [43]
372
+    sbrs    shift, 0        ;1 [44]
373
+    eor     x1, x4          ;1 [45]
374
+    ror     shift           ;1 [46]
375
+didStuff6:
376
+    ror     x2              ;1 [47]
377
+    out     USBOUT, x1      ;1 [48] <-- out bit 6
378
+    cpi     x2, 0xfc        ;1 [49]
379
+    brsh    bitstuff6       ;1 [50]
380
+    sbrs    shift, 0        ;1 [51]
381
+    eor     x1, x4          ;1 [52]
382
+    ror     shift           ;1 [53]
383
+didStuff7:
384
+    ror     x2              ;1 [54]
385
+    cpi     x2, 0xfc        ;1 [55]
386
+    out     USBOUT, x1      ;1 [56] <-- out bit 7
387
+    brsh    bitstuff7       ;1 [57]
388
+    mov     shift, x3       ;1 [58]
389
+    dec     cnt             ;1 [59]
390
+    brne    txLoop          ;1/2 [60/61]
391
+;make SE0:
392
+    cbr     x1, USBMASK     ;1 [61] prepare SE0 [spec says EOP may be 15 to 18 cycles]
393
+    pop     x4              ;2 [63]
394
+;brackets are cycles from start of SE0 now
395
+    out     USBOUT, x1      ;1 [0] <-- out SE0 -- from now 2 bits = 16 cycles until bus idle
396
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
397
+;set address only after data packet was sent, not after handshake
398
+    lds     x2, usbNewDeviceAddr;2 [2]
399
+    lsl     x2;             ;1 [3] we compare with left shifted address
400
+    subi    YL, 20 + 2      ;1 [4] Only assign address on data packets, not ACK/NAK in x3
401
+    sbci    YH, 0           ;1 [5]
402
+    breq    skipAddrAssign  ;2 [7]
403
+    sts     usbDeviceAddr, x2; if not skipped: SE0 is one cycle longer
404
+skipAddrAssign:
405
+;end of usbDeviceAddress transfer
406
+    ldi     x2, 1<<USB_INTR_PENDING_BIT;1 [8] int0 occurred during TX -- clear pending flag
407
+    USB_STORE_PENDING(x2)   ;1 [9]
408
+    ori     x1, USBIDLE     ;1 [10]
409
+    in      x2, USBDDR      ;1 [11]
410
+    cbr     x2, USBMASK     ;1 [12] set both pins to input
411
+    mov     x3, x1          ;1 [13]
412
+    cbr     x3, USBMASK     ;1 [14] configure no pullup on both pins
413
+    out     USBOUT, x1      ;1 [15] <-- out J (idle) -- end of SE0 (EOP signal)
414
+    out     USBDDR, x2      ;1 [16] <-- release bus now
415
+    out     USBOUT, x3      ;1 [17] <-- ensure no pull-up resistors are active
416
+    rjmp    doReturn
417
+
418
+bitstuff5:                  ;1 (for branch taken)
419
+    eor     x1, x4          ;1
420
+    rjmp    didStuff5       ;2 same trick as in bitstuff1...
421
+bitstuff6:                  ;1 (for branch taken)
422
+    eor     x1, x4          ;1
423
+    rjmp    didStuff6       ;2 same trick as above...
424
+bitstuff7:                  ;1 (for branch taken)
425
+    eor     x1, x4          ;1
426
+    rjmp    didStuff7       ;2 same trick as above...
427
+

+ 418
- 0
UsbJoystick/usbdrvasm15.inc Переглянути файл

@@ -0,0 +1,418 @@
1
+/* Name: usbdrvasm15.inc
2
+ * Project: AVR USB driver
3
+ * Author: contributed by V. Bosch
4
+ * Creation Date: 2007-08-06
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt)
8
+ * Revision: $Id$
9
+ */
10
+
11
+/* Do not link this file! Link usbdrvasm.S instead, which includes the
12
+ * appropriate implementation!
13
+ */
14
+
15
+/*
16
+General Description:
17
+This file is the 15 MHz version of the asssembler part of the USB driver. It
18
+requires a 15 MHz crystal (not a ceramic resonator and not a calibrated RC
19
+oscillator).
20
+
21
+See usbdrv.h for a description of the entire driver.
22
+
23
+Since almost all of this code is timing critical, don't change unless you
24
+really know what you are doing! Many parts require not only a maximum number
25
+of CPU cycles, but even an exact number of cycles!
26
+*/
27
+
28
+;max stack usage: [ret(2), YL, SREG, YH, bitcnt, shift, x1, x2, x3, x4, cnt] = 12 bytes
29
+;nominal frequency: 15 MHz -> 10.0 cycles per bit, 80.0 cycles per byte
30
+; Numbers in brackets are clocks counted from center of last sync bit
31
+; when instruction starts
32
+
33
+;----------------------------------------------------------------------------
34
+; order of registers pushed: 
35
+;	YL, SREG [sofError] YH, shift, x1, x2, x3, bitcnt, cnt, x4
36
+;----------------------------------------------------------------------------
37
+USB_INTR_VECTOR:              
38
+    push    YL                   ;2 	push only what is necessary to sync with edge ASAP
39
+    in      YL, SREG             ;1 
40
+    push    YL                   ;2 
41
+;----------------------------------------------------------------------------
42
+; Synchronize with sync pattern:
43
+;
44
+;   sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K]
45
+;   sync up with J to K edge during sync pattern -- use fastest possible loops
46
+;   first part has no timeout because it waits for IDLE or SE1 (== disconnected)
47
+;-------------------------------------------------------------------------------
48
+waitForJ:			 ;- 
49
+    sbis    USBIN, USBMINUS      ;1 <-- sample: wait for D- == 1
50
+    rjmp    waitForJ		 ;2 
51
+;-------------------------------------------------------------------------------
52
+; The following code results in a sampling window of < 1/4 bit 
53
+;	which meets the spec.
54
+;-------------------------------------------------------------------------------
55
+waitForK:			 ;- 
56
+    sbis    USBIN, USBMINUS      ;1 [00] <-- sample
57
+    rjmp    foundK               ;2 [01]
58
+    sbis    USBIN, USBMINUS	 ;	 <-- sample
59
+    rjmp    foundK
60
+    sbis    USBIN, USBMINUS	 ;	 <-- sample
61
+    rjmp    foundK
62
+    sbis    USBIN, USBMINUS	 ;	 <-- sample
63
+    rjmp    foundK
64
+    sbis    USBIN, USBMINUS	 ;	 <-- sample
65
+    rjmp    foundK
66
+    sbis    USBIN, USBMINUS	 ;	 <-- sample
67
+    rjmp    foundK
68
+#if USB_COUNT_SOF
69
+    lds     YL, usbSofCount
70
+    inc     YL
71
+    sts     usbSofCount, YL
72
+#endif  /* USB_COUNT_SOF */
73
+    rjmp    sofError
74
+;------------------------------------------------------------------------------
75
+; {3, 5} after falling D- edge, average delay: 4 cycles [we want 5 for 
76
+;	center sampling] 
77
+; 	we have 1 bit time for setup purposes, then sample again. 
78
+;	Numbers in brackets are cycles from center of first sync (double K) 
79
+;	bit after the instruction
80
+;------------------------------------------------------------------------------
81
+foundK:                          ;- [02]
82
+    lds     YL, usbInputBufOffset;2 [03+04]	tx loop
83
+    push    YH                   ;2 [05+06]
84
+    clr     YH                   ;1 [07]
85
+    subi    YL, lo8(-(usbRxBuf)) ;1 [08] 	[rx loop init]
86
+    sbci    YH, hi8(-(usbRxBuf)) ;1 [09] 	[rx loop init]
87
+    push    shift                ;2 [10+11]
88
+    ser	    shift		 ;1 [12]
89
+    sbis    USBIN, USBMINUS      ;1 [-1] [13] <--sample:we want two bits K (sample 1 cycle too early)
90
+    rjmp    haveTwoBitsK         ;2 [00] [14]
91
+    pop     shift                ;2 	 [15+16] undo the push from before
92
+    pop     YH 			 ;2 	 [17+18] undo the push from before
93
+    rjmp    waitForK             ;2 	 [19+20] this was not the end of sync, retry
94
+; The entire loop from waitForK until rjmp waitForK above must not exceed two
95
+; bit times (= 20 cycles).
96
+
97
+;----------------------------------------------------------------------------
98
+; push more registers and initialize values while we sample the first bits:
99
+;----------------------------------------------------------------------------
100
+haveTwoBitsK:			;- [01]
101
+    push    x1              	;2 [02+03]
102
+    push    x2              	;2 [04+05]
103
+    push    x3              	;2 [06+07]
104
+    push    bitcnt              ;2 [08+09]	
105
+    in      x1, USBIN       	;1 [00] [10] <-- sample bit 0
106
+    bst     x1, USBMINUS    	;1 [01]
107
+    bld     shift, 0        	;1 [02]
108
+    push    cnt             	;2 [03+04]
109
+    ldi     cnt, USB_BUFSIZE	;1 [05] 
110
+    push    x4              	;2 [06+07] tx loop
111
+    rjmp    rxLoop          	;2 [08]
112
+;----------------------------------------------------------------------------
113
+; Receiver loop (numbers in brackets are cycles within byte after instr)
114
+;----------------------------------------------------------------------------
115
+unstuff0:               	;- [07] (branch taken)
116
+    andi    x3, ~0x01   	;1 [08]
117
+    mov     x1, x2      	;1 [09] x2 contains last sampled (stuffed) bit
118
+    in      x2, USBIN   	;1 [00] [10] <-- sample bit 1 again
119
+    andi    x2, USBMASK 	;1 [01]
120
+    breq    se0Hop         	;1 [02] SE0 check for bit 1 
121
+    ori     shift, 0x01 	;1 [03] 0b00000001
122
+    nop				;1 [04]
123
+    rjmp    didUnstuff0 	;2 [05]
124
+;-----------------------------------------------------
125
+unstuff1:               	;- [05] (branch taken)
126
+    mov     x2, x1      	;1 [06] x1 contains last sampled (stuffed) bit
127
+    andi    x3, ~0x02   	;1 [07]
128
+    ori     shift, 0x02 	;1 [08] 0b00000010
129
+    nop                 	;1 [09]
130
+    in      x1, USBIN   	;1 [00] [10] <-- sample bit 2 again
131
+    andi    x1, USBMASK 	;1 [01]
132
+    breq    se0Hop         	;1 [02] SE0 check for bit 2 
133
+    rjmp    didUnstuff1 	;2 [03]
134
+;-----------------------------------------------------
135
+unstuff2:               	;- [05] (branch taken)
136
+    andi    x3, ~0x04   	;1 [06]
137
+    ori     shift, 0x04 	;1 [07] 0b00000100
138
+    mov     x1, x2      	;1 [08] x2 contains last sampled (stuffed) bit
139
+    nop                 	;1 [09]
140
+    in      x2, USBIN   	;1 [00] [10] <-- sample bit 3
141
+    andi    x2, USBMASK 	;1 [01]
142
+    breq    se0Hop         	;1 [02] SE0 check for bit 3 
143
+    rjmp    didUnstuff2 	;2 [03]
144
+;-----------------------------------------------------
145
+unstuff3:               	;- [00] [10]  (branch taken)
146
+    in      x2, USBIN   	;1 [01] [11] <-- sample stuffed bit 3 one cycle too late
147
+    andi    x2, USBMASK 	;1 [02]
148
+    breq    se0Hop         	;1 [03] SE0 check for stuffed bit 3 
149
+    andi    x3, ~0x08   	;1 [04]
150
+    ori     shift, 0x08 	;1 [05] 0b00001000
151
+    rjmp    didUnstuff3 	;2 [06]
152
+;----------------------------------------------------------------------------
153
+; extra jobs done during bit interval:
154
+;
155
+; bit 0:    store, clear [SE0 is unreliable here due to bit dribbling in hubs], 
156
+; 		overflow check, jump to the head of rxLoop
157
+; bit 1:    SE0 check
158
+; bit 2:    SE0 check, recovery from delay [bit 0 tasks took too long]
159
+; bit 3:    SE0 check, recovery from delay [bit 0 tasks took too long]
160
+; bit 4:    SE0 check, none
161
+; bit 5:    SE0 check, none
162
+; bit 6:    SE0 check, none
163
+; bit 7:    SE0 check, reconstruct: x3 is 0 at bit locations we changed, 1 at others
164
+;----------------------------------------------------------------------------
165
+rxLoop:				;- [09]
166
+    in      x2, USBIN   	;1 [00] [10] <-- sample bit 1 (or possibly bit 0 stuffed)
167
+    andi    x2, USBMASK 	;1 [01]
168
+    brne    SkipSe0Hop		;1 [02]
169
+se0Hop:				;- [02]
170
+    rjmp    se0         	;2 [03] SE0 check for bit 1 
171
+SkipSe0Hop:			;- [03]
172
+    ser     x3          	;1 [04]
173
+    andi    shift, 0xf9 	;1 [05] 0b11111001
174
+    breq    unstuff0    	;1 [06]
175
+didUnstuff0:			;- [06]
176
+    eor     x1, x2      	;1 [07]
177
+    bst     x1, USBMINUS	;1 [08]
178
+    bld     shift, 1    	;1 [09] 
179
+    in      x1, USBIN   	;1 [00] [10] <-- sample bit 2 (or possibly bit 1 stuffed)
180
+    andi    x1, USBMASK 	;1 [01]
181
+    breq    se0Hop         	;1 [02] SE0 check for bit 2 
182
+    andi    shift, 0xf3 	;1 [03] 0b11110011
183
+    breq    unstuff1    	;1 [04] do remaining work for bit 1
184
+didUnstuff1:			;- [04]
185
+    eor     x2, x1      	;1 [05]
186
+    bst     x2, USBMINUS	;1 [06]
187
+    bld     shift, 2    	;1 [07]
188
+    nop2			;2 [08+09]
189
+    in      x2, USBIN   	;1 [00] [10] <-- sample bit 3 (or possibly bit 2 stuffed)
190
+    andi    x2, USBMASK 	;1 [01]
191
+    breq    se0Hop         	;1 [02] SE0 check for bit 3 
192
+    andi    shift, 0xe7 	;1 [03] 0b11100111
193
+    breq    unstuff2    	;1 [04]
194
+didUnstuff2:			;- [04]
195
+    eor     x1, x2      	;1 [05]
196
+    bst     x1, USBMINUS	;1 [06]
197
+    bld     shift, 3    	;1 [07]
198
+didUnstuff3:			;- [07]
199
+    andi    shift, 0xcf 	;1 [08] 0b11001111
200
+    breq    unstuff3    	;1 [09]
201
+    in      x1, USBIN   	;1 [00] [10] <-- sample bit 4
202
+    andi    x1, USBMASK 	;1 [01]
203
+    breq    se0Hop         	;1 [02] SE0 check for bit 4
204
+    eor     x2, x1      	;1 [03]
205
+    bst     x2, USBMINUS	;1 [04]
206
+    bld     shift, 4    	;1 [05]
207
+didUnstuff4:			;- [05]
208
+    andi    shift, 0x9f 	;1 [06] 0b10011111
209
+    breq    unstuff4    	;1 [07]
210
+    nop2			;2 [08+09]
211
+    in      x2, USBIN   	;1 [00] [10] <-- sample bit 5
212
+    andi    x2, USBMASK 	;1 [01]
213
+    breq    se0         	;1 [02] SE0 check for bit 5
214
+    eor     x1, x2      	;1 [03]
215
+    bst     x1, USBMINUS	;1 [04]
216
+    bld     shift, 5    	;1 [05]
217
+didUnstuff5:			;- [05]
218
+    andi    shift, 0x3f 	;1 [06] 0b00111111
219
+    breq    unstuff5    	;1 [07]
220
+    nop2			;2 [08+09]
221
+    in      x1, USBIN   	;1 [00] [10] <-- sample bit 6
222
+    andi    x1, USBMASK 	;1 [01]
223
+    breq    se0         	;1 [02] SE0 check for bit 6
224
+    eor     x2, x1      	;1 [03]
225
+    bst     x2, USBMINUS	;1 [04]
226
+    bld     shift, 6   	 	;1 [05]
227
+didUnstuff6:			;- [05]
228
+    cpi     shift, 0x02 	;1 [06] 0b00000010
229
+    brlo    unstuff6    	;1 [07]
230
+    nop2			;2 [08+09]
231
+    in      x2, USBIN   	;1 [00] [10] <-- sample bit 7
232
+    andi    x2, USBMASK 	;1 [01]
233
+    breq    se0         	;1 [02] SE0 check for bit 7
234
+    eor     x1, x2      	;1 [03]
235
+    bst     x1, USBMINUS	;1 [04]
236
+    bld     shift, 7    	;1 [05]
237
+didUnstuff7:			;- [05] 
238
+    cpi     shift, 0x04 	;1 [06] 0b00000100
239
+    brlo    unstuff7		;1 [07]
240
+    eor     x3, shift   	;1 [08] reconstruct: x3 is 0 at bit locations we changed, 1 at others
241
+    nop				;1 [09]
242
+    in      x1, USBIN   	;1 [00]	[10] <-- sample bit 0
243
+    st      y+, x3      	;2 [01+02] store data
244
+    eor     x2, x1      	;1 [03]
245
+    bst     x2, USBMINUS	;1 [04]
246
+    bld     shift, 0    	;1 [05]
247
+    subi    cnt, 1		;1 [06]
248
+    brcs    overflow	;1 [07]
249
+    rjmp    rxLoop		;2 [08]
250
+;-----------------------------------------------------
251
+unstuff4:               	;- [08] 
252
+    andi    x3, ~0x10   	;1 [09]
253
+    in      x1, USBIN   	;1 [00] [10] <-- sample stuffed bit 4
254
+    andi    x1, USBMASK 	;1 [01]
255
+    breq    se0         	;1 [02] SE0 check for stuffed bit 4
256
+    ori     shift, 0x10 	;1 [03]
257
+    rjmp    didUnstuff4 	;2 [04]
258
+;-----------------------------------------------------
259
+unstuff5:               	;- [08] 
260
+    ori     shift, 0x20 	;1 [09]
261
+    in      x2, USBIN   	;1 [00] [10] <-- sample stuffed bit 5
262
+    andi    x2, USBMASK 	;1 [01]
263
+    breq    se0         	;1 [02] SE0 check for stuffed bit 5
264
+    andi    x3, ~0x20   	;1 [03]
265
+    rjmp    didUnstuff5		;2 [04]
266
+;-----------------------------------------------------
267
+unstuff6:               	;- [08] 
268
+    andi    x3, ~0x40   	;1 [09]
269
+    in      x1, USBIN   	;1 [00] [10] <-- sample stuffed bit 6
270
+    andi    x1, USBMASK 	;1 [01]
271
+    breq    se0         	;1 [02] SE0 check for stuffed bit 6
272
+    ori     shift, 0x40 	;1 [03]
273
+    rjmp    didUnstuff6 	;2 [04]
274
+;-----------------------------------------------------
275
+unstuff7:			;- [08]
276
+    andi    x3, ~0x80   	;1 [09]
277
+    in      x2, USBIN   	;1 [00] [10] <-- sample stuffed bit 7
278
+    andi    x2, USBMASK 	;1 [01]
279
+    breq    se0         	;1 [02] SE0 check for stuffed bit 7
280
+    ori     shift, 0x80 	;1 [03]
281
+    rjmp    didUnstuff7 	;2 [04]
282
+    
283
+macro POP_STANDARD ; 16 cycles
284
+    pop     x4    
285
+    pop     cnt
286
+    pop     bitcnt
287
+    pop     x3
288
+    pop     x2
289
+    pop     x1
290
+    pop     shift
291
+    pop     YH
292
+endm
293
+macro POP_RETI     ; 5 cycles
294
+    pop     YL
295
+    out     SREG, YL
296
+    pop     YL
297
+endm
298
+
299
+#include "asmcommon.inc"
300
+
301
+;---------------------------------------------------------------------------
302
+; USB spec says:
303
+; idle = J
304
+; J = (D+ = 0), (D- = 1)
305
+; K = (D+ = 1), (D- = 0)
306
+; Spec allows 7.5 bit times from EOP to SOP for replies
307
+;---------------------------------------------------------------------------
308
+bitstuffN:		    	;- [04]
309
+    eor     x1, x4          	;1 [05]
310
+    clr	    x2			;1 [06]
311
+    nop				;1 [07]
312
+    rjmp    didStuffN       	;1 [08]
313
+;---------------------------------------------------------------------------    
314
+bitstuff6:		    	;- [04]
315
+    eor     x1, x4          	;1 [05]
316
+    clr	    x2			;1 [06]
317
+    rjmp    didStuff6       	;1 [07]
318
+;---------------------------------------------------------------------------
319
+bitstuff7:		    	;- [02]
320
+    eor     x1, x4          	;1 [03]
321
+    clr	    x2			;1 [06]
322
+    nop			    	;1 [05]
323
+    rjmp    didStuff7       	;1 [06]
324
+;---------------------------------------------------------------------------
325
+sendNakAndReti:			;- [-19]
326
+    ldi     x3, USBPID_NAK  	;1 [-18]
327
+    rjmp    sendX3AndReti   	;1 [-17]
328
+;---------------------------------------------------------------------------
329
+sendAckAndReti:			;- [-17]
330
+    ldi     cnt, USBPID_ACK 	;1 [-16]
331
+sendCntAndReti:			;- [-16]
332
+    mov     x3, cnt         	;1 [-15]
333
+sendX3AndReti:			;- [-15]
334
+    ldi     YL, 20          	;1 [-14] x3==r20 address is 20
335
+    ldi     YH, 0           	;1 [-13]
336
+    ldi     cnt, 2          	;1 [-12]
337
+;   rjmp    usbSendAndReti      fallthrough
338
+;---------------------------------------------------------------------------
339
+;usbSend:
340
+;pointer to data in 'Y'
341
+;number of bytes in 'cnt' -- including sync byte [range 2 ... 12]
342
+;uses: x1...x4, btcnt, shift, cnt, Y
343
+;Numbers in brackets are time since first bit of sync pattern is sent
344
+;We need not to match the transfer rate exactly because the spec demands 
345
+;only 1.5% precision anyway.
346
+usbSendAndReti:             	;- [-13] 13 cycles until SOP
347
+    in      x2, USBDDR      	;1 [-12]
348
+    ori     x2, USBMASK     	;1 [-11]
349
+    sbi     USBOUT, USBMINUS	;2 [-09-10] prepare idle state; D+ and D- must have been 0 (no pullups)
350
+    in      x1, USBOUT      	;1 [-08] port mirror for tx loop
351
+    out     USBDDR, x2      	;1 [-07] <- acquire bus
352
+	; need not init x2 (bitstuff history) because sync starts with 0 
353
+    ldi     x4, USBMASK     	;1 [-06] 	exor mask
354
+    ldi     shift, 0x80     	;1 [-05] 	sync byte is first byte sent
355
+    ldi     bitcnt, 6    	;1 [-04] 
356
+txBitLoop:		    	;- [-04] [06]
357
+    sbrs    shift, 0        	;1 [-03] [07]
358
+    eor     x1, x4          	;1 [-02] [08] 
359
+    ror     shift           	;1 [-01] [09]  
360
+didStuffN:		    	;-       [09]
361
+    out     USBOUT, x1      	;1 [00]  [10] <-- out N
362
+    ror     x2              	;1 [01]
363
+    cpi     x2, 0xfc        	;1 [02]
364
+    brcc    bitstuffN       	;1 [03]
365
+    dec     bitcnt          	;1 [04]
366
+    brne    txBitLoop       	;1 [05]
367
+    sbrs    shift, 0        	;1 [06]
368
+    eor     x1, x4          	;1 [07]
369
+    ror     shift           	;1 [08]
370
+didStuff6:			;- [08]
371
+    nop				;1 [09]
372
+    out     USBOUT, x1      	;1 [00] [10] <-- out 6
373
+    ror     x2              	;1 [01] 
374
+    cpi     x2, 0xfc        	;1 [02]
375
+    brcc    bitstuff6       	;1 [03]
376
+    sbrs    shift, 0        	;1 [04]
377
+    eor     x1, x4          	;1 [05]
378
+    ror     shift           	;1 [06]
379
+    ror     x2              	;1 [07]
380
+didStuff7:			;- [07]
381
+    ldi     bitcnt, 6    	;1 [08]
382
+    cpi     x2, 0xfc        	;1 [09]
383
+    out     USBOUT, x1      	;1 [00] [10] <-- out 7
384
+    brcc    bitstuff7       	;1 [01]
385
+    ld      shift, y+       	;2 [02+03]
386
+    dec     cnt             	;1 [04]
387
+    brne    txBitLoop      	;1 [05]
388
+makeSE0:
389
+    cbr     x1, USBMASK     	;1 [06] 	prepare SE0 [spec says EOP may be 19 to 23 cycles]
390
+    lds     x2, usbNewDeviceAddr;2 [07+08]
391
+    lsl     x2                  ;1 [09] we compare with left shifted address
392
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
393
+;set address only after data packet was sent, not after handshake
394
+    out     USBOUT, x1      	;1 [00] [10] <-- out SE0-- from now 2 bits==20 cycl. until bus idle
395
+    subi    YL, 20 + 2          ;1 [01] Only assign address on data packets, not ACK/NAK in x3
396
+    sbci    YH, 0           	;1 [02]
397
+    breq    skipAddrAssign  	;1 [03]
398
+    sts     usbDeviceAddr, x2	;2 [04+05] if not skipped: SE0 is one cycle longer
399
+;----------------------------------------------------------------------------
400
+;end of usbDeviceAddress transfer
401
+skipAddrAssign:				;- [03/04]
402
+    ldi     x2, 1<<USB_INTR_PENDING_BIT	;1 [05] int0 occurred during TX -- clear pending flag
403
+    USB_STORE_PENDING(x2)           ;1 [06]
404
+    ori     x1, USBIDLE     		;1 [07]
405
+    in      x2, USBDDR      		;1 [08]
406
+    cbr     x2, USBMASK     		;1 [09] set both pins to input
407
+    mov     x3, x1          		;1 [10]
408
+    cbr     x3, USBMASK     		;1 [11] configure no pullup on both pins
409
+    ldi     x4, 3           		;1 [12]
410
+se0Delay:				;- [12] [15] 
411
+    dec     x4              		;1 [13] [16] 
412
+    brne    se0Delay        		;1 [14] [17] 
413
+    nop2				;2      [18+19]
414
+    out     USBOUT, x1      		;1      [20] <--out J (idle) -- end of SE0 (EOP sig.)
415
+    out     USBDDR, x2      		;1      [21] <--release bus now
416
+    out     USBOUT, x3      		;1      [22] <--ensure no pull-up resistors are active
417
+    rjmp    doReturn			;1	[23]
418
+;---------------------------------------------------------------------------

+ 337
- 0
UsbJoystick/usbdrvasm16.inc Переглянути файл

@@ -0,0 +1,337 @@
1
+/* Name: usbdrvasm16.inc
2
+ * Project: AVR USB driver
3
+ * Author: Christian Starkjohann
4
+ * Creation Date: 2007-06-15
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt)
8
+ * Revision: $Id$
9
+ */
10
+
11
+/* Do not link this file! Link usbdrvasm.S instead, which includes the
12
+ * appropriate implementation!
13
+ */
14
+
15
+/*
16
+General Description:
17
+This file is the 16 MHz version of the asssembler part of the USB driver. It
18
+requires a 16 MHz crystal (not a ceramic resonator and not a calibrated RC
19
+oscillator).
20
+
21
+See usbdrv.h for a description of the entire driver.
22
+
23
+Since almost all of this code is timing critical, don't change unless you
24
+really know what you are doing! Many parts require not only a maximum number
25
+of CPU cycles, but even an exact number of cycles!
26
+*/
27
+
28
+;max stack usage: [ret(2), YL, SREG, YH, bitcnt, shift, x1, x2, x3, x4, cnt] = 12 bytes
29
+;nominal frequency: 16 MHz -> 10.6666666 cycles per bit, 85.333333333 cycles per byte
30
+; Numbers in brackets are clocks counted from center of last sync bit
31
+; when instruction starts
32
+
33
+USB_INTR_VECTOR:
34
+;order of registers pushed: YL, SREG YH, [sofError], bitcnt, shift, x1, x2, x3, x4, cnt
35
+    push    YL                  ;[-25] push only what is necessary to sync with edge ASAP
36
+    in      YL, SREG            ;[-23]
37
+    push    YL                  ;[-22]
38
+    push    YH                  ;[-20]
39
+;----------------------------------------------------------------------------
40
+; Synchronize with sync pattern:
41
+;----------------------------------------------------------------------------
42
+;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K]
43
+;sync up with J to K edge during sync pattern -- use fastest possible loops
44
+;first part has no timeout because it waits for IDLE or SE1 (== disconnected)
45
+waitForJ:
46
+    sbis    USBIN, USBMINUS     ;[-18] wait for D- == 1
47
+    rjmp    waitForJ
48
+waitForK:
49
+;The following code results in a sampling window of < 1/4 bit which meets the spec.
50
+    sbis    USBIN, USBMINUS     ;[-15]
51
+    rjmp    foundK              ;[-14]
52
+    sbis    USBIN, USBMINUS
53
+    rjmp    foundK
54
+    sbis    USBIN, USBMINUS
55
+    rjmp    foundK
56
+    sbis    USBIN, USBMINUS
57
+    rjmp    foundK
58
+    sbis    USBIN, USBMINUS
59
+    rjmp    foundK
60
+    sbis    USBIN, USBMINUS
61
+    rjmp    foundK
62
+#if USB_COUNT_SOF
63
+    lds     YL, usbSofCount
64
+    inc     YL
65
+    sts     usbSofCount, YL
66
+#endif  /* USB_COUNT_SOF */
67
+    rjmp    sofError
68
+foundK:                         ;[-12]
69
+;{3, 5} after falling D- edge, average delay: 4 cycles [we want 5 for center sampling]
70
+;we have 1 bit time for setup purposes, then sample again. Numbers in brackets
71
+;are cycles from center of first sync (double K) bit after the instruction
72
+    push    bitcnt              ;[-12]
73
+;   [---]                       ;[-11]
74
+    lds     YL, usbInputBufOffset;[-10]
75
+;   [---]                       ;[-9]
76
+    clr     YH                  ;[-8]
77
+    subi    YL, lo8(-(usbRxBuf));[-7] [rx loop init]
78
+    sbci    YH, hi8(-(usbRxBuf));[-6] [rx loop init]
79
+    push    shift               ;[-5]
80
+;   [---]                       ;[-4]
81
+    ldi     bitcnt, 0x55        ;[-3] [rx loop init]
82
+    sbis    USBIN, USBMINUS     ;[-2] we want two bits K (sample 2 cycles too early)
83
+    rjmp    haveTwoBitsK        ;[-1]
84
+    pop     shift               ;[0] undo the push from before
85
+    pop     bitcnt              ;[2] undo the push from before
86
+    rjmp    waitForK            ;[4] this was not the end of sync, retry
87
+; The entire loop from waitForK until rjmp waitForK above must not exceed two
88
+; bit times (= 21 cycles).
89
+
90
+;----------------------------------------------------------------------------
91
+; push more registers and initialize values while we sample the first bits:
92
+;----------------------------------------------------------------------------
93
+haveTwoBitsK:
94
+    push    x1              ;[1]
95
+    push    x2              ;[3]
96
+    push    x3              ;[5]
97
+    ldi     shift, 0        ;[7]
98
+    ldi     x3, 1<<4        ;[8] [rx loop init] first sample is inverse bit, compensate that
99
+    push    x4              ;[9] == leap
100
+
101
+    in      x1, USBIN       ;[11] <-- sample bit 0
102
+    andi    x1, USBMASK     ;[12]
103
+    bst     x1, USBMINUS    ;[13]
104
+    bld     shift, 7        ;[14]
105
+    push    cnt             ;[15]
106
+    ldi     leap, 0         ;[17] [rx loop init]
107
+    ldi     cnt, USB_BUFSIZE;[18] [rx loop init]
108
+    rjmp    rxbit1          ;[19] arrives at [21]
109
+
110
+;----------------------------------------------------------------------------
111
+; Receiver loop (numbers in brackets are cycles within byte after instr)
112
+;----------------------------------------------------------------------------
113
+
114
+unstuff6:
115
+    andi    x2, USBMASK ;[03]
116
+    ori     x3, 1<<6    ;[04] will not be shifted any more
117
+    andi    shift, ~0x80;[05]
118
+    mov     x1, x2      ;[06] sampled bit 7 is actually re-sampled bit 6
119
+    subi    leap, 3     ;[07] since this is a short (10 cycle) bit, enforce leap bit
120
+    rjmp    didUnstuff6 ;[08]
121
+
122
+unstuff7:
123
+    ori     x3, 1<<7    ;[09] will not be shifted any more
124
+    in      x2, USBIN   ;[00] [10]  re-sample bit 7
125
+    andi    x2, USBMASK ;[01]
126
+    andi    shift, ~0x80;[02]
127
+    subi    leap, 3     ;[03] since this is a short (10 cycle) bit, enforce leap bit
128
+    rjmp    didUnstuff7 ;[04]
129
+
130
+unstuffEven:
131
+    ori     x3, 1<<6    ;[09] will be shifted right 6 times for bit 0
132
+    in      x1, USBIN   ;[00] [10]
133
+    andi    shift, ~0x80;[01]
134
+    andi    x1, USBMASK ;[02]
135
+    breq    se0         ;[03]
136
+    subi    leap, 3     ;[04] since this is a short (10 cycle) bit, enforce leap bit
137
+    nop                 ;[05]
138
+    rjmp    didUnstuffE ;[06]
139
+
140
+unstuffOdd:
141
+    ori     x3, 1<<5    ;[09] will be shifted right 4 times for bit 1
142
+    in      x2, USBIN   ;[00] [10]
143
+    andi    shift, ~0x80;[01]
144
+    andi    x2, USBMASK ;[02]
145
+    breq    se0         ;[03]
146
+    subi    leap, 3     ;[04] since this is a short (10 cycle) bit, enforce leap bit
147
+    nop                 ;[05]
148
+    rjmp    didUnstuffO ;[06]
149
+
150
+rxByteLoop:
151
+    andi    x1, USBMASK ;[03]
152
+    eor     x2, x1      ;[04]
153
+    subi    leap, 1     ;[05]
154
+    brpl    skipLeap    ;[06]
155
+    subi    leap, -3    ;1 one leap cycle every 3rd byte -> 85 + 1/3 cycles per byte
156
+    nop                 ;1
157
+skipLeap:
158
+    subi    x2, 1       ;[08]
159
+    ror     shift       ;[09]
160
+didUnstuff6:
161
+    cpi     shift, 0xfc ;[10]
162
+    in      x2, USBIN   ;[00] [11] <-- sample bit 7
163
+    brcc    unstuff6    ;[01]
164
+    andi    x2, USBMASK ;[02]
165
+    eor     x1, x2      ;[03]
166
+    subi    x1, 1       ;[04]
167
+    ror     shift       ;[05]
168
+didUnstuff7:
169
+    cpi     shift, 0xfc ;[06]
170
+    brcc    unstuff7    ;[07]
171
+    eor     x3, shift   ;[08] reconstruct: x3 is 1 at bit locations we changed, 0 at others
172
+    st      y+, x3      ;[09] store data
173
+rxBitLoop:
174
+    in      x1, USBIN   ;[00] [11] <-- sample bit 0/2/4
175
+    andi    x1, USBMASK ;[01]
176
+    eor     x2, x1      ;[02]
177
+    andi    x3, 0x3f    ;[03] topmost two bits reserved for 6 and 7
178
+    subi    x2, 1       ;[04]
179
+    ror     shift       ;[05]
180
+    cpi     shift, 0xfc ;[06]
181
+    brcc    unstuffEven ;[07]
182
+didUnstuffE:
183
+    lsr     x3          ;[08]
184
+    lsr     x3          ;[09]
185
+rxbit1:
186
+    in      x2, USBIN   ;[00] [10] <-- sample bit 1/3/5
187
+    andi    x2, USBMASK ;[01]
188
+    breq    se0         ;[02]
189
+    eor     x1, x2      ;[03]
190
+    subi    x1, 1       ;[04]
191
+    ror     shift       ;[05]
192
+    cpi     shift, 0xfc ;[06]
193
+    brcc    unstuffOdd  ;[07]
194
+didUnstuffO:
195
+    subi    bitcnt, 0xab;[08] == addi 0x55, 0x55 = 0x100/3
196
+    brcs    rxBitLoop   ;[09]
197
+
198
+    subi    cnt, 1      ;[10]
199
+    in      x1, USBIN   ;[00] [11] <-- sample bit 6
200
+    brcc    rxByteLoop  ;[01]
201
+    rjmp    overflow
202
+
203
+macro POP_STANDARD ; 14 cycles
204
+    pop     cnt
205
+    pop     x4
206
+    pop     x3
207
+    pop     x2
208
+    pop     x1
209
+    pop     shift
210
+    pop     bitcnt
211
+endm
212
+macro POP_RETI     ; 7 cycles
213
+    pop     YH
214
+    pop     YL
215
+    out     SREG, YL
216
+    pop     YL
217
+endm
218
+
219
+#include "asmcommon.inc"
220
+
221
+; USB spec says:
222
+; idle = J
223
+; J = (D+ = 0), (D- = 1)
224
+; K = (D+ = 1), (D- = 0)
225
+; Spec allows 7.5 bit times from EOP to SOP for replies
226
+
227
+bitstuffN:
228
+    eor     x1, x4          ;[5]
229
+    ldi     x2, 0           ;[6]
230
+    nop2                    ;[7]
231
+    nop                     ;[9]
232
+    out     USBOUT, x1      ;[10] <-- out
233
+    rjmp    didStuffN       ;[0]
234
+    
235
+bitstuff6:
236
+    eor     x1, x4          ;[5]
237
+    ldi     x2, 0           ;[6] Carry is zero due to brcc
238
+    rol     shift           ;[7] compensate for ror shift at branch destination
239
+    rjmp    didStuff6       ;[8]
240
+
241
+bitstuff7:
242
+    ldi     x2, 0           ;[2] Carry is zero due to brcc
243
+    rjmp    didStuff7       ;[3]
244
+
245
+
246
+sendNakAndReti:
247
+    ldi     x3, USBPID_NAK  ;[-18]
248
+    rjmp    sendX3AndReti   ;[-17]
249
+sendAckAndReti:
250
+    ldi     cnt, USBPID_ACK ;[-17]
251
+sendCntAndReti:
252
+    mov     x3, cnt         ;[-16]
253
+sendX3AndReti:
254
+    ldi     YL, 20          ;[-15] x3==r20 address is 20
255
+    ldi     YH, 0           ;[-14]
256
+    ldi     cnt, 2          ;[-13]
257
+;   rjmp    usbSendAndReti      fallthrough
258
+
259
+;usbSend:
260
+;pointer to data in 'Y'
261
+;number of bytes in 'cnt' -- including sync byte [range 2 ... 12]
262
+;uses: x1...x4, btcnt, shift, cnt, Y
263
+;Numbers in brackets are time since first bit of sync pattern is sent
264
+;We don't match the transfer rate exactly (don't insert leap cycles every third
265
+;byte) because the spec demands only 1.5% precision anyway.
266
+usbSendAndReti:             ; 12 cycles until SOP
267
+    in      x2, USBDDR      ;[-12]
268
+    ori     x2, USBMASK     ;[-11]
269
+    sbi     USBOUT, USBMINUS;[-10] prepare idle state; D+ and D- must have been 0 (no pullups)
270
+    in      x1, USBOUT      ;[-8] port mirror for tx loop
271
+    out     USBDDR, x2      ;[-7] <- acquire bus
272
+; need not init x2 (bitstuff history) because sync starts with 0
273
+    ldi     x4, USBMASK     ;[-6] exor mask
274
+    ldi     shift, 0x80     ;[-5] sync byte is first byte sent
275
+txByteLoop:
276
+    ldi     bitcnt, 0x35    ;[-4] [6] binary 0011 0101
277
+txBitLoop:
278
+    sbrs    shift, 0        ;[-3] [7]
279
+    eor     x1, x4          ;[-2] [8]
280
+    out     USBOUT, x1      ;[-1] [9] <-- out N
281
+    ror     shift           ;[0] [10]
282
+    ror     x2              ;[1]
283
+didStuffN:
284
+    cpi     x2, 0xfc        ;[2]
285
+    brcc    bitstuffN       ;[3]
286
+    lsr     bitcnt          ;[4]
287
+    brcc    txBitLoop       ;[5]
288
+    brne    txBitLoop       ;[6]
289
+
290
+    sbrs    shift, 0        ;[7]
291
+    eor     x1, x4          ;[8]
292
+didStuff6:
293
+    out     USBOUT, x1      ;[-1] [9] <-- out 6
294
+    ror     shift           ;[0] [10]
295
+    ror     x2              ;[1]
296
+    cpi     x2, 0xfc        ;[2]
297
+    brcc    bitstuff6       ;[3]
298
+    ror     shift           ;[4]
299
+didStuff7:
300
+    ror     x2              ;[5]
301
+    sbrs    x2, 7           ;[6]
302
+    eor     x1, x4          ;[7]
303
+    nop                     ;[8]
304
+    cpi     x2, 0xfc        ;[9]
305
+    out     USBOUT, x1      ;[-1][10] <-- out 7
306
+    brcc    bitstuff7       ;[0] [11]
307
+    ld      shift, y+       ;[1]
308
+    dec     cnt             ;[3]
309
+    brne    txByteLoop      ;[4]
310
+;make SE0:
311
+    cbr     x1, USBMASK     ;[5] prepare SE0 [spec says EOP may be 21 to 25 cycles]
312
+    lds     x2, usbNewDeviceAddr;[6]
313
+    lsl     x2              ;[8] we compare with left shifted address
314
+    subi    YL, 20 + 2      ;[9] Only assign address on data packets, not ACK/NAK in x3
315
+    sbci    YH, 0           ;[10]
316
+    out     USBOUT, x1      ;[11] <-- out SE0 -- from now 2 bits = 22 cycles until bus idle
317
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
318
+;set address only after data packet was sent, not after handshake
319
+    breq    skipAddrAssign  ;[0]
320
+    sts     usbDeviceAddr, x2; if not skipped: SE0 is one cycle longer
321
+skipAddrAssign:
322
+;end of usbDeviceAddress transfer
323
+    ldi     x2, 1<<USB_INTR_PENDING_BIT;[2] int0 occurred during TX -- clear pending flag
324
+    USB_STORE_PENDING(x2)   ;[3]
325
+    ori     x1, USBIDLE     ;[4]
326
+    in      x2, USBDDR      ;[5]
327
+    cbr     x2, USBMASK     ;[6] set both pins to input
328
+    mov     x3, x1          ;[7]
329
+    cbr     x3, USBMASK     ;[8] configure no pullup on both pins
330
+    ldi     x4, 4           ;[9]
331
+se0Delay:
332
+    dec     x4              ;[10] [13] [16] [19]
333
+    brne    se0Delay        ;[11] [14] [17] [20]
334
+    out     USBOUT, x1      ;[21] <-- out J (idle) -- end of SE0 (EOP signal)
335
+    out     USBDDR, x2      ;[22] <-- release bus now
336
+    out     USBOUT, x3      ;[23] <-- ensure no pull-up resistors are active
337
+    rjmp    doReturn

+ 447
- 0
UsbJoystick/usbdrvasm165.inc Переглянути файл

@@ -0,0 +1,447 @@
1
+/* Name: usbdrvasm165.inc
2
+ * Project: AVR USB driver
3
+ * Author: Christian Starkjohann
4
+ * Creation Date: 2007-04-22
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt)
8
+ * Revision: $Id$
9
+ */
10
+
11
+/* Do not link this file! Link usbdrvasm.S instead, which includes the
12
+ * appropriate implementation!
13
+ */
14
+
15
+/*
16
+General Description:
17
+This file is the 16.5 MHz version of the USB driver. It is intended for the
18
+ATTiny45 and similar controllers running on 16.5 MHz internal RC oscillator.
19
+This version contains a phase locked loop in the receiver routine to cope with
20
+slight clock rate deviations of up to +/- 1%.
21
+
22
+See usbdrv.h for a description of the entire driver.
23
+
24
+Since almost all of this code is timing critical, don't change unless you
25
+really know what you are doing! Many parts require not only a maximum number
26
+of CPU cycles, but even an exact number of cycles!
27
+*/
28
+
29
+;Software-receiver engine. Strict timing! Don't change unless you can preserve timing!
30
+;interrupt response time: 4 cycles + insn running = 7 max if interrupts always enabled
31
+;max allowable interrupt latency: 59 cycles -> max 52 cycles interrupt disable
32
+;max stack usage: [ret(2), r0, SREG, YL, YH, shift, x1, x2, x3, x4, cnt] = 12 bytes
33
+;nominal frequency: 16.5 MHz -> 11 cycles per bit
34
+; 16.3125 MHz < F_CPU < 16.6875 MHz (+/- 1.1%)
35
+; Numbers in brackets are clocks counted from center of last sync bit
36
+; when instruction starts
37
+
38
+
39
+USB_INTR_VECTOR:
40
+;order of registers pushed: YL, SREG [sofError], r0, YH, shift, x1, x2, x3, x4, cnt
41
+    push    YL                  ;[-23] push only what is necessary to sync with edge ASAP
42
+    in      YL, SREG            ;[-21]
43
+    push    YL                  ;[-20]
44
+;----------------------------------------------------------------------------
45
+; Synchronize with sync pattern:
46
+;----------------------------------------------------------------------------
47
+;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K]
48
+;sync up with J to K edge during sync pattern -- use fastest possible loops
49
+;first part has no timeout because it waits for IDLE or SE1 (== disconnected)
50
+waitForJ:
51
+    sbis    USBIN, USBMINUS     ;[-18] wait for D- == 1
52
+    rjmp    waitForJ
53
+waitForK:
54
+;The following code results in a sampling window of < 1/4 bit which meets the spec.
55
+    sbis    USBIN, USBMINUS     ;[-15]
56
+    rjmp    foundK              ;[-14]
57
+    sbis    USBIN, USBMINUS
58
+    rjmp    foundK
59
+    sbis    USBIN, USBMINUS
60
+    rjmp    foundK
61
+    sbis    USBIN, USBMINUS
62
+    rjmp    foundK
63
+    sbis    USBIN, USBMINUS
64
+    rjmp    foundK
65
+    sbis    USBIN, USBMINUS
66
+    rjmp    foundK
67
+#if USB_COUNT_SOF
68
+    lds     YL, usbSofCount
69
+    inc     YL
70
+    sts     usbSofCount, YL
71
+#endif  /* USB_COUNT_SOF */
72
+    rjmp    sofError
73
+foundK:                         ;[-12]
74
+;{3, 5} after falling D- edge, average delay: 4 cycles [we want 5 for center sampling]
75
+;we have 1 bit time for setup purposes, then sample again. Numbers in brackets
76
+;are cycles from center of first sync (double K) bit after the instruction
77
+    push    r0                  ;[-12]
78
+;   [---]                       ;[-11]
79
+    push    YH                  ;[-10]
80
+;   [---]                       ;[-9]
81
+    lds     YL, usbInputBufOffset;[-8]
82
+;   [---]                       ;[-7]
83
+    clr     YH                  ;[-6]
84
+    subi    YL, lo8(-(usbRxBuf));[-5] [rx loop init]
85
+    sbci    YH, hi8(-(usbRxBuf));[-4] [rx loop init]
86
+    mov     r0, x2              ;[-3] [rx loop init]
87
+    sbis    USBIN, USBMINUS     ;[-2] we want two bits K (sample 2 cycles too early)
88
+    rjmp    haveTwoBitsK        ;[-1]
89
+    pop     YH                  ;[0] undo the pushes from before
90
+    pop     r0                  ;[2]
91
+    rjmp    waitForK            ;[4] this was not the end of sync, retry
92
+; The entire loop from waitForK until rjmp waitForK above must not exceed two
93
+; bit times (= 22 cycles).
94
+
95
+;----------------------------------------------------------------------------
96
+; push more registers and initialize values while we sample the first bits:
97
+;----------------------------------------------------------------------------
98
+haveTwoBitsK:               ;[1]
99
+    push    shift           ;[1]
100
+    push    x1              ;[3]
101
+    push    x2              ;[5]
102
+    push    x3              ;[7]
103
+    ldi     shift, 0xff     ;[9] [rx loop init]
104
+    ori     x3, 0xff        ;[10] [rx loop init] == ser x3, clear zero flag
105
+
106
+    in      x1, USBIN       ;[11] <-- sample bit 0
107
+    bst     x1, USBMINUS    ;[12]
108
+    bld     shift, 0        ;[13]
109
+    push    x4              ;[14] == phase
110
+;   [---]                   ;[15]
111
+    push    cnt             ;[16]
112
+;   [---]                   ;[17]
113
+    ldi     phase, 0        ;[18] [rx loop init]
114
+    ldi     cnt, USB_BUFSIZE;[19] [rx loop init]
115
+    rjmp    rxbit1          ;[20]
116
+;   [---]                   ;[21]
117
+
118
+;----------------------------------------------------------------------------
119
+; Receiver loop (numbers in brackets are cycles within byte after instr)
120
+;----------------------------------------------------------------------------
121
+/*
122
+byte oriented operations done during loop:
123
+bit 0: store data
124
+bit 1: SE0 check
125
+bit 2: overflow check
126
+bit 3: catch up
127
+bit 4: rjmp to achieve conditional jump range
128
+bit 5: PLL
129
+bit 6: catch up
130
+bit 7: jump, fixup bitstuff
131
+; 87 [+ 2] cycles
132
+------------------------------------------------------------------
133
+*/
134
+continueWithBit5:
135
+    in      x2, USBIN       ;[055] <-- bit 5
136
+    eor     r0, x2          ;[056]
137
+    or      phase, r0       ;[057]
138
+    sbrc    phase, USBMINUS ;[058]
139
+    lpm                     ;[059] optional nop3; modifies r0
140
+    in      phase, USBIN    ;[060] <-- phase
141
+    eor     x1, x2          ;[061]
142
+    bst     x1, USBMINUS    ;[062]
143
+    bld     shift, 5        ;[063]
144
+    andi    shift, 0x3f     ;[064]
145
+    in      x1, USBIN       ;[065] <-- bit 6
146
+    breq    unstuff5        ;[066] *** unstuff escape
147
+    eor     phase, x1       ;[067]
148
+    eor     x2, x1          ;[068]
149
+    bst     x2, USBMINUS    ;[069]
150
+    bld     shift, 6        ;[070]
151
+didUnstuff6:                ;[   ]
152
+    in      r0, USBIN       ;[071] <-- phase
153
+    cpi     shift, 0x02     ;[072]
154
+    brlo    unstuff6        ;[073] *** unstuff escape
155
+didUnstuff5:                ;[   ]
156
+    nop2                    ;[074]
157
+;   [---]                   ;[075]
158
+    in      x2, USBIN       ;[076] <-- bit 7
159
+    eor     x1, x2          ;[077]
160
+    bst     x1, USBMINUS    ;[078]
161
+    bld     shift, 7        ;[079]
162
+didUnstuff7:                ;[   ]
163
+    eor     r0, x2          ;[080]
164
+    or      phase, r0       ;[081]
165
+    in      r0, USBIN       ;[082] <-- phase
166
+    cpi     shift, 0x04     ;[083]
167
+    brsh    rxLoop          ;[084]
168
+;   [---]                   ;[085]
169
+unstuff7:                   ;[   ]
170
+    andi    x3, ~0x80       ;[085]
171
+    ori     shift, 0x80     ;[086]
172
+    in      x2, USBIN       ;[087] <-- sample stuffed bit 7
173
+    nop                     ;[088]
174
+    rjmp    didUnstuff7     ;[089]
175
+;   [---]                   ;[090]
176
+                            ;[080]
177
+
178
+unstuff5:                   ;[067]
179
+    eor     phase, x1       ;[068]
180
+    andi    x3, ~0x20       ;[069]
181
+    ori     shift, 0x20     ;[070]
182
+    in      r0, USBIN       ;[071] <-- phase
183
+    mov     x2, x1          ;[072]
184
+    nop                     ;[073]
185
+    nop2                    ;[074]
186
+;   [---]                   ;[075]
187
+    in      x1, USBIN       ;[076] <-- bit 6
188
+    eor     r0, x1          ;[077]
189
+    or      phase, r0       ;[078]
190
+    eor     x2, x1          ;[079]
191
+    bst     x2, USBMINUS    ;[080]
192
+    bld     shift, 6        ;[081] no need to check bitstuffing, we just had one
193
+    in      r0, USBIN       ;[082] <-- phase
194
+    rjmp    didUnstuff5     ;[083]
195
+;   [---]                   ;[084]
196
+                            ;[074]
197
+
198
+unstuff6:                   ;[074]
199
+    andi    x3, ~0x40       ;[075]
200
+    in      x1, USBIN       ;[076] <-- bit 6 again
201
+    ori     shift, 0x40     ;[077]
202
+    nop2                    ;[078]
203
+;   [---]                   ;[079]
204
+    rjmp    didUnstuff6     ;[080]
205
+;   [---]                   ;[081]
206
+                            ;[071]
207
+
208
+unstuff0:                   ;[013]
209
+    eor     r0, x2          ;[014]
210
+    or      phase, r0       ;[015]
211
+    andi    x2, USBMASK     ;[016] check for SE0
212
+    in      r0, USBIN       ;[017] <-- phase
213
+    breq    didUnstuff0     ;[018] direct jump to se0 would be too long
214
+    andi    x3, ~0x01       ;[019]
215
+    ori     shift, 0x01     ;[020]
216
+    mov     x1, x2          ;[021] mov existing sample
217
+    in      x2, USBIN       ;[022] <-- bit 1 again
218
+    rjmp    didUnstuff0     ;[023]
219
+;   [---]                   ;[024]
220
+                            ;[014]
221
+
222
+unstuff1:                   ;[024]
223
+    eor     r0, x1          ;[025]
224
+    or      phase, r0       ;[026]
225
+    andi    x3, ~0x02       ;[027]
226
+    in      r0, USBIN       ;[028] <-- phase
227
+    ori     shift, 0x02     ;[029]
228
+    mov     x2, x1          ;[030]
229
+    rjmp    didUnstuff1     ;[031]
230
+;   [---]                   ;[032]
231
+                            ;[022]
232
+
233
+unstuff2:                   ;[035]
234
+    eor     r0, x2          ;[036]
235
+    or      phase, r0       ;[037]
236
+    andi    x3, ~0x04       ;[038]
237
+    in      r0, USBIN       ;[039] <-- phase
238
+    ori     shift, 0x04     ;[040]
239
+    mov     x1, x2          ;[041]
240
+    rjmp    didUnstuff2     ;[042]
241
+;   [---]                   ;[043]
242
+                            ;[033]
243
+
244
+unstuff3:                   ;[043]
245
+    in      x2, USBIN       ;[044] <-- bit 3 again
246
+    eor     r0, x2          ;[045]
247
+    or      phase, r0       ;[046]
248
+    andi    x3, ~0x08       ;[047]
249
+    ori     shift, 0x08     ;[048]
250
+    nop                     ;[049]
251
+    in      r0, USBIN       ;[050] <-- phase
252
+    rjmp    didUnstuff3     ;[051]
253
+;   [---]                   ;[052]
254
+                            ;[042]
255
+
256
+unstuff4:                   ;[053]
257
+    andi    x3, ~0x10       ;[054]
258
+    in      x1, USBIN       ;[055] <-- bit 4 again
259
+    ori     shift, 0x10     ;[056]
260
+    rjmp    didUnstuff4     ;[057]
261
+;   [---]                   ;[058]
262
+                            ;[048]
263
+
264
+rxLoop:                     ;[085]
265
+    eor     x3, shift       ;[086] reconstruct: x3 is 0 at bit locations we changed, 1 at others
266
+    in      x1, USBIN       ;[000] <-- bit 0
267
+    st      y+, x3          ;[001]
268
+;   [---]                   ;[002]
269
+    eor     r0, x1          ;[003]
270
+    or      phase, r0       ;[004]
271
+    eor     x2, x1          ;[005]
272
+    in      r0, USBIN       ;[006] <-- phase
273
+    ser     x3              ;[007]
274
+    bst     x2, USBMINUS    ;[008]
275
+    bld     shift, 0        ;[009]
276
+    andi    shift, 0xf9     ;[010]
277
+rxbit1:                     ;[   ]
278
+    in      x2, USBIN       ;[011] <-- bit 1
279
+    breq    unstuff0        ;[012] *** unstuff escape
280
+    andi    x2, USBMASK     ;[013] SE0 check for bit 1
281
+didUnstuff0:                ;[   ] Z only set if we detected SE0 in bitstuff
282
+    breq    se0             ;[014]
283
+    eor     r0, x2          ;[015]
284
+    or      phase, r0       ;[016]
285
+    in      r0, USBIN       ;[017] <-- phase
286
+    eor     x1, x2          ;[018]
287
+    bst     x1, USBMINUS    ;[019]
288
+    bld     shift, 1        ;[020]
289
+    andi    shift, 0xf3     ;[021]
290
+didUnstuff1:                ;[   ]
291
+    in      x1, USBIN       ;[022] <-- bit 2
292
+    breq    unstuff1        ;[023] *** unstuff escape
293
+    eor     r0, x1          ;[024]
294
+    or      phase, r0       ;[025]
295
+    subi    cnt, 1          ;[026] overflow check
296
+    brcs    overflow        ;[027]
297
+    in      r0, USBIN       ;[028] <-- phase
298
+    eor     x2, x1          ;[029]
299
+    bst     x2, USBMINUS    ;[030]
300
+    bld     shift, 2        ;[031]
301
+    andi    shift, 0xe7     ;[032]
302
+didUnstuff2:                ;[   ]
303
+    in      x2, USBIN       ;[033] <-- bit 3
304
+    breq    unstuff2        ;[034] *** unstuff escape
305
+    eor     r0, x2          ;[035]
306
+    or      phase, r0       ;[036]
307
+    eor     x1, x2          ;[037]
308
+    bst     x1, USBMINUS    ;[038]
309
+    in      r0, USBIN       ;[039] <-- phase
310
+    bld     shift, 3        ;[040]
311
+    andi    shift, 0xcf     ;[041]
312
+didUnstuff3:                ;[   ]
313
+    breq    unstuff3        ;[042] *** unstuff escape
314
+    nop                     ;[043]
315
+    in      x1, USBIN       ;[044] <-- bit 4
316
+    eor     x2, x1          ;[045]
317
+    bst     x2, USBMINUS    ;[046]
318
+    bld     shift, 4        ;[047]
319
+didUnstuff4:                ;[   ]
320
+    eor     r0, x1          ;[048]
321
+    or      phase, r0       ;[049]
322
+    in      r0, USBIN       ;[050] <-- phase
323
+    andi    shift, 0x9f     ;[051]
324
+    breq    unstuff4        ;[052] *** unstuff escape
325
+    rjmp    continueWithBit5;[053]
326
+;   [---]                   ;[054]
327
+
328
+macro POP_STANDARD ; 16 cycles
329
+    pop     cnt
330
+    pop     x4
331
+    pop     x3
332
+    pop     x2
333
+    pop     x1
334
+    pop     shift
335
+    pop     YH
336
+    pop     r0
337
+endm
338
+macro POP_RETI     ; 5 cycles
339
+    pop     YL
340
+    out     SREG, YL
341
+    pop     YL
342
+endm
343
+
344
+#include "asmcommon.inc"
345
+
346
+
347
+; USB spec says:
348
+; idle = J
349
+; J = (D+ = 0), (D- = 1)
350
+; K = (D+ = 1), (D- = 0)
351
+; Spec allows 7.5 bit times from EOP to SOP for replies
352
+
353
+bitstuff7:
354
+    eor     x1, x4          ;[4]
355
+    ldi     x2, 0           ;[5]
356
+    nop2                    ;[6] C is zero (brcc)
357
+    rjmp    didStuff7       ;[8]
358
+
359
+bitstuffN:
360
+    eor     x1, x4          ;[5]
361
+    ldi     x2, 0           ;[6]
362
+    lpm                     ;[7] 3 cycle NOP, modifies r0
363
+    out     USBOUT, x1      ;[10] <-- out
364
+    rjmp    didStuffN       ;[0]
365
+
366
+#define bitStatus   x3
367
+
368
+sendNakAndReti:
369
+    ldi     cnt, USBPID_NAK ;[-19]
370
+    rjmp    sendCntAndReti  ;[-18]
371
+sendAckAndReti:
372
+    ldi     cnt, USBPID_ACK ;[-17]
373
+sendCntAndReti:
374
+    mov     r0, cnt         ;[-16]
375
+    ldi     YL, 0           ;[-15] R0 address is 0
376
+    ldi     YH, 0           ;[-14]
377
+    ldi     cnt, 2          ;[-13]
378
+;   rjmp    usbSendAndReti      fallthrough
379
+
380
+;usbSend:
381
+;pointer to data in 'Y'
382
+;number of bytes in 'cnt' -- including sync byte [range 2 ... 12]
383
+;uses: x1...x4, shift, cnt, Y
384
+;Numbers in brackets are time since first bit of sync pattern is sent
385
+usbSendAndReti:             ; 12 cycles until SOP
386
+    in      x2, USBDDR      ;[-12]
387
+    ori     x2, USBMASK     ;[-11]
388
+    sbi     USBOUT, USBMINUS;[-10] prepare idle state; D+ and D- must have been 0 (no pullups)
389
+    in      x1, USBOUT      ;[-8] port mirror for tx loop
390
+    out     USBDDR, x2      ;[-7] <- acquire bus
391
+; need not init x2 (bitstuff history) because sync starts with 0
392
+    ldi     x4, USBMASK     ;[-6] exor mask
393
+    ldi     shift, 0x80     ;[-5] sync byte is first byte sent
394
+    ldi     bitStatus, 0xff ;[-4] init bit loop counter, works for up to 12 bytes
395
+byteloop:
396
+bitloop:
397
+    sbrs    shift, 0        ;[8] [-3]
398
+    eor     x1, x4          ;[9] [-2]
399
+    out     USBOUT, x1      ;[10] [-1] <-- out
400
+    ror     shift           ;[0]
401
+    ror     x2              ;[1]
402
+didStuffN:
403
+    cpi     x2, 0xfc        ;[2]
404
+    brcc    bitstuffN       ;[3]
405
+    nop                     ;[4]
406
+    subi    bitStatus, 37   ;[5] 256 / 7 ~=~ 37
407
+    brcc    bitloop         ;[6] when we leave the loop, bitStatus has almost the initial value
408
+    sbrs    shift, 0        ;[7]
409
+    eor     x1, x4          ;[8]
410
+    ror     shift           ;[9]
411
+didStuff7:
412
+    out     USBOUT, x1      ;[10] <-- out
413
+    ror     x2              ;[0]
414
+    cpi     x2, 0xfc        ;[1]
415
+    brcc    bitstuff7       ;[2]
416
+    ld      shift, y+       ;[3]
417
+    dec     cnt             ;[5]
418
+    brne    byteloop        ;[6]
419
+;make SE0:
420
+    cbr     x1, USBMASK     ;[7] prepare SE0 [spec says EOP may be 21 to 25 cycles]
421
+    lds     x2, usbNewDeviceAddr;[8]
422
+    lsl     x2              ;[10] we compare with left shifted address
423
+    out     USBOUT, x1      ;[11] <-- out SE0 -- from now 2 bits = 22 cycles until bus idle
424
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
425
+;set address only after data packet was sent, not after handshake
426
+    subi    YL, 2           ;[0] Only assign address on data packets, not ACK/NAK in r0
427
+    sbci    YH, 0           ;[1]
428
+    breq    skipAddrAssign  ;[2]
429
+    sts     usbDeviceAddr, x2; if not skipped: SE0 is one cycle longer
430
+skipAddrAssign:
431
+;end of usbDeviceAddress transfer
432
+    ldi     x2, 1<<USB_INTR_PENDING_BIT;[4] int0 occurred during TX -- clear pending flag
433
+    USB_STORE_PENDING(x2)   ;[5]
434
+    ori     x1, USBIDLE     ;[6]
435
+    in      x2, USBDDR      ;[7]
436
+    cbr     x2, USBMASK     ;[8] set both pins to input
437
+    mov     x3, x1          ;[9]
438
+    cbr     x3, USBMASK     ;[10] configure no pullup on both pins
439
+    ldi     x4, 4           ;[11]
440
+se0Delay:
441
+    dec     x4              ;[12] [15] [18] [21]
442
+    brne    se0Delay        ;[13] [16] [19] [22]
443
+    out     USBOUT, x1      ;[23] <-- out J (idle) -- end of SE0 (EOP signal)
444
+    out     USBDDR, x2      ;[24] <-- release bus now
445
+    out     USBOUT, x3      ;[25] <-- ensure no pull-up resistors are active
446
+    rjmp    doReturn
447
+

Завантаження…
Відмінити
Зберегти