Browse Source

init

master
Robin Thoni 8 years ago
commit
f4810e95c6
33 changed files with 8492 additions and 0 deletions
  1. 1
    0
      .idea/.name
  2. 8
    0
      .idea/UsbKeyboard.iml
  3. 15
    0
      .idea/misc.xml
  4. 8
    0
      .idea/modules.xml
  5. 6
    0
      .idea/vcs.xml
  6. 198
    0
      .idea/workspace.xml
  7. 34
    0
      ArduinoNotes.txt
  8. 296
    0
      Changelog.txt
  9. 166
    0
      CommercialLicense.txt
  10. 361
    0
      License.txt
  11. 158
    0
      Readme.txt
  12. 149
    0
      USB-ID-FAQ.txt
  13. 148
    0
      USB-IDs-for-free.txt
  14. 154
    0
      USBID-License.txt
  15. 264
    0
      UsbKeyboard.h
  16. 188
    0
      asmcommon.inc
  17. 63
    0
      examples/UsbKeyboardDemo1/UsbKeyboardDemo1.pde
  18. 50
    0
      oddebug.c
  19. 123
    0
      oddebug.h
  20. 369
    0
      usbconfig-prototype.h
  21. 371
    0
      usbconfig.h
  22. 625
    0
      usbdrv.c
  23. 759
    0
      usbdrv.h
  24. 385
    0
      usbdrvasm.S
  25. 21
    0
      usbdrvasm.asm
  26. 393
    0
      usbdrvasm12.inc
  27. 750
    0
      usbdrvasm128.inc
  28. 423
    0
      usbdrvasm15.inc
  29. 346
    0
      usbdrvasm16.inc
  30. 453
    0
      usbdrvasm165.inc
  31. 707
    0
      usbdrvasm18-crc.inc
  32. 360
    0
      usbdrvasm20.inc
  33. 140
    0
      usbportability.h

+ 1
- 0
.idea/.name View File

@@ -0,0 +1 @@
1
+UsbKeyboard

+ 8
- 0
.idea/UsbKeyboard.iml View File

@@ -0,0 +1,8 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<module type="CPP_MODULE" version="4">
3
+  <component name="NewModuleRootManager">
4
+    <content url="file://$MODULE_DIR$" />
5
+    <orderEntry type="inheritedJdk" />
6
+    <orderEntry type="sourceFolder" forTests="false" />
7
+  </component>
8
+</module>

+ 15
- 0
.idea/misc.xml View File

@@ -0,0 +1,15 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<project version="4">
3
+  <component name="CMakeWorkspace" PROJECT_DIR="$PROJECT_DIR$" />
4
+  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
5
+    <OptionsSetting value="true" id="Add" />
6
+    <OptionsSetting value="true" id="Remove" />
7
+    <OptionsSetting value="true" id="Checkout" />
8
+    <OptionsSetting value="true" id="Update" />
9
+    <OptionsSetting value="true" id="Status" />
10
+    <OptionsSetting value="true" id="Edit" />
11
+    <ConfirmationsSetting value="0" id="Add" />
12
+    <ConfirmationsSetting value="0" id="Remove" />
13
+  </component>
14
+  <component name="ProjectRootManager" version="2" />
15
+</project>

+ 8
- 0
.idea/modules.xml View File

@@ -0,0 +1,8 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<project version="4">
3
+  <component name="ProjectModuleManager">
4
+    <modules>
5
+      <module fileurl="file://$PROJECT_DIR$/.idea/UsbKeyboard.iml" filepath="$PROJECT_DIR$/.idea/UsbKeyboard.iml" />
6
+    </modules>
7
+  </component>
8
+</project>

+ 6
- 0
.idea/vcs.xml View File

@@ -0,0 +1,6 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<project version="4">
3
+  <component name="VcsDirectoryMappings">
4
+    <mapping directory="" vcs="" />
5
+  </component>
6
+</project>

+ 198
- 0
.idea/workspace.xml View File

@@ -0,0 +1,198 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<project version="4">
3
+  <component name="CMakeRunConfigurationManager" shouldGenerate="true" assignedExecutableTargets="true" buildAllGenerated="false">
4
+    <generated />
5
+  </component>
6
+  <component name="CMakeSettings" AUTO_RELOAD="false" GENERATION_PASS_SYSTEM_ENVIRONMENT="true">
7
+    <ADDITIONAL_GENERATION_ENVIRONMENT>
8
+      <envs />
9
+    </ADDITIONAL_GENERATION_ENVIRONMENT>
10
+  </component>
11
+  <component name="ChangeListManager">
12
+    <list default="true" id="ccee955d-0be2-4bc1-8c38-c4bb22e37e1e" name="Default" comment="" />
13
+    <ignored path="UsbKeyboard.iws" />
14
+    <ignored path=".idea/workspace.xml" />
15
+    <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
16
+    <option name="TRACKING_ENABLED" value="true" />
17
+    <option name="SHOW_DIALOG" value="false" />
18
+    <option name="HIGHLIGHT_CONFLICTS" value="true" />
19
+    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
20
+    <option name="LAST_RESOLUTION" value="IGNORE" />
21
+  </component>
22
+  <component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
23
+  <component name="CreatePatchCommitExecutor">
24
+    <option name="PATCH_PATH" value="" />
25
+  </component>
26
+  <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
27
+  <component name="FavoritesManager">
28
+    <favorites_list name="UsbKeyboard" />
29
+  </component>
30
+  <component name="FileEditorManager">
31
+    <leaf>
32
+      <file leaf-file-name="UsbKeyboard.h" pinned="false" current-in-tab="true">
33
+        <entry file="file://$PROJECT_DIR$/UsbKeyboard.h">
34
+          <provider selected="true" editor-type-id="text-editor">
35
+            <state vertical-scroll-proportion="0.33216783">
36
+              <caret line="118" column="15" selection-start-line="118" selection-start-column="12" selection-end-line="118" selection-end-column="15" />
37
+              <folding />
38
+            </state>
39
+          </provider>
40
+        </entry>
41
+      </file>
42
+    </leaf>
43
+  </component>
44
+  <component name="IdeDocumentHistory">
45
+    <option name="CHANGED_PATHS">
46
+      <list>
47
+        <option value="$PROJECT_DIR$/UsbKeyboard.h" />
48
+      </list>
49
+    </option>
50
+  </component>
51
+  <component name="JsBuildToolGruntFileManager" detection-done="true" />
52
+  <component name="JsGulpfileManager">
53
+    <detection-done>true</detection-done>
54
+  </component>
55
+  <component name="NamedScopeManager">
56
+    <order />
57
+  </component>
58
+  <component name="ProjectFrameBounds">
59
+    <option name="x" value="960" />
60
+    <option name="width" value="960" />
61
+    <option name="height" value="1061" />
62
+  </component>
63
+  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
64
+    <OptionsSetting value="true" id="Add" />
65
+    <OptionsSetting value="true" id="Remove" />
66
+    <OptionsSetting value="true" id="Checkout" />
67
+    <OptionsSetting value="true" id="Update" />
68
+    <OptionsSetting value="true" id="Status" />
69
+    <OptionsSetting value="true" id="Edit" />
70
+    <ConfirmationsSetting value="0" id="Add" />
71
+    <ConfirmationsSetting value="0" id="Remove" />
72
+  </component>
73
+  <component name="ProjectView">
74
+    <navigator currentView="ProjectPane" proportions="" version="1">
75
+      <flattenPackages />
76
+      <showMembers />
77
+      <showModules />
78
+      <showLibraryContents />
79
+      <hideEmptyPackages />
80
+      <abbreviatePackageNames />
81
+      <autoscrollToSource />
82
+      <autoscrollFromSource />
83
+      <sortByType />
84
+    </navigator>
85
+    <panes>
86
+      <pane id="ProjectPane">
87
+        <subPane>
88
+          <PATH>
89
+            <PATH_ELEMENT>
90
+              <option name="myItemId" value="UsbKeyboard" />
91
+              <option name="myItemType" value="com.jetbrains.cidr.projectView.CidrFilesViewHelper$1$1" />
92
+            </PATH_ELEMENT>
93
+          </PATH>
94
+          <PATH>
95
+            <PATH_ELEMENT>
96
+              <option name="myItemId" value="UsbKeyboard" />
97
+              <option name="myItemType" value="com.jetbrains.cidr.projectView.CidrFilesViewHelper$1$1" />
98
+            </PATH_ELEMENT>
99
+            <PATH_ELEMENT>
100
+              <option name="myItemId" value="UsbKeyboard" />
101
+              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
102
+            </PATH_ELEMENT>
103
+          </PATH>
104
+        </subPane>
105
+      </pane>
106
+    </panes>
107
+  </component>
108
+  <component name="PropertiesComponent">
109
+    <property name="last_opened_file_path" value="$PROJECT_DIR$" />
110
+  </component>
111
+  <component name="RunManager">
112
+    <configuration default="true" type="js.build_tools.gulp" factoryName="Gulp.js">
113
+      <method />
114
+    </configuration>
115
+  </component>
116
+  <component name="ShelveChangesManager" show_recycled="false" />
117
+  <component name="TaskManager">
118
+    <task active="true" id="Default" summary="Default task">
119
+      <changelist id="ccee955d-0be2-4bc1-8c38-c4bb22e37e1e" name="Default" comment="" />
120
+      <created>1452172947648</created>
121
+      <option name="number" value="Default" />
122
+      <updated>1452172947648</updated>
123
+    </task>
124
+    <servers />
125
+  </component>
126
+  <component name="ToolWindowManager">
127
+    <frame x="960" y="0" width="960" height="1061" extended-state="0" />
128
+    <editor active="true" />
129
+    <layout>
130
+      <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.23012552" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
131
+      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
132
+      <window_info id="CMake" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.3299075" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
133
+      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="true" content_ui="tabs" />
134
+      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.3299075" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
135
+      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
136
+      <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
137
+      <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
138
+      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
139
+      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
140
+      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
141
+      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
142
+      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
143
+      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
144
+      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
145
+      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
146
+      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
147
+    </layout>
148
+  </component>
149
+  <component name="VcsContentAnnotationSettings">
150
+    <option name="myLimit" value="2678400000" />
151
+  </component>
152
+  <component name="XDebuggerManager">
153
+    <breakpoint-manager />
154
+    <watches-manager />
155
+  </component>
156
+  <component name="editorHistoryManager">
157
+    <entry file="file://$PROJECT_DIR$/usbconfig-prototype.h">
158
+      <provider selected="true" editor-type-id="text-editor">
159
+        <state vertical-scroll-proportion="0.0">
160
+          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
161
+          <folding />
162
+        </state>
163
+      </provider>
164
+    </entry>
165
+    <entry file="file://$PROJECT_DIR$/usbdrv.h">
166
+      <provider selected="true" editor-type-id="text-editor">
167
+        <state vertical-scroll-proportion="0.2768">
168
+          <caret line="259" column="28" selection-start-line="259" selection-start-column="28" selection-end-line="259" selection-end-column="28" />
169
+          <folding />
170
+        </state>
171
+      </provider>
172
+    </entry>
173
+    <entry file="file://$PROJECT_DIR$/usbconfig.h">
174
+      <provider selected="true" editor-type-id="text-editor">
175
+        <state vertical-scroll-proportion="0.3328">
176
+          <caret line="247" column="32" selection-start-line="247" selection-start-column="32" selection-end-line="247" selection-end-column="32" />
177
+          <folding />
178
+        </state>
179
+      </provider>
180
+    </entry>
181
+    <entry file="file://$PROJECT_DIR$/usbconfig-prototype.h">
182
+      <provider selected="true" editor-type-id="text-editor">
183
+        <state vertical-scroll-proportion="0.0">
184
+          <caret line="237" column="34" selection-start-line="237" selection-start-column="34" selection-end-line="237" selection-end-column="34" />
185
+          <folding />
186
+        </state>
187
+      </provider>
188
+    </entry>
189
+    <entry file="file://$PROJECT_DIR$/UsbKeyboard.h">
190
+      <provider selected="true" editor-type-id="text-editor">
191
+        <state vertical-scroll-proportion="0.33216783">
192
+          <caret line="118" column="15" selection-start-line="118" selection-start-column="12" selection-end-line="118" selection-end-column="15" />
193
+          <folding />
194
+        </state>
195
+      </provider>
196
+    </entry>
197
+  </component>
198
+</project>

+ 34
- 0
ArduinoNotes.txt View File

@@ -0,0 +1,34 @@
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 PCB (not protoboard) hardware shield are:
9
+
10
+     INT0 == PD2 == IC Pin 4 == Arduino Digital Pin 2 == D+
11
+
12
+     ---- == PD4 == -------- == Arduino Digital Pin 4 == D-
13
+
14
+     ---- == PD5 == -------- == Arduino Digital Pin 5 == pull-up
15
+
16
+  (DONE: Change to not use PD3 so INT1 is left free?)
17
+
18
+* In order to compile a valid 'usbconfig.h' file must exit. The content of this
19
+  file will vary depending on whether the device is a generic USB device,
20
+  generic HID device or specific class of HID device for example.
21
+
22
+  The file 'usbconfig-prototype.h' can be used as a starting point, however
23
+  it might be easier to use the 'usbconfig.h' from one of the example projects.
24
+
25
+  TODO: Specify the settings that need to be changed to match the shield
26
+        design we use.
27
+
28
+* (NOTE: Initial 'usbconfig.h' used will be based on the file from
29
+ 'HIDKeys.2007-03-29'.) (Note: Have now upgraded to V-USB 2009-08-22.)
30
+
31
+* Versions of the Arduino IDE prior to 0018 won't compile our library
32
+  so it needs to be pre-compiled with:
33
+
34
+    avr-g++  -Wall -Os -I. -DF_CPU=16000000 -mmcu=atmega168  -c usbdrvasm.S  -c usbdrv.c

+ 296
- 0
Changelog.txt View File

@@ -0,0 +1,296 @@
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
+
217
+  - USB_INITIAL_DATATOKEN defaults to USBPID_DATA1 now, which means that we
218
+    start with sending USBPID_DATA0.
219
+  - Changed defaults in usbconfig-prototype.h
220
+  - Added free USB VID/PID pair for MIDI class devices
221
+  - Restructured AVR-USB as separate package, not part of PowerSwitch any more.
222
+
223
+* Release 2008-04-18
224
+
225
+  - Restructured usbdrv.c so that it is easier to read and understand.
226
+  - Better code optimization with gcc 4.
227
+  - If a second interrupt in endpoint is enabled, also add it to config
228
+    descriptor.
229
+  - Added config option for long transfers (above 254 bytes), see
230
+    USB_CFG_LONG_TRANSFERS in usbconfig.h.
231
+  - Added 20 MHz module contributed by Jeroen Benschop.
232
+
233
+* Release 2008-05-13
234
+
235
+  - Fixed bug in libs-host/hiddata.c function usbhidGetReport(): length
236
+    was not incremented, pointer to length was incremented instead.
237
+  - Added code to command line tool(s) which claims an interface. This code
238
+    is disabled by default, but may be necessary on newer Linux kernels.
239
+  - Added usbconfig.h option "USB_CFG_CHECK_DATA_TOGGLING".
240
+  - New header "usbportability.h" prepares ports to other development
241
+    environments.
242
+  - Long transfers (above 254 bytes) did not work when usbFunctionRead() was
243
+    used to supply the data. Fixed this bug. [Thanks to Alexander Neumann!]
244
+  - In hiddata.c (example code for sending/receiving data over HID), use
245
+    USB_RECIP_DEVICE instead of USB_RECIP_INTERFACE for control transfers so
246
+    that we need not claim the interface.
247
+  - in usbPoll() loop 20 times polling for RESET state instead of 10 times.
248
+    This accounts for the higher clock rates we now support.
249
+  - Added a module for 12.8 MHz RC oscillator with PLL in receiver loop.
250
+  - Added hook to SOF code so that oscillator can be tuned to USB frame clock.
251
+  - Added timeout to waitForJ loop. Helps preventing unexpected hangs.
252
+  - Added example code for oscillator tuning to libs-device (thanks to
253
+    Henrik Haftmann for the idea to this routine).
254
+  - Implemented option USB_CFG_SUPPRESS_INTR_CODE.
255
+
256
+* Release 2008-10-22
257
+
258
+  - Fixed libs-device/osctune.h: OSCCAL is memory address on ATMega88 and
259
+    similar, not offset of 0x20 needs to be added.
260
+  - Allow distribution under GPLv3 for those who have to link against other
261
+    code distributed under GPLv3.
262
+
263
+* Release 2008-11-26
264
+
265
+  - Removed libusb-win32 dependency for hid-data example in Makefile.windows.
266
+    It was never required and confused many people.
267
+  - Added extern uchar usbRxToken to usbdrv.h.
268
+  - Integrated a module with CRC checks at 18 MHz by Lukas Schrittwieser.
269
+
270
+* Release 2009-03-23
271
+
272
+  - Hid-mouse example used settings from hid-data example, fixed that.
273
+  - Renamed project to V-USB due to a trademark issue with Atmel(r).
274
+  - Changed CommercialLicense.txt and USBID-License.txt to make the
275
+    background of USB ID registration clearer.
276
+
277
+* Release 2009-04-15
278
+
279
+  - Changed CommercialLicense.txt to reflect the new range of PIDs from
280
+    Jason Kotzin.
281
+  - Removed USBID-License.txt in favor of USB-IDs-for-free.txt and
282
+    USB-ID-FAQ.txt
283
+  - Fixed a bug in the 12.8 MHz module: End Of Packet decection was made in
284
+    the center between bit 0 and 1 of each byte. This is where the data lines
285
+    are expected to change and the sampled data may therefore be nonsense.
286
+    We therefore check EOP ONLY if bits 0 AND 1 have both been read as 0 on D-.
287
+  - Fixed a bitstuffing problem in the 16 MHz module: If bit 6 was stuffed,
288
+    the unstuffing code in the receiver routine was 1 cycle too long. If
289
+    multiple bytes had the unstuffing in bit 6, the error summed up until the
290
+    receiver was out of sync.
291
+  - Included option for faster CRC routine.
292
+    Thanks to Slawomir Fras (BoskiDialer) for this code!
293
+  - Updated bits in Configuration Descriptor's bmAttributes according to
294
+    USB 1.1 (in particular bit 7, it is a must-be-set bit now).
295
+
296
+* Release 2009-08-22

+ 166
- 0
CommercialLicense.txt View File

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

+ 361
- 0
License.txt View File

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

+ 158
- 0
Readme.txt View File

@@ -0,0 +1,158 @@
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/vusb/
4
+
5
+This directory contains the USB firmware only. Copy it as-is to your own
6
+project and add all .c and .S files to your project (these files are marked
7
+with an asterisk in the list below). Then copy usbconfig-prototype.h as
8
+usbconfig.h to your project and edit it according to your configuration.
9
+
10
+
11
+TECHNICAL DOCUMENTATION
12
+=======================
13
+The technical documentation (API) for the firmware driver is contained in the
14
+file "usbdrv.h". Please read all of it carefully! Configuration options are
15
+documented in "usbconfig-prototype.h".
16
+
17
+The driver consists of the following files:
18
+  Readme.txt ............. The file you are currently reading.
19
+  Changelog.txt .......... Release notes for all versions of the driver.
20
+  usbdrv.h ............... Driver interface definitions and technical docs.
21
+* usbdrv.c ............... High level language part of the driver. Link this
22
+                           module to your code!
23
+* usbdrvasm.S ............ Assembler part of the driver. This module is mostly
24
+                           a stub and includes one of the usbdrvasm*.S files
25
+                           depending on processor clock. Link this module to
26
+                           your code!
27
+  usbdrvasm*.inc ......... Assembler routines for particular clock frequencies.
28
+                           Included by usbdrvasm.S, don't link it directly!
29
+  asmcommon.inc .......... Common assembler routines. Included by
30
+                           usbdrvasm*.inc, don't link it directly!
31
+  usbconfig-prototype.h .. Prototype for your own usbdrv.h file.
32
+* oddebug.c .............. Debug functions. Only used when DEBUG_LEVEL is
33
+                           defined to a value greater than 0. Link this module
34
+                           to your code!
35
+  oddebug.h .............. Interface definitions of the debug module.
36
+  usbportability.h ....... Header with compiler-dependent stuff.
37
+  usbdrvasm.asm .......... Compatibility stub for IAR-C-compiler. Use this
38
+                           module instead of usbdrvasm.S when you assembler
39
+                           with IAR's tools.
40
+  License.txt ............ Open Source license for this driver.
41
+  CommercialLicense.txt .. Optional commercial license for this driver.
42
+  USB-ID-FAQ.txt ......... General infos about USB Product- and Vendor-IDs.
43
+  USB-IDs-for-free.txt ... List and terms of use for free shared PIDs.
44
+
45
+(*) ... These files should be linked to your project.
46
+
47
+
48
+CPU CORE CLOCK FREQUENCY
49
+========================
50
+We supply assembler modules for clock frequencies of 12 MHz, 12.8 MHz, 15 MHz,
51
+16 MHz, 16.5 MHz 18 MHz and 20 MHz. Other clock rates are not supported. The
52
+actual clock rate must be configured in usbdrv.h unless you use the default
53
+12 MHz.
54
+
55
+12 MHz Clock
56
+This is the traditional clock rate of V-USB because it's the lowest clock
57
+rate where the timing constraints of the USB spec can be met.
58
+
59
+15 MHz Clock
60
+Similar to 12 MHz, but some NOPs inserted. On the other hand, the higher clock
61
+rate allows for some loops which make the resulting code size somewhat smaller
62
+than the 12 MHz version.
63
+
64
+16 MHz Clock
65
+This clock rate has been added for users of the Arduino board and other
66
+ready-made boards which come with a fixed 16 MHz crystal. It's also an option
67
+if you need the slightly higher clock rate for performance reasons. Since
68
+16 MHz is not divisible by the USB low speed bit clock of 1.5 MHz, the code
69
+is somewhat tricky and has to insert a leap cycle every third byte.
70
+
71
+12.8 MHz and 16.5 MHz Clock
72
+The assembler modules for these clock rates differ from the other modules
73
+because they have been built for an RC oscillator with only 1% precision. The
74
+receiver code inserts leap cycles to compensate for clock deviations. 1% is
75
+also the precision which can be achieved by calibrating the internal RC
76
+oscillator of the AVR. Please note that only AVRs with internal 64 MHz PLL
77
+oscillator can reach 16.5 MHz with the RC oscillator. This includes the very
78
+popular ATTiny25, ATTiny45, ATTiny85 series as well as the ATTiny26. Almost
79
+all AVRs can reach 12.8 MHz, although this is outside the specified range.
80
+
81
+See the EasyLogger example at http://www.obdev.at/vusb/easylogger.html for
82
+code which calibrates the RC oscillator based on the USB frame clock.
83
+
84
+18 MHz Clock
85
+This module is closer to the USB specification because it performs an on the
86
+fly CRC check for incoming packets. Packets with invalid checksum are
87
+discarded as required by the spec. If you also implement checks for data
88
+PID toggling on application level (see option USB_CFG_CHECK_DATA_TOGGLING
89
+in usbconfig.h for more info), this ensures data integrity. Due to the CRC
90
+tables and alignment requirements, this code is bigger than modules for other
91
+clock rates. To activate this module, you must define USB_CFG_CHECK_CRC to 1
92
+and USB_CFG_CLOCK_KHZ to 18000 in usbconfig.h.
93
+
94
+20 MHz Clock
95
+This module is for people who won't do it with less than the maximum. Since
96
+20 MHz is not divisible by the USB low speed bit clock of 1.5 MHz, the code
97
+uses similar tricks as the 16 MHz module to insert leap cycles.
98
+
99
+
100
+USB IDENTIFIERS
101
+===============
102
+Every USB device needs a vendor- and a product-identifier (VID and PID). VIDs
103
+are obtained from usb.org for a price of 1,500 USD. Once you have a VID, you
104
+can assign PIDs at will.
105
+
106
+Since an entry level cost of 1,500 USD is too high for most small companies
107
+and hobbyists, we provide some VID/PID pairs for free. See the file
108
+USB-IDs-for-free.txt for details.
109
+
110
+Objective Development also has some license offerings which include product
111
+IDs. See http://www.obdev.at/vusb/ for details.
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. V-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 V-USB FOR FREE
127
+====================
128
+The AVR firmware driver is published under the GNU General Public License
129
+Version 2 (GPL2) and the GNU General Public License Version 3 (GPL3). It is
130
+your choice whether you apply the terms of version 2 or version 3.
131
+
132
+If you decide for the free GPL2 or GPL3, we STRONGLY ENCOURAGE you to do the
133
+following things IN ADDITION to the obligations from the GPL:
134
+
135
+(1) Publish your entire project on a web site and drop us a note with the URL.
136
+Use the form at http://www.obdev.at/vusb/feedback.html for your submission.
137
+If you don't have a web site, you can publish the project in obdev's
138
+documentation wiki at
139
+http://www.obdev.at/goto.php?t=vusb-wiki&p=hosted-projects.
140
+
141
+(2) Adhere to minimum publication standards. Please include AT LEAST:
142
+    - a circuit diagram in PDF, PNG or GIF format
143
+    - full source code for the host software
144
+    - a Readme.txt file in ASCII format which describes the purpose of the
145
+      project and what can be found in which directories and which files
146
+    - a reference to http://www.obdev.at/vusb/
147
+
148
+(3) If you improve the driver firmware itself, please give us a free license
149
+to your modifications for our commercial license offerings.
150
+
151
+
152
+COMMERCIAL LICENSES FOR V-USB
153
+=============================
154
+If you don't want to publish your source code under the terms of the GPL,
155
+you can simply pay money for V-USB. As an additional benefit you get
156
+USB PIDs for free, reserved exclusively to you. See the file
157
+"CommercialLicense.txt" for details.
158
+

+ 149
- 0
USB-ID-FAQ.txt View File

@@ -0,0 +1,149 @@
1
+Version 2009-08-22
2
+
3
+==========================
4
+WHY DO WE NEED THESE IDs?
5
+==========================
6
+
7
+USB is more than a low level protocol for data transport. It also defines a
8
+common set of requests which must be understood by all devices. And as part
9
+of these common requests, the specification defines data structures, the
10
+USB Descriptors, which are used to describe the properties of the device.
11
+
12
+From the perspective of an operating system, it is therefore possible to find
13
+out basic properties of a device (such as e.g. the manufacturer and the name
14
+of the device) without a device-specific driver. This is essential because
15
+the operating system can choose a driver to load based on this information
16
+(Plug-And-Play).
17
+
18
+Among the most important properties in the Device Descriptor are the USB
19
+Vendor- and Product-ID. Both are 16 bit integers. The most simple form of
20
+driver matching is based on these IDs. The driver announces the Vendor- and
21
+Product-IDs of the devices it can handle and the operating system loads the
22
+appropriate driver when the device is connected.
23
+
24
+It is obvious that this technique only works if the pair Vendor- plus
25
+Product-ID is unique: Only devices which require the same driver can have the
26
+same pair of IDs.
27
+
28
+
29
+=====================================================
30
+HOW DOES THE USB STANDARD ENSURE THAT IDs ARE UNIQUE?
31
+=====================================================
32
+
33
+Since it is so important that USB IDs are unique, the USB Implementers Forum,
34
+Inc. (usb.org) needs a way to enforce this legally. It is not forbidden by
35
+law to build a device and assign it any random numbers as IDs. Usb.org
36
+therefore needs an agreement to regulate the use of USB IDs. The agreement
37
+binds only parties who agreed to it, of course. Everybody else is free to use
38
+any numbers for their IDs.
39
+
40
+So how can usb.org ensure that every manufacturer of USB devices enters into
41
+an agreement with them? They do it via trademark licensing. Usb.org has
42
+registered the trademark "USB", all associated logos and related terms. If
43
+you want to put an USB logo on your product or claim that it is USB
44
+compliant, you must license these trademarks from usb.org. And this is where
45
+you enter into an agreement. See the "USB-IF Trademark License Agreement and
46
+Usage Guidelines for the USB-IF Logo" at
47
+http://www.usb.org/developers/logo_license/.
48
+
49
+Licensing the USB trademarks requires that you buy a USB Vendor-ID from
50
+usb.org (one-time fee of ca. 2,000 USD), that you become a member of usb.org
51
+(yearly fee of ca. 4,000 USD) and that you meet all the technical
52
+specifications from the USB spec.
53
+
54
+This means that most hobbyists and small companies will never be able to
55
+become USB compliant, just because membership is so expensive. And you can't
56
+be compliant with a driver based on V-USB anyway, because the AVR's port pins
57
+don't meet the electrical specifications for USB. So, in principle, all
58
+hobbyists and small companies are free to choose any random numbers for their
59
+IDs. They have nothing to lose...
60
+
61
+There is one exception worth noting, though: If you use a sub-component which
62
+implements USB, the vendor of the sub-components may guarantee USB
63
+compliance. This might apply to some or all of FTDI's solutions.
64
+
65
+
66
+=======================================================================
67
+WHY SHOULD YOU OBTAIN USB IDs EVEN IF YOU DON'T LICENSE USB TRADEMARKS?
68
+=======================================================================
69
+
70
+You have learned in the previous section that you are free to choose any
71
+numbers for your IDs anyway. So why not do exactly this? There is still the
72
+technical issue. If you choose IDs which are already in use by somebody else,
73
+operating systems will load the wrong drivers and your device won't work.
74
+Even if you choose IDs which are not currently in use, they may be in use in
75
+the next version of the operating system or even after an automatic update.
76
+
77
+So what you need is a pair of Vendor- and Product-IDs for which you have the
78
+guarantee that no USB compliant product uses them. This implies that no
79
+operating system will ever ship with drivers responsible for these IDs.
80
+
81
+
82
+==============================================
83
+HOW DOES OBJECTIVE DEVELOPMENT HANDLE USB IDs?
84
+==============================================
85
+
86
+Objective Development gives away pairs of USB-IDs with their V-USB licenses.
87
+In order to ensure that these IDs are unique, Objective Development has an
88
+agreement with the company/person who has bought the USB Vendor-ID from
89
+usb.org. This agreement ensures that a range of USB Product-IDs is reserved
90
+for assignment by Objective Development and that the owner of the Vendor-ID
91
+won't give it to anybody else.
92
+
93
+This means that you have to trust three parties to ensure uniqueness of
94
+your IDs:
95
+
96
+  - Objective Development, that they don't give the same PID to more than
97
+    one person.
98
+  - The owner of the Vendor-ID that they don't assign PIDs from the range
99
+    assigned to Objective Development to anybody else.
100
+  - Usb.org that they don't assign the same Vendor-ID a second time.
101
+
102
+
103
+==================================
104
+WHO IS THE OWNER OF THE VENDOR-ID?
105
+==================================
106
+
107
+Objective Development has obtained ranges of USB Product-IDs under two
108
+Vendor-IDs: Under Vendor-ID 5824 from Wouter van Ooijen (Van Ooijen
109
+Technische Informatica, www.voti.nl) and under Vendor-ID 8352 from Jason
110
+Kotzin (Clay Logic, www.claylogic.com). Both VID owners have received their
111
+Vendor-ID directly from usb.org.
112
+
113
+
114
+=========================================================================
115
+CAN I USE USB-IDs FROM OBJECTIVE DEVELOPMENT WITH OTHER DRIVERS/HARDWARE?
116
+=========================================================================
117
+
118
+The short answer is: Yes. All you get is a guarantee that the IDs are never
119
+assigned to anybody else. What more do you need?
120
+
121
+
122
+============================
123
+WHAT ABOUT SHARED ID PAIRS?
124
+============================
125
+
126
+Objective Development has reserved some PID/VID pairs for shared use. You
127
+have no guarantee of uniqueness for them, except that no USB compliant device
128
+uses them. In order to avoid technical problems, we must ensure that all
129
+devices with the same pair of IDs use the same driver on kernel level. For
130
+details, see the file USB-IDs-for-free.txt.
131
+
132
+
133
+======================================================
134
+I HAVE HEARD THAT SUB-LICENSING OF USB-IDs IS ILLEGAL?
135
+======================================================
136
+
137
+A 16 bit integer number cannot be protected by copyright laws. It is not
138
+sufficiently complex. And since none of the parties involved entered into the
139
+USB-IF Trademark License Agreement, we are not bound by this agreement. So
140
+there is no reason why it should be illegal to sub-license USB-IDs.
141
+
142
+
143
+=============================================
144
+WHO IS LIABLE IF THERE ARE INCOMPATIBILITIES?
145
+=============================================
146
+
147
+Objective Development disclaims all liabilities which might arise from the
148
+assignment of IDs. If you guarantee product features to your customers
149
+without proper disclaimer, YOU are liable for that.

+ 148
- 0
USB-IDs-for-free.txt View File

@@ -0,0 +1,148 @@
1
+Version 2009-08-22
2
+
3
+===========================
4
+FREE USB-IDs FOR SHARED USE
5
+===========================
6
+
7
+Objective Development has reserved a set of USB Product-IDs for use according
8
+to the guidelines outlined below. For more information about the concept of
9
+USB IDs please see the file USB-ID-FAQ.txt. Objective Development guarantees
10
+that the IDs listed below are not used by any USB compliant devices.
11
+
12
+
13
+====================
14
+MECHANISM OF SHARING
15
+====================
16
+
17
+From a technical point of view, two different devices can share the same USB
18
+Vendor- and Product-ID if they require the same driver on operating system
19
+level. We make use of this fact by assigning separate IDs for various device
20
+classes. On application layer, devices must be distinguished by their textual
21
+name or serial number. We offer separate sets of IDs for discrimination by
22
+textual name and for serial number.
23
+
24
+Examples for shared use of USB IDs are included with V-USB in the "examples"
25
+subdirectory.
26
+
27
+
28
+======================================
29
+IDs FOR DISCRIMINATION BY TEXTUAL NAME
30
+======================================
31
+
32
+If you use one of the IDs listed below, your device and host-side software
33
+must conform to these rules:
34
+
35
+(1) The USB device MUST provide a textual representation of the manufacturer
36
+and product identification. The manufacturer identification MUST be available
37
+at least in USB language 0x0409 (English/US).
38
+
39
+(2) The textual manufacturer identification MUST contain either an Internet
40
+domain name (e.g. "mycompany.com") registered and owned by you, or an e-mail
41
+address under your control (e.g. "myname@gmx.net"). You can embed the domain
42
+name or e-mail address in any string you like, e.g.  "Objective Development
43
+http://www.obdev.at/vusb/".
44
+
45
+(3) You are responsible for retaining ownership of the domain or e-mail
46
+address for as long as any of your products are in use.
47
+
48
+(4) You may choose any string for the textual product identification, as long
49
+as this string is unique within the scope of your textual manufacturer
50
+identification.
51
+
52
+(5) Application side device look-up MUST be based on the textual manufacturer
53
+and product identification in addition to VID/PID matching. The driver
54
+matching MUST be a comparison of the entire strings, NOT a sub-string match.
55
+
56
+(6) For devices which implement a particular USB device class (e.g. HID), the
57
+operating system's default class driver MUST be used. If an operating system
58
+driver for Vendor Class devices is needed, this driver must be libusb or
59
+libusb-win32 (see http://libusb.org/ and
60
+http://libusb-win32.sourceforge.net/).
61
+
62
+Table if IDs for discrimination by textual name:
63
+
64
+PID dec (hex) | VID dec (hex) | Description of use
65
+==============+===============+============================================
66
+1500 (0x05dc) | 5824 (0x16c0) | For Vendor Class devices with libusb
67
+--------------+---------------+--------------------------------------------
68
+1503 (0x05df) | 5824 (0x16c0) | For generic HID class devices (which are
69
+              |               | NOT mice, keyboards or joysticks)
70
+--------------+---------------+--------------------------------------------
71
+1505 (0x05e1) | 5824 (0x16c0) | For CDC-ACM class devices (modems)
72
+--------------+---------------+--------------------------------------------
73
+1508 (0x05e4) | 5824 (0x16c0) | For MIDI class devices
74
+--------------+---------------+--------------------------------------------
75
+
76
+Note that Windows caches the textual product- and vendor-description for
77
+mice, keyboards and joysticks. Name-bsed discrimination is therefore not
78
+recommended for these device classes.
79
+
80
+
81
+=======================================
82
+IDs FOR DISCRIMINATION BY SERIAL NUMBER
83
+=======================================
84
+
85
+If you use one of the IDs listed below, your device and host-side software
86
+must conform to these rules:
87
+
88
+(1) The USB device MUST provide a textual representation of the serial
89
+number. The serial number string MUST be available at least in USB language
90
+0x0409 (English/US).
91
+
92
+(2) The serial number MUST start with either an Internet domain name (e.g.
93
+"mycompany.com") registered and owned by you, or an e-mail address under your
94
+control (e.g. "myname@gmx.net"), both terminated with a colon (":") character.
95
+You MAY append any string you like for further discrimination of your devices.
96
+
97
+(3) You are responsible for retaining ownership of the domain or e-mail
98
+address for as long as any of your products are in use.
99
+
100
+(5) Application side device look-up MUST be based on the serial number string
101
+in addition to VID/PID matching. The matching must start at the first
102
+character of the serial number string and include the colon character
103
+terminating your domain or e-mail address. It MAY stop anywhere after that.
104
+
105
+(6) For devices which implement a particular USB device class (e.g. HID), the
106
+operating system's default class driver MUST be used. If an operating system
107
+driver for Vendor Class devices is needed, this driver must be libusb or
108
+libusb-win32 (see http://libusb.org/ and
109
+http://libusb-win32.sourceforge.net/).
110
+
111
+Table if IDs for discrimination by serial number string:
112
+
113
+PID dec (hex)  | VID dec (hex) | Description of use
114
+===============+===============+===========================================
115
+10200 (0x27d8) | 5824 (0x16c0) | For Vendor Class devices with libusb
116
+---------------+---------------+-------------------------------------------
117
+10201 (0x27d9) | 5824 (0x16c0) | For generic HID class devices (which are
118
+               |               | NOT mice, keyboards or joysticks)
119
+---------------+---------------+-------------------------------------------
120
+10202 (0x27da) | 5824 (0x16c0) | For USB Mice
121
+---------------+---------------+-------------------------------------------
122
+10203 (0x27db) | 5824 (0x16c0) | For USB Keyboards
123
+---------------+---------------+-------------------------------------------
124
+10204 (0x27db) | 5824 (0x16c0) | For USB Joysticks
125
+---------------+---------------+-------------------------------------------
126
+10205 (0x27dc) | 5824 (0x16c0) | For CDC-ACM class devices (modems)
127
+---------------+---------------+-------------------------------------------
128
+10206 (0x27dd) | 5824 (0x16c0) | For MIDI class devices
129
+---------------+---------------+-------------------------------------------
130
+
131
+
132
+=================
133
+ORIGIN OF USB-IDs
134
+=================
135
+
136
+OBJECTIVE DEVELOPMENT Software GmbH has obtained all VID/PID pairs listed
137
+here from Wouter van Ooijen (see www.voti.nl) for exclusive disposition.
138
+Wouter van Ooijen has obtained the VID from the USB Implementers Forum, Inc.
139
+(see www.usb.org). The VID is registered for the company name "Van Ooijen
140
+Technische Informatica".
141
+
142
+
143
+==========
144
+DISCLAIMER
145
+==========
146
+
147
+OBJECTIVE DEVELOPMENT Software GmbH disclaims all liability for any
148
+problems which are caused by the shared use of these VID/PID pairs.

+ 154
- 0
USBID-License.txt View File

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

+ 264
- 0
UsbKeyboard.h View File

@@ -0,0 +1,264 @@
1
+/*
2
+ * Based on Obdev's AVRUSB code and under the same license.
3
+ *
4
+ * TODO: Make a proper file header. :-)
5
+ */
6
+#ifndef __UsbKeyboard_h__
7
+#define __UsbKeyboard_h__
8
+
9
+#include <avr/pgmspace.h>
10
+#include <avr/interrupt.h>
11
+#include <string.h>
12
+
13
+#include "usbdrv.h"
14
+
15
+// TODO: Work around Arduino 12 issues better.
16
+//#include <WConstants.h>
17
+//#undef int()
18
+
19
+typedef uint8_t byte;
20
+
21
+
22
+#define BUFFER_SIZE 4 // Minimum of 2: 1 for modifiers + 1 for keystroke 
23
+
24
+
25
+static uchar    idleRate;           // in 4 ms units 
26
+
27
+
28
+/* We use a simplifed keyboard report descriptor which does not support the
29
+ * boot protocol. We don't allow setting status LEDs and but we do allow
30
+ * simultaneous key presses. 
31
+ * The report descriptor has been created with usb.org's "HID Descriptor Tool"
32
+ * which can be downloaded from http://www.usb.org/developers/hidpage/.
33
+ * Redundant entries (such as LOGICAL_MINIMUM and USAGE_PAGE) have been omitted
34
+ * for the second INPUT item.
35
+ */
36
+PROGMEM char usbHidReportDescriptor[35] = { /* USB report descriptor */
37
+  0x05, 0x01,                    // USAGE_PAGE (Generic Desktop) 
38
+  0x09, 0x06,                    // USAGE (Keyboard) 
39
+  0xa1, 0x01,                    // COLLECTION (Application) 
40
+  0x05, 0x07,                    //   USAGE_PAGE (Keyboard) 
41
+  0x19, 0xe0,                    //   USAGE_MINIMUM (Keyboard LeftControl) 
42
+  0x29, 0xe7,                    //   USAGE_MAXIMUM (Keyboard Right GUI) 
43
+  0x15, 0x00,                    //   LOGICAL_MINIMUM (0) 
44
+  0x25, 0x01,                    //   LOGICAL_MAXIMUM (1) 
45
+  0x75, 0x01,                    //   REPORT_SIZE (1) 
46
+  0x95, 0x08,                    //   REPORT_COUNT (8) 
47
+  0x81, 0x02,                    //   INPUT (Data,Var,Abs) 
48
+  0x95, BUFFER_SIZE-1,           //   REPORT_COUNT (simultaneous keystrokes) 
49
+  0x75, 0x08,                    //   REPORT_SIZE (8) 
50
+  0x25, 0x65,                    //   LOGICAL_MAXIMUM (101) 
51
+  0x19, 0x00,                    //   USAGE_MINIMUM (Reserved (no event indicated)) 
52
+  0x29, 0x65,                    //   USAGE_MAXIMUM (Keyboard Application) 
53
+  0x81, 0x00,                    //   INPUT (Data,Ary,Abs) 
54
+  0xc0                           // END_COLLECTION 
55
+};
56
+
57
+
58
+
59
+/* Keyboard usage values, see usb.org's HID-usage-tables document, chapter
60
+ * 10 Keyboard/Keypad Page for more codes.
61
+ */
62
+#define MOD_CONTROL_LEFT    (1<<0)
63
+#define MOD_SHIFT_LEFT      (1<<1)
64
+#define MOD_ALT_LEFT        (1<<2)
65
+#define MOD_GUI_LEFT        (1<<3)
66
+#define MOD_CONTROL_RIGHT   (1<<4)
67
+#define MOD_SHIFT_RIGHT     (1<<5)
68
+#define MOD_ALT_RIGHT       (1<<6)
69
+#define MOD_GUI_RIGHT       (1<<7)
70
+
71
+#define KEY_A       4
72
+#define KEY_B       5
73
+#define KEY_C       6
74
+#define KEY_D       7
75
+#define KEY_E       8
76
+#define KEY_F       9
77
+#define KEY_G       10
78
+#define KEY_H       11
79
+#define KEY_I       12
80
+#define KEY_J       13
81
+#define KEY_K       14
82
+#define KEY_L       15
83
+#define KEY_M       16
84
+#define KEY_N       17
85
+#define KEY_O       18
86
+#define KEY_P       19
87
+#define KEY_Q       20
88
+#define KEY_R       21
89
+#define KEY_S       22
90
+#define KEY_T       23
91
+#define KEY_U       24
92
+#define KEY_V       25
93
+#define KEY_W       26
94
+#define KEY_X       27
95
+#define KEY_Y       28
96
+#define KEY_Z       29
97
+#define KEY_1       30
98
+#define KEY_2       31
99
+#define KEY_3       32
100
+#define KEY_4       33
101
+#define KEY_5       34
102
+#define KEY_6       35
103
+#define KEY_7       36
104
+#define KEY_8       37
105
+#define KEY_9       38
106
+#define KEY_0       39
107
+
108
+#define KEY_ENTER   40
109
+#define KEY_ESCAPE  41
110
+#define KEY_BSPACE  42
111
+#define KEY_TAB     43
112
+#define KEY_SPACE   44
113
+
114
+
115
+#define KEY_HYPHEN    45
116
+#define KEY_EQUAL     46
117
+#define KEY_LBRACKET  47
118
+#define KEY_RBRACKET  48
119
+#define KEY_BSLASH    49
120
+#define KEY_HASHTAG   50
121
+#define KEY_SEMICOLON 51
122
+#define KEY_QUOTE    52
123
+#define KEY_TILDE     53
124
+#define KEY_COMMA     54
125
+#define KEY_DOT       55
126
+#define KEY_SLASH     56
127
+#define KEY_CAPSLOCK  57
128
+
129
+#define KEY_F1      58
130
+#define KEY_F2      59
131
+#define KEY_F3      60
132
+#define KEY_F4      61
133
+#define KEY_F5      62
134
+#define KEY_F6      63
135
+#define KEY_F7      64
136
+#define KEY_F8      65
137
+#define KEY_F9      66
138
+#define KEY_F10     67
139
+#define KEY_F11     68
140
+#define KEY_F12     69
141
+
142
+#define KEY_PRINTSCREEN 70
143
+#define KEY_SCROLLLOCK  71
144
+#define KEY_PAUSE       72
145
+#define KEY_INSERT      73
146
+#define KEY_HOME        74
147
+#define KEY_PAGEUP      75
148
+#define KEY_DELETE      76
149
+#define KEY_END         77
150
+#define KEY_PAGEDOWN    78
151
+
152
+#define KEY_ARROW_RIGHT 79
153
+#define KEY_ARROW_LEFT  80
154
+#define KEY_ARROW_DOWN  81
155
+#define KEY_ARROW_UP    82
156
+
157
+
158
+#define KEY_NUMLOCK     83
159
+#define KEYP_SLASH      84
160
+#define KEYP_STAR       85
161
+#define KEYP_MINUS      86
162
+#define KEYP_PLUS       87
163
+#define KEYP_ENTER      88
164
+
165
+class UsbKeyboardDevice {
166
+ public:
167
+  UsbKeyboardDevice () {
168
+    PORTD = 0; // TODO: Only for USB pins?
169
+    DDRD |= ~USBMASK;
170
+
171
+    cli();
172
+    usbDeviceDisconnect();
173
+    usbDeviceConnect();
174
+
175
+
176
+    usbInit();
177
+      
178
+    sei();
179
+
180
+    // TODO: Remove the next two lines once we fix
181
+    //       missing first keystroke bug properly.
182
+    memset(reportBuffer, 0, sizeof(reportBuffer));      
183
+    usbSetInterrupt(reportBuffer, sizeof(reportBuffer));
184
+  }
185
+    
186
+  void update() {
187
+    usbPoll();
188
+  }
189
+    
190
+  void sendKeyStroke(byte keyStroke) {
191
+    sendKeyStroke(keyStroke, 0);
192
+  }
193
+
194
+  void sendKeyStroke(byte keyStroke, byte modifiers) {
195
+      
196
+    while (!usbInterruptIsReady()) {
197
+      // Note: We wait until we can send keystroke
198
+      //       so we know the previous keystroke was
199
+      //       sent.
200
+    }
201
+      
202
+    memset(reportBuffer, 0, sizeof(reportBuffer));
203
+
204
+    reportBuffer[0] = modifiers;
205
+    reportBuffer[1] = keyStroke;
206
+        
207
+    usbSetInterrupt(reportBuffer, sizeof(reportBuffer));
208
+
209
+    while (!usbInterruptIsReady()) {
210
+      // Note: We wait until we can send keystroke
211
+      //       so we know the previous keystroke was
212
+      //       sent.
213
+    }
214
+      
215
+    // This stops endlessly repeating keystrokes:
216
+    memset(reportBuffer, 0, sizeof(reportBuffer));      
217
+    usbSetInterrupt(reportBuffer, sizeof(reportBuffer));
218
+
219
+  }
220
+    
221
+  //private: TODO: Make friend?
222
+  uchar    reportBuffer[4];    // buffer for HID reports [ 1 modifier byte + (len-1) key strokes]
223
+
224
+};
225
+
226
+UsbKeyboardDevice UsbKeyboard = UsbKeyboardDevice();
227
+
228
+#ifdef __cplusplus
229
+extern "C"{
230
+#endif 
231
+  // USB_PUBLIC uchar usbFunctionSetup
232
+uchar usbFunctionSetup(uchar data[8]) 
233
+  {
234
+    usbRequest_t    *rq = (usbRequest_t *)((void *)data);
235
+
236
+    usbMsgPtr = UsbKeyboard.reportBuffer; //
237
+    if((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS){
238
+      /* class request type */
239
+
240
+      if(rq->bRequest == USBRQ_HID_GET_REPORT){
241
+	/* wValue: ReportType (highbyte), ReportID (lowbyte) */
242
+
243
+	/* we only have one report type, so don't look at wValue */
244
+        // TODO: Ensure it's okay not to return anything here?    
245
+	return 0;
246
+
247
+      }else if(rq->bRequest == USBRQ_HID_GET_IDLE){
248
+	//            usbMsgPtr = &idleRate;
249
+	//            return 1;
250
+	return 0;
251
+      }else if(rq->bRequest == USBRQ_HID_SET_IDLE){
252
+	idleRate = rq->wValue.bytes[1];
253
+      }
254
+    }else{
255
+      /* no vendor specific requests implemented */
256
+    }
257
+    return 0;
258
+  }
259
+#ifdef __cplusplus
260
+} // extern "C"
261
+#endif
262
+
263
+
264
+#endif // __UsbKeyboard_h__

+ 188
- 0
asmcommon.inc View File

@@ -0,0 +1,188 @@
1
+/* Name: asmcommon.inc
2
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
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), GNU GPL v3 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
+#if USB_CFG_CHECK_CRC
107
+    CRC_CLEANUP_AND_CHECK       ; jumps to ignorePacket if CRC error
108
+#endif
109
+    lds     shift, usbCurrentTok;[18]
110
+    tst     shift               ;[20]
111
+    breq    doReturn            ;[21]
112
+    lds     x2, usbRxLen        ;[22]
113
+    tst     x2                  ;[24]
114
+    brne    sendNakAndReti      ;[25]
115
+; 2006-03-11: The following two lines fix a problem where the device was not
116
+; recognized if usbPoll() was called less frequently than once every 4 ms.
117
+    cpi     cnt, 4              ;[26] zero sized data packets are status phase only -- ignore and ack
118
+    brmi    sendAckAndReti      ;[27] keep rx buffer clean -- we must not NAK next SETUP
119
+#if USB_CFG_CHECK_DATA_TOGGLING
120
+    sts     usbCurrentDataToken, token  ; store for checking by C code
121
+#endif
122
+    sts     usbRxLen, cnt       ;[28] store received data, swap buffers
123
+    sts     usbRxToken, shift   ;[30]
124
+    lds     x2, usbInputBufOffset;[32] swap buffers
125
+    ldi     cnt, USB_BUFSIZE    ;[34]
126
+    sub     cnt, x2             ;[35]
127
+    sts     usbInputBufOffset, cnt;[36] buffers now swapped
128
+    rjmp    sendAckAndReti      ;[38] 40 + 17 = 57 until SOP
129
+
130
+handleIn:
131
+;We don't send any data as long as the C code has not processed the current
132
+;input data and potentially updated the output data. That's more efficient
133
+;in terms of code size than clearing the tx buffers when a packet is received.
134
+    lds     x1, usbRxLen        ;[30]
135
+    cpi     x1, 1               ;[32] negative values are flow control, 0 means "buffer free"
136
+    brge    sendNakAndReti      ;[33] unprocessed input packet?
137
+    ldi     x1, USBPID_NAK      ;[34] prepare value for usbTxLen
138
+#if USB_CFG_HAVE_INTRIN_ENDPOINT
139
+    andi    x3, 0xf             ;[35] x3 contains endpoint
140
+#if USB_CFG_SUPPRESS_INTR_CODE
141
+    brne    sendNakAndReti      ;[36]
142
+#else
143
+    brne    handleIn1           ;[36]
144
+#endif
145
+#endif
146
+    lds     cnt, usbTxLen       ;[37]
147
+    sbrc    cnt, 4              ;[39] all handshake tokens have bit 4 set
148
+    rjmp    sendCntAndReti      ;[40] 42 + 16 = 58 until SOP
149
+    sts     usbTxLen, x1        ;[41] x1 == USBPID_NAK from above
150
+    ldi     YL, lo8(usbTxBuf)   ;[43]
151
+    ldi     YH, hi8(usbTxBuf)   ;[44]
152
+    rjmp    usbSendAndReti      ;[45] 57 + 12 = 59 until SOP
153
+
154
+; Comment about when to set usbTxLen to USBPID_NAK:
155
+; We should set it back when we receive the ACK from the host. This would
156
+; be simple to implement: One static variable which stores whether the last
157
+; tx was for endpoint 0 or 1 and a compare in the receiver to distinguish the
158
+; ACK. However, we set it back immediately when we send the package,
159
+; assuming that no error occurs and the host sends an ACK. We save one byte
160
+; RAM this way and avoid potential problems with endless retries. The rest of
161
+; the driver assumes error-free transfers anyway.
162
+
163
+#if !USB_CFG_SUPPRESS_INTR_CODE && USB_CFG_HAVE_INTRIN_ENDPOINT /* placed here due to relative jump range */
164
+handleIn1:                      ;[38]
165
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
166
+; 2006-06-10 as suggested by O.Tamura: support second INTR IN / BULK IN endpoint
167
+    cpi     x3, USB_CFG_EP3_NUMBER;[38]
168
+    breq    handleIn3           ;[39]
169
+#endif
170
+    lds     cnt, usbTxLen1      ;[40]
171
+    sbrc    cnt, 4              ;[42] all handshake tokens have bit 4 set
172
+    rjmp    sendCntAndReti      ;[43] 47 + 16 = 63 until SOP
173
+    sts     usbTxLen1, x1       ;[44] x1 == USBPID_NAK from above
174
+    ldi     YL, lo8(usbTxBuf1)  ;[46]
175
+    ldi     YH, hi8(usbTxBuf1)  ;[47]
176
+    rjmp    usbSendAndReti      ;[48] 50 + 12 = 62 until SOP
177
+
178
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
179
+handleIn3:
180
+    lds     cnt, usbTxLen3      ;[41]
181
+    sbrc    cnt, 4              ;[43]
182
+    rjmp    sendCntAndReti      ;[44] 49 + 16 = 65 until SOP
183
+    sts     usbTxLen3, x1       ;[45] x1 == USBPID_NAK from above
184
+    ldi     YL, lo8(usbTxBuf3)  ;[47]
185
+    ldi     YH, hi8(usbTxBuf3)  ;[48]
186
+    rjmp    usbSendAndReti      ;[49] 51 + 12 = 63 until SOP
187
+#endif
188
+#endif

+ 63
- 0
examples/UsbKeyboardDemo1/UsbKeyboardDemo1.pde View File

@@ -0,0 +1,63 @@
1
+#include "UsbKeyboard.h"
2
+
3
+#define BUTTON_PIN 12
4
+
5
+// If the timer isr is corrected
6
+// to not take so long change this to 0.
7
+#define BYPASS_TIMER_ISR 1
8
+
9
+void setup() {
10
+  pinMode(BUTTON_PIN, INPUT);
11
+  digitalWrite(BUTTON_PIN, HIGH);
12
+  
13
+#if BYPASS_TIMER_ISR
14
+  // disable timer 0 overflow interrupt (used for millis)
15
+  TIMSK0&=!(1<<TOIE0); // ++
16
+#endif
17
+}
18
+
19
+#if BYPASS_TIMER_ISR
20
+void delayMs(unsigned int ms) {
21
+   /*
22
+  */ 
23
+  for (int i = 0; i < ms; i++) {
24
+    delayMicroseconds(1000);
25
+  }
26
+}
27
+#endif
28
+
29
+void loop() {
30
+  
31
+  UsbKeyboard.update();
32
+
33
+  digitalWrite(13, !digitalRead(13));
34
+
35
+  if (digitalRead(BUTTON_PIN) == 0) {
36
+    
37
+    //UsbKeyboard.sendKeyStroke(KEY_B, MOD_GUI_LEFT);
38
+    
39
+    UsbKeyboard.sendKeyStroke(KEY_H);
40
+    UsbKeyboard.sendKeyStroke(KEY_E);
41
+    UsbKeyboard.sendKeyStroke(KEY_L);
42
+    UsbKeyboard.sendKeyStroke(KEY_L);
43
+    UsbKeyboard.sendKeyStroke(KEY_O);
44
+
45
+    UsbKeyboard.sendKeyStroke(KEY_SPACE);
46
+
47
+    UsbKeyboard.sendKeyStroke(KEY_W);
48
+    UsbKeyboard.sendKeyStroke(KEY_O);
49
+    UsbKeyboard.sendKeyStroke(KEY_R);
50
+    UsbKeyboard.sendKeyStroke(KEY_L);
51
+    UsbKeyboard.sendKeyStroke(KEY_D);
52
+    //UsbKeyboard.sendKeyStroke(KEY_B, MOD_GUI_LEFT);
53
+
54
+    UsbKeyboard.sendKeyStroke(KEY_ENTER);
55
+#if BYPASS_TIMER_ISR  // check if timer isr fixed.
56
+    delayMs(20);
57
+#else
58
+    delay(20);
59
+#endif
60
+    
61
+   }
62
+
63
+}

+ 50
- 0
oddebug.c View File

@@ -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), GNU GPL v3 or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: oddebug.c 692 2008-11-07 15:07:40Z 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

+ 123
- 0
oddebug.h View File

@@ -0,0 +1,123 @@
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), GNU GPL v3 or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: oddebug.h 692 2008-11-07 15:07:40Z 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 "usbportability.h"
33
+
34
+#ifndef uchar
35
+#   define  uchar   unsigned char
36
+#endif
37
+
38
+#if DEBUG_LEVEL > 0 && !(defined TXEN || defined TXEN0) /* no UART in device */
39
+#   warning "Debugging disabled because device has no UART"
40
+#   undef   DEBUG_LEVEL
41
+#endif
42
+
43
+#ifndef DEBUG_LEVEL
44
+#   define  DEBUG_LEVEL 0
45
+#endif
46
+
47
+/* ------------------------------------------------------------------------- */
48
+
49
+#if DEBUG_LEVEL > 0
50
+#   define  DBG1(prefix, data, len) odDebug(prefix, data, len)
51
+#else
52
+#   define  DBG1(prefix, data, len)
53
+#endif
54
+
55
+#if DEBUG_LEVEL > 1
56
+#   define  DBG2(prefix, data, len) odDebug(prefix, data, len)
57
+#else
58
+#   define  DBG2(prefix, data, len)
59
+#endif
60
+
61
+/* ------------------------------------------------------------------------- */
62
+
63
+#if DEBUG_LEVEL > 0
64
+extern void odDebug(uchar prefix, uchar *data, uchar len);
65
+
66
+/* Try to find our control registers; ATMEL likes to rename these */
67
+
68
+#if defined UBRR
69
+#   define  ODDBG_UBRR  UBRR
70
+#elif defined UBRRL
71
+#   define  ODDBG_UBRR  UBRRL
72
+#elif defined UBRR0
73
+#   define  ODDBG_UBRR  UBRR0
74
+#elif defined UBRR0L
75
+#   define  ODDBG_UBRR  UBRR0L
76
+#endif
77
+
78
+#if defined UCR
79
+#   define  ODDBG_UCR   UCR
80
+#elif defined UCSRB
81
+#   define  ODDBG_UCR   UCSRB
82
+#elif defined UCSR0B
83
+#   define  ODDBG_UCR   UCSR0B
84
+#endif
85
+
86
+#if defined TXEN
87
+#   define  ODDBG_TXEN  TXEN
88
+#else
89
+#   define  ODDBG_TXEN  TXEN0
90
+#endif
91
+
92
+#if defined USR
93
+#   define  ODDBG_USR   USR
94
+#elif defined UCSRA
95
+#   define  ODDBG_USR   UCSRA
96
+#elif defined UCSR0A
97
+#   define  ODDBG_USR   UCSR0A
98
+#endif
99
+
100
+#if defined UDRE
101
+#   define  ODDBG_UDRE  UDRE
102
+#else
103
+#   define  ODDBG_UDRE  UDRE0
104
+#endif
105
+
106
+#if defined UDR
107
+#   define  ODDBG_UDR   UDR
108
+#elif defined UDR0
109
+#   define  ODDBG_UDR   UDR0
110
+#endif
111
+
112
+static inline void  odDebugInit(void)
113
+{
114
+    ODDBG_UCR |= (1<<ODDBG_TXEN);
115
+    ODDBG_UBRR = F_CPU / (19200 * 16L) - 1;
116
+}
117
+#else
118
+#   define odDebugInit()
119
+#endif
120
+
121
+/* ------------------------------------------------------------------------- */
122
+
123
+#endif /* __oddebug_h_included__ */

+ 369
- 0
usbconfig-prototype.h View File

@@ -0,0 +1,369 @@
1
+/* Name: usbconfig.h
2
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
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), GNU GPL v3 or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: usbconfig-prototype.h 767 2009-08-22 11:39:22Z 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 V-USB for USB D+ connected to Port D bit 2 (which is
18
+also hardware interrupt 0 on many devices) and USB D- to Port D bit 4. You may
19
+wire the lines to any other port, as long as D+ is also wired to INT0 (or any
20
+other hardware interrupt, as long as it is the highest level interrupt, see
21
+section at the end of this file).
22
++ To create your own usbconfig.h file, copy this file to your project's
23
++ firmware source directory) and rename it to "usbconfig.h".
24
++ Then edit it accordingly.
25
+*/
26
+
27
+/* ---------------------------- Hardware Config ---------------------------- */
28
+
29
+#define USB_CFG_IOPORTNAME      D
30
+/* This is the port where the USB bus is connected. When you configure it to
31
+ * "B", the registers PORTB, PINB and DDRB will be used.
32
+ */
33
+#define USB_CFG_DMINUS_BIT      4
34
+/* This is the bit number in USB_CFG_IOPORT where the USB D- line is connected.
35
+ * This may be any bit in the port.
36
+ */
37
+#define USB_CFG_DPLUS_BIT       2
38
+/* This is the bit number in USB_CFG_IOPORT where the USB D+ line is connected.
39
+ * This may be any bit in the port. Please note that D+ must also be connected
40
+ * to interrupt pin INT0! [You can also use other interrupts, see section
41
+ * "Optional MCU Description" below, or you can connect D- to the interrupt, as
42
+ * it is required if you use the USB_COUNT_SOF feature. If you use D- for the
43
+ * interrupt, the USB interrupt will also be triggered at Start-Of-Frame
44
+ * markers every millisecond.]
45
+ */
46
+#define USB_CFG_CLOCK_KHZ       (F_CPU/1000)
47
+/* Clock rate of the AVR in kHz. Legal values are 12000, 12800, 15000, 16000,
48
+ * 16500 and 20000. The 12.8 MHz and 16.5 MHz versions of the code require no
49
+ * crystal, they tolerate +/- 1% deviation from the nominal frequency. All
50
+ * other rates require a precision of 2000 ppm and thus a crystal!
51
+ * Default if not specified: 12 MHz
52
+ */
53
+#define USB_CFG_CHECK_CRC       0
54
+/* Define this to 1 if you want that the driver checks integrity of incoming
55
+ * data packets (CRC checks). CRC checks cost quite a bit of code size and are
56
+ * currently only available for 18 MHz crystal clock. You must choose
57
+ * USB_CFG_CLOCK_KHZ = 18000 if you enable this option.
58
+ */
59
+
60
+/* ----------------------- Optional Hardware Config ------------------------ */
61
+
62
+/* #define USB_CFG_PULLUP_IOPORTNAME   D */
63
+/* If you connect the 1.5k pullup resistor from D- to a port pin instead of
64
+ * V+, you can connect and disconnect the device from firmware by calling
65
+ * the macros usbDeviceConnect() and usbDeviceDisconnect() (see usbdrv.h).
66
+ * This constant defines the port on which the pullup resistor is connected.
67
+ */
68
+/* #define USB_CFG_PULLUP_BIT          4 */
69
+/* This constant defines the bit number in USB_CFG_PULLUP_IOPORT (defined
70
+ * above) where the 1.5k pullup resistor is connected. See description
71
+ * above for details.
72
+ */
73
+
74
+/* --------------------------- Functional Range ---------------------------- */
75
+
76
+#define USB_CFG_HAVE_INTRIN_ENDPOINT    0
77
+/* Define this to 1 if you want to compile a version with two endpoints: The
78
+ * default control endpoint 0 and an interrupt-in endpoint (any other endpoint
79
+ * number).
80
+ */
81
+#define USB_CFG_HAVE_INTRIN_ENDPOINT3   0
82
+/* Define this to 1 if you want to compile a version with three endpoints: The
83
+ * default control endpoint 0, an interrupt-in endpoint 3 (or the number
84
+ * configured below) and a catch-all default interrupt-in endpoint as above.
85
+ * You must also define USB_CFG_HAVE_INTRIN_ENDPOINT to 1 for this feature.
86
+ */
87
+#define USB_CFG_EP3_NUMBER              3
88
+/* If the so-called endpoint 3 is used, it can now be configured to any other
89
+ * endpoint number (except 0) with this macro. Default if undefined is 3.
90
+ */
91
+/* #define USB_INITIAL_DATATOKEN           USBPID_DATA1 */
92
+/* The above macro defines the startup condition for data toggling on the
93
+ * interrupt/bulk endpoints 1 and 3. Defaults to USBPID_DATA1.
94
+ * Since the token is toggled BEFORE sending any data, the first packet is
95
+ * sent with the oposite value of this configuration!
96
+ */
97
+#define USB_CFG_IMPLEMENT_HALT          0
98
+/* Define this to 1 if you also want to implement the ENDPOINT_HALT feature
99
+ * for endpoint 1 (interrupt endpoint). Although you may not need this feature,
100
+ * it is required by the standard. We have made it a config option because it
101
+ * bloats the code considerably.
102
+ */
103
+#define USB_CFG_SUPPRESS_INTR_CODE      0
104
+/* Define this to 1 if you want to declare interrupt-in endpoints, but don't
105
+ * want to send any data over them. If this macro is defined to 1, functions
106
+ * usbSetInterrupt() and usbSetInterrupt3() are omitted. This is useful if
107
+ * you need the interrupt-in endpoints in order to comply to an interface
108
+ * (e.g. HID), but never want to send any data. This option saves a couple
109
+ * of bytes in flash memory and the transmit buffers in RAM.
110
+ */
111
+#define USB_CFG_INTR_POLL_INTERVAL      10
112
+/* If you compile a version with endpoint 1 (interrupt-in), this is the poll
113
+ * interval. The value is in milliseconds and must not be less than 10 ms for
114
+ * low speed devices.
115
+ */
116
+#define USB_CFG_IS_SELF_POWERED         0
117
+/* Define this to 1 if the device has its own power supply. Set it to 0 if the
118
+ * device is powered from the USB bus.
119
+ */
120
+#define USB_CFG_MAX_BUS_POWER           100
121
+/* Set this variable to the maximum USB bus power consumption of your device.
122
+ * The value is in milliamperes. [It will be divided by two since USB
123
+ * communicates power requirements in units of 2 mA.]
124
+ */
125
+#define USB_CFG_IMPLEMENT_FN_WRITE      0
126
+/* Set this to 1 if you want usbFunctionWrite() to be called for control-out
127
+ * transfers. Set it to 0 if you don't need it and want to save a couple of
128
+ * bytes.
129
+ */
130
+#define USB_CFG_IMPLEMENT_FN_READ       0
131
+/* Set this to 1 if you need to send control replies which are generated
132
+ * "on the fly" when usbFunctionRead() is called. If you only want to send
133
+ * data from a static buffer, set it to 0 and return the data from
134
+ * usbFunctionSetup(). This saves a couple of bytes.
135
+ */
136
+#define USB_CFG_IMPLEMENT_FN_WRITEOUT   0
137
+/* Define this to 1 if you want to use interrupt-out (or bulk out) endpoints.
138
+ * You must implement the function usbFunctionWriteOut() which receives all
139
+ * interrupt/bulk data sent to any endpoint other than 0. The endpoint number
140
+ * can be found in 'usbRxToken'.
141
+ */
142
+#define USB_CFG_HAVE_FLOWCONTROL        0
143
+/* Define this to 1 if you want flowcontrol over USB data. See the definition
144
+ * of the macros usbDisableAllRequests() and usbEnableAllRequests() in
145
+ * usbdrv.h.
146
+ */
147
+#define USB_CFG_LONG_TRANSFERS          0
148
+/* Define this to 1 if you want to send/receive blocks of more than 254 bytes
149
+ * in a single control-in or control-out transfer. Note that the capability
150
+ * for long transfers increases the driver size.
151
+ */
152
+/* #define USB_RX_USER_HOOK(data, len)     if(usbRxToken == (uchar)USBPID_SETUP) blinkLED(); */
153
+/* This macro is a hook if you want to do unconventional things. If it is
154
+ * defined, it's inserted at the beginning of received message processing.
155
+ * If you eat the received message and don't want default processing to
156
+ * proceed, do a return after doing your things. One possible application
157
+ * (besides debugging) is to flash a status LED on each packet.
158
+ */
159
+/* #define USB_RESET_HOOK(resetStarts)     if(!resetStarts){hadUsbReset();} */
160
+/* This macro is a hook if you need to know when an USB RESET occurs. It has
161
+ * one parameter which distinguishes between the start of RESET state and its
162
+ * end.
163
+ */
164
+/* #define USB_SET_ADDRESS_HOOK()              hadAddressAssigned(); */
165
+/* This macro (if defined) is executed when a USB SET_ADDRESS request was
166
+ * received.
167
+ */
168
+#define USB_COUNT_SOF                   0
169
+/* define this macro to 1 if you need the global variable "usbSofCount" which
170
+ * counts SOF packets. This feature requires that the hardware interrupt is
171
+ * connected to D- instead of D+.
172
+ */
173
+/* #ifdef __ASSEMBLER__
174
+ * macro myAssemblerMacro
175
+ *     in      YL, TCNT0
176
+ *     sts     timer0Snapshot, YL
177
+ *     endm
178
+ * #endif
179
+ * #define USB_SOF_HOOK                    myAssemblerMacro
180
+ * This macro (if defined) is executed in the assembler module when a
181
+ * Start Of Frame condition is detected. It is recommended to define it to
182
+ * the name of an assembler macro which is defined here as well so that more
183
+ * than one assembler instruction can be used. The macro may use the register
184
+ * YL and modify SREG. If it lasts longer than a couple of cycles, USB messages
185
+ * immediately after an SOF pulse may be lost and must be retried by the host.
186
+ * What can you do with this hook? Since the SOF signal occurs exactly every
187
+ * 1 ms (unless the host is in sleep mode), you can use it to tune OSCCAL in
188
+ * designs running on the internal RC oscillator.
189
+ * Please note that Start Of Frame detection works only if D- is wired to the
190
+ * interrupt, not D+. THIS IS DIFFERENT THAN MOST EXAMPLES!
191
+ */
192
+#define USB_CFG_CHECK_DATA_TOGGLING     0
193
+/* define this macro to 1 if you want to filter out duplicate data packets
194
+ * sent by the host. Duplicates occur only as a consequence of communication
195
+ * errors, when the host does not receive an ACK. Please note that you need to
196
+ * implement the filtering yourself in usbFunctionWriteOut() and
197
+ * usbFunctionWrite(). Use the global usbCurrentDataToken and a static variable
198
+ * for each control- and out-endpoint to check for duplicate packets.
199
+ */
200
+#define USB_CFG_HAVE_MEASURE_FRAME_LENGTH   0
201
+/* define this macro to 1 if you want the function usbMeasureFrameLength()
202
+ * compiled in. This function can be used to calibrate the AVR's RC oscillator.
203
+ */
204
+#define USB_USE_FAST_CRC                0
205
+/* The assembler module has two implementations for the CRC algorithm. One is
206
+ * faster, the other is smaller. This CRC routine is only used for transmitted
207
+ * messages where timing is not critical. The faster routine needs 31 cycles
208
+ * per byte while the smaller one needs 61 to 69 cycles. The faster routine
209
+ * may be worth the 32 bytes bigger code size if you transmit lots of data and
210
+ * run the AVR close to its limit.
211
+ */
212
+
213
+/* -------------------------- Device Description --------------------------- */
214
+
215
+#define  USB_CFG_VENDOR_ID       0xc0, 0x16 /* = 0x16c0 = 5824 = voti.nl */
216
+/* USB vendor ID for the device, low byte first. If you have registered your
217
+ * own Vendor ID, define it here. Otherwise you may use one of obdev's free
218
+ * shared VID/PID pairs. Be sure to read USB-IDs-for-free.txt for rules!
219
+ * *** IMPORTANT NOTE ***
220
+ * This template uses obdev's shared VID/PID pair for Vendor Class devices
221
+ * with libusb: 0x16c0/0x5dc.  Use this VID/PID pair ONLY if you understand
222
+ * the implications!
223
+ */
224
+#define  USB_CFG_DEVICE_ID       0xdc, 0x05 /* = 0x05dc = 1500 */
225
+/* This is the ID of the product, low byte first. It is interpreted in the
226
+ * scope of the vendor ID. If you have registered your own VID with usb.org
227
+ * or if you have licensed a PID from somebody else, define it here. Otherwise
228
+ * you may use one of obdev's free shared VID/PID pairs. See the file
229
+ * USB-IDs-for-free.txt for details!
230
+ * *** IMPORTANT NOTE ***
231
+ * This template uses obdev's shared VID/PID pair for Vendor Class devices
232
+ * with libusb: 0x16c0/0x5dc.  Use this VID/PID pair ONLY if you understand
233
+ * the implications!
234
+ */
235
+#define USB_CFG_DEVICE_VERSION  0x00, 0x01
236
+/* Version number of the device: Minor number first, then major number.
237
+ */
238
+#define USB_CFG_VENDOR_NAME     'o', 'b', 'd', 'e', 'v', '.', 'a', 't'
239
+#define USB_CFG_VENDOR_NAME_LEN 8
240
+/* These two values define the vendor name returned by the USB device. The name
241
+ * must be given as a list of characters under single quotes. The characters
242
+ * are interpreted as Unicode (UTF-16) entities.
243
+ * If you don't want a vendor name string, undefine these macros.
244
+ * ALWAYS define a vendor name containing your Internet domain name if you use
245
+ * obdev's free shared VID/PID pair. See the file USB-IDs-for-free.txt for
246
+ * details.
247
+ */
248
+#define USB_CFG_DEVICE_NAME     'T', 'e', 'm', 'p', 'l', 'a', 't', 'e'
249
+#define USB_CFG_DEVICE_NAME_LEN 8
250
+/* Same as above for the device name. If you don't want a device name, undefine
251
+ * the macros. See the file USB-IDs-for-free.txt before you assign a name if
252
+ * you use a shared VID/PID.
253
+ */
254
+/*#define USB_CFG_SERIAL_NUMBER   'N', 'o', 'n', 'e' */
255
+/*#define USB_CFG_SERIAL_NUMBER_LEN   0 */
256
+/* Same as above for the serial number. If you don't want a serial number,
257
+ * undefine the macros.
258
+ * It may be useful to provide the serial number through other means than at
259
+ * compile time. See the section about descriptor properties below for how
260
+ * to fine tune control over USB descriptors such as the string descriptor
261
+ * for the serial number.
262
+ */
263
+#define USB_CFG_DEVICE_CLASS        0xff    /* set to 0 if deferred to interface */
264
+#define USB_CFG_DEVICE_SUBCLASS     0
265
+/* See USB specification if you want to conform to an existing device class.
266
+ * Class 0xff is "vendor specific".
267
+ */
268
+#define USB_CFG_INTERFACE_CLASS     0   /* define class here if not at device level */
269
+#define USB_CFG_INTERFACE_SUBCLASS  0
270
+#define USB_CFG_INTERFACE_PROTOCOL  0
271
+/* See USB specification if you want to conform to an existing device class or
272
+ * protocol. The following classes must be set at interface level:
273
+ * HID class is 3, no subclass and protocol required (but may be useful!)
274
+ * CDC class is 2, use subclass 2 and protocol 1 for ACM
275
+ */
276
+/* #define USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH    42 */
277
+/* Define this to the length of the HID report descriptor, if you implement
278
+ * an HID device. Otherwise don't define it or define it to 0.
279
+ * If you use this define, you must add a PROGMEM character array named
280
+ * "usbHidReportDescriptor" to your code which contains the report descriptor.
281
+ * Don't forget to keep the array and this define in sync!
282
+ */
283
+
284
+/* #define USB_PUBLIC static */
285
+/* Use the define above if you #include usbdrv.c instead of linking against it.
286
+ * This technique saves a couple of bytes in flash memory.
287
+ */
288
+
289
+/* ------------------- Fine Control over USB Descriptors ------------------- */
290
+/* If you don't want to use the driver's default USB descriptors, you can
291
+ * provide our own. These can be provided as (1) fixed length static data in
292
+ * flash memory, (2) fixed length static data in RAM or (3) dynamically at
293
+ * runtime in the function usbFunctionDescriptor(). See usbdrv.h for more
294
+ * information about this function.
295
+ * Descriptor handling is configured through the descriptor's properties. If
296
+ * no properties are defined or if they are 0, the default descriptor is used.
297
+ * Possible properties are:
298
+ *   + USB_PROP_IS_DYNAMIC: The data for the descriptor should be fetched
299
+ *     at runtime via usbFunctionDescriptor(). If the usbMsgPtr mechanism is
300
+ *     used, the data is in FLASH by default. Add property USB_PROP_IS_RAM if
301
+ *     you want RAM pointers.
302
+ *   + USB_PROP_IS_RAM: The data returned by usbFunctionDescriptor() or found
303
+ *     in static memory is in RAM, not in flash memory.
304
+ *   + USB_PROP_LENGTH(len): If the data is in static memory (RAM or flash),
305
+ *     the driver must know the descriptor's length. The descriptor itself is
306
+ *     found at the address of a well known identifier (see below).
307
+ * List of static descriptor names (must be declared PROGMEM if in flash):
308
+ *   char usbDescriptorDevice[];
309
+ *   char usbDescriptorConfiguration[];
310
+ *   char usbDescriptorHidReport[];
311
+ *   char usbDescriptorString0[];
312
+ *   int usbDescriptorStringVendor[];
313
+ *   int usbDescriptorStringDevice[];
314
+ *   int usbDescriptorStringSerialNumber[];
315
+ * Other descriptors can't be provided statically, they must be provided
316
+ * dynamically at runtime.
317
+ *
318
+ * Descriptor properties are or-ed or added together, e.g.:
319
+ * #define USB_CFG_DESCR_PROPS_DEVICE   (USB_PROP_IS_RAM | USB_PROP_LENGTH(18))
320
+ *
321
+ * The following descriptors are defined:
322
+ *   USB_CFG_DESCR_PROPS_DEVICE
323
+ *   USB_CFG_DESCR_PROPS_CONFIGURATION
324
+ *   USB_CFG_DESCR_PROPS_STRINGS
325
+ *   USB_CFG_DESCR_PROPS_STRING_0
326
+ *   USB_CFG_DESCR_PROPS_STRING_VENDOR
327
+ *   USB_CFG_DESCR_PROPS_STRING_PRODUCT
328
+ *   USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
329
+ *   USB_CFG_DESCR_PROPS_HID
330
+ *   USB_CFG_DESCR_PROPS_HID_REPORT
331
+ *   USB_CFG_DESCR_PROPS_UNKNOWN (for all descriptors not handled by the driver)
332
+ *
333
+ * Note about string descriptors: String descriptors are not just strings, they
334
+ * are Unicode strings prefixed with a 2 byte header. Example:
335
+ * int  serialNumberDescriptor[] = {
336
+ *     USB_STRING_DESCRIPTOR_HEADER(6),
337
+ *     'S', 'e', 'r', 'i', 'a', 'l'
338
+ * };
339
+ */
340
+
341
+#define USB_CFG_DESCR_PROPS_DEVICE                  0
342
+#define USB_CFG_DESCR_PROPS_CONFIGURATION           0
343
+#define USB_CFG_DESCR_PROPS_STRINGS                 0
344
+#define USB_CFG_DESCR_PROPS_STRING_0                0
345
+#define USB_CFG_DESCR_PROPS_STRING_VENDOR           0
346
+#define USB_CFG_DESCR_PROPS_STRING_PRODUCT          0
347
+#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER    0
348
+#define USB_CFG_DESCR_PROPS_HID                     0
349
+#define USB_CFG_DESCR_PROPS_HID_REPORT              0
350
+#define USB_CFG_DESCR_PROPS_UNKNOWN                 0
351
+
352
+/* ----------------------- Optional MCU Description ------------------------ */
353
+
354
+/* The following configurations have working defaults in usbdrv.h. You
355
+ * usually don't need to set them explicitly. Only if you want to run
356
+ * the driver on a device which is not yet supported or with a compiler
357
+ * which is not fully supported (such as IAR C) or if you use a differnt
358
+ * interrupt than INT0, you may have to define some of these.
359
+ */
360
+/* #define USB_INTR_CFG            MCUCR */
361
+/* #define USB_INTR_CFG_SET        ((1 << ISC00) | (1 << ISC01)) */
362
+/* #define USB_INTR_CFG_CLR        0 */
363
+/* #define USB_INTR_ENABLE         GIMSK */
364
+/* #define USB_INTR_ENABLE_BIT     INT0 */
365
+/* #define USB_INTR_PENDING        GIFR */
366
+/* #define USB_INTR_PENDING_BIT    INTF0 */
367
+/* #define USB_INTR_VECTOR         SIG_INTERRUPT0 */
368
+
369
+#endif /* __usbconfig_h_included__ */

+ 371
- 0
usbconfig.h View File

@@ -0,0 +1,371 @@
1
+/* Name: usbconfig.h
2
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
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), GNU GPL v3 or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: usbconfig-prototype.h 767 2009-08-22 11:39:22Z 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 V-USB for USB D+ connected to Port D bit 2 (which is
18
+also hardware interrupt 0 on many devices) and USB D- to Port D bit 4. You may
19
+wire the lines to any other port, as long as D+ is also wired to INT0 (or any
20
+other hardware interrupt, as long as it is the highest level interrupt, see
21
+section at the end of this file).
22
++ To create your own usbconfig.h file, copy this file to your project's
23
++ firmware source directory) and rename it to "usbconfig.h".
24
++ Then edit it accordingly.
25
+*/
26
+
27
+/* ---------------------------- Hardware Config ---------------------------- */
28
+
29
+#define USB_CFG_IOPORTNAME      D
30
+/* This is the port where the USB bus is connected. When you configure it to
31
+ * "B", the registers PORTB, PINB and DDRB will be used.
32
+ */
33
+#define USB_CFG_DMINUS_BIT      4
34
+/* This is the bit number in USB_CFG_IOPORT where the USB D- line is connected.
35
+ * This may be any bit in the port.
36
+ */
37
+#define USB_CFG_DPLUS_BIT       2
38
+/* This is the bit number in USB_CFG_IOPORT where the USB D+ line is connected.
39
+ * This may be any bit in the port. Please note that D+ must also be connected
40
+ * to interrupt pin INT0! [You can also use other interrupts, see section
41
+ * "Optional MCU Description" below, or you can connect D- to the interrupt, as
42
+ * it is required if you use the USB_COUNT_SOF feature. If you use D- for the
43
+ * interrupt, the USB interrupt will also be triggered at Start-Of-Frame
44
+ * markers every millisecond.]
45
+ */
46
+#define USB_CFG_CLOCK_KHZ       (F_CPU/1000)
47
+/* Clock rate of the AVR in kHz. Legal values are 12000, 12800, 15000, 16000,
48
+ * 16500 and 20000. The 12.8 MHz and 16.5 MHz versions of the code require no
49
+ * crystal, they tolerate +/- 1% deviation from the nominal frequency. All
50
+ * other rates require a precision of 2000 ppm and thus a crystal!
51
+ * Default if not specified: 12 MHz
52
+ */
53
+#define USB_CFG_CHECK_CRC       0
54
+/* Define this to 1 if you want that the driver checks integrity of incoming
55
+ * data packets (CRC checks). CRC checks cost quite a bit of code size and are
56
+ * currently only available for 18 MHz crystal clock. You must choose
57
+ * USB_CFG_CLOCK_KHZ = 18000 if you enable this option.
58
+ */
59
+
60
+/* ----------------------- Optional Hardware Config ------------------------ */
61
+
62
+#define USB_CFG_PULLUP_IOPORTNAME   D
63
+/* If you connect the 1.5k pullup resistor from D- to a port pin instead of
64
+ * V+, you can connect and disconnect the device from firmware by calling
65
+ * the macros usbDeviceConnect() and usbDeviceDisconnect() (see usbdrv.h).
66
+ * This constant defines the port on which the pullup resistor is connected.
67
+ */
68
+#define USB_CFG_PULLUP_BIT          5
69
+/* This constant defines the bit number in USB_CFG_PULLUP_IOPORT (defined
70
+ * above) where the 1.5k pullup resistor is connected. See description
71
+ * above for details.
72
+ */
73
+
74
+/* --------------------------- Functional Range ---------------------------- */
75
+
76
+#define USB_CFG_HAVE_INTRIN_ENDPOINT    1
77
+/* Define this to 1 if you want to compile a version with two endpoints: The
78
+ * default control endpoint 0 and an interrupt-in endpoint (any other endpoint
79
+ * number).
80
+ */
81
+#define USB_CFG_HAVE_INTRIN_ENDPOINT3   0
82
+/* Define this to 1 if you want to compile a version with three endpoints: The
83
+ * default control endpoint 0, an interrupt-in endpoint 3 (or the number
84
+ * configured below) and a catch-all default interrupt-in endpoint as above.
85
+ * You must also define USB_CFG_HAVE_INTRIN_ENDPOINT to 1 for this feature.
86
+ */
87
+#define USB_CFG_EP3_NUMBER              3
88
+/* If the so-called endpoint 3 is used, it can now be configured to any other
89
+ * endpoint number (except 0) with this macro. Default if undefined is 3.
90
+ */
91
+/* #define USB_INITIAL_DATATOKEN           USBPID_DATA1 */
92
+/* The above macro defines the startup condition for data toggling on the
93
+ * interrupt/bulk endpoints 1 and 3. Defaults to USBPID_DATA1.
94
+ * Since the token is toggled BEFORE sending any data, the first packet is
95
+ * sent with the oposite value of this configuration!
96
+ */
97
+#define USB_CFG_IMPLEMENT_HALT          0
98
+/* Define this to 1 if you also want to implement the ENDPOINT_HALT feature
99
+ * for endpoint 1 (interrupt endpoint). Although you may not need this feature,
100
+ * it is required by the standard. We have made it a config option because it
101
+ * bloats the code considerably.
102
+ */
103
+#define USB_CFG_SUPPRESS_INTR_CODE      0
104
+/* Define this to 1 if you want to declare interrupt-in endpoints, but don't
105
+ * want to send any data over them. If this macro is defined to 1, functions
106
+ * usbSetInterrupt() and usbSetInterrupt3() are omitted. This is useful if
107
+ * you need the interrupt-in endpoints in order to comply to an interface
108
+ * (e.g. HID), but never want to send any data. This option saves a couple
109
+ * of bytes in flash memory and the transmit buffers in RAM.
110
+ */
111
+#define USB_CFG_INTR_POLL_INTERVAL      10
112
+/* If you compile a version with endpoint 1 (interrupt-in), this is the poll
113
+ * interval. The value is in milliseconds and must not be less than 10 ms for
114
+ * low speed devices.
115
+ */
116
+#define USB_CFG_IS_SELF_POWERED         0
117
+/* Define this to 1 if the device has its own power supply. Set it to 0 if the
118
+ * device is powered from the USB bus.
119
+ */
120
+#define USB_CFG_MAX_BUS_POWER           100
121
+/* Set this variable to the maximum USB bus power consumption of your device.
122
+ * The value is in milliamperes. [It will be divided by two since USB
123
+ * communicates power requirements in units of 2 mA.]
124
+ */
125
+#define USB_CFG_IMPLEMENT_FN_WRITE      0
126
+/* Set this to 1 if you want usbFunctionWrite() to be called for control-out
127
+ * transfers. Set it to 0 if you don't need it and want to save a couple of
128
+ * bytes.
129
+ */
130
+#define USB_CFG_IMPLEMENT_FN_READ       0
131
+/* Set this to 1 if you need to send control replies which are generated
132
+ * "on the fly" when usbFunctionRead() is called. If you only want to send
133
+ * data from a static buffer, set it to 0 and return the data from
134
+ * usbFunctionSetup(). This saves a couple of bytes.
135
+ */
136
+#define USB_CFG_IMPLEMENT_FN_WRITEOUT   0
137
+/* Define this to 1 if you want to use interrupt-out (or bulk out) endpoints.
138
+ * You must implement the function usbFunctionWriteOut() which receives all
139
+ * interrupt/bulk data sent to any endpoint other than 0. The endpoint number
140
+ * can be found in 'usbRxToken'.
141
+ */
142
+#define USB_CFG_HAVE_FLOWCONTROL        0
143
+/* Define this to 1 if you want flowcontrol over USB data. See the definition
144
+ * of the macros usbDisableAllRequests() and usbEnableAllRequests() in
145
+ * usbdrv.h.
146
+ */
147
+#define USB_CFG_LONG_TRANSFERS          0
148
+/* Define this to 1 if you want to send/receive blocks of more than 254 bytes
149
+ * in a single control-in or control-out transfer. Note that the capability
150
+ * for long transfers increases the driver size.
151
+ */
152
+/* #define USB_RX_USER_HOOK(data, len)     if(usbRxToken == (uchar)USBPID_SETUP) blinkLED(); */
153
+/* This macro is a hook if you want to do unconventional things. If it is
154
+ * defined, it's inserted at the beginning of received message processing.
155
+ * If you eat the received message and don't want default processing to
156
+ * proceed, do a return after doing your things. One possible application
157
+ * (besides debugging) is to flash a status LED on each packet.
158
+ */
159
+/* #define USB_RESET_HOOK(resetStarts)     if(!resetStarts){hadUsbReset();} */
160
+/* This macro is a hook if you need to know when an USB RESET occurs. It has
161
+ * one parameter which distinguishes between the start of RESET state and its
162
+ * end.
163
+ */
164
+/* #define USB_SET_ADDRESS_HOOK()              hadAddressAssigned(); */
165
+/* This macro (if defined) is executed when a USB SET_ADDRESS request was
166
+ * received.
167
+ */
168
+#define USB_COUNT_SOF                   0
169
+/* define this macro to 1 if you need the global variable "usbSofCount" which
170
+ * counts SOF packets. This feature requires that the hardware interrupt is
171
+ * connected to D- instead of D+.
172
+ */
173
+/* #ifdef __ASSEMBLER__
174
+ * macro myAssemblerMacro
175
+ *     in      YL, TCNT0
176
+ *     sts     timer0Snapshot, YL
177
+ *     endm
178
+ * #endif
179
+ * #define USB_SOF_HOOK                    myAssemblerMacro
180
+ * This macro (if defined) is executed in the assembler module when a
181
+ * Start Of Frame condition is detected. It is recommended to define it to
182
+ * the name of an assembler macro which is defined here as well so that more
183
+ * than one assembler instruction can be used. The macro may use the register
184
+ * YL and modify SREG. If it lasts longer than a couple of cycles, USB messages
185
+ * immediately after an SOF pulse may be lost and must be retried by the host.
186
+ * What can you do with this hook? Since the SOF signal occurs exactly every
187
+ * 1 ms (unless the host is in sleep mode), you can use it to tune OSCCAL in
188
+ * designs running on the internal RC oscillator.
189
+ * Please note that Start Of Frame detection works only if D- is wired to the
190
+ * interrupt, not D+. THIS IS DIFFERENT THAN MOST EXAMPLES!
191
+ */
192
+#define USB_CFG_CHECK_DATA_TOGGLING     0
193
+/* define this macro to 1 if you want to filter out duplicate data packets
194
+ * sent by the host. Duplicates occur only as a consequence of communication
195
+ * errors, when the host does not receive an ACK. Please note that you need to
196
+ * implement the filtering yourself in usbFunctionWriteOut() and
197
+ * usbFunctionWrite(). Use the global usbCurrentDataToken and a static variable
198
+ * for each control- and out-endpoint to check for duplicate packets.
199
+ */
200
+#define USB_CFG_HAVE_MEASURE_FRAME_LENGTH   0
201
+/* define this macro to 1 if you want the function usbMeasureFrameLength()
202
+ * compiled in. This function can be used to calibrate the AVR's RC oscillator.
203
+ */
204
+#define USB_USE_FAST_CRC                0
205
+/* The assembler module has two implementations for the CRC algorithm. One is
206
+ * faster, the other is smaller. This CRC routine is only used for transmitted
207
+ * messages where timing is not critical. The faster routine needs 31 cycles
208
+ * per byte while the smaller one needs 61 to 69 cycles. The faster routine
209
+ * may be worth the 32 bytes bigger code size if you transmit lots of data and
210
+ * run the AVR close to its limit.
211
+ */
212
+
213
+/* -------------------------- Device Description --------------------------- */
214
+
215
+#define  USB_CFG_VENDOR_ID       0x42, 0x42
216
+/* USB vendor ID for the device, low byte first. If you have registered your
217
+ * own Vendor ID, define it here. Otherwise you may use one of obdev's free
218
+ * shared VID/PID pairs. Be sure to read USB-IDs-for-free.txt for rules!
219
+ * *** IMPORTANT NOTE ***
220
+ * This template uses obdev's shared VID/PID pair for Vendor Class devices
221
+ * with libusb: 0x16c0/0x5dc.  Use this VID/PID pair ONLY if you understand
222
+ * the implications!
223
+ */
224
+#define  USB_CFG_DEVICE_ID       0x31, 0xe1
225
+/* This is the ID of the product, low byte first. It is interpreted in the
226
+ * scope of the vendor ID. If you have registered your own VID with usb.org
227
+ * or if you have licensed a PID from somebody else, define it here. Otherwise
228
+ * you may use one of obdev's free shared VID/PID pairs. See the file
229
+ * USB-IDs-for-free.txt for details!
230
+ * *** IMPORTANT NOTE ***
231
+ * This template uses obdev's shared VID/PID pair for Vendor Class devices
232
+ * with libusb: 0x16c0/0x5dc.  Use this VID/PID pair ONLY if you understand
233
+ * the implications!
234
+ */
235
+#define USB_CFG_DEVICE_VERSION  0x00, 0x01
236
+/* Version number of the device: Minor number first, then major number.
237
+ */
238
+#define USB_CFG_VENDOR_NAME     'r','t','h','o','n','i','.','c','o','m'
239
+#define USB_CFG_VENDOR_NAME_LEN 10
240
+/* These two values define the vendor name returned by the USB device. The name
241
+ * must be given as a list of characters under single quotes. The characters
242
+ * are interpreted as Unicode (UTF-16) entities.
243
+ * If you don't want a vendor name string, undefine these macros.
244
+ * ALWAYS define a vendor name containing your Internet domain name if you use
245
+ * obdev's free shared VID/PID pair. See the file USB-IDs-for-free.txt for
246
+ * details.
247
+ */
248
+#define USB_CFG_DEVICE_NAME     'R','o','b','l','o','w','c','h','o','n'
249
+#define USB_CFG_DEVICE_NAME_LEN 10
250
+/* Same as above for the device name. If you don't want a device name, undefine
251
+ * the macros. See the file USB-IDs-for-free.txt before you assign a name if
252
+ * you use a shared VID/PID.
253
+ */
254
+/*#define USB_CFG_SERIAL_NUMBER   'N', 'o', 'n', 'e' */
255
+/*#define USB_CFG_SERIAL_NUMBER_LEN   0 */
256
+/* Same as above for the serial number. If you don't want a serial number,
257
+ * undefine the macros.
258
+ * It may be useful to provide the serial number through other means than at
259
+ * compile time. See the section about descriptor properties below for how
260
+ * to fine tune control over USB descriptors such as the string descriptor
261
+ * for the serial number.
262
+ */
263
+#define USB_CFG_DEVICE_CLASS        0    /* set to 0 if deferred to interface */
264
+#define USB_CFG_DEVICE_SUBCLASS     0
265
+/* See USB specification if you want to conform to an existing device class.
266
+ * Class 0xff is "vendor specific".
267
+ */
268
+#define USB_CFG_INTERFACE_CLASS     0x03  /* HID */ /* define class here if not at device level */
269
+#define USB_CFG_INTERFACE_SUBCLASS  0
270
+#define USB_CFG_INTERFACE_PROTOCOL  0
271
+/* See USB specification if you want to conform to an existing device class or
272
+ * protocol. The following classes must be set at interface level:
273
+ * HID class is 3, no subclass and protocol required (but may be useful!)
274
+ * CDC class is 2, use subclass 2 and protocol 1 for ACM
275
+ */
276
+#define USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH    35
277
+/* Define this to the length of the HID report descriptor, if you implement
278
+ * an HID device. Otherwise don't define it or define it to 0.
279
+ * If you use this define, you must add a PROGMEM character array named
280
+ * "usbHidReportDescriptor" to your code which contains the report descriptor.
281
+ * Don't forget to keep the array and this define in sync!
282
+ */
283
+
284
+/* #define USB_PUBLIC static */
285
+/* Use the define above if you #include usbdrv.c instead of linking against it.
286
+ * This technique saves a couple of bytes in flash memory.
287
+ */
288
+
289
+/* ------------------- Fine Control over USB Descriptors ------------------- */
290
+/* If you don't want to use the driver's default USB descriptors, you can
291
+ * provide our own. These can be provided as (1) fixed length static data in
292
+ * flash memory, (2) fixed length static data in RAM or (3) dynamically at
293
+ * runtime in the function usbFunctionDescriptor(). See usbdrv.h for more
294
+ * information about this function.
295
+ * Descriptor handling is configured through the descriptor's properties. If
296
+ * no properties are defined or if they are 0, the default descriptor is used.
297
+ * Possible properties are:
298
+ *   + USB_PROP_IS_DYNAMIC: The data for the descriptor should be fetched
299
+ *     at runtime via usbFunctionDescriptor(). If the usbMsgPtr mechanism is
300
+ *     used, the data is in FLASH by default. Add property USB_PROP_IS_RAM if
301
+ *     you want RAM pointers.
302
+ *   + USB_PROP_IS_RAM: The data returned by usbFunctionDescriptor() or found
303
+ *     in static memory is in RAM, not in flash memory.
304
+ *   + USB_PROP_LENGTH(len): If the data is in static memory (RAM or flash),
305
+ *     the driver must know the descriptor's length. The descriptor itself is
306
+ *     found at the address of a well known identifier (see below).
307
+ * List of static descriptor names (must be declared PROGMEM if in flash):
308
+ *   char usbDescriptorDevice[];
309
+ *   char usbDescriptorConfiguration[];
310
+ *   char usbDescriptorHidReport[];
311
+ *   char usbDescriptorString0[];
312
+ *   int usbDescriptorStringVendor[];
313
+ *   int usbDescriptorStringDevice[];
314
+ *   int usbDescriptorStringSerialNumber[];
315
+ * Other descriptors can't be provided statically, they must be provided
316
+ * dynamically at runtime.
317
+ *
318
+ * Descriptor properties are or-ed or added together, e.g.:
319
+ * #define USB_CFG_DESCR_PROPS_DEVICE   (USB_PROP_IS_RAM | USB_PROP_LENGTH(18))
320
+ *
321
+ * The following descriptors are defined:
322
+ *   USB_CFG_DESCR_PROPS_DEVICE
323
+ *   USB_CFG_DESCR_PROPS_CONFIGURATION
324
+ *   USB_CFG_DESCR_PROPS_STRINGS
325
+ *   USB_CFG_DESCR_PROPS_STRING_0
326
+ *   USB_CFG_DESCR_PROPS_STRING_VENDOR
327
+ *   USB_CFG_DESCR_PROPS_STRING_PRODUCT
328
+ *   USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
329
+ *   USB_CFG_DESCR_PROPS_HID
330
+ *   USB_CFG_DESCR_PROPS_HID_REPORT
331
+ *   USB_CFG_DESCR_PROPS_UNKNOWN (for all descriptors not handled by the driver)
332
+ *
333
+ * Note about string descriptors: String descriptors are not just strings, they
334
+ * are Unicode strings prefixed with a 2 byte header. Example:
335
+ * int  serialNumberDescriptor[] = {
336
+ *     USB_STRING_DESCRIPTOR_HEADER(6),
337
+ *     'S', 'e', 'r', 'i', 'a', 'l'
338
+ * };
339
+ */
340
+
341
+#define USB_CFG_DESCR_PROPS_DEVICE                  0
342
+#define USB_CFG_DESCR_PROPS_CONFIGURATION           0
343
+#define USB_CFG_DESCR_PROPS_STRINGS                 0
344
+#define USB_CFG_DESCR_PROPS_STRING_0                0
345
+#define USB_CFG_DESCR_PROPS_STRING_VENDOR           0
346
+#define USB_CFG_DESCR_PROPS_STRING_PRODUCT          0
347
+#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER    0
348
+#define USB_CFG_DESCR_PROPS_HID                     0
349
+#define USB_CFG_DESCR_PROPS_HID_REPORT              0
350
+#define USB_CFG_DESCR_PROPS_UNKNOWN                 0
351
+
352
+/* ----------------------- Optional MCU Description ------------------------ */
353
+
354
+/* The following configurations have working defaults in usbdrv.h. You
355
+ * usually don't need to set them explicitly. Only if you want to run
356
+ * the driver on a device which is not yet supported or with a compiler
357
+ * which is not fully supported (such as IAR C) or if you use a differnt
358
+ * interrupt than INT0, you may have to define some of these.
359
+ */
360
+/* #define USB_INTR_CFG            MCUCR */
361
+/* #define USB_INTR_CFG_SET        ((1 << ISC00) | (1 << ISC01)) */
362
+/* #define USB_INTR_CFG_CLR        0 */
363
+/* #define USB_INTR_ENABLE         GIMSK */
364
+/* #define USB_INTR_ENABLE_BIT     INT0 */
365
+/* #define USB_INTR_PENDING        GIFR */
366
+/* #define USB_INTR_PENDING_BIT    INTF0 */
367
+/* #define USB_INTR_VECTOR         SIG_INTERRUPT0 */
368
+
369
+#define USB_INTR_VECTOR INT0_vect
370
+
371
+#endif /* __usbconfig_h_included__ */

+ 625
- 0
usbdrv.c View File

@@ -0,0 +1,625 @@
1
+/* Name: usbdrv.c
2
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
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), GNU GPL v3 or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: usbdrv.c 763 2009-08-22 10:27:24Z cs $
9
+ */
10
+
11
+#include "usbportability.h"
12
+#include "usbdrv.h"
13
+#include "oddebug.h"
14
+
15
+/*
16
+General Description:
17
+This module implements the C-part of the USB driver. See usbdrv.h for a
18
+documentation of the entire driver.
19
+*/
20
+
21
+/* ------------------------------------------------------------------------- */
22
+
23
+/* raw USB registers / interface to assembler code: */
24
+uchar usbRxBuf[2*USB_BUFSIZE];  /* raw RX buffer: PID, 8 bytes data, 2 bytes CRC */
25
+uchar       usbInputBufOffset;  /* offset in usbRxBuf used for low level receiving */
26
+uchar       usbDeviceAddr;      /* assigned during enumeration, defaults to 0 */
27
+uchar       usbNewDeviceAddr;   /* device ID which should be set after status phase */
28
+uchar       usbConfiguration;   /* currently selected configuration. Administered by driver, but not used */
29
+volatile schar usbRxLen;        /* = 0; number of bytes in usbRxBuf; 0 means free, -1 for flow control */
30
+uchar       usbCurrentTok;      /* last token received or endpoint number for last OUT token if != 0 */
31
+uchar       usbRxToken;         /* token for data we received; or endpont number for last OUT */
32
+volatile uchar usbTxLen = USBPID_NAK;   /* number of bytes to transmit with next IN token or handshake token */
33
+uchar       usbTxBuf[USB_BUFSIZE];/* data to transmit with next IN, free if usbTxLen contains handshake token */
34
+#if USB_COUNT_SOF
35
+volatile uchar  usbSofCount;    /* incremented by assembler module every SOF */
36
+#endif
37
+#if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
38
+usbTxStatus_t  usbTxStatus1;
39
+#   if USB_CFG_HAVE_INTRIN_ENDPOINT3
40
+usbTxStatus_t  usbTxStatus3;
41
+#   endif
42
+#endif
43
+#if USB_CFG_CHECK_DATA_TOGGLING
44
+uchar       usbCurrentDataToken;/* when we check data toggling to ignore duplicate packets */
45
+#endif
46
+
47
+/* USB status registers / not shared with asm code */
48
+uchar               *usbMsgPtr;     /* data to transmit next -- ROM or RAM address */
49
+static usbMsgLen_t  usbMsgLen = USB_NO_MSG; /* remaining number of bytes */
50
+static uchar        usbMsgFlags;    /* flag values see below */
51
+
52
+#define USB_FLG_MSGPTR_IS_ROM   (1<<6)
53
+#define USB_FLG_USE_USER_RW     (1<<7)
54
+
55
+/*
56
+optimizing hints:
57
+- do not post/pre inc/dec integer values in operations
58
+- assign value of USB_READ_FLASH() to register variables and don't use side effects in arg
59
+- use narrow scope for variables which should be in X/Y/Z register
60
+- assign char sized expressions to variables to force 8 bit arithmetics
61
+*/
62
+
63
+/* -------------------------- String Descriptors --------------------------- */
64
+
65
+#if USB_CFG_DESCR_PROPS_STRINGS == 0
66
+
67
+#if USB_CFG_DESCR_PROPS_STRING_0 == 0
68
+#undef USB_CFG_DESCR_PROPS_STRING_0
69
+#define USB_CFG_DESCR_PROPS_STRING_0    sizeof(usbDescriptorString0)
70
+PROGMEM char usbDescriptorString0[] = { /* language descriptor */
71
+    4,          /* sizeof(usbDescriptorString0): length of descriptor in bytes */
72
+    3,          /* descriptor type */
73
+    0x09, 0x04, /* language index (0x0409 = US-English) */
74
+};
75
+#endif
76
+
77
+#if USB_CFG_DESCR_PROPS_STRING_VENDOR == 0 && USB_CFG_VENDOR_NAME_LEN
78
+#undef USB_CFG_DESCR_PROPS_STRING_VENDOR
79
+#define USB_CFG_DESCR_PROPS_STRING_VENDOR   sizeof(usbDescriptorStringVendor)
80
+PROGMEM int  usbDescriptorStringVendor[] = {
81
+    USB_STRING_DESCRIPTOR_HEADER(USB_CFG_VENDOR_NAME_LEN),
82
+    USB_CFG_VENDOR_NAME
83
+};
84
+#endif
85
+
86
+#if USB_CFG_DESCR_PROPS_STRING_PRODUCT == 0 && USB_CFG_DEVICE_NAME_LEN
87
+#undef USB_CFG_DESCR_PROPS_STRING_PRODUCT
88
+#define USB_CFG_DESCR_PROPS_STRING_PRODUCT   sizeof(usbDescriptorStringDevice)
89
+PROGMEM int  usbDescriptorStringDevice[] = {
90
+    USB_STRING_DESCRIPTOR_HEADER(USB_CFG_DEVICE_NAME_LEN),
91
+    USB_CFG_DEVICE_NAME
92
+};
93
+#endif
94
+
95
+#if USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER == 0 && USB_CFG_SERIAL_NUMBER_LEN
96
+#undef USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
97
+#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER    sizeof(usbDescriptorStringSerialNumber)
98
+PROGMEM int usbDescriptorStringSerialNumber[] = {
99
+    USB_STRING_DESCRIPTOR_HEADER(USB_CFG_SERIAL_NUMBER_LEN),
100
+    USB_CFG_SERIAL_NUMBER
101
+};
102
+#endif
103
+
104
+#endif  /* USB_CFG_DESCR_PROPS_STRINGS == 0 */
105
+
106
+/* --------------------------- Device Descriptor --------------------------- */
107
+
108
+#if USB_CFG_DESCR_PROPS_DEVICE == 0
109
+#undef USB_CFG_DESCR_PROPS_DEVICE
110
+#define USB_CFG_DESCR_PROPS_DEVICE  sizeof(usbDescriptorDevice)
111
+PROGMEM char usbDescriptorDevice[] = {    /* USB device descriptor */
112
+    18,         /* sizeof(usbDescriptorDevice): length of descriptor in bytes */
113
+    USBDESCR_DEVICE,        /* descriptor type */
114
+    0x10, 0x01,             /* USB version supported */
115
+    USB_CFG_DEVICE_CLASS,
116
+    USB_CFG_DEVICE_SUBCLASS,
117
+    0,                      /* protocol */
118
+    8,                      /* max packet size */
119
+    /* the following two casts affect the first byte of the constant only, but
120
+     * that's sufficient to avoid a warning with the default values.
121
+     */
122
+    (char)USB_CFG_VENDOR_ID,/* 2 bytes */
123
+    (char)USB_CFG_DEVICE_ID,/* 2 bytes */
124
+    USB_CFG_DEVICE_VERSION, /* 2 bytes */
125
+    USB_CFG_DESCR_PROPS_STRING_VENDOR != 0 ? 1 : 0,         /* manufacturer string index */
126
+    USB_CFG_DESCR_PROPS_STRING_PRODUCT != 0 ? 2 : 0,        /* product string index */
127
+    USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER != 0 ? 3 : 0,  /* serial number string index */
128
+    1,          /* number of configurations */
129
+};
130
+#endif
131
+
132
+/* ----------------------- Configuration Descriptor ------------------------ */
133
+
134
+#if USB_CFG_DESCR_PROPS_HID_REPORT != 0 && USB_CFG_DESCR_PROPS_HID == 0
135
+#undef USB_CFG_DESCR_PROPS_HID
136
+#define USB_CFG_DESCR_PROPS_HID     9   /* length of HID descriptor in config descriptor below */
137
+#endif
138
+
139
+#if USB_CFG_DESCR_PROPS_CONFIGURATION == 0
140
+#undef USB_CFG_DESCR_PROPS_CONFIGURATION
141
+#define USB_CFG_DESCR_PROPS_CONFIGURATION   sizeof(usbDescriptorConfiguration)
142
+PROGMEM char usbDescriptorConfiguration[] = {    /* USB configuration descriptor */
143
+    9,          /* sizeof(usbDescriptorConfiguration): length of descriptor in bytes */
144
+    USBDESCR_CONFIG,    /* descriptor type */
145
+    18 + 7 * USB_CFG_HAVE_INTRIN_ENDPOINT + 7 * USB_CFG_HAVE_INTRIN_ENDPOINT3 +
146
+                (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
+    (1 << 7) | USBATTR_SELFPOWER,       /* attributes */
153
+#else
154
+    (1 << 7),                           /* 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 + USB_CFG_HAVE_INTRIN_ENDPOINT3, /* 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
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3   /* endpoint descriptor for endpoint 3 */
185
+    7,          /* sizeof(usbDescrEndpoint) */
186
+    USBDESCR_ENDPOINT,  /* descriptor type = endpoint */
187
+    (char)0x83, /* IN endpoint number 1 */
188
+    0x03,       /* attrib: Interrupt endpoint */
189
+    8, 0,       /* maximum packet size */
190
+    USB_CFG_INTR_POLL_INTERVAL, /* in ms */
191
+#endif
192
+};
193
+#endif
194
+
195
+/* ------------------------------------------------------------------------- */
196
+
197
+static inline void  usbResetDataToggling(void)
198
+{
199
+#if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
200
+    USB_SET_DATATOKEN1(USB_INITIAL_DATATOKEN);  /* reset data toggling for interrupt endpoint */
201
+#   if USB_CFG_HAVE_INTRIN_ENDPOINT3
202
+    USB_SET_DATATOKEN3(USB_INITIAL_DATATOKEN);  /* reset data toggling for interrupt endpoint */
203
+#   endif
204
+#endif
205
+}
206
+
207
+static inline void  usbResetStall(void)
208
+{
209
+#if USB_CFG_IMPLEMENT_HALT && USB_CFG_HAVE_INTRIN_ENDPOINT
210
+        usbTxLen1 = USBPID_NAK;
211
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
212
+        usbTxLen3 = USBPID_NAK;
213
+#endif
214
+#endif
215
+}
216
+
217
+/* ------------------------------------------------------------------------- */
218
+
219
+#if !USB_CFG_SUPPRESS_INTR_CODE
220
+#if USB_CFG_HAVE_INTRIN_ENDPOINT
221
+static void usbGenericSetInterrupt(uchar *data, uchar len, usbTxStatus_t *txStatus)
222
+{
223
+uchar   *p;
224
+char    i;
225
+
226
+#if USB_CFG_IMPLEMENT_HALT
227
+    if(usbTxLen1 == USBPID_STALL)
228
+        return;
229
+#endif
230
+    if(txStatus->len & 0x10){   /* packet buffer was empty */
231
+        txStatus->buffer[0] ^= USBPID_DATA0 ^ USBPID_DATA1; /* toggle token */
232
+    }else{
233
+        txStatus->len = USBPID_NAK; /* avoid sending outdated (overwritten) interrupt data */
234
+    }
235
+    p = txStatus->buffer + 1;
236
+    i = len;
237
+    do{                         /* if len == 0, we still copy 1 byte, but that's no problem */
238
+        *p++ = *data++;
239
+    }while(--i > 0);            /* loop control at the end is 2 bytes shorter than at beginning */
240
+    usbCrc16Append(&txStatus->buffer[1], len);
241
+    txStatus->len = len + 4;    /* len must be given including sync byte */
242
+    DBG2(0x21 + (((int)txStatus >> 3) & 3), txStatus->buffer, len + 3);
243
+}
244
+
245
+USB_PUBLIC void usbSetInterrupt(uchar *data, uchar len)
246
+{
247
+    usbGenericSetInterrupt(data, len, &usbTxStatus1);
248
+}
249
+#endif
250
+
251
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
252
+USB_PUBLIC void usbSetInterrupt3(uchar *data, uchar len)
253
+{
254
+    usbGenericSetInterrupt(data, len, &usbTxStatus3);
255
+}
256
+#endif
257
+#endif /* USB_CFG_SUPPRESS_INTR_CODE */
258
+
259
+/* ------------------ utilities for code following below ------------------- */
260
+
261
+/* Use defines for the switch statement so that we can choose between an
262
+ * if()else if() and a switch/case based implementation. switch() is more
263
+ * efficient for a LARGE set of sequential choices, if() is better in all other
264
+ * cases.
265
+ */
266
+#if USB_CFG_USE_SWITCH_STATEMENT
267
+#   define SWITCH_START(cmd)       switch(cmd){{
268
+#   define SWITCH_CASE(value)      }break; case (value):{
269
+#   define SWITCH_CASE2(v1,v2)     }break; case (v1): case(v2):{
270
+#   define SWITCH_CASE3(v1,v2,v3)  }break; case (v1): case(v2): case(v3):{
271
+#   define SWITCH_DEFAULT          }break; default:{
272
+#   define SWITCH_END              }}
273
+#else
274
+#   define SWITCH_START(cmd)       {uchar _cmd = cmd; if(0){
275
+#   define SWITCH_CASE(value)      }else if(_cmd == (value)){
276
+#   define SWITCH_CASE2(v1,v2)     }else if(_cmd == (v1) || _cmd == (v2)){
277
+#   define SWITCH_CASE3(v1,v2,v3)  }else if(_cmd == (v1) || _cmd == (v2) || (_cmd == v3)){
278
+#   define SWITCH_DEFAULT          }else{
279
+#   define SWITCH_END              }}
280
+#endif
281
+
282
+#ifndef USB_RX_USER_HOOK
283
+#define USB_RX_USER_HOOK(data, len)
284
+#endif
285
+#ifndef USB_SET_ADDRESS_HOOK
286
+#define USB_SET_ADDRESS_HOOK()
287
+#endif
288
+
289
+/* ------------------------------------------------------------------------- */
290
+
291
+/* We use if() instead of #if in the macro below because #if can't be used
292
+ * in macros and the compiler optimizes constant conditions anyway.
293
+ * This may cause problems with undefined symbols if compiled without
294
+ * optimizing!
295
+ */
296
+#define GET_DESCRIPTOR(cfgProp, staticName)         \
297
+    if(cfgProp){                                    \
298
+        if((cfgProp) & USB_PROP_IS_RAM)             \
299
+            flags = 0;                              \
300
+        if((cfgProp) & USB_PROP_IS_DYNAMIC){        \
301
+            len = usbFunctionDescriptor(rq);        \
302
+        }else{                                      \
303
+            len = USB_PROP_LENGTH(cfgProp);         \
304
+            usbMsgPtr = (uchar *)(staticName);      \
305
+        }                                           \
306
+    }
307
+
308
+/* usbDriverDescriptor() is similar to usbFunctionDescriptor(), but used
309
+ * internally for all types of descriptors.
310
+ */
311
+static inline usbMsgLen_t usbDriverDescriptor(usbRequest_t *rq)
312
+{
313
+usbMsgLen_t len = 0;
314
+uchar       flags = USB_FLG_MSGPTR_IS_ROM;
315
+
316
+    SWITCH_START(rq->wValue.bytes[1])
317
+    SWITCH_CASE(USBDESCR_DEVICE)    /* 1 */
318
+        GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_DEVICE, usbDescriptorDevice)
319
+    SWITCH_CASE(USBDESCR_CONFIG)    /* 2 */
320
+        GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_CONFIGURATION, usbDescriptorConfiguration)
321
+    SWITCH_CASE(USBDESCR_STRING)    /* 3 */
322
+#if USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC
323
+        if(USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_RAM)
324
+            flags = 0;
325
+        len = usbFunctionDescriptor(rq);
326
+#else   /* USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC */
327
+        SWITCH_START(rq->wValue.bytes[0])
328
+        SWITCH_CASE(0)
329
+            GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_0, usbDescriptorString0)
330
+        SWITCH_CASE(1)
331
+            GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_VENDOR, usbDescriptorStringVendor)
332
+        SWITCH_CASE(2)
333
+            GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_PRODUCT, usbDescriptorStringDevice)
334
+        SWITCH_CASE(3)
335
+            GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER, usbDescriptorStringSerialNumber)
336
+        SWITCH_DEFAULT
337
+            if(USB_CFG_DESCR_PROPS_UNKNOWN & USB_PROP_IS_DYNAMIC){
338
+                len = usbFunctionDescriptor(rq);
339
+            }
340
+        SWITCH_END
341
+#endif  /* USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC */
342
+#if USB_CFG_DESCR_PROPS_HID_REPORT  /* only support HID descriptors if enabled */
343
+    SWITCH_CASE(USBDESCR_HID)       /* 0x21 */
344
+        GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_HID, usbDescriptorConfiguration + 18)
345
+    SWITCH_CASE(USBDESCR_HID_REPORT)/* 0x22 */
346
+        GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_HID_REPORT, usbDescriptorHidReport)
347
+#endif
348
+    SWITCH_DEFAULT
349
+        if(USB_CFG_DESCR_PROPS_UNKNOWN & USB_PROP_IS_DYNAMIC){
350
+            len = usbFunctionDescriptor(rq);
351
+        }
352
+    SWITCH_END
353
+    usbMsgFlags = flags;
354
+    return len;
355
+}
356
+
357
+/* ------------------------------------------------------------------------- */
358
+
359
+/* usbDriverSetup() is similar to usbFunctionSetup(), but it's used for
360
+ * standard requests instead of class and custom requests.
361
+ */
362
+static inline usbMsgLen_t usbDriverSetup(usbRequest_t *rq)
363
+{
364
+uchar   len  = 0, *dataPtr = usbTxBuf + 9;  /* there are 2 bytes free space at the end of the buffer */
365
+uchar   value = rq->wValue.bytes[0];
366
+#if USB_CFG_IMPLEMENT_HALT
367
+uchar   index = rq->wIndex.bytes[0];
368
+#endif
369
+
370
+    dataPtr[0] = 0; /* default reply common to USBRQ_GET_STATUS and USBRQ_GET_INTERFACE */
371
+    SWITCH_START(rq->bRequest)
372
+    SWITCH_CASE(USBRQ_GET_STATUS)           /* 0 */
373
+        uchar recipient = rq->bmRequestType & USBRQ_RCPT_MASK;  /* assign arith ops to variables to enforce byte size */
374
+        if(USB_CFG_IS_SELF_POWERED && recipient == USBRQ_RCPT_DEVICE)
375
+            dataPtr[0] =  USB_CFG_IS_SELF_POWERED;
376
+#if USB_CFG_IMPLEMENT_HALT
377
+        if(recipient == USBRQ_RCPT_ENDPOINT && index == 0x81)   /* request status for endpoint 1 */
378
+            dataPtr[0] = usbTxLen1 == USBPID_STALL;
379
+#endif
380
+        dataPtr[1] = 0;
381
+        len = 2;
382
+#if USB_CFG_IMPLEMENT_HALT
383
+    SWITCH_CASE2(USBRQ_CLEAR_FEATURE, USBRQ_SET_FEATURE)    /* 1, 3 */
384
+        if(value == 0 && index == 0x81){    /* feature 0 == HALT for endpoint == 1 */
385
+            usbTxLen1 = rq->bRequest == USBRQ_CLEAR_FEATURE ? USBPID_NAK : USBPID_STALL;
386
+            usbResetDataToggling();
387
+        }
388
+#endif
389
+    SWITCH_CASE(USBRQ_SET_ADDRESS)          /* 5 */
390
+        usbNewDeviceAddr = value;
391
+        USB_SET_ADDRESS_HOOK();
392
+    SWITCH_CASE(USBRQ_GET_DESCRIPTOR)       /* 6 */
393
+        len = usbDriverDescriptor(rq);
394
+        goto skipMsgPtrAssignment;
395
+    SWITCH_CASE(USBRQ_GET_CONFIGURATION)    /* 8 */
396
+        dataPtr = &usbConfiguration;  /* send current configuration value */
397
+        len = 1;
398
+    SWITCH_CASE(USBRQ_SET_CONFIGURATION)    /* 9 */
399
+        usbConfiguration = value;
400
+        usbResetStall();
401
+    SWITCH_CASE(USBRQ_GET_INTERFACE)        /* 10 */
402
+        len = 1;
403
+#if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
404
+    SWITCH_CASE(USBRQ_SET_INTERFACE)        /* 11 */
405
+        usbResetDataToggling();
406
+        usbResetStall();
407
+#endif
408
+    SWITCH_DEFAULT                          /* 7=SET_DESCRIPTOR, 12=SYNC_FRAME */
409
+        /* Should we add an optional hook here? */
410
+    SWITCH_END
411
+    usbMsgPtr = dataPtr;
412
+skipMsgPtrAssignment:
413
+    return len;
414
+}
415
+
416
+/* ------------------------------------------------------------------------- */
417
+
418
+/* usbProcessRx() is called for every message received by the interrupt
419
+ * routine. It distinguishes between SETUP and DATA packets and processes
420
+ * them accordingly.
421
+ */
422
+static inline void usbProcessRx(uchar *data, uchar len)
423
+{
424
+  usbRequest_t    *rq = (usbRequest_t *)((void *)data);
425
+
426
+/* usbRxToken can be:
427
+ * 0x2d 00101101 (USBPID_SETUP for setup data)
428
+ * 0xe1 11100001 (USBPID_OUT: data phase of setup transfer)
429
+ * 0...0x0f for OUT on endpoint X
430
+ */
431
+    DBG2(0x10 + (usbRxToken & 0xf), data, len + 2); /* SETUP=1d, SETUP-DATA=11, OUTx=1x */
432
+    USB_RX_USER_HOOK(data, len)
433
+#if USB_CFG_IMPLEMENT_FN_WRITEOUT
434
+    if(usbRxToken < 0x10){  /* OUT to endpoint != 0: endpoint number in usbRxToken */
435
+        usbFunctionWriteOut(data, len);
436
+        return;
437
+    }
438
+#endif
439
+    if(usbRxToken == (uchar)USBPID_SETUP){
440
+        if(len != 8)    /* Setup size must be always 8 bytes. Ignore otherwise. */
441
+            return;
442
+        usbMsgLen_t replyLen;
443
+        usbTxBuf[0] = USBPID_DATA0;         /* initialize data toggling */
444
+        usbTxLen = USBPID_NAK;              /* abort pending transmit */
445
+        usbMsgFlags = 0;
446
+        uchar type = rq->bmRequestType & USBRQ_TYPE_MASK;
447
+        if(type != USBRQ_TYPE_STANDARD){    /* standard requests are handled by driver */
448
+            replyLen = usbFunctionSetup(data);
449
+        }else{
450
+            replyLen = usbDriverSetup(rq);
451
+        }
452
+#if USB_CFG_IMPLEMENT_FN_READ || USB_CFG_IMPLEMENT_FN_WRITE
453
+        if(replyLen == USB_NO_MSG){         /* use user-supplied read/write function */
454
+            /* do some conditioning on replyLen, but on IN transfers only */
455
+            if((rq->bmRequestType & USBRQ_DIR_MASK) != USBRQ_DIR_HOST_TO_DEVICE){
456
+                if(sizeof(replyLen) < sizeof(rq->wLength.word)){ /* help compiler with optimizing */
457
+                    replyLen = rq->wLength.bytes[0];
458
+                }else{
459
+                    replyLen = rq->wLength.word;
460
+                }
461
+            }
462
+            usbMsgFlags = USB_FLG_USE_USER_RW;
463
+        }else   /* The 'else' prevents that we limit a replyLen of USB_NO_MSG to the maximum transfer len. */
464
+#endif
465
+        if(sizeof(replyLen) < sizeof(rq->wLength.word)){ /* help compiler with optimizing */
466
+            if(!rq->wLength.bytes[1] && replyLen > rq->wLength.bytes[0])    /* limit length to max */
467
+                replyLen = rq->wLength.bytes[0];
468
+        }else{
469
+            if(replyLen > rq->wLength.word)     /* limit length to max */
470
+                replyLen = rq->wLength.word;
471
+        }
472
+        usbMsgLen = replyLen;
473
+    }else{  /* usbRxToken must be USBPID_OUT, which means data phase of setup (control-out) */
474
+#if USB_CFG_IMPLEMENT_FN_WRITE
475
+        if(usbMsgFlags & USB_FLG_USE_USER_RW){
476
+            uchar rval = usbFunctionWrite(data, len);
477
+            if(rval == 0xff){   /* an error occurred */
478
+                usbTxLen = USBPID_STALL;
479
+            }else if(rval != 0){    /* This was the final package */
480
+                usbMsgLen = 0;  /* answer with a zero-sized data packet */
481
+            }
482
+        }
483
+#endif
484
+    }
485
+}
486
+
487
+/* ------------------------------------------------------------------------- */
488
+
489
+/* This function is similar to usbFunctionRead(), but it's also called for
490
+ * data handled automatically by the driver (e.g. descriptor reads).
491
+ */
492
+static uchar usbDeviceRead(uchar *data, uchar len)
493
+{
494
+    if(len > 0){    /* don't bother app with 0 sized reads */
495
+#if USB_CFG_IMPLEMENT_FN_READ
496
+        if(usbMsgFlags & USB_FLG_USE_USER_RW){
497
+            len = usbFunctionRead(data, len);
498
+        }else
499
+#endif
500
+        {
501
+            uchar i = len, *r = usbMsgPtr;
502
+            if(usbMsgFlags & USB_FLG_MSGPTR_IS_ROM){    /* ROM data */
503
+                do{
504
+                    uchar c = USB_READ_FLASH(r);    /* assign to char size variable to enforce byte ops */
505
+                    *data++ = c;
506
+                    r++;
507
+                }while(--i);
508
+            }else{  /* RAM data */
509
+                do{
510
+                    *data++ = *r++;
511
+                }while(--i);
512
+            }
513
+            usbMsgPtr = r;
514
+        }
515
+    }
516
+    return len;
517
+}
518
+
519
+/* ------------------------------------------------------------------------- */
520
+
521
+/* usbBuildTxBlock() is called when we have data to transmit and the
522
+ * interrupt routine's transmit buffer is empty.
523
+ */
524
+static inline void usbBuildTxBlock(void)
525
+{
526
+usbMsgLen_t wantLen;
527
+uchar       len;
528
+
529
+    wantLen = usbMsgLen;
530
+    if(wantLen > 8)
531
+        wantLen = 8;
532
+    usbMsgLen -= wantLen;
533
+    usbTxBuf[0] ^= USBPID_DATA0 ^ USBPID_DATA1; /* DATA toggling */
534
+    len = usbDeviceRead(usbTxBuf + 1, wantLen);
535
+    if(len <= 8){           /* valid data packet */
536
+        usbCrc16Append(&usbTxBuf[1], len);
537
+        len += 4;           /* length including sync byte */
538
+        if(len < 12)        /* a partial package identifies end of message */
539
+            usbMsgLen = USB_NO_MSG;
540
+    }else{
541
+        len = USBPID_STALL;   /* stall the endpoint */
542
+        usbMsgLen = USB_NO_MSG;
543
+    }
544
+    usbTxLen = len;
545
+    DBG2(0x20, usbTxBuf, len-1);
546
+}
547
+
548
+/* ------------------------------------------------------------------------- */
549
+
550
+static inline void usbHandleResetHook(uchar notResetState)
551
+{
552
+#ifdef USB_RESET_HOOK
553
+static uchar    wasReset;
554
+uchar           isReset = !notResetState;
555
+
556
+    if(wasReset != isReset){
557
+        USB_RESET_HOOK(isReset);
558
+        wasReset = isReset;
559
+    }
560
+#endif
561
+}
562
+
563
+/* ------------------------------------------------------------------------- */
564
+
565
+USB_PUBLIC void usbPoll(void)
566
+{
567
+schar   len;
568
+uchar   i;
569
+
570
+    len = usbRxLen - 3;
571
+    if(len >= 0){
572
+/* We could check CRC16 here -- but ACK has already been sent anyway. If you
573
+ * need data integrity checks with this driver, check the CRC in your app
574
+ * code and report errors back to the host. Since the ACK was already sent,
575
+ * retries must be handled on application level.
576
+ * unsigned crc = usbCrc16(buffer + 1, usbRxLen - 3);
577
+ */
578
+        usbProcessRx(usbRxBuf + USB_BUFSIZE + 1 - usbInputBufOffset, len);
579
+#if USB_CFG_HAVE_FLOWCONTROL
580
+        if(usbRxLen > 0)    /* only mark as available if not inactivated */
581
+            usbRxLen = 0;
582
+#else
583
+        usbRxLen = 0;       /* mark rx buffer as available */
584
+#endif
585
+    }
586
+    if(usbTxLen & 0x10){    /* transmit system idle */
587
+        if(usbMsgLen != USB_NO_MSG){    /* transmit data pending? */
588
+            usbBuildTxBlock();
589
+        }
590
+    }
591
+    for(i = 20; i > 0; i--){
592
+        uchar usbLineStatus = USBIN & USBMASK;
593
+        if(usbLineStatus != 0)  /* SE0 has ended */
594
+            goto isNotReset;
595
+    }
596
+    /* RESET condition, called multiple times during reset */
597
+    usbNewDeviceAddr = 0;
598
+    usbDeviceAddr = 0;
599
+    usbResetStall();
600
+    DBG1(0xff, 0, 0);
601
+isNotReset:
602
+    usbHandleResetHook(i);
603
+}
604
+
605
+/* ------------------------------------------------------------------------- */
606
+
607
+USB_PUBLIC void usbInit(void)
608
+{
609
+#if USB_INTR_CFG_SET != 0
610
+    USB_INTR_CFG |= USB_INTR_CFG_SET;
611
+#endif
612
+#if USB_INTR_CFG_CLR != 0
613
+    USB_INTR_CFG &= ~(USB_INTR_CFG_CLR);
614
+#endif
615
+    USB_INTR_ENABLE |= (1 << USB_INTR_ENABLE_BIT);
616
+    usbResetDataToggling();
617
+#if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
618
+    usbTxLen1 = USBPID_NAK;
619
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
620
+    usbTxLen3 = USBPID_NAK;
621
+#endif
622
+#endif
623
+}
624
+
625
+/* ------------------------------------------------------------------------- */

+ 759
- 0
usbdrv.h View File

@@ -0,0 +1,759 @@
1
+/* Name: usbdrv.h
2
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
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), GNU GPL v3 or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: usbdrv.h 769 2009-08-22 11:49:05Z cs $
9
+ */
10
+
11
+#ifndef __usbdrv_h_included__
12
+#define __usbdrv_h_included__
13
+#include "usbconfig.h"
14
+#include "usbportability.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, 16 MHz or 20 MHz
38
+or at 12.8 MHz resp. 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  20090822
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
+#if USB_CFG_LONG_TRANSFERS  /* if more than 254 bytes transfer size required */
154
+#   define usbMsgLen_t unsigned
155
+#else
156
+#   define usbMsgLen_t uchar
157
+#endif
158
+/* usbMsgLen_t is the data type used for transfer lengths. By default, it is
159
+ * defined to uchar, allowing a maximum of 254 bytes (255 is reserved for
160
+ * USB_NO_MSG below). If the usbconfig.h defines USB_CFG_LONG_TRANSFERS to 1,
161
+ * a 16 bit data type is used, allowing up to 16384 bytes (the rest is used
162
+ * for flags in the descriptor configuration).
163
+ */
164
+#define USB_NO_MSG  ((usbMsgLen_t)-1)   /* constant meaning "no message" */
165
+
166
+struct usbRequest;  /* forward declaration */
167
+
168
+#ifdef __cplusplus
169
+extern "C"{
170
+#endif
171
+USB_PUBLIC void usbInit(void);
172
+/* This function must be called before interrupts are enabled and the main
173
+ * loop is entered. We exepct that the PORT and DDR bits for D+ and D- have
174
+ * not been changed from their default status (which is 0). If you have changed
175
+ * them, set both back to 0 (configure them as input with no internal pull-up).
176
+ */
177
+USB_PUBLIC void usbPoll(void);
178
+/* This function must be called at regular intervals from the main loop.
179
+ * Maximum delay between calls is somewhat less than 50ms (USB timeout for
180
+ * accepting a Setup message). Otherwise the device will not be recognized.
181
+ * Please note that debug outputs through the UART take ~ 0.5ms per byte
182
+ * at 19200 bps.
183
+ */
184
+#ifdef __cplusplus
185
+} // extern "C"
186
+#endif
187
+extern uchar *usbMsgPtr;
188
+/* This variable may be used to pass transmit data to the driver from the
189
+ * implementation of usbFunctionWrite(). It is also used internally by the
190
+ * driver for standard control requests.
191
+ */
192
+#ifdef __cplusplus
193
+extern "C"{
194
+#endif
195
+USB_PUBLIC usbMsgLen_t usbFunctionSetup(uchar data[8]);
196
+#ifdef __cplusplus
197
+} // extern "C"
198
+#endif
199
+/* This function is called when the driver receives a SETUP transaction from
200
+ * the host which is not answered by the driver itself (in practice: class and
201
+ * vendor requests). All control transfers start with a SETUP transaction where
202
+ * the host communicates the parameters of the following (optional) data
203
+ * transfer. The SETUP data is available in the 'data' parameter which can
204
+ * (and should) be casted to 'usbRequest_t *' for a more user-friendly access
205
+ * to parameters.
206
+ *
207
+ * If the SETUP indicates a control-in transfer, you should provide the
208
+ * requested data to the driver. There are two ways to transfer this data:
209
+ * (1) Set the global pointer 'usbMsgPtr' to the base of the static RAM data
210
+ * block and return the length of the data in 'usbFunctionSetup()'. The driver
211
+ * will handle the rest. Or (2) return USB_NO_MSG in 'usbFunctionSetup()'. The
212
+ * driver will then call 'usbFunctionRead()' when data is needed. See the
213
+ * documentation for usbFunctionRead() for details.
214
+ *
215
+ * If the SETUP indicates a control-out transfer, the only way to receive the
216
+ * data from the host is through the 'usbFunctionWrite()' call. If you
217
+ * implement this function, you must return USB_NO_MSG in 'usbFunctionSetup()'
218
+ * to indicate that 'usbFunctionWrite()' should be used. See the documentation
219
+ * of this function for more information. If you just want to ignore the data
220
+ * sent by the host, return 0 in 'usbFunctionSetup()'.
221
+ *
222
+ * Note that calls to the functions usbFunctionRead() and usbFunctionWrite()
223
+ * are only done if enabled by the configuration in usbconfig.h.
224
+ */
225
+USB_PUBLIC usbMsgLen_t usbFunctionDescriptor(struct usbRequest *rq);
226
+/* You need to implement this function ONLY if you provide USB descriptors at
227
+ * runtime (which is an expert feature). It is very similar to
228
+ * usbFunctionSetup() above, but it is called only to request USB descriptor
229
+ * data. See the documentation of usbFunctionSetup() above for more info.
230
+ */
231
+#if USB_CFG_HAVE_INTRIN_ENDPOINT
232
+#ifdef __cplusplus
233
+extern "C"{
234
+#endif
235
+USB_PUBLIC void usbSetInterrupt(uchar *data, uchar len);
236
+#ifdef __cplusplus
237
+} // extern "C"
238
+#endif
239
+/* This function sets the message which will be sent during the next interrupt
240
+ * IN transfer. The message is copied to an internal buffer and must not exceed
241
+ * a length of 8 bytes. The message may be 0 bytes long just to indicate the
242
+ * interrupt status to the host.
243
+ * If you need to transfer more bytes, use a control read after the interrupt.
244
+ */
245
+#define usbInterruptIsReady()   (usbTxLen1 & 0x10)
246
+/* This macro indicates whether the last interrupt message has already been
247
+ * sent. If you set a new interrupt message before the old was sent, the
248
+ * message already buffered will be lost.
249
+ */
250
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
251
+USB_PUBLIC void usbSetInterrupt3(uchar *data, uchar len);
252
+#define usbInterruptIsReady3()   (usbTxLen3 & 0x10)
253
+/* Same as above for endpoint 3 */
254
+#endif
255
+#endif /* USB_CFG_HAVE_INTRIN_ENDPOINT */
256
+#if USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH    /* simplified interface for backward compatibility */
257
+#define usbHidReportDescriptor  usbDescriptorHidReport
258
+/* should be declared as: PROGMEM char usbHidReportDescriptor[]; */
259
+/* If you implement an HID device, you need to provide a report descriptor.
260
+ * The HID report descriptor syntax is a bit complex. If you understand how
261
+ * report descriptors are constructed, we recommend that you use the HID
262
+ * Descriptor Tool from usb.org, see http://www.usb.org/developers/hidpage/.
263
+ * Otherwise you should probably start with a working example.
264
+ */
265
+#endif  /* USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH */
266
+#if USB_CFG_IMPLEMENT_FN_WRITE
267
+USB_PUBLIC uchar usbFunctionWrite(uchar *data, uchar len);
268
+/* This function is called by the driver to provide a control transfer's
269
+ * payload data (control-out). It is called in chunks of up to 8 bytes. The
270
+ * total count provided in the current control transfer can be obtained from
271
+ * the 'length' property in the setup data. If an error occurred during
272
+ * processing, return 0xff (== -1). The driver will answer the entire transfer
273
+ * with a STALL token in this case. If you have received the entire payload
274
+ * successfully, return 1. If you expect more data, return 0. If you don't
275
+ * know whether the host will send more data (you should know, the total is
276
+ * provided in the usbFunctionSetup() call!), return 1.
277
+ * NOTE: If you return 0xff for STALL, 'usbFunctionWrite()' may still be called
278
+ * for the remaining data. You must continue to return 0xff for STALL in these
279
+ * calls.
280
+ * In order to get usbFunctionWrite() called, define USB_CFG_IMPLEMENT_FN_WRITE
281
+ * to 1 in usbconfig.h and return 0xff in usbFunctionSetup()..
282
+ */
283
+#endif /* USB_CFG_IMPLEMENT_FN_WRITE */
284
+#if USB_CFG_IMPLEMENT_FN_READ
285
+USB_PUBLIC uchar usbFunctionRead(uchar *data, uchar len);
286
+/* This function is called by the driver to ask the application for a control
287
+ * transfer's payload data (control-in). It is called in chunks of up to 8
288
+ * bytes each. You should copy the data to the location given by 'data' and
289
+ * return the actual number of bytes copied. If you return less than requested,
290
+ * the control-in transfer is terminated. If you return 0xff, the driver aborts
291
+ * the transfer with a STALL token.
292
+ * In order to get usbFunctionRead() called, define USB_CFG_IMPLEMENT_FN_READ
293
+ * to 1 in usbconfig.h and return 0xff in usbFunctionSetup()..
294
+ */
295
+#endif /* USB_CFG_IMPLEMENT_FN_READ */
296
+
297
+extern uchar usbRxToken;    /* may be used in usbFunctionWriteOut() below */
298
+#if USB_CFG_IMPLEMENT_FN_WRITEOUT
299
+USB_PUBLIC void usbFunctionWriteOut(uchar *data, uchar len);
300
+/* This function is called by the driver when data is received on an interrupt-
301
+ * or bulk-out endpoint. The endpoint number can be found in the global
302
+ * variable usbRxToken. You must define USB_CFG_IMPLEMENT_FN_WRITEOUT to 1 in
303
+ * usbconfig.h to get this function called.
304
+ */
305
+#endif /* USB_CFG_IMPLEMENT_FN_WRITEOUT */
306
+#ifdef USB_CFG_PULLUP_IOPORTNAME
307
+#define usbDeviceConnect()      ((USB_PULLUP_DDR |= (1<<USB_CFG_PULLUP_BIT)), \
308
+                                  (USB_PULLUP_OUT |= (1<<USB_CFG_PULLUP_BIT)))
309
+#define usbDeviceDisconnect()   ((USB_PULLUP_DDR &= ~(1<<USB_CFG_PULLUP_BIT)), \
310
+                                  (USB_PULLUP_OUT &= ~(1<<USB_CFG_PULLUP_BIT)))
311
+#else /* USB_CFG_PULLUP_IOPORTNAME */
312
+#define usbDeviceConnect()      (USBDDR &= ~(1<<USBMINUS))
313
+#define usbDeviceDisconnect()   (USBDDR |= (1<<USBMINUS))
314
+#endif /* USB_CFG_PULLUP_IOPORTNAME */
315
+/* The macros usbDeviceConnect() and usbDeviceDisconnect() (intended to look
316
+ * like a function) connect resp. disconnect the device from the host's USB.
317
+ * If the constants USB_CFG_PULLUP_IOPORT and USB_CFG_PULLUP_BIT are defined
318
+ * in usbconfig.h, a disconnect consists of removing the pull-up resisitor
319
+ * from D-, otherwise the disconnect is done by brute-force pulling D- to GND.
320
+ * This does not conform to the spec, but it works.
321
+ * Please note that the USB interrupt must be disabled while the device is
322
+ * in disconnected state, or the interrupt handler will hang! You can either
323
+ * turn off the USB interrupt selectively with
324
+ *     USB_INTR_ENABLE &= ~(1 << USB_INTR_ENABLE_BIT)
325
+ * or use cli() to disable interrupts globally.
326
+ */
327
+extern unsigned usbCrc16(unsigned data, uchar len);
328
+#define usbCrc16(data, len) usbCrc16((unsigned)(data), len)
329
+/* This function calculates the binary complement of the data CRC used in
330
+ * USB data packets. The value is used to build raw transmit packets.
331
+ * You may want to use this function for data checksums or to verify received
332
+ * data. We enforce 16 bit calling conventions for compatibility with IAR's
333
+ * tiny memory model.
334
+ */
335
+#ifdef __cplusplus
336
+extern "C"{
337
+#endif
338
+extern unsigned usbCrc16Append(unsigned data, uchar len);
339
+#ifdef __cplusplus
340
+} // extern "C"
341
+#endif
342
+#define usbCrc16Append(data, len)    usbCrc16Append((unsigned)(data), len)
343
+/* This function is equivalent to usbCrc16() above, except that it appends
344
+ * the 2 bytes CRC (lowbyte first) in the 'data' buffer after reading 'len'
345
+ * bytes.
346
+ */
347
+#if USB_CFG_HAVE_MEASURE_FRAME_LENGTH
348
+extern unsigned usbMeasureFrameLength(void);
349
+/* This function MUST be called IMMEDIATELY AFTER USB reset and measures 1/7 of
350
+ * the number of CPU cycles during one USB frame minus one low speed bit
351
+ * length. In other words: return value = 1499 * (F_CPU / 10.5 MHz)
352
+ * Since this is a busy wait, you MUST disable all interrupts with cli() before
353
+ * calling this function.
354
+ * This can be used to calibrate the AVR's RC oscillator.
355
+ */
356
+#endif
357
+extern uchar    usbConfiguration;
358
+/* This value contains the current configuration set by the host. The driver
359
+ * allows setting and querying of this variable with the USB SET_CONFIGURATION
360
+ * and GET_CONFIGURATION requests, but does not use it otherwise.
361
+ * You may want to reflect the "configured" status with a LED on the device or
362
+ * switch on high power parts of the circuit only if the device is configured.
363
+ */
364
+#if USB_COUNT_SOF
365
+extern volatile uchar   usbSofCount;
366
+/* This variable is incremented on every SOF packet. It is only available if
367
+ * the macro USB_COUNT_SOF is defined to a value != 0.
368
+ */
369
+#endif
370
+#if USB_CFG_CHECK_DATA_TOGGLING
371
+extern uchar    usbCurrentDataToken;
372
+/* This variable can be checked in usbFunctionWrite() and usbFunctionWriteOut()
373
+ * to ignore duplicate packets.
374
+ */
375
+#endif
376
+
377
+#define USB_STRING_DESCRIPTOR_HEADER(stringLength) ((2*(stringLength)+2) | (3<<8))
378
+/* This macro builds a descriptor header for a string descriptor given the
379
+ * string's length. See usbdrv.c for an example how to use it.
380
+ */
381
+#if USB_CFG_HAVE_FLOWCONTROL
382
+extern volatile schar   usbRxLen;
383
+#define usbDisableAllRequests()     usbRxLen = -1
384
+/* Must be called from usbFunctionWrite(). This macro disables all data input
385
+ * from the USB interface. Requests from the host are answered with a NAK
386
+ * while they are disabled.
387
+ */
388
+#define usbEnableAllRequests()      usbRxLen = 0
389
+/* May only be called if requests are disabled. This macro enables input from
390
+ * the USB interface after it has been disabled with usbDisableAllRequests().
391
+ */
392
+#define usbAllRequestsAreDisabled() (usbRxLen < 0)
393
+/* Use this macro to find out whether requests are disabled. It may be needed
394
+ * to ensure that usbEnableAllRequests() is never called when requests are
395
+ * enabled.
396
+ */
397
+#endif
398
+
399
+#define USB_SET_DATATOKEN1(token)   usbTxBuf1[0] = token
400
+#define USB_SET_DATATOKEN3(token)   usbTxBuf3[0] = token
401
+/* These two macros can be used by application software to reset data toggling
402
+ * for interrupt-in endpoints 1 and 3. Since the token is toggled BEFORE
403
+ * sending data, you must set the opposite value of the token which should come
404
+ * first.
405
+ */
406
+
407
+#endif  /* __ASSEMBLER__ */
408
+
409
+
410
+/* ------------------------------------------------------------------------- */
411
+/* ----------------- Definitions for Descriptor Properties ----------------- */
412
+/* ------------------------------------------------------------------------- */
413
+/* This is advanced stuff. See usbconfig-prototype.h for more information
414
+ * about the various methods to define USB descriptors. If you do nothing,
415
+ * the default descriptors will be used.
416
+ */
417
+#define USB_PROP_IS_DYNAMIC     (1 << 14)
418
+/* If this property is set for a descriptor, usbFunctionDescriptor() will be
419
+ * used to obtain the particular descriptor. Data directly returned via
420
+ * usbMsgPtr are FLASH data by default, combine (OR) with USB_PROP_IS_RAM to
421
+ * return RAM data.
422
+ */
423
+#define USB_PROP_IS_RAM         (1 << 15)
424
+/* If this property is set for a descriptor, the data is read from RAM
425
+ * memory instead of Flash. The property is used for all methods to provide
426
+ * external descriptors.
427
+ */
428
+#define USB_PROP_LENGTH(len)    ((len) & 0x3fff)
429
+/* If a static external descriptor is used, this is the total length of the
430
+ * descriptor in bytes.
431
+ */
432
+
433
+/* all descriptors which may have properties: */
434
+#ifndef USB_CFG_DESCR_PROPS_DEVICE
435
+#define USB_CFG_DESCR_PROPS_DEVICE                  0
436
+#endif
437
+#ifndef USB_CFG_DESCR_PROPS_CONFIGURATION
438
+#define USB_CFG_DESCR_PROPS_CONFIGURATION           0
439
+#endif
440
+#ifndef USB_CFG_DESCR_PROPS_STRINGS
441
+#define USB_CFG_DESCR_PROPS_STRINGS                 0
442
+#endif
443
+#ifndef USB_CFG_DESCR_PROPS_STRING_0
444
+#define USB_CFG_DESCR_PROPS_STRING_0                0
445
+#endif
446
+#ifndef USB_CFG_DESCR_PROPS_STRING_VENDOR
447
+#define USB_CFG_DESCR_PROPS_STRING_VENDOR           0
448
+#endif
449
+#ifndef USB_CFG_DESCR_PROPS_STRING_PRODUCT
450
+#define USB_CFG_DESCR_PROPS_STRING_PRODUCT          0
451
+#endif
452
+#ifndef USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
453
+#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER    0
454
+#endif
455
+#ifndef USB_CFG_DESCR_PROPS_HID
456
+#define USB_CFG_DESCR_PROPS_HID                     0
457
+#endif
458
+#if !(USB_CFG_DESCR_PROPS_HID_REPORT)
459
+#   undef USB_CFG_DESCR_PROPS_HID_REPORT
460
+#   if USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH /* do some backward compatibility tricks */
461
+#       define USB_CFG_DESCR_PROPS_HID_REPORT       USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH
462
+#   else
463
+#       define USB_CFG_DESCR_PROPS_HID_REPORT       0
464
+#   endif
465
+#endif
466
+#ifndef USB_CFG_DESCR_PROPS_UNKNOWN
467
+#define USB_CFG_DESCR_PROPS_UNKNOWN                 0
468
+#endif
469
+
470
+/* ------------------ forward declaration of descriptors ------------------- */
471
+/* If you use external static descriptors, they must be stored in global
472
+ * arrays as declared below:
473
+ */
474
+#ifndef __ASSEMBLER__
475
+extern
476
+#if !(USB_CFG_DESCR_PROPS_DEVICE & USB_PROP_IS_RAM)
477
+PROGMEM
478
+#endif
479
+char usbDescriptorDevice[];
480
+
481
+extern
482
+#if !(USB_CFG_DESCR_PROPS_CONFIGURATION & USB_PROP_IS_RAM)
483
+PROGMEM
484
+#endif
485
+char usbDescriptorConfiguration[];
486
+
487
+extern
488
+#if !(USB_CFG_DESCR_PROPS_HID_REPORT & USB_PROP_IS_RAM)
489
+PROGMEM
490
+#endif
491
+char usbDescriptorHidReport[];
492
+
493
+extern
494
+#if !(USB_CFG_DESCR_PROPS_STRING_0 & USB_PROP_IS_RAM)
495
+PROGMEM
496
+#endif
497
+char usbDescriptorString0[];
498
+
499
+extern
500
+#if !(USB_CFG_DESCR_PROPS_STRING_VENDOR & USB_PROP_IS_RAM)
501
+PROGMEM
502
+#endif
503
+int usbDescriptorStringVendor[];
504
+
505
+extern
506
+#if !(USB_CFG_DESCR_PROPS_STRING_PRODUCT & USB_PROP_IS_RAM)
507
+PROGMEM
508
+#endif
509
+int usbDescriptorStringDevice[];
510
+
511
+extern
512
+#if !(USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER & USB_PROP_IS_RAM)
513
+PROGMEM
514
+#endif
515
+int usbDescriptorStringSerialNumber[];
516
+
517
+#endif /* __ASSEMBLER__ */
518
+
519
+/* ------------------------------------------------------------------------- */
520
+/* ------------------------ General Purpose Macros ------------------------- */
521
+/* ------------------------------------------------------------------------- */
522
+
523
+#define USB_CONCAT(a, b)            a ## b
524
+#define USB_CONCAT_EXPANDED(a, b)   USB_CONCAT(a, b)
525
+
526
+#define USB_OUTPORT(name)           USB_CONCAT(PORT, name)
527
+#define USB_INPORT(name)            USB_CONCAT(PIN, name)
528
+#define USB_DDRPORT(name)           USB_CONCAT(DDR, name)
529
+/* The double-define trick above lets us concatenate strings which are
530
+ * defined by macros.
531
+ */
532
+
533
+/* ------------------------------------------------------------------------- */
534
+/* ------------------------- Constant definitions -------------------------- */
535
+/* ------------------------------------------------------------------------- */
536
+
537
+#if !defined __ASSEMBLER__ && (!defined USB_CFG_VENDOR_ID || !defined USB_CFG_DEVICE_ID)
538
+#warning "You should define USB_CFG_VENDOR_ID and USB_CFG_DEVICE_ID in usbconfig.h"
539
+/* If the user has not defined IDs, we default to obdev's free IDs.
540
+ * See USB-IDs-for-free.txt for details.
541
+ */
542
+#endif
543
+
544
+/* make sure we have a VID and PID defined, byte order is lowbyte, highbyte */
545
+#ifndef USB_CFG_VENDOR_ID
546
+#   define  USB_CFG_VENDOR_ID   0xc0, 0x16  /* = 0x16c0 = 5824 = voti.nl */
547
+#endif
548
+
549
+#ifndef USB_CFG_DEVICE_ID
550
+#   if USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH
551
+#       define USB_CFG_DEVICE_ID    0xdf, 0x05  /* = 0x5df = 1503, shared PID for HIDs */
552
+#   elif USB_CFG_INTERFACE_CLASS == 2
553
+#       define USB_CFG_DEVICE_ID    0xe1, 0x05  /* = 0x5e1 = 1505, shared PID for CDC Modems */
554
+#   else
555
+#       define USB_CFG_DEVICE_ID    0xdc, 0x05  /* = 0x5dc = 1500, obdev's free PID */
556
+#   endif
557
+#endif
558
+
559
+/* Derive Output, Input and DataDirection ports from port names */
560
+#ifndef USB_CFG_IOPORTNAME
561
+#error "You must define USB_CFG_IOPORTNAME in usbconfig.h, see usbconfig-prototype.h"
562
+#endif
563
+
564
+#define USBOUT          USB_OUTPORT(USB_CFG_IOPORTNAME)
565
+#define USB_PULLUP_OUT  USB_OUTPORT(USB_CFG_PULLUP_IOPORTNAME)
566
+#define USBIN           USB_INPORT(USB_CFG_IOPORTNAME)
567
+#define USBDDR          USB_DDRPORT(USB_CFG_IOPORTNAME)
568
+#define USB_PULLUP_DDR  USB_DDRPORT(USB_CFG_PULLUP_IOPORTNAME)
569
+
570
+#define USBMINUS    USB_CFG_DMINUS_BIT
571
+#define USBPLUS     USB_CFG_DPLUS_BIT
572
+#define USBIDLE     (1<<USB_CFG_DMINUS_BIT) /* value representing J state */
573
+#define USBMASK     ((1<<USB_CFG_DPLUS_BIT) | (1<<USB_CFG_DMINUS_BIT))  /* mask for USB I/O bits */
574
+
575
+/* defines for backward compatibility with older driver versions: */
576
+#define USB_CFG_IOPORT          USB_OUTPORT(USB_CFG_IOPORTNAME)
577
+#ifdef USB_CFG_PULLUP_IOPORTNAME
578
+#define USB_CFG_PULLUP_IOPORT   USB_OUTPORT(USB_CFG_PULLUP_IOPORTNAME)
579
+#endif
580
+
581
+#ifndef USB_CFG_EP3_NUMBER  /* if not defined in usbconfig.h */
582
+#define USB_CFG_EP3_NUMBER  3
583
+#endif
584
+
585
+#ifndef USB_CFG_HAVE_INTRIN_ENDPOINT3
586
+#define USB_CFG_HAVE_INTRIN_ENDPOINT3   0
587
+#endif
588
+
589
+#define USB_BUFSIZE     11  /* PID, 8 bytes data, 2 bytes CRC */
590
+
591
+/* ----- Try to find registers and bits responsible for ext interrupt 0 ----- */
592
+
593
+#ifndef USB_INTR_CFG    /* allow user to override our default */
594
+#   if defined  EICRA
595
+#       define USB_INTR_CFG EICRA
596
+#   else
597
+#       define USB_INTR_CFG MCUCR
598
+#   endif
599
+#endif
600
+#ifndef USB_INTR_CFG_SET    /* allow user to override our default */
601
+#   if defined(USB_COUNT_SOF) || defined(USB_SOF_HOOK)
602
+#       define USB_INTR_CFG_SET (1 << ISC01)                    /* cfg for falling edge */
603
+        /* If any SOF logic is used, the interrupt must be wired to D- where
604
+         * we better trigger on falling edge
605
+         */
606
+#   else
607
+#       define USB_INTR_CFG_SET ((1 << ISC00) | (1 << ISC01))   /* cfg for rising edge */
608
+#   endif
609
+#endif
610
+#ifndef USB_INTR_CFG_CLR    /* allow user to override our default */
611
+#   define USB_INTR_CFG_CLR 0    /* no bits to clear */
612
+#endif
613
+
614
+#ifndef USB_INTR_ENABLE     /* allow user to override our default */
615
+#   if defined GIMSK
616
+#       define USB_INTR_ENABLE  GIMSK
617
+#   elif defined EIMSK
618
+#       define USB_INTR_ENABLE  EIMSK
619
+#   else
620
+#       define USB_INTR_ENABLE  GICR
621
+#   endif
622
+#endif
623
+#ifndef USB_INTR_ENABLE_BIT /* allow user to override our default */
624
+#   define USB_INTR_ENABLE_BIT  INT0
625
+#endif
626
+
627
+#ifndef USB_INTR_PENDING    /* allow user to override our default */
628
+#   if defined  EIFR
629
+#       define USB_INTR_PENDING EIFR
630
+#   else
631
+#       define USB_INTR_PENDING GIFR
632
+#   endif
633
+#endif
634
+#ifndef USB_INTR_PENDING_BIT    /* allow user to override our default */
635
+#   define USB_INTR_PENDING_BIT INTF0
636
+#endif
637
+
638
+/*
639
+The defines above don't work for the following chips
640
+at90c8534: no ISC0?, no PORTB, can't find a data sheet
641
+at86rf401: no PORTB, no MCUCR etc, low clock rate
642
+atmega103: no ISC0? (maybe omission in header, can't find data sheet)
643
+atmega603: not defined in avr-libc
644
+at43usb320, at43usb355, at76c711: have USB anyway
645
+at94k: is different...
646
+
647
+at90s1200, attiny11, attiny12, attiny15, attiny28: these have no RAM
648
+*/
649
+
650
+/* ------------------------------------------------------------------------- */
651
+/* ----------------- USB Specification Constants and Types ----------------- */
652
+/* ------------------------------------------------------------------------- */
653
+
654
+/* USB Token values */
655
+#define USBPID_SETUP    0x2d
656
+#define USBPID_OUT      0xe1
657
+#define USBPID_IN       0x69
658
+#define USBPID_DATA0    0xc3
659
+#define USBPID_DATA1    0x4b
660
+
661
+#define USBPID_ACK      0xd2
662
+#define USBPID_NAK      0x5a
663
+#define USBPID_STALL    0x1e
664
+
665
+#ifndef USB_INITIAL_DATATOKEN
666
+#define USB_INITIAL_DATATOKEN   USBPID_DATA1
667
+#endif
668
+
669
+#ifndef __ASSEMBLER__
670
+
671
+typedef struct usbTxStatus{
672
+    volatile uchar   len;
673
+    uchar   buffer[USB_BUFSIZE];
674
+}usbTxStatus_t;
675
+
676
+extern usbTxStatus_t   usbTxStatus1, usbTxStatus3;
677
+#define usbTxLen1   usbTxStatus1.len
678
+#define usbTxBuf1   usbTxStatus1.buffer
679
+#define usbTxLen3   usbTxStatus3.len
680
+#define usbTxBuf3   usbTxStatus3.buffer
681
+
682
+
683
+typedef union usbWord{
684
+    unsigned    word;
685
+    uchar       bytes[2];
686
+}usbWord_t;
687
+
688
+typedef struct usbRequest{
689
+    uchar       bmRequestType;
690
+    uchar       bRequest;
691
+    usbWord_t   wValue;
692
+    usbWord_t   wIndex;
693
+    usbWord_t   wLength;
694
+}usbRequest_t;
695
+/* This structure matches the 8 byte setup request */
696
+#endif
697
+
698
+/* bmRequestType field in USB setup:
699
+ * d t t r r r r r, where
700
+ * d ..... direction: 0=host->device, 1=device->host
701
+ * t ..... type: 0=standard, 1=class, 2=vendor, 3=reserved
702
+ * r ..... recipient: 0=device, 1=interface, 2=endpoint, 3=other
703
+ */
704
+
705
+/* USB setup recipient values */
706
+#define USBRQ_RCPT_MASK         0x1f
707
+#define USBRQ_RCPT_DEVICE       0
708
+#define USBRQ_RCPT_INTERFACE    1
709
+#define USBRQ_RCPT_ENDPOINT     2
710
+
711
+/* USB request type values */
712
+#define USBRQ_TYPE_MASK         0x60
713
+#define USBRQ_TYPE_STANDARD     (0<<5)
714
+#define USBRQ_TYPE_CLASS        (1<<5)
715
+#define USBRQ_TYPE_VENDOR       (2<<5)
716
+
717
+/* USB direction values: */
718
+#define USBRQ_DIR_MASK              0x80
719
+#define USBRQ_DIR_HOST_TO_DEVICE    (0<<7)
720
+#define USBRQ_DIR_DEVICE_TO_HOST    (1<<7)
721
+
722
+/* USB Standard Requests */
723
+#define USBRQ_GET_STATUS        0
724
+#define USBRQ_CLEAR_FEATURE     1
725
+#define USBRQ_SET_FEATURE       3
726
+#define USBRQ_SET_ADDRESS       5
727
+#define USBRQ_GET_DESCRIPTOR    6
728
+#define USBRQ_SET_DESCRIPTOR    7
729
+#define USBRQ_GET_CONFIGURATION 8
730
+#define USBRQ_SET_CONFIGURATION 9
731
+#define USBRQ_GET_INTERFACE     10
732
+#define USBRQ_SET_INTERFACE     11
733
+#define USBRQ_SYNCH_FRAME       12
734
+
735
+/* USB descriptor constants */
736
+#define USBDESCR_DEVICE         1
737
+#define USBDESCR_CONFIG         2
738
+#define USBDESCR_STRING         3
739
+#define USBDESCR_INTERFACE      4
740
+#define USBDESCR_ENDPOINT       5
741
+#define USBDESCR_HID            0x21
742
+#define USBDESCR_HID_REPORT     0x22
743
+#define USBDESCR_HID_PHYS       0x23
744
+
745
+//#define USBATTR_BUSPOWER        0x80  // USB 1.1 does not define this value any more
746
+#define USBATTR_SELFPOWER       0x40
747
+#define USBATTR_REMOTEWAKE      0x20
748
+
749
+/* USB HID Requests */
750
+#define USBRQ_HID_GET_REPORT    0x01
751
+#define USBRQ_HID_GET_IDLE      0x02
752
+#define USBRQ_HID_GET_PROTOCOL  0x03
753
+#define USBRQ_HID_SET_REPORT    0x09
754
+#define USBRQ_HID_SET_IDLE      0x0a
755
+#define USBRQ_HID_SET_PROTOCOL  0x0b
756
+
757
+/* ------------------------------------------------------------------------- */
758
+
759
+#endif /* __usbdrv_h_included__ */

+ 385
- 0
usbdrvasm.S View File

@@ -0,0 +1,385 @@
1
+/* Name: usbdrvasm.S
2
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
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), GNU GPL v3 or proprietary (CommercialLicense.txt)
8
+ * Revision: $Id: usbdrvasm.S 761 2009-08-12 16:30:23Z cs $
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
+#define __SFR_OFFSET 0      /* used by avr-libc's register definitions */
19
+#include "usbportability.h"
20
+#include "usbdrv.h"         /* for common defs */
21
+
22
+/* register names */
23
+#define x1      r16
24
+#define x2      r17
25
+#define shift   r18
26
+#define cnt     r19
27
+#define x3      r20
28
+#define x4      r21
29
+#define x5		r22
30
+#define bitcnt  x5
31
+#define phase   x4
32
+#define leap    x4
33
+
34
+/* Some assembler dependent definitions and declarations: */
35
+
36
+#ifdef __IAR_SYSTEMS_ASM__
37
+    extern  usbRxBuf, usbDeviceAddr, usbNewDeviceAddr, usbInputBufOffset
38
+    extern  usbCurrentTok, usbRxLen, usbRxToken, usbTxLen
39
+    extern  usbTxBuf, usbTxStatus1, usbTxStatus3
40
+#   if USB_COUNT_SOF
41
+        extern usbSofCount
42
+#   endif
43
+    public  usbCrc16
44
+    public  usbCrc16Append
45
+
46
+    COMMON  INTVEC
47
+#   ifndef USB_INTR_VECTOR
48
+        ORG     INT0_vect
49
+#   else /* USB_INTR_VECTOR */
50
+        ORG     USB_INTR_VECTOR
51
+#       undef   USB_INTR_VECTOR
52
+#   endif /* USB_INTR_VECTOR */
53
+#   define  USB_INTR_VECTOR usbInterruptHandler
54
+    rjmp    USB_INTR_VECTOR
55
+    RSEG    CODE
56
+
57
+#else /* __IAR_SYSTEMS_ASM__ */
58
+
59
+#   ifndef USB_INTR_VECTOR /* default to hardware interrupt INT0 */
60
+#       define USB_INTR_VECTOR  SIG_INTERRUPT0
61
+#   endif
62
+    .text
63
+    .global USB_INTR_VECTOR
64
+    .type   USB_INTR_VECTOR, @function
65
+    .global usbCrc16
66
+    .global usbCrc16Append
67
+#endif /* __IAR_SYSTEMS_ASM__ */
68
+
69
+
70
+#if USB_INTR_PENDING < 0x40 /* This is an I/O address, use in and out */
71
+#   define  USB_LOAD_PENDING(reg)   in reg, USB_INTR_PENDING
72
+#   define  USB_STORE_PENDING(reg)  out USB_INTR_PENDING, reg
73
+#else   /* It's a memory address, use lds and sts */
74
+#   define  USB_LOAD_PENDING(reg)   lds reg, USB_INTR_PENDING
75
+#   define  USB_STORE_PENDING(reg)  sts USB_INTR_PENDING, reg
76
+#endif
77
+
78
+#define usbTxLen1   usbTxStatus1
79
+#define usbTxBuf1   (usbTxStatus1 + 1)
80
+#define usbTxLen3   usbTxStatus3
81
+#define usbTxBuf3   (usbTxStatus3 + 1)
82
+
83
+
84
+;----------------------------------------------------------------------------
85
+; Utility functions
86
+;----------------------------------------------------------------------------
87
+
88
+#ifdef __IAR_SYSTEMS_ASM__
89
+/* Register assignments for usbCrc16 on IAR cc */
90
+/* Calling conventions on IAR:
91
+ * First parameter passed in r16/r17, second in r18/r19 and so on.
92
+ * Callee must preserve r4-r15, r24-r29 (r28/r29 is frame pointer)
93
+ * Result is passed in r16/r17
94
+ * In case of the "tiny" memory model, pointers are only 8 bit with no
95
+ * padding. We therefore pass argument 1 as "16 bit unsigned".
96
+ */
97
+RTMODEL "__rt_version", "3"
98
+/* The line above will generate an error if cc calling conventions change.
99
+ * The value "3" above is valid for IAR 4.10B/W32
100
+ */
101
+#   define argLen   r18 /* argument 2 */
102
+#   define argPtrL  r16 /* argument 1 */
103
+#   define argPtrH  r17 /* argument 1 */
104
+
105
+#   define resCrcL  r16 /* result */
106
+#   define resCrcH  r17 /* result */
107
+
108
+#   define ptrL     ZL
109
+#   define ptrH     ZH
110
+#   define ptr      Z
111
+#   define byte     r22
112
+#   define bitCnt   r19
113
+#   define polyL    r20
114
+#   define polyH    r21
115
+#   define scratch  r23
116
+
117
+#else  /* __IAR_SYSTEMS_ASM__ */ 
118
+/* Register assignments for usbCrc16 on gcc */
119
+/* Calling conventions on gcc:
120
+ * First parameter passed in r24/r25, second in r22/23 and so on.
121
+ * Callee must preserve r1-r17, r28/r29
122
+ * Result is passed in r24/r25
123
+ */
124
+#   define argLen   r22 /* argument 2 */
125
+#   define argPtrL  r24 /* argument 1 */
126
+#   define argPtrH  r25 /* argument 1 */
127
+
128
+#   define resCrcL  r24 /* result */
129
+#   define resCrcH  r25 /* result */
130
+
131
+#   define ptrL     XL
132
+#   define ptrH     XH
133
+#   define ptr      x
134
+#   define byte     r18
135
+#   define bitCnt   r19
136
+#   define polyL    r20
137
+#   define polyH    r21
138
+#   define scratch  r23
139
+
140
+#endif
141
+
142
+#if USB_USE_FAST_CRC
143
+
144
+; This implementation is faster, but has bigger code size
145
+; Thanks to Slawomir Fras (BoskiDialer) for this code!
146
+; It implements the following C pseudo-code:
147
+; unsigned table(unsigned char x)
148
+; {
149
+; unsigned    value;
150
+; 
151
+;     value = (unsigned)x << 6;
152
+;     value ^= (unsigned)x << 7;
153
+;     if(parity(x))
154
+;         value ^= 0xc001;
155
+;     return value;
156
+; }
157
+; unsigned usbCrc16(unsigned char *argPtr, unsigned char argLen)
158
+; {
159
+; unsigned crc = 0xffff;
160
+; 
161
+;     while(argLen--)
162
+;         crc = table(lo8(crc) ^ *argPtr++) ^ hi8(crc);
163
+;     return ~crc;
164
+; }
165
+
166
+; extern unsigned usbCrc16(unsigned char *argPtr, unsigned char argLen);
167
+;   argPtr  r24+25 / r16+r17
168
+;   argLen  r22 / r18
169
+; temp variables:
170
+;   byte    r18 / r22
171
+;   scratch r23
172
+;   resCrc  r24+r25 / r16+r17
173
+;   ptr     X / Z
174
+usbCrc16:
175
+    mov     ptrL, argPtrL
176
+    mov     ptrH, argPtrH
177
+    ldi     resCrcL, 0xFF
178
+    ldi     resCrcH, 0xFF
179
+    rjmp    usbCrc16LoopTest
180
+usbCrc16ByteLoop:
181
+    ld      byte, ptr+
182
+    eor     resCrcL, byte   ; resCrcL is now 'x' in table()
183
+    mov     byte, resCrcL   ; compute parity of 'x'
184
+    swap    byte
185
+    eor     byte, resCrcL
186
+    mov     scratch, byte
187
+    lsr     byte
188
+    lsr     byte
189
+    eor     byte, scratch
190
+    inc     byte
191
+    lsr     byte
192
+    andi    byte, 1         ; byte is now parity(x)
193
+    mov     scratch, resCrcL
194
+    mov     resCrcL, resCrcH
195
+    eor     resCrcL, byte   ; low byte of if(parity(x)) value ^= 0xc001;
196
+    neg     byte
197
+    andi    byte, 0xc0
198
+    mov     resCrcH, byte   ; high byte of if(parity(x)) value ^= 0xc001;
199
+    clr     byte
200
+    lsr     scratch
201
+    ror     byte
202
+    eor     resCrcH, scratch
203
+    eor     resCrcL, byte
204
+    lsr     scratch
205
+    ror     byte
206
+    eor     resCrcH, scratch
207
+    eor     resCrcL, byte
208
+usbCrc16LoopTest:
209
+    subi    argLen, 1
210
+    brsh    usbCrc16ByteLoop
211
+    com     resCrcL
212
+    com     resCrcH
213
+    ret
214
+
215
+#else   /* USB_USE_FAST_CRC */
216
+
217
+; This implementation is slower, but has less code size
218
+;
219
+; extern unsigned usbCrc16(unsigned char *argPtr, unsigned char argLen);
220
+;   argPtr  r24+25 / r16+r17
221
+;   argLen  r22 / r18
222
+; temp variables:
223
+;   byte    r18 / r22
224
+;   bitCnt  r19
225
+;   poly    r20+r21
226
+;   scratch r23
227
+;   resCrc  r24+r25 / r16+r17
228
+;   ptr     X / Z
229
+usbCrc16:
230
+    mov     ptrL, argPtrL
231
+    mov     ptrH, argPtrH
232
+    ldi     resCrcL, 0
233
+    ldi     resCrcH, 0
234
+    ldi     polyL, lo8(0xa001)
235
+    ldi     polyH, hi8(0xa001)
236
+    com     argLen      ; argLen = -argLen - 1: modified loop to ensure that carry is set
237
+    ldi     bitCnt, 0   ; loop counter with starnd condition = end condition
238
+    rjmp    usbCrcLoopEntry
239
+usbCrcByteLoop:
240
+    ld      byte, ptr+
241
+    eor     resCrcL, byte
242
+usbCrcBitLoop:
243
+    ror     resCrcH     ; carry is always set here (see brcs jumps to here)
244
+    ror     resCrcL
245
+    brcs    usbCrcNoXor
246
+    eor     resCrcL, polyL
247
+    eor     resCrcH, polyH
248
+usbCrcNoXor:
249
+    subi    bitCnt, 224 ; (8 * 224) % 256 = 0; this loop iterates 8 times
250
+    brcs    usbCrcBitLoop
251
+usbCrcLoopEntry:
252
+    subi    argLen, -1
253
+    brcs    usbCrcByteLoop
254
+usbCrcReady:
255
+    ret
256
+; Thanks to Reimar Doeffinger for optimizing this CRC routine!
257
+
258
+#endif /* USB_USE_FAST_CRC */
259
+
260
+; extern unsigned usbCrc16Append(unsigned char *data, unsigned char len);
261
+usbCrc16Append:
262
+    rcall   usbCrc16
263
+    st      ptr+, resCrcL
264
+    st      ptr+, resCrcH
265
+    ret
266
+
267
+#undef argLen
268
+#undef argPtrL
269
+#undef argPtrH
270
+#undef resCrcL
271
+#undef resCrcH
272
+#undef ptrL
273
+#undef ptrH
274
+#undef ptr
275
+#undef byte
276
+#undef bitCnt
277
+#undef polyL
278
+#undef polyH
279
+#undef scratch
280
+
281
+
282
+#if USB_CFG_HAVE_MEASURE_FRAME_LENGTH
283
+#ifdef __IAR_SYSTEMS_ASM__
284
+/* Register assignments for usbMeasureFrameLength on IAR cc */
285
+/* Calling conventions on IAR:
286
+ * First parameter passed in r16/r17, second in r18/r19 and so on.
287
+ * Callee must preserve r4-r15, r24-r29 (r28/r29 is frame pointer)
288
+ * Result is passed in r16/r17
289
+ * In case of the "tiny" memory model, pointers are only 8 bit with no
290
+ * padding. We therefore pass argument 1 as "16 bit unsigned".
291
+ */
292
+#   define resL     r16
293
+#   define resH     r17
294
+#   define cnt16L   r30
295
+#   define cnt16H   r31
296
+#   define cntH     r18
297
+
298
+#else  /* __IAR_SYSTEMS_ASM__ */ 
299
+/* Register assignments for usbMeasureFrameLength on gcc */
300
+/* Calling conventions on gcc:
301
+ * First parameter passed in r24/r25, second in r22/23 and so on.
302
+ * Callee must preserve r1-r17, r28/r29
303
+ * Result is passed in r24/r25
304
+ */
305
+#   define resL     r24
306
+#   define resH     r25
307
+#   define cnt16L   r24
308
+#   define cnt16H   r25
309
+#   define cntH     r26
310
+#endif
311
+#   define cnt16    cnt16L
312
+
313
+; extern unsigned usbMeasurePacketLength(void);
314
+; returns time between two idle strobes in multiples of 7 CPU clocks
315
+.global usbMeasureFrameLength
316
+usbMeasureFrameLength:
317
+    ldi     cntH, 6         ; wait ~ 10 ms for D- == 0
318
+    clr     cnt16L
319
+    clr     cnt16H
320
+usbMFTime16:
321
+    dec     cntH
322
+    breq    usbMFTimeout
323
+usbMFWaitStrobe:            ; first wait for D- == 0 (idle strobe)
324
+    sbiw    cnt16, 1        ;[0] [6]
325
+    breq    usbMFTime16     ;[2]
326
+    sbic    USBIN, USBMINUS ;[3]
327
+    rjmp    usbMFWaitStrobe ;[4]
328
+usbMFWaitIdle:              ; then wait until idle again
329
+    sbis    USBIN, USBMINUS ;1 wait for D- == 1
330
+    rjmp    usbMFWaitIdle   ;2
331
+    ldi     cnt16L, 1       ;1 represents cycles so far
332
+    clr     cnt16H          ;1
333
+usbMFWaitLoop:
334
+    in      cntH, USBIN     ;[0] [7]
335
+    adiw    cnt16, 1        ;[1]
336
+    breq    usbMFTimeout    ;[3]
337
+    andi    cntH, USBMASK   ;[4]
338
+    brne    usbMFWaitLoop   ;[5]
339
+usbMFTimeout:
340
+#if resL != cnt16L
341
+    mov     resL, cnt16L
342
+    mov     resH, cnt16H
343
+#endif
344
+    ret
345
+
346
+#undef resL
347
+#undef resH
348
+#undef cnt16
349
+#undef cnt16L
350
+#undef cnt16H
351
+#undef cntH
352
+
353
+#endif  /* USB_CFG_HAVE_MEASURE_FRAME_LENGTH */
354
+
355
+;----------------------------------------------------------------------------
356
+; Now include the clock rate specific code
357
+;----------------------------------------------------------------------------
358
+
359
+#ifndef USB_CFG_CLOCK_KHZ
360
+#   define USB_CFG_CLOCK_KHZ 12000
361
+#endif
362
+
363
+#if USB_CFG_CHECK_CRC   /* separate dispatcher for CRC type modules */
364
+#   if USB_CFG_CLOCK_KHZ == 18000
365
+#       include "usbdrvasm18-crc.inc"
366
+#   else
367
+#       error "USB_CFG_CLOCK_KHZ is not one of the supported crc-rates!"
368
+#   endif
369
+#else   /* USB_CFG_CHECK_CRC */
370
+#   if USB_CFG_CLOCK_KHZ == 12000
371
+#       include "usbdrvasm12.inc"
372
+#   elif USB_CFG_CLOCK_KHZ == 12800
373
+#       include "usbdrvasm128.inc"
374
+#   elif USB_CFG_CLOCK_KHZ == 15000
375
+#       include "usbdrvasm15.inc"
376
+#   elif USB_CFG_CLOCK_KHZ == 16000
377
+#       include "usbdrvasm16.inc"
378
+#   elif USB_CFG_CLOCK_KHZ == 16500
379
+#       include "usbdrvasm165.inc"
380
+#   elif USB_CFG_CLOCK_KHZ == 20000
381
+#       include "usbdrvasm20.inc"
382
+#   else
383
+#       error "USB_CFG_CLOCK_KHZ is not one of the supported non-crc-rates!"
384
+#   endif
385
+#endif /* USB_CFG_CHECK_CRC */

+ 21
- 0
usbdrvasm.asm View File

@@ -0,0 +1,21 @@
1
+/* Name: usbdrvasm.asm
2
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
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), GNU GPL v3 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

+ 393
- 0
usbdrvasm12.inc View File

@@ -0,0 +1,393 @@
1
+/* Name: usbdrvasm12.inc
2
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
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), GNU GPL v3 or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: usbdrvasm12.inc 740 2009-04-13 18:23:31Z 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
+;The first part waits at most 1 bit long since we must be in sync pattern.
52
+;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to
53
+;waitForJ, ensure that this prerequisite is met.
54
+waitForJ:
55
+    inc     YL
56
+    sbis    USBIN, USBMINUS
57
+    brne    waitForJ        ; just make sure we have ANY timeout
58
+waitForK:
59
+;The following code results in a sampling window of 1/4 bit which meets the spec.
60
+    sbis    USBIN, USBMINUS
61
+    rjmp    foundK
62
+    sbis    USBIN, USBMINUS
63
+    rjmp    foundK
64
+    sbis    USBIN, USBMINUS
65
+    rjmp    foundK
66
+    sbis    USBIN, USBMINUS
67
+    rjmp    foundK
68
+    sbis    USBIN, USBMINUS
69
+    rjmp    foundK
70
+#if USB_COUNT_SOF
71
+    lds     YL, usbSofCount
72
+    inc     YL
73
+    sts     usbSofCount, YL
74
+#endif  /* USB_COUNT_SOF */
75
+#ifdef USB_SOF_HOOK
76
+    USB_SOF_HOOK
77
+#endif
78
+    rjmp    sofError
79
+foundK:
80
+;{3, 5} after falling D- edge, average delay: 4 cycles [we want 4 for center sampling]
81
+;we have 1 bit time for setup purposes, then sample again. Numbers in brackets
82
+;are cycles from center of first sync (double K) bit after the instruction
83
+    push    YH                  ;2 [2]
84
+    lds     YL, usbInputBufOffset;2 [4]
85
+    clr     YH                  ;1 [5]
86
+    subi    YL, lo8(-(usbRxBuf));1 [6]
87
+    sbci    YH, hi8(-(usbRxBuf));1 [7]
88
+
89
+    sbis    USBIN, USBMINUS ;1 [8] we want two bits K [sample 1 cycle too early]
90
+    rjmp    haveTwoBitsK    ;2 [10]
91
+    pop     YH              ;2 [11] undo the push from before
92
+    rjmp    waitForK        ;2 [13] this was not the end of sync, retry
93
+haveTwoBitsK:
94
+;----------------------------------------------------------------------------
95
+; push more registers and initialize values while we sample the first bits:
96
+;----------------------------------------------------------------------------
97
+    push    shift           ;2 [16]
98
+    push    x1              ;2 [12]
99
+    push    x2              ;2 [14]
100
+
101
+    in      x1, USBIN       ;1 [17] <-- sample bit 0
102
+    ldi     shift, 0xff     ;1 [18]
103
+    bst     x1, USBMINUS    ;1 [19]
104
+    bld     shift, 0        ;1 [20]
105
+    push    x3              ;2 [22]
106
+    push    cnt             ;2 [24]
107
+    
108
+    in      x2, USBIN       ;1 [25] <-- sample bit 1
109
+    ser     x3              ;1 [26] [inserted init instruction]
110
+    eor     x1, x2          ;1 [27]
111
+    bst     x1, USBMINUS    ;1 [28]
112
+    bld     shift, 1        ;1 [29]
113
+    ldi     cnt, USB_BUFSIZE;1 [30] [inserted init instruction]
114
+    rjmp    rxbit2          ;2 [32]
115
+
116
+;----------------------------------------------------------------------------
117
+; Receiver loop (numbers in brackets are cycles within byte after instr)
118
+;----------------------------------------------------------------------------
119
+
120
+unstuff0:               ;1 (branch taken)
121
+    andi    x3, ~0x01   ;1 [15]
122
+    mov     x1, x2      ;1 [16] x2 contains last sampled (stuffed) bit
123
+    in      x2, USBIN   ;1 [17] <-- sample bit 1 again
124
+    ori     shift, 0x01 ;1 [18]
125
+    rjmp    didUnstuff0 ;2 [20]
126
+
127
+unstuff1:               ;1 (branch taken)
128
+    mov     x2, x1      ;1 [21] x1 contains last sampled (stuffed) bit
129
+    andi    x3, ~0x02   ;1 [22]
130
+    ori     shift, 0x02 ;1 [23]
131
+    nop                 ;1 [24]
132
+    in      x1, USBIN   ;1 [25] <-- sample bit 2 again
133
+    rjmp    didUnstuff1 ;2 [27]
134
+
135
+unstuff2:               ;1 (branch taken)
136
+    andi    x3, ~0x04   ;1 [29]
137
+    ori     shift, 0x04 ;1 [30]
138
+    mov     x1, x2      ;1 [31] x2 contains last sampled (stuffed) bit
139
+    nop                 ;1 [32]
140
+    in      x2, USBIN   ;1 [33] <-- sample bit 3
141
+    rjmp    didUnstuff2 ;2 [35]
142
+
143
+unstuff3:               ;1 (branch taken)
144
+    in      x2, USBIN   ;1 [34] <-- sample stuffed bit 3 [one cycle too late]
145
+    andi    x3, ~0x08   ;1 [35]
146
+    ori     shift, 0x08 ;1 [36]
147
+    rjmp    didUnstuff3 ;2 [38]
148
+
149
+unstuff4:               ;1 (branch taken)
150
+    andi    x3, ~0x10   ;1 [40]
151
+    in      x1, USBIN   ;1 [41] <-- sample stuffed bit 4
152
+    ori     shift, 0x10 ;1 [42]
153
+    rjmp    didUnstuff4 ;2 [44]
154
+
155
+unstuff5:               ;1 (branch taken)
156
+    andi    x3, ~0x20   ;1 [48]
157
+    in      x2, USBIN   ;1 [49] <-- sample stuffed bit 5
158
+    ori     shift, 0x20 ;1 [50]
159
+    rjmp    didUnstuff5 ;2 [52]
160
+
161
+unstuff6:               ;1 (branch taken)
162
+    andi    x3, ~0x40   ;1 [56]
163
+    in      x1, USBIN   ;1 [57] <-- sample stuffed bit 6
164
+    ori     shift, 0x40 ;1 [58]
165
+    rjmp    didUnstuff6 ;2 [60]
166
+
167
+; extra jobs done during bit interval:
168
+; bit 0:    store, clear [SE0 is unreliable here due to bit dribbling in hubs]
169
+; bit 1:    se0 check
170
+; bit 2:    overflow check
171
+; bit 3:    recovery from delay [bit 0 tasks took too long]
172
+; bit 4:    none
173
+; bit 5:    none
174
+; bit 6:    none
175
+; bit 7:    jump, eor
176
+rxLoop:
177
+    eor     x3, shift   ;1 [0] reconstruct: x3 is 0 at bit locations we changed, 1 at others
178
+    in      x1, USBIN   ;1 [1] <-- sample bit 0
179
+    st      y+, x3      ;2 [3] store data
180
+    ser     x3          ;1 [4]
181
+    nop                 ;1 [5]
182
+    eor     x2, x1      ;1 [6]
183
+    bst     x2, USBMINUS;1 [7]
184
+    bld     shift, 0    ;1 [8]
185
+    in      x2, USBIN   ;1 [9] <-- sample bit 1 (or possibly bit 0 stuffed)
186
+    andi    x2, USBMASK ;1 [10]
187
+    breq    se0         ;1 [11] SE0 check for bit 1
188
+    andi    shift, 0xf9 ;1 [12]
189
+didUnstuff0:
190
+    breq    unstuff0    ;1 [13]
191
+    eor     x1, x2      ;1 [14]
192
+    bst     x1, USBMINUS;1 [15]
193
+    bld     shift, 1    ;1 [16]
194
+rxbit2:
195
+    in      x1, USBIN   ;1 [17] <-- sample bit 2 (or possibly bit 1 stuffed)
196
+    andi    shift, 0xf3 ;1 [18]
197
+    breq    unstuff1    ;1 [19] do remaining work for bit 1
198
+didUnstuff1:
199
+    subi    cnt, 1      ;1 [20]
200
+    brcs    overflow    ;1 [21] loop control
201
+    eor     x2, x1      ;1 [22]
202
+    bst     x2, USBMINUS;1 [23]
203
+    bld     shift, 2    ;1 [24]
204
+    in      x2, USBIN   ;1 [25] <-- sample bit 3 (or possibly bit 2 stuffed)
205
+    andi    shift, 0xe7 ;1 [26]
206
+    breq    unstuff2    ;1 [27]
207
+didUnstuff2:
208
+    eor     x1, x2      ;1 [28]
209
+    bst     x1, USBMINUS;1 [29]
210
+    bld     shift, 3    ;1 [30]
211
+didUnstuff3:
212
+    andi    shift, 0xcf ;1 [31]
213
+    breq    unstuff3    ;1 [32]
214
+    in      x1, USBIN   ;1 [33] <-- sample bit 4
215
+    eor     x2, x1      ;1 [34]
216
+    bst     x2, USBMINUS;1 [35]
217
+    bld     shift, 4    ;1 [36]
218
+didUnstuff4:
219
+    andi    shift, 0x9f ;1 [37]
220
+    breq    unstuff4    ;1 [38]
221
+    nop2                ;2 [40]
222
+    in      x2, USBIN   ;1 [41] <-- sample bit 5
223
+    eor     x1, x2      ;1 [42]
224
+    bst     x1, USBMINUS;1 [43]
225
+    bld     shift, 5    ;1 [44]
226
+didUnstuff5:
227
+    andi    shift, 0x3f ;1 [45]
228
+    breq    unstuff5    ;1 [46]
229
+    nop2                ;2 [48]
230
+    in      x1, USBIN   ;1 [49] <-- sample bit 6
231
+    eor     x2, x1      ;1 [50]
232
+    bst     x2, USBMINUS;1 [51]
233
+    bld     shift, 6    ;1 [52]
234
+didUnstuff6:
235
+    cpi     shift, 0x02 ;1 [53]
236
+    brlo    unstuff6    ;1 [54]
237
+    nop2                ;2 [56]
238
+    in      x2, USBIN   ;1 [57] <-- sample bit 7
239
+    eor     x1, x2      ;1 [58]
240
+    bst     x1, USBMINUS;1 [59]
241
+    bld     shift, 7    ;1 [60]
242
+didUnstuff7:
243
+    cpi     shift, 0x04 ;1 [61]
244
+    brsh    rxLoop      ;2 [63] loop control
245
+unstuff7:
246
+    andi    x3, ~0x80   ;1 [63]
247
+    ori     shift, 0x80 ;1 [64]
248
+    in      x2, USBIN   ;1 [65] <-- sample stuffed bit 7
249
+    nop                 ;1 [66]
250
+    rjmp    didUnstuff7 ;2 [68]
251
+
252
+macro POP_STANDARD ; 12 cycles
253
+    pop     cnt
254
+    pop     x3
255
+    pop     x2
256
+    pop     x1
257
+    pop     shift
258
+    pop     YH
259
+    endm
260
+macro POP_RETI     ; 5 cycles
261
+    pop     YL
262
+    out     SREG, YL
263
+    pop     YL
264
+    endm
265
+
266
+#include "asmcommon.inc"
267
+
268
+;----------------------------------------------------------------------------
269
+; Transmitting data
270
+;----------------------------------------------------------------------------
271
+
272
+txByteLoop:
273
+txBitloop:
274
+stuffN1Delay:                   ;     [03]
275
+    ror     shift               ;[-5] [11] [59]
276
+    brcc    doExorN1            ;[-4]      [60]
277
+    subi    x4, 1               ;[-3]
278
+    brne    commonN1            ;[-2]
279
+    lsl     shift               ;[-1] compensate ror after rjmp stuffDelay
280
+    nop                         ;[00] stuffing consists of just waiting 8 cycles
281
+    rjmp    stuffN1Delay        ;[01] after ror, C bit is reliably clear
282
+
283
+sendNakAndReti:                 ;0 [-19] 19 cycles until SOP
284
+    ldi     x3, USBPID_NAK      ;1 [-18]
285
+    rjmp    usbSendX3           ;2 [-16]
286
+sendAckAndReti:                 ;0 [-19] 19 cycles until SOP
287
+    ldi     x3, USBPID_ACK      ;1 [-18]
288
+    rjmp    usbSendX3           ;2 [-16]
289
+sendCntAndReti:                 ;0 [-17] 17 cycles until SOP
290
+    mov     x3, cnt             ;1 [-16]
291
+usbSendX3:                      ;0 [-16]
292
+    ldi     YL, 20              ;1 [-15] 'x3' is R20
293
+    ldi     YH, 0               ;1 [-14]
294
+    ldi     cnt, 2              ;1 [-13]
295
+;   rjmp    usbSendAndReti      fallthrough
296
+
297
+; USB spec says:
298
+; idle = J
299
+; J = (D+ = 0), (D- = 1) or USBOUT = 0x01
300
+; K = (D+ = 1), (D- = 0) or USBOUT = 0x02
301
+; Spec allows 7.5 bit times from EOP to SOP for replies (= 60 cycles)
302
+
303
+;usbSend:
304
+;pointer to data in 'Y'
305
+;number of bytes in 'cnt' -- including sync byte
306
+;uses: x1...x2, x4, shift, cnt, Y [x1 = mirror USBOUT, x2 = USBMASK, x4 = bitstuff cnt]
307
+;Numbers in brackets are time since first bit of sync pattern is sent (start of instruction)
308
+usbSendAndReti:
309
+    in      x2, USBDDR          ;[-12] 12 cycles until SOP
310
+    ori     x2, USBMASK         ;[-11]
311
+    sbi     USBOUT, USBMINUS    ;[-10] prepare idle state; D+ and D- must have been 0 (no pullups)
312
+    out     USBDDR, x2          ;[-8] <--- acquire bus
313
+    in      x1, USBOUT          ;[-7] port mirror for tx loop
314
+    ldi     shift, 0x40         ;[-6] sync byte is first byte sent (we enter loop after ror)
315
+    ldi     x2, USBMASK         ;[-5]
316
+    push    x4                  ;[-4]
317
+doExorN1:
318
+    eor     x1, x2              ;[-2] [06] [62]
319
+    ldi     x4, 6               ;[-1] [07] [63]
320
+commonN1:
321
+stuffN2Delay:
322
+    out     USBOUT, x1          ;[00] [08] [64] <--- set bit
323
+    ror     shift               ;[01]
324
+    brcc    doExorN2            ;[02]
325
+    subi    x4, 1               ;[03]
326
+    brne    commonN2            ;[04]
327
+    lsl     shift               ;[05] compensate ror after rjmp stuffDelay
328
+    rjmp    stuffN2Delay        ;[06] after ror, C bit is reliably clear
329
+doExorN2:
330
+    eor     x1, x2              ;[04] [12]
331
+    ldi     x4, 6               ;[05] [13]
332
+commonN2:
333
+    nop                         ;[06] [14]
334
+    subi    cnt, 171            ;[07] [15] trick: (3 * 171) & 0xff = 1
335
+    out     USBOUT, x1          ;[08] [16] <--- set bit
336
+    brcs    txBitloop           ;[09]      [25] [41]
337
+
338
+stuff6Delay:
339
+    ror     shift               ;[42] [50]
340
+    brcc    doExor6             ;[43]
341
+    subi    x4, 1               ;[44]
342
+    brne    common6             ;[45]
343
+    lsl     shift               ;[46] compensate ror after rjmp stuffDelay
344
+    nop                         ;[47] stuffing consists of just waiting 8 cycles
345
+    rjmp    stuff6Delay         ;[48] after ror, C bit is reliably clear
346
+doExor6:
347
+    eor     x1, x2              ;[45] [53]
348
+    ldi     x4, 6               ;[46]
349
+common6:
350
+stuff7Delay:
351
+    ror     shift               ;[47] [55]
352
+    out     USBOUT, x1          ;[48] <--- set bit
353
+    brcc    doExor7             ;[49]
354
+    subi    x4, 1               ;[50]
355
+    brne    common7             ;[51]
356
+    lsl     shift               ;[52] compensate ror after rjmp stuffDelay
357
+    rjmp    stuff7Delay         ;[53] after ror, C bit is reliably clear
358
+doExor7:
359
+    eor     x1, x2              ;[51] [59]
360
+    ldi     x4, 6               ;[52]
361
+common7:
362
+    ld      shift, y+           ;[53]
363
+    tst     cnt                 ;[55]
364
+    out     USBOUT, x1          ;[56] <--- set bit
365
+    brne    txByteLoop          ;[57]
366
+
367
+;make SE0:
368
+    cbr     x1, USBMASK         ;[58] prepare SE0 [spec says EOP may be 15 to 18 cycles]
369
+    lds     x2, usbNewDeviceAddr;[59]
370
+    lsl     x2                  ;[61] we compare with left shifted address
371
+    subi    YL, 2 + 20          ;[62] Only assign address on data packets, not ACK/NAK in x3
372
+    sbci    YH, 0               ;[63]
373
+    out     USBOUT, x1          ;[00] <-- out SE0 -- from now 2 bits = 16 cycles until bus idle
374
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
375
+;set address only after data packet was sent, not after handshake
376
+    breq    skipAddrAssign      ;[01]
377
+    sts     usbDeviceAddr, x2   ; if not skipped: SE0 is one cycle longer
378
+skipAddrAssign:
379
+;end of usbDeviceAddress transfer
380
+    ldi     x2, 1<<USB_INTR_PENDING_BIT;[03] int0 occurred during TX -- clear pending flag
381
+    USB_STORE_PENDING(x2)       ;[04]
382
+    ori     x1, USBIDLE         ;[05]
383
+    in      x2, USBDDR          ;[06]
384
+    cbr     x2, USBMASK         ;[07] set both pins to input
385
+    mov     x3, x1              ;[08]
386
+    cbr     x3, USBMASK         ;[09] configure no pullup on both pins
387
+    pop     x4                  ;[10]
388
+    nop2                        ;[12]
389
+    nop2                        ;[14]
390
+    out     USBOUT, x1          ;[16] <-- out J (idle) -- end of SE0 (EOP signal)
391
+    out     USBDDR, x2          ;[17] <-- release bus now
392
+    out     USBOUT, x3          ;[18] <-- ensure no pull-up resistors are active
393
+    rjmp    doReturn

+ 750
- 0
usbdrvasm128.inc View File

@@ -0,0 +1,750 @@
1
+/* Name: usbdrvasm128.inc
2
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
3
+ * Author: Christian Starkjohann
4
+ * Creation Date: 2008-10-11
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: usbdrvasm128.inc 758 2009-08-06 10:12:54Z 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.8 MHz version of the USB driver. It is intended for use
18
+with the internal RC oscillator. Although 12.8 MHz is outside the guaranteed
19
+calibration range of the oscillator, almost all AVRs can reach this frequency.
20
+This version contains a phase locked loop in the receiver routine to cope with
21
+slight clock rate deviations of up to +/- 1%.
22
+
23
+See usbdrv.h for a description of the entire driver.
24
+
25
+LIMITATIONS
26
+===========
27
+Although it may seem very handy to save the crystal and use the internal
28
+RC oscillator of the CPU, this method (and this module) has some serious
29
+limitations:
30
+(1) The guaranteed calibration range of the oscillator is only 8.1 MHz.
31
+They typical range is 14.5 MHz and most AVRs can actually reach this rate.
32
+(2) Writing EEPROM and Flash may be unreliable (short data lifetime) since
33
+the write procedure is timed from the RC oscillator.
34
+(3) End Of Packet detection (SE0) should be in bit 1, bit it is only checked
35
+if bits 0 and 1 both read as 0 on D- and D+ read as 0 in the middle. This may
36
+cause problems with old hubs which delay SE0 by up to one cycle.
37
+(4) Code size is much larger than that of the other modules.
38
+
39
+Since almost all of this code is timing critical, don't change unless you
40
+really know what you are doing! Many parts require not only a maximum number
41
+of CPU cycles, but even an exact number of cycles!
42
+
43
+Implementation notes:
44
+======================
45
+min frequency: 67 cycles for 8 bit -> 12.5625 MHz
46
+max frequency: 69.286 cycles for 8 bit -> 12.99 MHz
47
+nominal frequency: 12.77 MHz ( = sqrt(min * max))
48
+
49
+sampling positions: (next even number in range [+/- 0.5])
50
+cycle index range: 0 ... 66
51
+bits:
52
+.5, 8.875, 17.25, 25.625, 34, 42.375, 50.75, 59.125
53
+[0/1], [9], [17], [25/+26], [34], [+42/43], [51], [59]
54
+
55
+bit number:     0   1   2   3   4   5   6   7
56
+spare cycles    1   2   1   2   1   1   1   0
57
+
58
+operations to perform:      duration cycle
59
+                            ----------------
60
+    eor     fix, shift          1 -> 00
61
+    andi    phase, USBMASK      1 -> 08
62
+    breq    se0                 1 -> 16 (moved to 11)
63
+    st      y+, data            2 -> 24, 25
64
+    mov     data, fix           1 -> 33
65
+    ser     data                1 -> 41
66
+    subi    cnt, 1              1 -> 49
67
+    brcs    overflow            1 -> 50
68
+
69
+layout of samples and operations:
70
+[##] = sample bit
71
+<##> = sample phase
72
+*##* = operation
73
+
74
+0:  *00* [01]  02   03   04  <05>  06   07
75
+1:  *08* [09]  10   11   12  <13>  14   15  *16*
76
+2:  [17]  18   19   20  <21>  22   23
77
+3:  *24* *25* [26]  27   28   29  <30>  31   32
78
+4:  *33* [34]  35   36   37  <38>  39   40
79
+5:  *41* [42]  43   44   45  <46>  47   48
80
+6:  *49* *50* [51]  52   53   54  <55>  56   57   58
81
+7:  [59]  60   61   62  <63>  64   65   66
82
+*****************************************************************************/
83
+
84
+/* we prefer positive expressions (do if condition) instead of negative
85
+ * (skip if condition), therefore use defines for skip instructions:
86
+ */
87
+#define ifioclr sbis
88
+#define ifioset sbic
89
+#define ifrclr  sbrs
90
+#define ifrset  sbrc
91
+
92
+/* The registers "fix" and "data" swap their meaning during the loop. Use
93
+ * defines to keep their name constant.
94
+ */
95
+#define fix     x2
96
+#define data    x1
97
+#undef phase        /* phase has a default definition to x4 */
98
+#define phase   x3
99
+
100
+
101
+USB_INTR_VECTOR:
102
+;order of registers pushed: YL, SREG [sofError], YH, shift, x1, x2, x3, cnt, r0
103
+    push    YL              ;2 push only what is necessary to sync with edge ASAP
104
+    in      YL, SREG        ;1
105
+    push    YL              ;2
106
+;----------------------------------------------------------------------------
107
+; Synchronize with sync pattern:
108
+;----------------------------------------------------------------------------
109
+;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K]
110
+;sync up with J to K edge during sync pattern -- use fastest possible loops
111
+;The first part waits at most 1 bit long since we must be in sync pattern.
112
+;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to
113
+;waitForJ, ensure that this prerequisite is met.
114
+waitForJ:
115
+    inc     YL
116
+    sbis    USBIN, USBMINUS
117
+    brne    waitForJ        ; just make sure we have ANY timeout
118
+waitForK:
119
+;The following code results in a sampling window of 1/4 bit which meets the spec.
120
+    sbis    USBIN, USBMINUS
121
+    rjmp    foundK
122
+    sbis    USBIN, USBMINUS
123
+    rjmp    foundK
124
+    sbis    USBIN, USBMINUS
125
+    rjmp    foundK
126
+    sbis    USBIN, USBMINUS
127
+    rjmp    foundK
128
+    sbis    USBIN, USBMINUS ;[0]
129
+    rjmp    foundK          ;[1]
130
+#if USB_COUNT_SOF
131
+    lds     YL, usbSofCount
132
+    inc     YL
133
+    sts     usbSofCount, YL
134
+#endif  /* USB_COUNT_SOF */
135
+#ifdef USB_SOF_HOOK
136
+    USB_SOF_HOOK
137
+#endif
138
+    rjmp    sofError
139
+
140
+foundK:
141
+;{3, 5} after falling D- edge, average delay: 4 cycles [we want 4 for center sampling]
142
+;we have 1 bit time for setup purposes, then sample again. Numbers in brackets
143
+;are cycles from center of first sync (double K) bit after the instruction
144
+    push    YH                  ;[2]
145
+    lds     YL, usbInputBufOffset;[4]
146
+    clr     YH                  ;[6]
147
+    subi    YL, lo8(-(usbRxBuf));[7]
148
+    sbci    YH, hi8(-(usbRxBuf));[8]
149
+
150
+    sbis    USBIN, USBMINUS     ;[9] we want two bits K [we want to sample at 8 + 4 - 1.5 = 10.5]
151
+    rjmp    haveTwoBitsK        ;[10]
152
+    pop     YH                  ;[11] undo the push from before
153
+    rjmp    waitForK            ;[13] this was not the end of sync, retry
154
+haveTwoBitsK:
155
+;----------------------------------------------------------------------------
156
+; push more registers and initialize values while we sample the first bits:
157
+;----------------------------------------------------------------------------
158
+#define fix     x2
159
+#define data    x1
160
+
161
+    push    shift               ;[12]
162
+    push    x1                  ;[14]
163
+    push    x2                  ;[16]
164
+    ldi     shift, 0x80         ;[18] prevent bit-unstuffing but init low bits to 0
165
+    ifioset USBIN, USBMINUS     ;[19] [01] <--- bit 0 [10.5 + 8 = 18.5]
166
+    ori     shift, 1<<0         ;[02]
167
+    push    x3                  ;[03]
168
+    push    cnt                 ;[05]
169
+    push    r0                  ;[07]
170
+    ifioset USBIN, USBMINUS     ;[09] <--- bit 1
171
+    ori     shift, 1<<1         ;[10]
172
+    ser     fix                 ;[11]
173
+    ldi     cnt, USB_BUFSIZE    ;[12]
174
+    mov     data, shift         ;[13]
175
+    lsl     shift               ;[14]
176
+    nop2                        ;[15]
177
+    ifioset USBIN, USBMINUS     ;[17] <--- bit 2
178
+    ori     data, 3<<2          ;[18] store in bit 2 AND bit 3
179
+    eor     shift, data         ;[19] do nrzi decoding
180
+    andi    data, 1<<3          ;[20]
181
+    in      phase, USBIN        ;[21] <- phase
182
+    brne    jumpToEntryAfterSet ;[22] if USBMINS at bit 3 was 1
183
+    nop                         ;[23]
184
+    rjmp    entryAfterClr       ;[24]
185
+jumpToEntryAfterSet:
186
+    rjmp    entryAfterSet       ;[24]
187
+
188
+;----------------------------------------------------------------------------
189
+; Receiver loop (numbers in brackets are cycles within byte after instr)
190
+;----------------------------------------------------------------------------
191
+#undef  fix
192
+#define  fix    x1
193
+#undef  data
194
+#define data    x2
195
+
196
+bit7IsSet:
197
+    ifrclr  phase, USBMINUS     ;[62] check phase only if D- changed
198
+    lpm                         ;[63]
199
+    in      phase, USBIN        ;[64] <- phase (one cycle too late)
200
+    ori     shift, 1 << 7       ;[65]
201
+    nop                         ;[66]
202
+;;;;rjmp    bit0AfterSet        ; -> [00] == [67] moved block up to save jump
203
+bit0AfterSet:
204
+    eor     fix, shift          ;[00]
205
+#undef  fix
206
+#define fix     x2
207
+#undef  data
208
+#define data    x1  /* we now have result in data, fix is reset to 0xff */
209
+    ifioclr USBIN, USBMINUS     ;[01] <--- sample 0
210
+    rjmp    bit0IsClr           ;[02]
211
+    andi    shift, ~(7 << 0)    ;[03]
212
+    breq    unstuff0s           ;[04]
213
+    in      phase, USBIN        ;[05] <- phase
214
+    rjmp    bit1AfterSet        ;[06]
215
+unstuff0s:
216
+    in      phase, USBIN        ;[06] <- phase (one cycle too late)
217
+    andi    fix, ~(1 << 0)      ;[07]
218
+    ifioclr USBIN, USBMINUS     ;[00]
219
+    ifioset USBIN, USBPLUS      ;[01]
220
+    rjmp    bit0IsClr           ;[02] executed if first expr false or second true
221
+se0AndStore:                    ; executed only if both bits 0
222
+    st      y+, x1              ;[15/17] cycles after start of byte
223
+    rjmp    se0                 ;[17/19]
224
+
225
+bit0IsClr:
226
+    ifrset  phase, USBMINUS     ;[04] check phase only if D- changed
227
+    lpm                         ;[05]
228
+    in      phase, USBIN        ;[06] <- phase (one cycle too late)
229
+    ori     shift, 1 << 0       ;[07]
230
+bit1AfterClr:
231
+    andi    phase, USBMASK      ;[08]
232
+    ifioset USBIN, USBMINUS     ;[09] <--- sample 1
233
+    rjmp    bit1IsSet           ;[10]
234
+    breq    se0AndStore         ;[11] if D- was 0 in bits 0 AND 1 and D+ was 0 in between, we have SE0
235
+    andi    shift, ~(7 << 1)    ;[12]
236
+    in      phase, USBIN        ;[13] <- phase
237
+    breq    unstuff1c           ;[14]
238
+    rjmp    bit2AfterClr        ;[15]
239
+unstuff1c:
240
+    andi    fix, ~(1 << 1)      ;[16]
241
+    nop2                        ;[08]
242
+    nop2                        ;[10]
243
+bit1IsSet:
244
+    ifrclr  phase, USBMINUS     ;[12] check phase only if D- changed
245
+    lpm                         ;[13]
246
+    in      phase, USBIN        ;[14] <- phase (one cycle too late)
247
+    ori     shift, 1 << 1       ;[15]
248
+    nop                         ;[16]
249
+bit2AfterSet:
250
+    ifioclr USBIN, USBMINUS     ;[17] <--- sample 2
251
+    rjmp    bit2IsClr           ;[18]
252
+    andi    shift, ~(7 << 2)    ;[19]
253
+    breq    unstuff2s           ;[20]
254
+    in      phase, USBIN        ;[21] <- phase
255
+    rjmp    bit3AfterSet        ;[22]
256
+unstuff2s:
257
+    in      phase, USBIN        ;[22] <- phase (one cycle too late)
258
+    andi    fix, ~(1 << 2)      ;[23]
259
+    nop2                        ;[16]
260
+    nop2                        ;[18]
261
+bit2IsClr:
262
+    ifrset  phase, USBMINUS     ;[20] check phase only if D- changed
263
+    lpm                         ;[21]
264
+    in      phase, USBIN        ;[22] <- phase (one cycle too late)
265
+    ori     shift, 1 << 2       ;[23]
266
+bit3AfterClr:
267
+    st      y+, data            ;[24]
268
+entryAfterClr:
269
+    ifioset USBIN, USBMINUS     ;[26] <--- sample 3
270
+    rjmp    bit3IsSet           ;[27]
271
+    andi    shift, ~(7 << 3)    ;[28]
272
+    breq    unstuff3c           ;[29]
273
+    in      phase, USBIN        ;[30] <- phase
274
+    rjmp    bit4AfterClr        ;[31]
275
+unstuff3c:
276
+    in      phase, USBIN        ;[31] <- phase (one cycle too late)
277
+    andi    fix, ~(1 << 3)      ;[32]
278
+    nop2                        ;[25]
279
+    nop2                        ;[27]
280
+bit3IsSet:
281
+    ifrclr  phase, USBMINUS     ;[29] check phase only if D- changed
282
+    lpm                         ;[30]
283
+    in      phase, USBIN        ;[31] <- phase (one cycle too late)
284
+    ori     shift, 1 << 3       ;[32]
285
+bit4AfterSet:
286
+    mov     data, fix           ;[33] undo this move by swapping defines
287
+#undef  fix
288
+#define fix     x1
289
+#undef  data
290
+#define data    x2
291
+    ifioclr USBIN, USBMINUS     ;[34] <--- sample 4
292
+    rjmp    bit4IsClr           ;[35]
293
+    andi    shift, ~(7 << 4)    ;[36]
294
+    breq    unstuff4s           ;[37]
295
+    in      phase, USBIN        ;[38] <- phase
296
+    rjmp    bit5AfterSet        ;[39]
297
+unstuff4s:
298
+    in      phase, USBIN        ;[39] <- phase (one cycle too late)
299
+    andi    fix, ~(1 << 4)      ;[40]
300
+    nop2                        ;[33]
301
+    nop2                        ;[35]
302
+bit4IsClr:
303
+    ifrset  phase, USBMINUS     ;[37] check phase only if D- changed
304
+    lpm                         ;[38]
305
+    in      phase, USBIN        ;[39] <- phase (one cycle too late)
306
+    ori     shift, 1 << 4       ;[40]
307
+bit5AfterClr:
308
+    ser     data                ;[41]
309
+    ifioset USBIN, USBMINUS     ;[42] <--- sample 5
310
+    rjmp    bit5IsSet           ;[43]
311
+    andi    shift, ~(7 << 5)    ;[44]
312
+    breq    unstuff5c           ;[45]
313
+    in      phase, USBIN        ;[46] <- phase
314
+    rjmp    bit6AfterClr        ;[47]
315
+unstuff5c:
316
+    in      phase, USBIN        ;[47] <- phase (one cycle too late)
317
+    andi    fix, ~(1 << 5)      ;[48]
318
+    nop2                        ;[41]
319
+    nop2                        ;[43]
320
+bit5IsSet:
321
+    ifrclr  phase, USBMINUS     ;[45] check phase only if D- changed
322
+    lpm                         ;[46]
323
+    in      phase, USBIN        ;[47] <- phase (one cycle too late)
324
+    ori     shift, 1 << 5       ;[48]
325
+bit6AfterSet:
326
+    subi    cnt, 1              ;[49]
327
+    brcs    jumpToOverflow      ;[50]
328
+    ifioclr USBIN, USBMINUS     ;[51] <--- sample 6
329
+    rjmp    bit6IsClr           ;[52]
330
+    andi    shift, ~(3 << 6)    ;[53]
331
+    cpi     shift, 2            ;[54]
332
+    in      phase, USBIN        ;[55] <- phase
333
+    brlt    unstuff6s           ;[56]
334
+    rjmp    bit7AfterSet        ;[57]
335
+
336
+jumpToOverflow:
337
+    rjmp    overflow
338
+
339
+unstuff6s:
340
+    andi    fix, ~(1 << 6)      ;[50]
341
+    lpm                         ;[51]
342
+bit6IsClr:
343
+    ifrset  phase, USBMINUS     ;[54] check phase only if D- changed
344
+    lpm                         ;[55]
345
+    in      phase, USBIN        ;[56] <- phase (one cycle too late)
346
+    ori     shift, 1 << 6       ;[57]
347
+    nop                         ;[58]
348
+bit7AfterClr:
349
+    ifioset USBIN, USBMINUS     ;[59] <--- sample 7
350
+    rjmp    bit7IsSet           ;[60]
351
+    andi    shift, ~(1 << 7)    ;[61]
352
+    cpi     shift, 4            ;[62]
353
+    in      phase, USBIN        ;[63] <- phase
354
+    brlt    unstuff7c           ;[64]
355
+    rjmp    bit0AfterClr        ;[65] -> [00] == [67]
356
+unstuff7c:
357
+    andi    fix, ~(1 << 7)      ;[58]
358
+    nop                         ;[59]
359
+    rjmp    bit7IsSet           ;[60]
360
+
361
+bit7IsClr:
362
+    ifrset  phase, USBMINUS     ;[62] check phase only if D- changed
363
+    lpm                         ;[63]
364
+    in      phase, USBIN        ;[64] <- phase (one cycle too late)
365
+    ori     shift, 1 << 7       ;[65]
366
+    nop                         ;[66]
367
+;;;;rjmp    bit0AfterClr        ; -> [00] == [67] moved block up to save jump
368
+bit0AfterClr:
369
+    eor     fix, shift          ;[00]
370
+#undef  fix
371
+#define fix     x2
372
+#undef  data
373
+#define data    x1  /* we now have result in data, fix is reset to 0xff */
374
+    ifioset USBIN, USBMINUS     ;[01] <--- sample 0
375
+    rjmp    bit0IsSet           ;[02]
376
+    andi    shift, ~(7 << 0)    ;[03]
377
+    breq    unstuff0c           ;[04]
378
+    in      phase, USBIN        ;[05] <- phase
379
+    rjmp    bit1AfterClr        ;[06]
380
+unstuff0c:
381
+    in      phase, USBIN        ;[06] <- phase (one cycle too late)
382
+    andi    fix, ~(1 << 0)      ;[07]
383
+    ifioclr USBIN, USBMINUS     ;[00]
384
+    ifioset USBIN, USBPLUS      ;[01]
385
+    rjmp    bit0IsSet           ;[02] executed if first expr false or second true
386
+    rjmp    se0AndStore         ;[03] executed only if both bits 0
387
+bit0IsSet:
388
+    ifrclr  phase, USBMINUS     ;[04] check phase only if D- changed
389
+    lpm                         ;[05]
390
+    in      phase, USBIN        ;[06] <- phase (one cycle too late)
391
+    ori     shift, 1 << 0       ;[07]
392
+bit1AfterSet:
393
+    andi    shift, ~(7 << 1)    ;[08] compensated by "ori shift, 1<<1" if bit1IsClr
394
+    ifioclr USBIN, USBMINUS     ;[09] <--- sample 1
395
+    rjmp    bit1IsClr           ;[10]
396
+    breq    unstuff1s           ;[11]
397
+    nop2                        ;[12] do not check for SE0 if bit 0 was 1
398
+    in      phase, USBIN        ;[14] <- phase (one cycle too late)
399
+    rjmp    bit2AfterSet        ;[15]
400
+unstuff1s:
401
+    in      phase, USBIN        ;[13] <- phase
402
+    andi    fix, ~(1 << 1)      ;[14]
403
+    lpm                         ;[07]
404
+    nop2                        ;[10]
405
+bit1IsClr:
406
+    ifrset  phase, USBMINUS     ;[12] check phase only if D- changed
407
+    lpm                         ;[13]
408
+    in      phase, USBIN        ;[14] <- phase (one cycle too late)
409
+    ori     shift, 1 << 1       ;[15]
410
+    nop                         ;[16]
411
+bit2AfterClr:
412
+    ifioset USBIN, USBMINUS     ;[17] <--- sample 2
413
+    rjmp    bit2IsSet           ;[18]
414
+    andi    shift, ~(7 << 2)    ;[19]
415
+    breq    unstuff2c           ;[20]
416
+    in      phase, USBIN        ;[21] <- phase
417
+    rjmp    bit3AfterClr        ;[22]
418
+unstuff2c:
419
+    in      phase, USBIN        ;[22] <- phase (one cycle too late)
420
+    andi    fix, ~(1 << 2)      ;[23]
421
+    nop2                        ;[16]
422
+    nop2                        ;[18]
423
+bit2IsSet:
424
+    ifrclr  phase, USBMINUS     ;[20] check phase only if D- changed
425
+    lpm                         ;[21]
426
+    in      phase, USBIN        ;[22] <- phase (one cycle too late)
427
+    ori     shift, 1 << 2       ;[23]
428
+bit3AfterSet:
429
+    st      y+, data            ;[24]
430
+entryAfterSet:
431
+    ifioclr USBIN, USBMINUS     ;[26] <--- sample 3
432
+    rjmp    bit3IsClr           ;[27]
433
+    andi    shift, ~(7 << 3)    ;[28]
434
+    breq    unstuff3s           ;[29]
435
+    in      phase, USBIN        ;[30] <- phase
436
+    rjmp    bit4AfterSet        ;[31]
437
+unstuff3s:
438
+    in      phase, USBIN        ;[31] <- phase (one cycle too late)
439
+    andi    fix, ~(1 << 3)      ;[32]
440
+    nop2                        ;[25]
441
+    nop2                        ;[27]
442
+bit3IsClr:
443
+    ifrset  phase, USBMINUS     ;[29] check phase only if D- changed
444
+    lpm                         ;[30]
445
+    in      phase, USBIN        ;[31] <- phase (one cycle too late)
446
+    ori     shift, 1 << 3       ;[32]
447
+bit4AfterClr:
448
+    mov     data, fix           ;[33] undo this move by swapping defines
449
+#undef  fix
450
+#define fix     x1
451
+#undef  data
452
+#define data    x2
453
+    ifioset USBIN, USBMINUS     ;[34] <--- sample 4
454
+    rjmp    bit4IsSet           ;[35]
455
+    andi    shift, ~(7 << 4)    ;[36]
456
+    breq    unstuff4c           ;[37]
457
+    in      phase, USBIN        ;[38] <- phase
458
+    rjmp    bit5AfterClr        ;[39]
459
+unstuff4c:
460
+    in      phase, USBIN        ;[39] <- phase (one cycle too late)
461
+    andi    fix, ~(1 << 4)      ;[40]
462
+    nop2                        ;[33]
463
+    nop2                        ;[35]
464
+bit4IsSet:
465
+    ifrclr  phase, USBMINUS     ;[37] check phase only if D- changed
466
+    lpm                         ;[38]
467
+    in      phase, USBIN        ;[39] <- phase (one cycle too late)
468
+    ori     shift, 1 << 4       ;[40]
469
+bit5AfterSet:
470
+    ser     data                ;[41]
471
+    ifioclr USBIN, USBMINUS     ;[42] <--- sample 5
472
+    rjmp    bit5IsClr           ;[43]
473
+    andi    shift, ~(7 << 5)    ;[44]
474
+    breq    unstuff5s           ;[45]
475
+    in      phase, USBIN        ;[46] <- phase
476
+    rjmp    bit6AfterSet        ;[47]
477
+unstuff5s:
478
+    in      phase, USBIN        ;[47] <- phase (one cycle too late)
479
+    andi    fix, ~(1 << 5)      ;[48]
480
+    nop2                        ;[41]
481
+    nop2                        ;[43]
482
+bit5IsClr:
483
+    ifrset  phase, USBMINUS     ;[45] check phase only if D- changed
484
+    lpm                         ;[46]
485
+    in      phase, USBIN        ;[47] <- phase (one cycle too late)
486
+    ori     shift, 1 << 5       ;[48]
487
+bit6AfterClr:
488
+    subi    cnt, 1              ;[49]
489
+    brcs    overflow            ;[50]
490
+    ifioset USBIN, USBMINUS     ;[51] <--- sample 6
491
+    rjmp    bit6IsSet           ;[52]
492
+    andi    shift, ~(3 << 6)    ;[53]
493
+    cpi     shift, 2            ;[54]
494
+    in      phase, USBIN        ;[55] <- phase
495
+    brlt    unstuff6c           ;[56]
496
+    rjmp    bit7AfterClr        ;[57]
497
+unstuff6c:
498
+    andi    fix, ~(1 << 6)      ;[50]
499
+    lpm                         ;[51]
500
+bit6IsSet:
501
+    ifrclr  phase, USBMINUS     ;[54] check phase only if D- changed
502
+    lpm                         ;[55]
503
+    in      phase, USBIN        ;[56] <- phase (one cycle too late)
504
+    ori     shift, 1 << 6       ;[57]
505
+bit7AfterSet:
506
+    ifioclr USBIN, USBMINUS     ;[59] <--- sample 7
507
+    rjmp    bit7IsClr           ;[60]
508
+    andi    shift, ~(1 << 7)    ;[61]
509
+    cpi     shift, 4            ;[62]
510
+    in      phase, USBIN        ;[63] <- phase
511
+    brlt    unstuff7s           ;[64]
512
+    rjmp    bit0AfterSet        ;[65] -> [00] == [67]
513
+unstuff7s:
514
+    andi    fix, ~(1 << 7)      ;[58]
515
+    nop                         ;[59]
516
+    rjmp    bit7IsClr           ;[60]
517
+
518
+macro POP_STANDARD ; 14 cycles
519
+    pop     r0
520
+    pop     cnt
521
+    pop     x3
522
+    pop     x2
523
+    pop     x1
524
+    pop     shift
525
+    pop     YH
526
+    endm
527
+macro POP_RETI     ; 5 cycles
528
+    pop     YL
529
+    out     SREG, YL
530
+    pop     YL
531
+    endm
532
+
533
+#include "asmcommon.inc"
534
+
535
+;----------------------------------------------------------------------------
536
+; Transmitting data
537
+;----------------------------------------------------------------------------
538
+
539
+txByteLoop:
540
+txBitloop:
541
+stuffN1Delay:                   ;     [03]
542
+    ror     shift               ;[-5] [11] [63]
543
+    brcc    doExorN1            ;[-4]      [64]
544
+    subi    x3, 1               ;[-3]
545
+    brne    commonN1            ;[-2]
546
+    lsl     shift               ;[-1] compensate ror after rjmp stuffDelay
547
+    nop                         ;[00] stuffing consists of just waiting 8 cycles
548
+    rjmp    stuffN1Delay        ;[01] after ror, C bit is reliably clear
549
+
550
+sendNakAndReti:
551
+    ldi     cnt, USBPID_NAK ;[-19]
552
+    rjmp    sendCntAndReti  ;[-18]
553
+sendAckAndReti:
554
+    ldi     cnt, USBPID_ACK ;[-17]
555
+sendCntAndReti:
556
+    mov     r0, cnt         ;[-16]
557
+    ldi     YL, 0           ;[-15] R0 address is 0
558
+    ldi     YH, 0           ;[-14]
559
+    ldi     cnt, 2          ;[-13]
560
+;   rjmp    usbSendAndReti      fallthrough
561
+
562
+; USB spec says:
563
+; idle = J
564
+; J = (D+ = 0), (D- = 1) or USBOUT = 0x01
565
+; K = (D+ = 1), (D- = 0) or USBOUT = 0x02
566
+; Spec allows 7.5 bit times from EOP to SOP for replies (= 60 cycles)
567
+
568
+;usbSend:
569
+;pointer to data in 'Y'
570
+;number of bytes in 'cnt' -- including sync byte
571
+;uses: x1...x3, shift, cnt, Y [x1 = mirror USBOUT, x2 = USBMASK, x3 = bitstuff cnt]
572
+;Numbers in brackets are time since first bit of sync pattern is sent (start of instruction)
573
+usbSendAndReti:
574
+    in      x2, USBDDR          ;[-10] 10 cycles until SOP
575
+    ori     x2, USBMASK         ;[-9]
576
+    sbi     USBOUT, USBMINUS    ;[-8] prepare idle state; D+ and D- must have been 0 (no pullups)
577
+    out     USBDDR, x2          ;[-6] <--- acquire bus
578
+    in      x1, USBOUT          ;[-5] port mirror for tx loop
579
+    ldi     shift, 0x40         ;[-4] sync byte is first byte sent (we enter loop after ror)
580
+    ldi     x2, USBMASK         ;[-3]
581
+doExorN1:
582
+    eor     x1, x2              ;[-2] [06] [62]
583
+    ldi     x3, 6               ;[-1] [07] [63]
584
+commonN1:
585
+stuffN2Delay:
586
+    out     USBOUT, x1          ;[00] [08] [64] <--- set bit
587
+    ror     shift               ;[01]
588
+    brcc    doExorN2            ;[02]
589
+    subi    x3, 1               ;[03]
590
+    brne    commonN2            ;[04]
591
+    lsl     shift               ;[05] compensate ror after rjmp stuffDelay
592
+    rjmp    stuffN2Delay        ;[06] after ror, C bit is reliably clear
593
+doExorN2:
594
+    eor     x1, x2              ;[04] [12]
595
+    ldi     x3, 6               ;[05] [13]
596
+commonN2:
597
+    nop2                        ;[06] [14]
598
+    subi    cnt, 171            ;[08] [16] trick: (3 * 171) & 0xff = 1
599
+    out     USBOUT, x1          ;[09] [17] <--- set bit
600
+    brcs    txBitloop           ;[10]      [27] [44]
601
+
602
+stuff6Delay:
603
+    ror     shift               ;[45] [53]
604
+    brcc    doExor6             ;[46]
605
+    subi    x3, 1               ;[47]
606
+    brne    common6             ;[48]
607
+    lsl     shift               ;[49] compensate ror after rjmp stuffDelay
608
+    nop                         ;[50] stuffing consists of just waiting 8 cycles
609
+    rjmp    stuff6Delay         ;[51] after ror, C bit is reliably clear
610
+doExor6:
611
+    eor     x1, x2              ;[48] [56]
612
+    ldi     x3, 6               ;[49]
613
+common6:
614
+stuff7Delay:
615
+    ror     shift               ;[50] [58]
616
+    out     USBOUT, x1          ;[51] <--- set bit
617
+    brcc    doExor7             ;[52]
618
+    subi    x3, 1               ;[53]
619
+    brne    common7             ;[54]
620
+    lsl     shift               ;[55] compensate ror after rjmp stuffDelay
621
+    rjmp    stuff7Delay         ;[56] after ror, C bit is reliably clear
622
+doExor7:
623
+    eor     x1, x2              ;[54] [62]
624
+    ldi     x3, 6               ;[55]
625
+common7:
626
+    ld      shift, y+           ;[56]
627
+    nop                         ;[58]
628
+    tst     cnt                 ;[59]
629
+    out     USBOUT, x1          ;[60] [00]<--- set bit
630
+    brne    txByteLoop          ;[61] [01]
631
+;make SE0:
632
+    cbr     x1, USBMASK         ;[02] prepare SE0 [spec says EOP may be 15 to 18 cycles]
633
+    lds     x2, usbNewDeviceAddr;[03]
634
+    lsl     x2                  ;[05] we compare with left shifted address
635
+    subi    YL, 2 + 0           ;[06] Only assign address on data packets, not ACK/NAK in r0
636
+    sbci    YH, 0               ;[07]
637
+    out     USBOUT, x1          ;[00] <-- out SE0 -- from now 2 bits = 16 cycles until bus idle
638
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
639
+;set address only after data packet was sent, not after handshake
640
+    breq    skipAddrAssign      ;[01]
641
+    sts     usbDeviceAddr, x2   ; if not skipped: SE0 is one cycle longer
642
+skipAddrAssign:
643
+;end of usbDeviceAddress transfer
644
+    ldi     x2, 1<<USB_INTR_PENDING_BIT;[03] int0 occurred during TX -- clear pending flag
645
+    USB_STORE_PENDING(x2)       ;[04]
646
+    ori     x1, USBIDLE         ;[05]
647
+    in      x2, USBDDR          ;[06]
648
+    cbr     x2, USBMASK         ;[07] set both pins to input
649
+    mov     x3, x1              ;[08]
650
+    cbr     x3, USBMASK         ;[09] configure no pullup on both pins
651
+    lpm                         ;[10]
652
+    lpm                         ;[13]
653
+    out     USBOUT, x1          ;[16] <-- out J (idle) -- end of SE0 (EOP signal)
654
+    out     USBDDR, x2          ;[17] <-- release bus now
655
+    out     USBOUT, x3          ;[18] <-- ensure no pull-up resistors are active
656
+    rjmp    doReturn
657
+
658
+
659
+
660
+/*****************************************************************************
661
+The following PHP script generates a code skeleton for the receiver routine:
662
+
663
+<?php
664
+
665
+function printCmdBuffer($thisBit)
666
+{
667
+global $cycle;
668
+
669
+    $nextBit = ($thisBit + 1) % 8;
670
+    $s = ob_get_contents();
671
+    ob_end_clean();
672
+    $s = str_replace("#", $thisBit, $s);
673
+    $s = str_replace("@", $nextBit, $s);
674
+    $lines = explode("\n", $s);
675
+    for($i = 0; $i < count($lines); $i++){
676
+        $s = $lines[$i];
677
+        if(ereg("\\[([0-9-][0-9])\\]", $s, $regs)){
678
+            $c = $cycle + (int)$regs[1];
679
+            $s = ereg_replace("\\[[0-9-][0-9]\\]", sprintf("[%02d]", $c), $s);
680
+        }
681
+        if(strlen($s) > 0)
682
+            echo "$s\n";
683
+    }
684
+}
685
+
686
+function printBit($isAfterSet, $bitNum)
687
+{
688
+    ob_start();
689
+    if($isAfterSet){
690
+?>
691
+    ifioclr USBIN, USBMINUS     ;[00] <--- sample
692
+    rjmp    bit#IsClr           ;[01]
693
+    andi    shift, ~(7 << #)    ;[02]
694
+    breq    unstuff#s           ;[03]
695
+    in      phase, USBIN        ;[04] <- phase
696
+    rjmp    bit@AfterSet        ;[05]
697
+unstuff#s:
698
+    in      phase, USBIN        ;[05] <- phase (one cycle too late)
699
+    andi    fix, ~(1 << #)      ;[06]
700
+    nop2                        ;[-1]
701
+    nop2                        ;[01]
702
+bit#IsClr:
703
+    ifrset  phase, USBMINUS     ;[03] check phase only if D- changed
704
+    lpm                         ;[04]
705
+    in      phase, USBIN        ;[05] <- phase (one cycle too late)
706
+    ori     shift, 1 << #       ;[06]
707
+<?php
708
+    }else{
709
+?>
710
+    ifioset USBIN, USBMINUS     ;[00] <--- sample
711
+    rjmp    bit#IsSet           ;[01]
712
+    andi    shift, ~(7 << #)    ;[02]
713
+    breq    unstuff#c           ;[03]
714
+    in      phase, USBIN        ;[04] <- phase
715
+    rjmp    bit@AfterClr        ;[05]
716
+unstuff#c:
717
+    in      phase, USBIN        ;[05] <- phase (one cycle too late)
718
+    andi    fix, ~(1 << #)      ;[06]
719
+    nop2                        ;[-1]
720
+    nop2                        ;[01]
721
+bit#IsSet:
722
+    ifrclr  phase, USBMINUS     ;[03] check phase only if D- changed
723
+    lpm                         ;[04]
724
+    in      phase, USBIN        ;[05] <- phase (one cycle too late)
725
+    ori     shift, 1 << #       ;[06]
726
+<?php
727
+    }
728
+    printCmdBuffer($bitNum);
729
+}
730
+
731
+$bitStartCycles = array(1, 9, 17, 26, 34, 42, 51, 59);
732
+for($i = 0; $i < 16; $i++){
733
+    $bit = $i % 8;
734
+    $emitClrCode = ($i + (int)($i / 8)) % 2;
735
+    $cycle = $bitStartCycles[$bit];
736
+    if($emitClrCode){
737
+        printf("bit%dAfterClr:\n", $bit);
738
+    }else{
739
+        printf("bit%dAfterSet:\n", $bit);
740
+    }
741
+    ob_start();
742
+    echo "    *****                       ;[-1]\n";
743
+    printCmdBuffer($bit);
744
+    printBit(!$emitClrCode, $bit);
745
+    if($i == 7)
746
+        echo "\n";
747
+}
748
+
749
+?>
750
+*****************************************************************************/

+ 423
- 0
usbdrvasm15.inc View File

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

+ 346
- 0
usbdrvasm16.inc View File

@@ -0,0 +1,346 @@
1
+/* Name: usbdrvasm16.inc
2
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
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), GNU GPL v3 or proprietary (CommercialLicense.txt)
8
+ * Revision: $Id: usbdrvasm16.inc 760 2009-08-09 18:59:43Z 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 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
+;The first part waits at most 1 bit long since we must be in sync pattern.
45
+;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to
46
+;waitForJ, ensure that this prerequisite is met.
47
+waitForJ:
48
+    inc     YL
49
+    sbis    USBIN, USBMINUS
50
+    brne    waitForJ        ; just make sure we have ANY timeout
51
+waitForK:
52
+;The following code results in a sampling window of < 1/4 bit which meets the spec.
53
+    sbis    USBIN, USBMINUS     ;[-15]
54
+    rjmp    foundK              ;[-14]
55
+    sbis    USBIN, USBMINUS
56
+    rjmp    foundK
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
+#if USB_COUNT_SOF
66
+    lds     YL, usbSofCount
67
+    inc     YL
68
+    sts     usbSofCount, YL
69
+#endif  /* USB_COUNT_SOF */
70
+#ifdef USB_SOF_HOOK
71
+    USB_SOF_HOOK
72
+#endif
73
+    rjmp    sofError
74
+foundK:                         ;[-12]
75
+;{3, 5} after falling D- edge, average delay: 4 cycles [we want 5 for center sampling]
76
+;we have 1 bit time for setup purposes, then sample again. Numbers in brackets
77
+;are cycles from center of first sync (double K) bit after the instruction
78
+    push    bitcnt              ;[-12]
79
+;   [---]                       ;[-11]
80
+    lds     YL, usbInputBufOffset;[-10]
81
+;   [---]                       ;[-9]
82
+    clr     YH                  ;[-8]
83
+    subi    YL, lo8(-(usbRxBuf));[-7] [rx loop init]
84
+    sbci    YH, hi8(-(usbRxBuf));[-6] [rx loop init]
85
+    push    shift               ;[-5]
86
+;   [---]                       ;[-4]
87
+    ldi     bitcnt, 0x55        ;[-3] [rx loop init]
88
+    sbis    USBIN, USBMINUS     ;[-2] we want two bits K (sample 2 cycles too early)
89
+    rjmp    haveTwoBitsK        ;[-1]
90
+    pop     shift               ;[0] undo the push from before
91
+    pop     bitcnt              ;[2] undo the push from before
92
+    rjmp    waitForK            ;[4] this was not the end of sync, retry
93
+; The entire loop from waitForK until rjmp waitForK above must not exceed two
94
+; bit times (= 21 cycles).
95
+
96
+;----------------------------------------------------------------------------
97
+; push more registers and initialize values while we sample the first bits:
98
+;----------------------------------------------------------------------------
99
+haveTwoBitsK:
100
+    push    x1              ;[1]
101
+    push    x2              ;[3]
102
+    push    x3              ;[5]
103
+    ldi     shift, 0        ;[7]
104
+    ldi     x3, 1<<4        ;[8] [rx loop init] first sample is inverse bit, compensate that
105
+    push    x4              ;[9] == leap
106
+
107
+    in      x1, USBIN       ;[11] <-- sample bit 0
108
+    andi    x1, USBMASK     ;[12]
109
+    bst     x1, USBMINUS    ;[13]
110
+    bld     shift, 7        ;[14]
111
+    push    cnt             ;[15]
112
+    ldi     leap, 0         ;[17] [rx loop init]
113
+    ldi     cnt, USB_BUFSIZE;[18] [rx loop init]
114
+    rjmp    rxbit1          ;[19] arrives at [21]
115
+
116
+;----------------------------------------------------------------------------
117
+; Receiver loop (numbers in brackets are cycles within byte after instr)
118
+;----------------------------------------------------------------------------
119
+
120
+; duration of unstuffing code should be 10.66666667 cycles. We adjust "leap"
121
+; accordingly to approximate this value in the long run.
122
+
123
+unstuff6:
124
+    andi    x2, USBMASK ;[03]
125
+    ori     x3, 1<<6    ;[04] will not be shifted any more
126
+    andi    shift, ~0x80;[05]
127
+    mov     x1, x2      ;[06] sampled bit 7 is actually re-sampled bit 6
128
+    subi    leap, -1    ;[07] total duration = 11 bits -> subtract 1/3
129
+    rjmp    didUnstuff6 ;[08]
130
+
131
+unstuff7:
132
+    ori     x3, 1<<7    ;[09] will not be shifted any more
133
+    in      x2, USBIN   ;[00] [10]  re-sample bit 7
134
+    andi    x2, USBMASK ;[01]
135
+    andi    shift, ~0x80;[02]
136
+    subi    leap, 2     ;[03] total duration = 10 bits -> add 1/3
137
+    rjmp    didUnstuff7 ;[04]
138
+
139
+unstuffEven:
140
+    ori     x3, 1<<6    ;[09] will be shifted right 6 times for bit 0
141
+    in      x1, USBIN   ;[00] [10]
142
+    andi    shift, ~0x80;[01]
143
+    andi    x1, USBMASK ;[02]
144
+    breq    se0         ;[03]
145
+    subi    leap, -1    ;[04] total duration = 11 bits -> subtract 1/3
146
+    nop2                ;[05]
147
+    rjmp    didUnstuffE ;[06]
148
+
149
+unstuffOdd:
150
+    ori     x3, 1<<5    ;[09] will be shifted right 4 times for bit 1
151
+    in      x2, USBIN   ;[00] [10]
152
+    andi    shift, ~0x80;[01]
153
+    andi    x2, USBMASK ;[02]
154
+    breq    se0         ;[03]
155
+    subi    leap, -1    ;[04] total duration = 11 bits -> subtract 1/3
156
+    nop2                ;[05]
157
+    rjmp    didUnstuffO ;[06]
158
+
159
+rxByteLoop:
160
+    andi    x1, USBMASK ;[03]
161
+    eor     x2, x1      ;[04]
162
+    subi    leap, 1     ;[05]
163
+    brpl    skipLeap    ;[06]
164
+    subi    leap, -3    ;1 one leap cycle every 3rd byte -> 85 + 1/3 cycles per byte
165
+    nop                 ;1
166
+skipLeap:
167
+    subi    x2, 1       ;[08]
168
+    ror     shift       ;[09]
169
+didUnstuff6:
170
+    cpi     shift, 0xfc ;[10]
171
+    in      x2, USBIN   ;[00] [11] <-- sample bit 7
172
+    brcc    unstuff6    ;[01]
173
+    andi    x2, USBMASK ;[02]
174
+    eor     x1, x2      ;[03]
175
+    subi    x1, 1       ;[04]
176
+    ror     shift       ;[05]
177
+didUnstuff7:
178
+    cpi     shift, 0xfc ;[06]
179
+    brcc    unstuff7    ;[07]
180
+    eor     x3, shift   ;[08] reconstruct: x3 is 1 at bit locations we changed, 0 at others
181
+    st      y+, x3      ;[09] store data
182
+rxBitLoop:
183
+    in      x1, USBIN   ;[00] [11] <-- sample bit 0/2/4
184
+    andi    x1, USBMASK ;[01]
185
+    eor     x2, x1      ;[02]
186
+    andi    x3, 0x3f    ;[03] topmost two bits reserved for 6 and 7
187
+    subi    x2, 1       ;[04]
188
+    ror     shift       ;[05]
189
+    cpi     shift, 0xfc ;[06]
190
+    brcc    unstuffEven ;[07]
191
+didUnstuffE:
192
+    lsr     x3          ;[08]
193
+    lsr     x3          ;[09]
194
+rxbit1:
195
+    in      x2, USBIN   ;[00] [10] <-- sample bit 1/3/5
196
+    andi    x2, USBMASK ;[01]
197
+    breq    se0         ;[02]
198
+    eor     x1, x2      ;[03]
199
+    subi    x1, 1       ;[04]
200
+    ror     shift       ;[05]
201
+    cpi     shift, 0xfc ;[06]
202
+    brcc    unstuffOdd  ;[07]
203
+didUnstuffO:
204
+    subi    bitcnt, 0xab;[08] == addi 0x55, 0x55 = 0x100/3
205
+    brcs    rxBitLoop   ;[09]
206
+
207
+    subi    cnt, 1      ;[10]
208
+    in      x1, USBIN   ;[00] [11] <-- sample bit 6
209
+    brcc    rxByteLoop  ;[01]
210
+    rjmp    overflow
211
+
212
+macro POP_STANDARD ; 14 cycles
213
+    pop     cnt
214
+    pop     x4
215
+    pop     x3
216
+    pop     x2
217
+    pop     x1
218
+    pop     shift
219
+    pop     bitcnt
220
+    endm
221
+macro POP_RETI     ; 7 cycles
222
+    pop     YH
223
+    pop     YL
224
+    out     SREG, YL
225
+    pop     YL
226
+    endm
227
+
228
+#include "asmcommon.inc"
229
+
230
+; USB spec says:
231
+; idle = J
232
+; J = (D+ = 0), (D- = 1)
233
+; K = (D+ = 1), (D- = 0)
234
+; Spec allows 7.5 bit times from EOP to SOP for replies
235
+
236
+bitstuffN:
237
+    eor     x1, x4          ;[5]
238
+    ldi     x2, 0           ;[6]
239
+    nop2                    ;[7]
240
+    nop                     ;[9]
241
+    out     USBOUT, x1      ;[10] <-- out
242
+    rjmp    didStuffN       ;[0]
243
+    
244
+bitstuff6:
245
+    eor     x1, x4          ;[5]
246
+    ldi     x2, 0           ;[6] Carry is zero due to brcc
247
+    rol     shift           ;[7] compensate for ror shift at branch destination
248
+    rjmp    didStuff6       ;[8]
249
+
250
+bitstuff7:
251
+    ldi     x2, 0           ;[2] Carry is zero due to brcc
252
+    rjmp    didStuff7       ;[3]
253
+
254
+
255
+sendNakAndReti:
256
+    ldi     x3, USBPID_NAK  ;[-18]
257
+    rjmp    sendX3AndReti   ;[-17]
258
+sendAckAndReti:
259
+    ldi     cnt, USBPID_ACK ;[-17]
260
+sendCntAndReti:
261
+    mov     x3, cnt         ;[-16]
262
+sendX3AndReti:
263
+    ldi     YL, 20          ;[-15] x3==r20 address is 20
264
+    ldi     YH, 0           ;[-14]
265
+    ldi     cnt, 2          ;[-13]
266
+;   rjmp    usbSendAndReti      fallthrough
267
+
268
+;usbSend:
269
+;pointer to data in 'Y'
270
+;number of bytes in 'cnt' -- including sync byte [range 2 ... 12]
271
+;uses: x1...x4, btcnt, shift, cnt, Y
272
+;Numbers in brackets are time since first bit of sync pattern is sent
273
+;We don't match the transfer rate exactly (don't insert leap cycles every third
274
+;byte) because the spec demands only 1.5% precision anyway.
275
+usbSendAndReti:             ; 12 cycles until SOP
276
+    in      x2, USBDDR      ;[-12]
277
+    ori     x2, USBMASK     ;[-11]
278
+    sbi     USBOUT, USBMINUS;[-10] prepare idle state; D+ and D- must have been 0 (no pullups)
279
+    in      x1, USBOUT      ;[-8] port mirror for tx loop
280
+    out     USBDDR, x2      ;[-7] <- acquire bus
281
+; need not init x2 (bitstuff history) because sync starts with 0
282
+    ldi     x4, USBMASK     ;[-6] exor mask
283
+    ldi     shift, 0x80     ;[-5] sync byte is first byte sent
284
+txByteLoop:
285
+    ldi     bitcnt, 0x35    ;[-4] [6] binary 0011 0101
286
+txBitLoop:
287
+    sbrs    shift, 0        ;[-3] [7]
288
+    eor     x1, x4          ;[-2] [8]
289
+    out     USBOUT, x1      ;[-1] [9] <-- out N
290
+    ror     shift           ;[0] [10]
291
+    ror     x2              ;[1]
292
+didStuffN:
293
+    cpi     x2, 0xfc        ;[2]
294
+    brcc    bitstuffN       ;[3]
295
+    lsr     bitcnt          ;[4]
296
+    brcc    txBitLoop       ;[5]
297
+    brne    txBitLoop       ;[6]
298
+
299
+    sbrs    shift, 0        ;[7]
300
+    eor     x1, x4          ;[8]
301
+didStuff6:
302
+    out     USBOUT, x1      ;[-1] [9] <-- out 6
303
+    ror     shift           ;[0] [10]
304
+    ror     x2              ;[1]
305
+    cpi     x2, 0xfc        ;[2]
306
+    brcc    bitstuff6       ;[3]
307
+    ror     shift           ;[4]
308
+didStuff7:
309
+    ror     x2              ;[5]
310
+    sbrs    x2, 7           ;[6]
311
+    eor     x1, x4          ;[7]
312
+    nop                     ;[8]
313
+    cpi     x2, 0xfc        ;[9]
314
+    out     USBOUT, x1      ;[-1][10] <-- out 7
315
+    brcc    bitstuff7       ;[0] [11]
316
+    ld      shift, y+       ;[1]
317
+    dec     cnt             ;[3]
318
+    brne    txByteLoop      ;[4]
319
+;make SE0:
320
+    cbr     x1, USBMASK     ;[5] prepare SE0 [spec says EOP may be 21 to 25 cycles]
321
+    lds     x2, usbNewDeviceAddr;[6]
322
+    lsl     x2              ;[8] we compare with left shifted address
323
+    subi    YL, 20 + 2      ;[9] Only assign address on data packets, not ACK/NAK in x3
324
+    sbci    YH, 0           ;[10]
325
+    out     USBOUT, x1      ;[11] <-- out SE0 -- from now 2 bits = 22 cycles until bus idle
326
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
327
+;set address only after data packet was sent, not after handshake
328
+    breq    skipAddrAssign  ;[0]
329
+    sts     usbDeviceAddr, x2; if not skipped: SE0 is one cycle longer
330
+skipAddrAssign:
331
+;end of usbDeviceAddress transfer
332
+    ldi     x2, 1<<USB_INTR_PENDING_BIT;[2] int0 occurred during TX -- clear pending flag
333
+    USB_STORE_PENDING(x2)   ;[3]
334
+    ori     x1, USBIDLE     ;[4]
335
+    in      x2, USBDDR      ;[5]
336
+    cbr     x2, USBMASK     ;[6] set both pins to input
337
+    mov     x3, x1          ;[7]
338
+    cbr     x3, USBMASK     ;[8] configure no pullup on both pins
339
+    ldi     x4, 4           ;[9]
340
+se0Delay:
341
+    dec     x4              ;[10] [13] [16] [19]
342
+    brne    se0Delay        ;[11] [14] [17] [20]
343
+    out     USBOUT, x1      ;[21] <-- out J (idle) -- end of SE0 (EOP signal)
344
+    out     USBDDR, x2      ;[22] <-- release bus now
345
+    out     USBOUT, x3      ;[23] <-- ensure no pull-up resistors are active
346
+    rjmp    doReturn

+ 453
- 0
usbdrvasm165.inc View File

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

+ 707
- 0
usbdrvasm18-crc.inc View File

@@ -0,0 +1,707 @@
1
+/* Name: usbdrvasm18.inc
2
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
3
+ * Author: Lukas Schrittwieser (based on 20 MHz usbdrvasm20.inc by Jeroen Benschop)
4
+ * Creation Date: 2009-01-20
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2008 by Lukas Schrittwieser and OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
8
+ * Revision: $Id: usbdrvasm18-crc.inc 740 2009-04-13 18:23:31Z 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 18 MHz version of the asssembler part of the USB driver. It
18
+requires a 18 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
+
29
+;max stack usage: [ret(2), YL, SREG, YH, [sofError], bitcnt(x5), shift, x1, x2, x3, x4, cnt, ZL, ZH] = 14 bytes
30
+;nominal frequency: 18 MHz -> 12 cycles per bit
31
+; Numbers in brackets are clocks counted from center of last sync bit
32
+; when instruction starts
33
+;register use in receive loop to receive the data bytes:
34
+; shift assembles the byte currently being received
35
+; x1 holds the D+ and D- line state
36
+; x2 holds the previous line state
37
+; cnt holds the number of bytes left in the receive buffer
38
+; x3 holds the higher crc byte (see algorithm below)
39
+; x4 is used as temporary register for the crc algorithm
40
+; x5 is used for unstuffing: when unstuffing the last received bit is inverted in shift (to prevent further
41
+;    unstuffing calls. In the same time the corresponding bit in x5 is cleared to mark the bit as beening iverted
42
+; zl lower crc value and crc table index
43
+; zh used for crc table accesses
44
+
45
+;--------------------------------------------------------------------------------------------------------------
46
+; CRC mods:
47
+;  table driven crc checker, Z points to table in prog space
48
+;   ZL is the lower crc byte, x3 is the higher crc byte
49
+;	x4 is used as temp register to store different results
50
+;	the initialization of the crc register is not 0xFFFF but 0xFE54. This is because during the receipt of the
51
+;	first data byte an virtual zero data byte is added to the crc register, this results in the correct initial
52
+;	value of 0xFFFF at beginning of the second data byte before the first data byte is added to the crc.
53
+;	The magic number 0xFE54 results form the crc table: At tabH[0x54] = 0xFF = crcH (required) and
54
+;	tabL[0x54] = 0x01  ->  crcL = 0x01 xor 0xFE = 0xFF
55
+;  bitcnt is renamed to x5 and is used for unstuffing purposes, the unstuffing works like in the 12MHz version
56
+;--------------------------------------------------------------------------------------------------------------
57
+; CRC algorithm:
58
+;	The crc register is formed by x3 (higher byte) and ZL (lower byte). The algorithm uses a 'reversed' form
59
+;	i.e. that it takes the least significant bit first and shifts to the right. So in fact the highest order
60
+;	bit seen from the polynomial devision point of view is the lsb of ZL. (If this sounds strange to you i
61
+;	propose a research on CRC :-) )
62
+;	Each data byte received is xored to ZL, the lower crc byte. This byte now builds the crc
63
+;	table index. Next the new high byte is loaded from the table and stored in x4 until we have space in x3
64
+;	(its destination).
65
+;	Afterwards the lower table is loaded from the table and stored in ZL (the old index is overwritten as
66
+;	we don't need it anymore. In fact this is a right shift by 8 bits.) Now the old crc high value is xored
67
+;	to ZL, this is the second shift of the old crc value. Now x4 (the temp reg) is moved to x3 and the crc
68
+; 	calculation is done.
69
+;	Prior to the first byte the two CRC register have to be initialized to 0xFFFF (as defined in usb spec)
70
+;	however the crc engine also runs during the receipt of the first byte, therefore x3 and zl are initialized
71
+;	to a magic number which results in a crc value of 0xFFFF after the first complete byte.
72
+;
73
+;	This algorithm is split into the extra cycles of the different bits:
74
+;	bit7:	XOR the received byte to ZL
75
+;	bit5:	load the new high byte to x4
76
+;	bit6:	load the lower xor byte from the table, xor zl and x3, store result in zl (=the new crc low value)
77
+;			move x4 (the new high byte) to x3, the crc value is ready
78
+;
79
+
80
+
81
+macro POP_STANDARD ; 18 cycles
82
+    pop		ZH
83
+    pop		ZL
84
+	pop     cnt
85
+    pop     x5
86
+    pop     x3
87
+    pop     x2
88
+    pop     x1
89
+    pop     shift
90
+    pop     x4
91
+    endm
92
+macro POP_RETI     ; 7 cycles
93
+    pop     YH
94
+    pop     YL
95
+    out     SREG, YL
96
+    pop     YL
97
+    endm
98
+
99
+macro CRC_CLEANUP_AND_CHECK
100
+	; the last byte has already been xored with the lower crc byte, we have to do the table lookup and xor
101
+	; x3 is the higher crc byte, zl the lower one
102
+	ldi		ZH, hi8(usbCrcTableHigh);[+1] get the new high byte from the table
103
+	lpm		x2, Z				;[+2][+3][+4]
104
+	ldi		ZH, hi8(usbCrcTableLow);[+5] get the new low xor byte from the table
105
+	lpm		ZL, Z				;[+6][+7][+8]
106
+	eor		ZL, x3				;[+7] xor the old high byte with the value from the table, x2:ZL now holds the crc value
107
+	cpi		ZL, 0x01			;[+8] if the crc is ok we have a fixed remainder value of 0xb001 in x2:ZL (see usb spec)
108
+	brne	ignorePacket		;[+9] detected a crc fault -> paket is ignored and retransmitted by the host
109
+	cpi		x2, 0xb0			;[+10]
110
+	brne	ignorePacket		;[+11] detected a crc fault -> paket is ignored and retransmitted by the host
111
+    endm
112
+
113
+
114
+USB_INTR_VECTOR:
115
+;order of registers pushed: YL, SREG, YH, [sofError], x4, shift, x1, x2, x3, x5, cnt, ZL, ZH
116
+    push    YL                  ;[-28] push only what is necessary to sync with edge ASAP
117
+    in      YL, SREG            ;[-26]
118
+    push    YL                  ;[-25]
119
+    push    YH                  ;[-23]
120
+;----------------------------------------------------------------------------
121
+; Synchronize with sync pattern:
122
+;----------------------------------------------------------------------------
123
+;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K]
124
+;sync up with J to K edge during sync pattern -- use fastest possible loops
125
+;The first part waits at most 1 bit long since we must be in sync pattern.
126
+;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to
127
+;waitForJ, ensure that this prerequisite is met.
128
+waitForJ:
129
+    inc     YL
130
+    sbis    USBIN, USBMINUS
131
+    brne    waitForJ        ; just make sure we have ANY timeout
132
+waitForK:
133
+;The following code results in a sampling window of < 1/4 bit which meets the spec.
134
+    sbis    USBIN, USBMINUS     ;[-17]
135
+    rjmp    foundK              ;[-16]
136
+    sbis    USBIN, USBMINUS
137
+    rjmp    foundK
138
+    sbis    USBIN, USBMINUS
139
+    rjmp    foundK
140
+    sbis    USBIN, USBMINUS
141
+    rjmp    foundK
142
+    sbis    USBIN, USBMINUS
143
+    rjmp    foundK
144
+    sbis    USBIN, USBMINUS
145
+    rjmp    foundK
146
+    sbis    USBIN, USBMINUS
147
+    rjmp    foundK
148
+    sbis    USBIN, USBMINUS
149
+    rjmp    foundK
150
+    sbis    USBIN, USBMINUS
151
+    rjmp    foundK
152
+#if USB_COUNT_SOF
153
+    lds     YL, usbSofCount
154
+    inc     YL
155
+    sts     usbSofCount, YL
156
+#endif  /* USB_COUNT_SOF */
157
+#ifdef USB_SOF_HOOK
158
+    USB_SOF_HOOK
159
+#endif
160
+    rjmp    sofError
161
+foundK:                         ;[-15]
162
+;{3, 5} after falling D- edge, average delay: 4 cycles
163
+;bit0 should be at 30  (2.5 bits) for center sampling. Currently at 4 so 26 cylces till bit 0 sample
164
+;use 1 bit time for setup purposes, then sample again. Numbers in brackets
165
+;are cycles from center of first sync (double K) bit after the instruction
166
+    push    x4                  ;[-14]
167
+;   [---]                       ;[-13]
168
+    lds     YL, usbInputBufOffset;[-12] used to toggle the two usb receive buffers
169
+;   [---]                       ;[-11]
170
+    clr     YH                  ;[-10]
171
+    subi    YL, lo8(-(usbRxBuf));[-9] [rx loop init]
172
+    sbci    YH, hi8(-(usbRxBuf));[-8] [rx loop init]
173
+    push    shift               ;[-7]
174
+;   [---]                       ;[-6]
175
+    ldi		shift, 0x80			;[-5] the last bit is the end of byte marker for the pid receiver loop
176
+    clc			      	      	;[-4] the carry has to be clear for receipt of pid bit 0
177
+    sbis    USBIN, USBMINUS     ;[-3] we want two bits K (sample 3 cycles too early)
178
+    rjmp    haveTwoBitsK        ;[-2]
179
+    pop     shift               ;[-1] undo the push from before
180
+    pop     x4                  ;[1]
181
+    rjmp    waitForK            ;[3] this was not the end of sync, retry
182
+; The entire loop from waitForK until rjmp waitForK above must not exceed two
183
+; bit times (= 24 cycles).
184
+
185
+;----------------------------------------------------------------------------
186
+; push more registers and initialize values while we sample the first bits:
187
+;----------------------------------------------------------------------------
188
+haveTwoBitsK:
189
+    push    x1                  ;[0]
190
+    push    x2                  ;[2]
191
+    push    x3                  ;[4] crc high byte
192
+    ldi     x2, 1<<USBPLUS      ;[6] [rx loop init] current line state is K state. D+=="1", D-=="0"
193
+    push    x5                  ;[7]
194
+    push    cnt                 ;[9]
195
+    ldi     cnt, USB_BUFSIZE    ;[11]
196
+
197
+
198
+;--------------------------------------------------------------------------------------------------------------
199
+; receives the pid byte
200
+; there is no real unstuffing algorithm implemented here as a stuffing bit is impossible in the pid byte.
201
+; That's because the last four bits of the byte are the inverted of the first four bits. If we detect a
202
+; unstuffing condition something went wrong and abort
203
+; shift has to be initialized to 0x80
204
+;--------------------------------------------------------------------------------------------------------------
205
+
206
+; pid bit 0 - used for even more register saving (we need the z pointer)
207
+	in      x1, USBIN           ;[0] sample line state
208
+    andi    x1, USBMASK         ;[1] filter only D+ and D- bits
209
+    eor		x2, x1				;[2] generate inverted of actual bit
210
+	sbrc	x2, USBMINUS		;[3] if the bit is set we received a zero
211
+	sec							;[4]
212
+	ror		shift				;[5] we perform no unstuffing check here as this is the first bit
213
+	mov		x2, x1				;[6]
214
+	push	ZL					;[7]
215
+								;[8]
216
+	push	ZH					;[9]
217
+								;[10]
218
+	ldi		x3, 0xFE			;[11] x3 is the high order crc value
219
+
220
+
221
+bitloopPid:						
222
+	in      x1, USBIN           ;[0] sample line state
223
+   	andi    x1, USBMASK         ;[1] filter only D+ and D- bits
224
+    breq    nse0                ;[2] both lines are low so handle se0	
225
+	eor		x2, x1				;[3] generate inverted of actual bit
226
+	sbrc	x2, USBMINUS		;[4] set the carry if we received a zero
227
+	sec							;[5]
228
+	ror		shift				;[6]
229
+	ldi		ZL, 0x54			;[7] ZL is the low order crc value
230
+	ser		x4					;[8] the is no bit stuffing check here as the pid bit can't be stuffed. if so
231
+								; some error occured. In this case the paket is discarded later on anyway.
232
+	mov		x2, x1				;[9] prepare for the next cycle
233
+	brcc	bitloopPid			;[10] while 0s drop out of shift we get the next bit
234
+	eor		x4, shift			;[11] invert all bits in shift and store result in x4
235
+
236
+;--------------------------------------------------------------------------------------------------------------
237
+; receives data bytes and calculates the crc
238
+; the last USBIN state has to be in x2
239
+; this is only the first half, due to branch distanc limitations the second half of the loop is near the end
240
+; of this asm file
241
+;--------------------------------------------------------------------------------------------------------------
242
+
243
+rxDataStart:
244
+    in      x1, USBIN           ;[0] sample line state (note: a se0 check is not useful due to bit dribbling)
245
+    ser		x5					;[1] prepare the unstuff marker register
246
+    eor		x2, x1             	;[2] generates the inverted of the actual bit
247
+    bst		x2, USBMINUS       	;[3] copy the bit from x2
248
+    bld		shift, 0	        ;[4] and store it in shift
249
+    mov		x2, shift	     	;[5] make a copy of shift for unstuffing check
250
+    andi	x2, 0xF9	      	;[6] mask the last six bits, if we got six zeros (which are six ones in fact)
251
+    breq	unstuff0	      	;[7] then Z is set now and we branch to the unstuffing handler
252
+didunstuff0:
253
+	subi    cnt, 1         		;[8] cannot use dec because it doesn't affect the carry flag
254
+    brcs    nOverflow    		;[9] Too many bytes received. Ignore packet							
255
+    st		Y+, x4				;[10] store the last received byte
256
+								;[11] st needs two cycles
257
+
258
+; bit1							
259
+	in		x2, USBIN			;[0] sample line state
260
+    andi	x1, USBMASK			;[1] check for se0 during bit 0
261
+    breq	nse0				;[2]
262
+    andi	x2, USBMASK			;[3] check se0 during bit 1
263
+    breq	nse0				;[4]
264
+	eor		x1, x2				;[5]
265
+    bst		x1, USBMINUS		;[6]
266
+    bld 	shift, 1	 		;[7]
267
+    mov		x1, shift			;[8]
268
+    andi	x1, 0xF3			;[9]
269
+    breq	unstuff1			;[10]
270
+didunstuff1:
271
+	nop							;[11]	
272
+
273
+; bit2
274
+	in      x1, USBIN           ;[0] sample line state
275
+    andi	x1, USBMASK			;[1] check for se0 (as there is nothing else to do here
276
+	breq	nOverflow	 		;[2]
277
+    eor		x2, x1              ;[3] generates the inverted of the actual bit
278
+    bst		x2, USBMINUS		;[4]
279
+    bld		shift, 2			;[5] store the bit
280
+    mov		x2, shift			;[6]
281
+    andi	x2, 0xE7			;[7] if we have six zeros here (which means six 1 in the stream)
282
+    breq	unstuff2			;[8] the next bit is a stuffing bit
283
+didunstuff2:
284
+	nop2						;[9]
285
+								;[10]
286
+	nop							;[11]					
287
+					
288
+; bit3							
289
+	in		x2, USBIN			;[0] sample line state
290
+    andi	x2, USBMASK			;[1] check for se0
291
+    breq	nOverflow           ;[2]
292
+    eor		x1, x2				;[3]
293
+    bst		x1, USBMINUS		;[4]
294
+    bld 	shift, 3	 		;[5]
295
+    mov		x1, shift			;[6]
296
+    andi	x1, 0xCF			;[7]
297
+    breq	unstuff3			;[8]
298
+didunstuff3:
299
+	nop							;[9]
300
+	rjmp 	rxDataBit4			;[10]
301
+								;[11]				
302
+
303
+; the avr branch instructions allow an offset of +63 insturction only, so we need this
304
+; 'local copy' of se0
305
+nse0:		
306
+	rjmp	se0					;[4]
307
+								;[5]
308
+; the same same as for se0 is needed for overflow and StuffErr
309
+nOverflow:
310
+stuffErr:
311
+	rjmp	overflow
312
+
313
+
314
+unstuff0:						;[8] this is the branch delay of breq unstuffX
315
+	andi	x1, USBMASK			;[9] do an se0 check here (if the last crc byte ends with 5 one's we might end up here
316
+	breq	didunstuff0			;[10] event tough the message is complete -> jump back and store the byte
317
+	ori		shift, 0x01			;[11] invert the last received bit to prevent furhter unstuffing
318
+	in		x2, USBIN			;[0] we have some free cycles so we could check for bit stuffing errors
319
+	andi	x5, 0xFE			;[1] mark this bit as inverted (will be corrected before storing shift)
320
+	eor		x1, x2				;[2] x1 and x2 have to be different because the stuff bit is always a zero
321
+	andi	x1, USBMASK			;[3] mask the interesting bits
322
+	breq	stuffErr			;[4] if the stuff bit is a 1-bit something went wrong
323
+	mov 	x1, x2				;[5] the next bit expects the last state to be in x1
324
+	rjmp 	didunstuff0			;[6]
325
+								;[7] jump delay of rjmp didunstuffX	
326
+
327
+unstuff1:						;[11] this is the jump delay of breq unstuffX
328
+	in		x1, USBIN			;[0] we have some free cycles so we could check for bit stuffing errors
329
+	ori		shift, 0x02			;[1] invert the last received bit to prevent furhter unstuffing
330
+	andi	x5, 0xFD			;[2] mark this bit as inverted (will be corrected before storing shift)
331
+	eor		x2, x1				;[3] x1 and x2 have to be different because the stuff bit is always a zero
332
+	andi	x2, USBMASK			;[4] mask the interesting bits
333
+	breq	stuffErr			;[5] if the stuff bit is a 1-bit something went wrong
334
+	mov 	x2, x1				;[6] the next bit expects the last state to be in x2
335
+	nop2						;[7]
336
+								;[8]
337
+	rjmp 	didunstuff1			;[9]
338
+								;[10] jump delay of rjmp didunstuffX		
339
+
340
+unstuff2:						;[9] this is the jump delay of breq unstuffX
341
+	ori		shift, 0x04			;[10] invert the last received bit to prevent furhter unstuffing
342
+	andi	x5, 0xFB			;[11] mark this bit as inverted (will be corrected before storing shift)
343
+	in		x2, USBIN			;[0] we have some free cycles so we could check for bit stuffing errors
344
+	eor		x1, x2				;[1] x1 and x2 have to be different because the stuff bit is always a zero
345
+	andi	x1, USBMASK			;[2] mask the interesting bits
346
+	breq	stuffErr			;[3] if the stuff bit is a 1-bit something went wrong
347
+	mov 	x1, x2				;[4] the next bit expects the last state to be in x1
348
+	nop2						;[5]
349
+								;[6]
350
+	rjmp 	didunstuff2			;[7]
351
+								;[8] jump delay of rjmp didunstuffX	
352
+
353
+unstuff3:						;[9] this is the jump delay of breq unstuffX
354
+	ori		shift, 0x08			;[10] invert the last received bit to prevent furhter unstuffing
355
+	andi	x5, 0xF7			;[11] mark this bit as inverted (will be corrected before storing shift)
356
+	in		x1, USBIN			;[0] we have some free cycles so we could check for bit stuffing errors
357
+	eor		x2, x1				;[1] x1 and x2 have to be different because the stuff bit is always a zero
358
+	andi	x2, USBMASK			;[2] mask the interesting bits
359
+	breq	stuffErr			;[3] if the stuff bit is a 1-bit something went wrong
360
+	mov 	x2, x1				;[4] the next bit expects the last state to be in x2
361
+	nop2						;[5]
362
+								;[6]
363
+	rjmp 	didunstuff3			;[7]
364
+								;[8] jump delay of rjmp didunstuffX			
365
+
366
+
367
+
368
+; the include has to be here due to branch distance restirctions
369
+#define __USE_CRC__
370
+#include "asmcommon.inc"
371
+
372
+	
373
+
374
+; USB spec says:
375
+; idle = J
376
+; J = (D+ = 0), (D- = 1)
377
+; K = (D+ = 1), (D- = 0)
378
+; Spec allows 7.5 bit times from EOP to SOP for replies
379
+; 7.5 bit times is 90 cycles. ...there is plenty of time
380
+
381
+
382
+sendNakAndReti:
383
+    ldi     x3, USBPID_NAK  ;[-18]
384
+    rjmp    sendX3AndReti   ;[-17]
385
+sendAckAndReti:
386
+    ldi     cnt, USBPID_ACK ;[-17]
387
+sendCntAndReti:
388
+    mov     x3, cnt         ;[-16]
389
+sendX3AndReti:
390
+    ldi     YL, 20          ;[-15] x3==r20 address is 20
391
+    ldi     YH, 0           ;[-14]
392
+    ldi     cnt, 2          ;[-13]
393
+;   rjmp    usbSendAndReti      fallthrough
394
+
395
+;usbSend:
396
+;pointer to data in 'Y'
397
+;number of bytes in 'cnt' -- including sync byte [range 2 ... 12]
398
+;uses: x1...x4, btcnt, shift, cnt, Y
399
+;Numbers in brackets are time since first bit of sync pattern is sent
400
+
401
+usbSendAndReti:             ; 12 cycles until SOP
402
+    in      x2, USBDDR      ;[-12]
403
+    ori     x2, USBMASK     ;[-11]
404
+    sbi     USBOUT, USBMINUS;[-10] prepare idle state; D+ and D- must have been 0 (no pullups)
405
+    in      x1, USBOUT      ;[-8] port mirror for tx loop
406
+    out     USBDDR, x2      ;[-6] <- acquire bus
407
+	ldi		x2, 0			;[-6] init x2 (bitstuff history) because sync starts with 0
408
+    ldi     x4, USBMASK     ;[-5] exor mask
409
+    ldi     shift, 0x80     ;[-4] sync byte is first byte sent
410
+txByteLoop:
411
+    ldi     bitcnt, 0x40    ;[-3]=[9]     binary 01000000
412
+txBitLoop:					; the loop sends the first 7 bits of the byte
413
+    sbrs    shift, 0        ;[-2]=[10] if we have to send a 1 don't change the line state
414
+    eor     x1, x4          ;[-1]=[11]
415
+    out     USBOUT, x1      ;[0]
416
+    ror     shift           ;[1]
417
+    ror     x2              ;[2] transfers the last sent bit to the stuffing history
418
+didStuffN:
419
+    nop	                    ;[3]
420
+    nop                     ;[4]
421
+    cpi     x2, 0xfc        ;[5] if we sent six consecutive ones
422
+    brcc    bitstuffN       ;[6]
423
+    lsr     bitcnt          ;[7]
424
+    brne    txBitLoop       ;[8] restart the loop while the 1 is still in the bitcount
425
+
426
+; transmit bit 7
427
+    sbrs    shift, 0        ;[9]
428
+    eor     x1, x4          ;[10]
429
+didStuff7:
430
+    ror     shift           ;[11]
431
+	out     USBOUT, x1      ;[0] transfer bit 7 to the pins
432
+    ror     x2              ;[1] move the bit into the stuffing history	
433
+    cpi     x2, 0xfc        ;[2]
434
+    brcc    bitstuff7       ;[3]
435
+    ld      shift, y+       ;[4] get next byte to transmit
436
+    dec     cnt             ;[5] decrement byte counter
437
+    brne    txByteLoop      ;[7] if we have more bytes start next one
438
+    						;[8] branch delay
439
+    						
440
+;make SE0:
441
+    cbr     x1, USBMASK     ;[8] 		prepare SE0 [spec says EOP may be 25 to 30 cycles]
442
+    lds     x2, usbNewDeviceAddr;[9]
443
+    lsl     x2              ;[11] 		we compare with left shifted address
444
+    out     USBOUT, x1      ;[0] 		<-- out SE0 -- from now 2 bits = 24 cycles until bus idle
445
+    subi    YL, 20 + 2      ;[1] 		Only assign address on data packets, not ACK/NAK in x3
446
+    sbci    YH, 0           ;[2]
447
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
448
+;set address only after data packet was sent, not after handshake
449
+    breq    skipAddrAssign  ;[3]
450
+    sts     usbDeviceAddr, x2		; if not skipped: SE0 is one cycle longer
451
+skipAddrAssign:
452
+;end of usbDeviceAddress transfer
453
+    ldi     x2, 1<<USB_INTR_PENDING_BIT;[5] int0 occurred during TX -- clear pending flag
454
+    USB_STORE_PENDING(x2)   ;[6]
455
+    ori     x1, USBIDLE     ;[7]
456
+    in      x2, USBDDR      ;[8]
457
+    cbr     x2, USBMASK     ;[9] set both pins to input
458
+    mov     x3, x1          ;[10]
459
+    cbr     x3, USBMASK     ;[11] configure no pullup on both pins
460
+    ldi     x4, 4           ;[12]
461
+se0Delay:
462
+    dec     x4              ;[13] [16] [19] [22]
463
+    brne    se0Delay        ;[14] [17] [20] [23]
464
+    out     USBOUT, x1      ;[24] <-- out J (idle) -- end of SE0 (EOP signal)
465
+    out     USBDDR, x2      ;[25] <-- release bus now
466
+    out     USBOUT, x3      ;[26] <-- ensure no pull-up resistors are active
467
+    rjmp    doReturn
468
+
469
+bitstuffN:
470
+    eor     x1, x4          ;[8] generate a zero
471
+    ldi     x2, 0           ;[9] reset the bit stuffing history
472
+    nop2                    ;[10]
473
+    out     USBOUT, x1      ;[0] <-- send the stuffing bit
474
+    rjmp    didStuffN       ;[1]
475
+
476
+bitstuff7:
477
+    eor     x1, x4          ;[5]
478
+    ldi     x2, 0           ;[6] reset bit stuffing history
479
+    clc						;[7] fill a zero into the shift register
480
+    rol     shift           ;[8] compensate for ror shift at branch destination
481
+    rjmp    didStuff7       ;[9]
482
+    						;[10] jump delay
483
+
484
+;--------------------------------------------------------------------------------------------------------------
485
+; receives data bytes and calculates the crc
486
+; second half of the data byte receiver loop
487
+; most parts of the crc algorithm are here
488
+;--------------------------------------------------------------------------------------------------------------
489
+
490
+nOverflow2:
491
+	rjmp overflow
492
+
493
+rxDataBit4:
494
+	in      x1, USBIN           ;[0] sample line state
495
+    andi	x1, USBMASK			;[1] check for se0
496
+    breq	nOverflow2			;[2]
497
+    eor		x2, x1              ;[3]
498
+    bst		x2, USBMINUS		;[4]
499
+    bld		shift, 4			;[5]
500
+    mov		x2, shift			;[6]
501
+    andi	x2, 0x9F			;[7]
502
+    breq	unstuff4			;[8]
503
+didunstuff4:
504
+	nop2						;[9][10]
505
+	nop							;[11]
506
+
507
+; bit5							
508
+	in		x2, USBIN			;[0] sample line state
509
+    ldi		ZH, hi8(usbCrcTableHigh);[1] use the table for the higher byte
510
+    eor		x1, x2				;[2]
511
+    bst		x1, USBMINUS		;[3]
512
+    bld 	shift, 5	 		;[4]
513
+    mov		x1, shift			;[5]
514
+    andi	x1, 0x3F			;[6]
515
+    breq	unstuff5			;[7]
516
+didunstuff5:
517
+	lpm		x4, Z				;[8] load the higher crc xor-byte and store it for later use
518
+								;[9] lpm needs 3 cycles
519
+								;[10]			
520
+	ldi		ZH, hi8(usbCrcTableLow);[11] load the lower crc xor byte adress
521
+
522
+; bit6	    					
523
+	in      x1, USBIN           ;[0] sample line state
524
+    eor		x2, x1              ;[1]
525
+    bst		x2, USBMINUS		;[2]
526
+    bld		shift, 6			;[3]
527
+    mov		x2, shift			;[4]
528
+    andi	x2, 0x7E			;[5]
529
+    breq	unstuff6			;[6]
530
+didunstuff6:
531
+	lpm		ZL, Z				;[7] load the lower xor crc byte
532
+								;[8] lpm needs 3 cycles
533
+	    						;[9]
534
+	eor		ZL, x3				;[10] xor the old high crc byte with the low xor-byte
535
+	mov		x3, x4				;[11] move the new high order crc value from temp to its destination
536
+			
537
+; bit7							
538
+	in		x2, USBIN			;[0] sample line state
539
+    eor		x1, x2				;[1]
540
+    bst		x1, USBMINUS		;[2]
541
+    bld 	shift, 7	 		;[3] now shift holds the complete but inverted data byte
542
+    mov		x1, shift			;[4]
543
+    andi	x1, 0xFC			;[5]
544
+    breq	unstuff7			;[6]
545
+didunstuff7:
546
+	eor		x5, shift			;[7] x5 marks all bits which have not been inverted by the unstuffing subs
547
+	mov		x4, x5				;[8] keep a copy of the data byte it will be stored during next bit0
548
+	eor		ZL, x4				;[9] feed the actual byte into the crc algorithm
549
+	rjmp	rxDataStart			;[10] next byte
550
+								;[11] during the reception of the next byte this one will be fed int the crc algorithm
551
+
552
+unstuff4:						;[9] this is the jump delay of rjmp unstuffX
553
+	ori		shift, 0x10			;[10] invert the last received bit to prevent furhter unstuffing
554
+	andi	x5, 0xEF			;[11] mark this bit as inverted (will be corrected before storing shift)
555
+	in		x2, USBIN			;[0] we have some free cycles so we could check for bit stuffing errors
556
+	eor		x1, x2				;[1] x1 and x2 have to be different because the stuff bit is always a zero
557
+	andi	x1, USBMASK			;[2] mask the interesting bits
558
+	breq	stuffErr2			;[3] if the stuff bit is a 1-bit something went wrong
559
+	mov 	x1, x2				;[4] the next bit expects the last state to be in x1
560
+	nop2						;[5]
561
+								;[6]
562
+	rjmp 	didunstuff4			;[7]
563
+								;[8] jump delay of rjmp didunstuffX	
564
+
565
+unstuff5:						;[8] this is the jump delay of rjmp unstuffX
566
+	nop							;[9]
567
+	ori		shift, 0x20			;[10] invert the last received bit to prevent furhter unstuffing
568
+	andi	x5, 0xDF			;[11] mark this bit as inverted (will be corrected before storing shift)
569
+	in		x1, USBIN			;[0] we have some free cycles so we could check for bit stuffing errors
570
+	eor		x2, x1				;[1] x1 and x2 have to be different because the stuff bit is always a zero
571
+	andi	x2, USBMASK			;[2] mask the interesting bits
572
+	breq	stuffErr2			;[3] if the stuff bit is a 1-bit something went wrong
573
+	mov 	x2, x1				;[4] the next bit expects the last state to be in x2
574
+	nop							;[5]
575
+	rjmp 	didunstuff5			;[6]
576
+								;[7] jump delay of rjmp didunstuffX													
577
+
578
+unstuff6:						;[7] this is the jump delay of rjmp unstuffX
579
+	nop2						;[8]
580
+								;[9]
581
+	ori		shift, 0x40			;[10] invert the last received bit to prevent furhter unstuffing
582
+	andi	x5, 0xBF			;[11] mark this bit as inverted (will be corrected before storing shift)
583
+	in		x2, USBIN			;[0] we have some free cycles so we could check for bit stuffing errors
584
+	eor		x1, x2				;[1] x1 and x2 have to be different because the stuff bit is always a zero
585
+	andi	x1, USBMASK			;[2] mask the interesting bits
586
+	breq	stuffErr2			;[3] if the stuff bit is a 1-bit something went wrong
587
+	mov 	x1, x2				;[4] the next bit expects the last state to be in x1
588
+	rjmp 	didunstuff6			;[5]
589
+								;[6] jump delay of rjmp didunstuffX	
590
+
591
+unstuff7:						;[7] this is the jump delay of rjmp unstuffX
592
+	nop							;[8]
593
+	nop							;[9]
594
+	ori		shift, 0x80			;[10] invert the last received bit to prevent furhter unstuffing
595
+	andi	x5, 0x7F			;[11] mark this bit as inverted (will be corrected before storing shift)
596
+	in		x1, USBIN			;[0] we have some free cycles so we could check for bit stuffing errors
597
+	eor		x2, x1				;[1] x1 and x2 have to be different because the stuff bit is always a zero
598
+	andi	x2, USBMASK			;[2] mask the interesting bits
599
+	breq	stuffErr2			;[3] if the stuff bit is a 1-bit something went wrong
600
+	mov 	x2, x1				;[4] the next bit expects the last state to be in x2
601
+	rjmp 	didunstuff7			;[5]
602
+								;[6] jump delay of rjmp didunstuff7
603
+
604
+; local copy of the stuffErr desitnation for the second half of the receiver loop
605
+stuffErr2:
606
+	rjmp	stuffErr
607
+
608
+;--------------------------------------------------------------------------------------------------------------
609
+; The crc table follows. It has to be aligned to enable a fast loading of the needed bytes.
610
+; There are two tables of 256 entries each, the low and the high byte table.
611
+; Table values were generated with the following C code:
612
+/*
613
+#include <stdio.h>
614
+int main (int argc, char **argv)
615
+{
616
+	int i, j;
617
+	for (i=0; i<512; i++){
618
+		unsigned short crc = i & 0xff;
619
+		for(j=0; j<8; j++) crc = (crc >> 1) ^ ((crc & 1) ? 0xa001 : 0);
620
+		if((i & 7) == 0) printf("\n.byte ");
621
+		printf("0x%02x, ", (i > 0xff ? (crc >> 8) : crc) & 0xff);
622
+		if(i == 255) printf("\n");
623
+	}
624
+	return 0;
625
+}
626
+
627
+// Use the following algorithm to compute CRC values:
628
+ushort computeCrc(uchar *msg, uchar msgLen)
629
+{
630
+    uchar i;
631
+	ushort crc = 0xffff;
632
+	for(i = 0; i < msgLen; i++)
633
+		crc = usbCrcTable16[lo8(crc) ^ msg[i]] ^ hi8(crc);
634
+    return crc;
635
+}
636
+*/
637
+
638
+.balign 256
639
+usbCrcTableLow:	
640
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
641
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
642
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
643
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
644
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
645
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
646
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
647
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
648
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
649
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
650
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
651
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
652
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
653
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
654
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
655
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
656
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
657
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
658
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
659
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
660
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
661
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
662
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
663
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
664
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
665
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
666
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
667
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
668
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
669
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
670
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
671
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
672
+
673
+; .balign 256
674
+usbCrcTableHigh:
675
+.byte 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2
676
+.byte 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04
677
+.byte 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E
678
+.byte 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8
679
+.byte 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A
680
+.byte 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC
681
+.byte 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6
682
+.byte 0xD2, 0x12, 0x13, 0xD3, 0x11, 0xD1, 0xD0, 0x10
683
+.byte 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32
684
+.byte 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4
685
+.byte 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE
686
+.byte 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38
687
+.byte 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA
688
+.byte 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C
689
+.byte 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26
690
+.byte 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0
691
+.byte 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62
692
+.byte 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4
693
+.byte 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE
694
+.byte 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68
695
+.byte 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA
696
+.byte 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C
697
+.byte 0xB4, 0x74, 0x75, 0xB5, 0x77, 0xB7, 0xB6, 0x76
698
+.byte 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0
699
+.byte 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92
700
+.byte 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54
701
+.byte 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E
702
+.byte 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98
703
+.byte 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A
704
+.byte 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C
705
+.byte 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86
706
+.byte 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, 0x40	
707
+

+ 360
- 0
usbdrvasm20.inc View File

@@ -0,0 +1,360 @@
1
+/* Name: usbdrvasm20.inc
2
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
3
+ * Author: Jeroen Benschop
4
+ * Based on usbdrvasm16.inc from Christian Starkjohann
5
+ * Creation Date: 2008-03-05
6
+ * Tabsize: 4
7
+ * Copyright: (c) 2008 by Jeroen Benschop and OBJECTIVE DEVELOPMENT Software GmbH
8
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
9
+ * Revision: $Id: usbdrvasm20.inc 740 2009-04-13 18:23:31Z cs $
10
+ */
11
+
12
+/* Do not link this file! Link usbdrvasm.S instead, which includes the
13
+ * appropriate implementation!
14
+ */
15
+
16
+/*
17
+General Description:
18
+This file is the 20 MHz version of the asssembler part of the USB driver. It
19
+requires a 20 MHz crystal (not a ceramic resonator and not a calibrated RC
20
+oscillator).
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
+#define leap2   x3
30
+#ifdef __IAR_SYSTEMS_ASM__
31
+#define nextInst    $+2
32
+#else
33
+#define nextInst    .+0
34
+#endif
35
+
36
+;max stack usage: [ret(2), YL, SREG, YH, bitcnt, shift, x1, x2, x3, x4, cnt] = 12 bytes
37
+;nominal frequency: 20 MHz -> 13.333333 cycles per bit, 106.666667 cycles per byte
38
+; Numbers in brackets are clocks counted from center of last sync bit
39
+; when instruction starts
40
+;register use in receive loop:
41
+; shift assembles the byte currently being received
42
+; x1 holds the D+ and D- line state
43
+; x2 holds the previous line state
44
+; x4 (leap)  is used to add a leap cycle once every three bytes received
45
+; X3 (leap2) is used to add a leap cycle once every three stuff bits received
46
+; bitcnt is used to determine when a stuff bit is due
47
+; cnt holds the number of bytes left in the receive buffer
48
+
49
+USB_INTR_VECTOR:
50
+;order of registers pushed: YL, SREG YH, [sofError], bitcnt, shift, x1, x2, x3, x4, cnt
51
+    push    YL                  ;[-28] push only what is necessary to sync with edge ASAP
52
+    in      YL, SREG            ;[-26]
53
+    push    YL                  ;[-25]
54
+    push    YH                  ;[-23]
55
+;----------------------------------------------------------------------------
56
+; Synchronize with sync pattern:
57
+;----------------------------------------------------------------------------
58
+;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K]
59
+;sync up with J to K edge during sync pattern -- use fastest possible loops
60
+;The first part waits at most 1 bit long since we must be in sync pattern.
61
+;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to
62
+;waitForJ, ensure that this prerequisite is met.
63
+waitForJ:
64
+    inc     YL
65
+    sbis    USBIN, USBMINUS
66
+    brne    waitForJ        ; just make sure we have ANY timeout
67
+waitForK:
68
+;The following code results in a sampling window of < 1/4 bit which meets the spec.
69
+    sbis    USBIN, USBMINUS     ;[-19]
70
+    rjmp    foundK              ;[-18]
71
+    sbis    USBIN, USBMINUS
72
+    rjmp    foundK
73
+    sbis    USBIN, USBMINUS
74
+    rjmp    foundK
75
+    sbis    USBIN, USBMINUS
76
+    rjmp    foundK
77
+    sbis    USBIN, USBMINUS
78
+    rjmp    foundK
79
+    sbis    USBIN, USBMINUS
80
+    rjmp    foundK
81
+    sbis    USBIN, USBMINUS
82
+    rjmp    foundK
83
+    sbis    USBIN, USBMINUS
84
+    rjmp    foundK
85
+    sbis    USBIN, USBMINUS
86
+    rjmp    foundK
87
+#if USB_COUNT_SOF
88
+    lds     YL, usbSofCount
89
+    inc     YL
90
+    sts     usbSofCount, YL
91
+#endif  /* USB_COUNT_SOF */
92
+#ifdef USB_SOF_HOOK
93
+    USB_SOF_HOOK
94
+#endif
95
+    rjmp    sofError
96
+foundK:                         ;[-16]
97
+;{3, 5} after falling D- edge, average delay: 4 cycles
98
+;bit0 should be at 34 for center sampling. Currently at 4 so 30 cylces till bit 0 sample
99
+;use 1 bit time for setup purposes, then sample again. Numbers in brackets
100
+;are cycles from center of first sync (double K) bit after the instruction
101
+    push    bitcnt              ;[-16]
102
+;   [---]                       ;[-15]
103
+    lds     YL, usbInputBufOffset;[-14]
104
+;   [---]                       ;[-13]
105
+    clr     YH                  ;[-12]
106
+    subi    YL, lo8(-(usbRxBuf));[-11] [rx loop init]
107
+    sbci    YH, hi8(-(usbRxBuf));[-10] [rx loop init]
108
+    push    shift               ;[-9]
109
+;   [---]                       ;[-8]
110
+    ldi     shift,0x40          ;[-7] set msb to "1" so processing bit7 can be detected
111
+    nop2                        ;[-6]
112
+;   [---]                       ;[-5]
113
+    ldi     bitcnt, 5           ;[-4] [rx loop init]
114
+    sbis    USBIN, USBMINUS     ;[-3] we want two bits K (sample 3 cycles too early)
115
+    rjmp    haveTwoBitsK        ;[-2]
116
+    pop     shift               ;[-1] undo the push from before
117
+    pop     bitcnt              ;[1] 
118
+    rjmp    waitForK            ;[3] this was not the end of sync, retry
119
+; The entire loop from waitForK until rjmp waitForK above must not exceed two
120
+; bit times (= 27 cycles).
121
+
122
+;----------------------------------------------------------------------------
123
+; push more registers and initialize values while we sample the first bits:
124
+;----------------------------------------------------------------------------
125
+haveTwoBitsK:
126
+    push    x1                  ;[0]
127
+    push    x2                  ;[2]
128
+    push    x3                  ;[4] (leap2)
129
+    ldi     leap2, 0x55         ;[6] add leap cycle on 2nd,5th,8th,... stuff bit
130
+    push    x4                  ;[7] == leap
131
+    ldi     leap, 0x55          ;[9] skip leap cycle on 2nd,5th,8th,... byte received
132
+    push    cnt                 ;[10]
133
+    ldi     cnt, USB_BUFSIZE    ;[12] [rx loop init]
134
+    ldi     x2, 1<<USBPLUS      ;[13] current line state is K state. D+=="1", D-=="0"
135
+bit0:       
136
+    in      x1, USBIN           ;[0] sample line state
137
+    andi    x1, USBMASK         ;[1] filter only D+ and D- bits
138
+    rjmp    handleBit           ;[2] make bit0 14 cycles long
139
+
140
+;----------------------------------------------------------------------------
141
+; Process bit7. However, bit 6 still may need unstuffing.
142
+;----------------------------------------------------------------------------
143
+
144
+b6checkUnstuff:
145
+    dec     bitcnt              ;[9]
146
+    breq    unstuff6            ;[10]
147
+bit7:
148
+    subi    cnt, 1              ;[11] cannot use dec becaus it does not affect the carry flag
149
+    brcs    overflow            ;[12] Too many bytes received. Ignore packet
150
+    in      x1, USBIN           ;[0] sample line state
151
+    andi    x1, USBMASK         ;[1] filter only D+ and D- bits
152
+    cpse    x1, x2              ;[2] when previous line state equals current line state, handle "1"
153
+    rjmp    b7handle0           ;[3] when line state differs, handle "0"
154
+    sec                         ;[4]
155
+    ror     shift               ;[5] shift "1" into the data
156
+    st      y+, shift           ;[6] store the data into the buffer
157
+    ldi     shift, 0x40         ;[7] reset data for receiving the next byte
158
+    subi    leap, 0x55          ;[9] trick to introduce a leap cycle every 3 bytes
159
+    brcc    nextInst            ;[10 or 11] it will fail after 85 bytes. However low speed can only receive 11
160
+    dec     bitcnt              ;[11 or 12]
161
+    brne    bit0                ;[12 or 13]
162
+    ldi     x1, 1               ;[13 or 14] unstuffing bit 7
163
+    in      bitcnt, USBIN       ;[0] sample stuff bit
164
+    rjmp    unstuff             ;[1]
165
+
166
+b7handle0:
167
+    mov     x2,x1               ;[5] Set x2 to current line state
168
+    ldi     bitcnt, 6           ;[6]
169
+    lsr     shift               ;[7] shift "0" into the data
170
+    st      y+, shift           ;[8] store data into the buffer
171
+    ldi     shift, 0x40         ;[10] reset data for receiving the next byte
172
+    subi    leap, 0x55          ;[11] trick to introduce a leap cycle every 3 bytes
173
+    brcs    bit0                ;[12] it will fail after 85 bytes. However low speed can only receive 11
174
+    rjmp    bit0                ;[13]
175
+
176
+
177
+;----------------------------------------------------------------------------
178
+; Handle unstuff
179
+; x1==0xFF indicate unstuffing bit6
180
+;----------------------------------------------------------------------------
181
+
182
+unstuff6:
183
+    ldi     x1,0xFF             ;[12] indicate unstuffing bit 6
184
+    in      bitcnt, USBIN       ;[0]  sample stuff bit
185
+    nop                         ;[1]  fix timing
186
+unstuff:                        ;b0-5  b6   b7
187
+    mov     x2,bitcnt           ;[3]  [2]  [3]  Set x2 to match line state
188
+    subi    leap2, 0x55         ;[4]  [3]  [4]  delay loop
189
+    brcs    nextInst            ;[5]  [4]  [5]  add one cycle every three stuff bits
190
+    sbci    leap2,0             ;[6]  [5]  [6]
191
+    ldi     bitcnt,6            ;[7]  [6]  [7]  reset bit stuff counter
192
+    andi    x2, USBMASK         ;[8]  [7]  [8] only keep D+ and D-
193
+    cpi     x1,0                ;[9]  [8]  [9]
194
+    brmi    bit7                ;[10] [9]  [10] finished unstuffing bit6 When x1<0
195
+    breq    bitloop             ;[11] ---  [11] finished unstuffing bit0-5 when x1=0
196
+    nop                         ;---  ---  [12]
197
+    in      x1, USBIN           ;---  ---  [0] sample line state for bit0
198
+    andi    x1, USBMASK         ;---  ---  [1] filter only D+ and D- bits
199
+    rjmp    handleBit           ;---  ---  [2] make bit0 14 cycles long
200
+
201
+;----------------------------------------------------------------------------
202
+; Receiver loop (numbers in brackets are cycles within byte after instr)
203
+;----------------------------------------------------------------------------
204
+bitloop:
205
+    in      x1, USBIN           ;[0] sample line state
206
+    andi    x1, USBMASK         ;[1] filter only D+ and D- bits
207
+    breq    se0                 ;[2] both lines are low so handle se0
208
+handleBit:
209
+    cpse    x1, x2              ;[3] when previous line state equals current line state, handle "1"
210
+    rjmp    handle0             ;[4] when line state differs, handle "0"
211
+    sec                         ;[5]
212
+    ror     shift               ;[6] shift "1" into the data
213
+    brcs    b6checkUnstuff      ;[7] When after shift C is set, next bit is bit7
214
+    nop2                        ;[8]
215
+    dec     bitcnt              ;[10]
216
+    brne    bitloop             ;[11]
217
+    ldi     x1,0                ;[12] indicate unstuff for bit other than bit6 or bit7
218
+    in      bitcnt, USBIN       ;[0] sample stuff bit
219
+    rjmp    unstuff             ;[1]
220
+
221
+handle0:
222
+    mov     x2, x1              ;[6] Set x2 to current line state
223
+    ldi     bitcnt, 6           ;[7] reset unstuff counter. 
224
+    lsr     shift               ;[8] shift "0" into the data
225
+    brcs    bit7                ;[9] When after shift C is set, next bit is bit7
226
+    nop                         ;[10]
227
+    rjmp    bitloop             ;[11] 
228
+    
229
+;----------------------------------------------------------------------------
230
+; End of receive loop. Now start handling EOP
231
+;----------------------------------------------------------------------------
232
+
233
+macro POP_STANDARD ; 14 cycles
234
+    pop     cnt
235
+    pop     x4
236
+    pop     x3
237
+    pop     x2
238
+    pop     x1
239
+    pop     shift
240
+    pop     bitcnt
241
+    endm
242
+macro POP_RETI     ; 7 cycles
243
+    pop     YH
244
+    pop     YL
245
+    out     SREG, YL
246
+    pop     YL
247
+    endm
248
+
249
+
250
+
251
+#include "asmcommon.inc"
252
+
253
+; USB spec says:
254
+; idle = J
255
+; J = (D+ = 0), (D- = 1)
256
+; K = (D+ = 1), (D- = 0)
257
+; Spec allows 7.5 bit times from EOP to SOP for replies
258
+; 7.5 bit times is 100 cycles. This implementation arrives a bit later at se0
259
+; then specified in the include file but there is plenty of time
260
+
261
+bitstuffN:
262
+    eor     x1, x4          ;[8]
263
+    ldi     x2, 0           ;[9]
264
+    nop2                    ;[10]
265
+    out     USBOUT, x1      ;[12] <-- out
266
+    rjmp    didStuffN       ;[0]
267
+    
268
+bitstuff7:
269
+    eor     x1, x4          ;[6]
270
+    ldi     x2, 0           ;[7] Carry is zero due to brcc
271
+    rol     shift           ;[8] compensate for ror shift at branch destination
272
+    nop2                    ;[9]
273
+    rjmp    didStuff7       ;[11]
274
+
275
+sendNakAndReti:
276
+    ldi     x3, USBPID_NAK  ;[-18]
277
+    rjmp    sendX3AndReti   ;[-17]
278
+sendAckAndReti:
279
+    ldi     cnt, USBPID_ACK ;[-17]
280
+sendCntAndReti:
281
+    mov     x3, cnt         ;[-16]
282
+sendX3AndReti:
283
+    ldi     YL, 20          ;[-15] x3==r20 address is 20
284
+    ldi     YH, 0           ;[-14]
285
+    ldi     cnt, 2          ;[-13]
286
+;   rjmp    usbSendAndReti      fallthrough
287
+
288
+;usbSend:
289
+;pointer to data in 'Y'
290
+;number of bytes in 'cnt' -- including sync byte [range 2 ... 12]
291
+;uses: x1...x4, btcnt, shift, cnt, Y
292
+;Numbers in brackets are time since first bit of sync pattern is sent
293
+;We don't match the transfer rate exactly (don't insert leap cycles every third
294
+;byte) because the spec demands only 1.5% precision anyway.
295
+usbSendAndReti:             ; 12 cycles until SOP
296
+    in      x2, USBDDR      ;[-12]
297
+    ori     x2, USBMASK     ;[-11]
298
+    sbi     USBOUT, USBMINUS;[-10] prepare idle state; D+ and D- must have been 0 (no pullups)
299
+    in      x1, USBOUT      ;[-8] port mirror for tx loop
300
+    out     USBDDR, x2      ;[-7] <- acquire bus
301
+; need not init x2 (bitstuff history) because sync starts with 0
302
+    ldi     x4, USBMASK     ;[-6] exor mask
303
+    ldi     shift, 0x80     ;[-5] sync byte is first byte sent
304
+txByteLoop:
305
+    ldi     bitcnt, 0x49    ;[-4]        [10] binary 01001001
306
+txBitLoop:
307
+    sbrs    shift, 0        ;[-3] [10]   [11]
308
+    eor     x1, x4          ;[-2] [11]   [12]
309
+    out     USBOUT, x1      ;[-1] [12]   [13]   <-- out N
310
+    ror     shift           ;[0]  [13]   [14]
311
+    ror     x2              ;[1]
312
+didStuffN:
313
+    nop2                    ;[2]
314
+    nop                     ;[4]
315
+    cpi     x2, 0xfc        ;[5]
316
+    brcc    bitstuffN       ;[6]
317
+    lsr     bitcnt          ;[7]
318
+    brcc    txBitLoop       ;[8]
319
+    brne    txBitLoop       ;[9]
320
+
321
+    sbrs    shift, 0        ;[10]
322
+    eor     x1, x4          ;[11]
323
+didStuff7:
324
+    out     USBOUT, x1      ;[-1] [13] <-- out 7
325
+    ror     shift           ;[0] [14]
326
+    ror     x2              ;[1]
327
+    nop                     ;[2]
328
+    cpi     x2, 0xfc        ;[3]
329
+    brcc    bitstuff7       ;[4]
330
+    ld      shift, y+       ;[5]
331
+    dec     cnt             ;[7]
332
+    brne    txByteLoop      ;[8]
333
+;make SE0:
334
+    cbr     x1, USBMASK     ;[9] prepare SE0 [spec says EOP may be 25 to 30 cycles]
335
+    lds     x2, usbNewDeviceAddr;[10]
336
+    lsl     x2              ;[12] we compare with left shifted address
337
+    out     USBOUT, x1      ;[13] <-- out SE0 -- from now 2 bits = 22 cycles until bus idle
338
+    subi    YL, 20 + 2      ;[0] Only assign address on data packets, not ACK/NAK in x3
339
+    sbci    YH, 0           ;[1]
340
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
341
+;set address only after data packet was sent, not after handshake
342
+    breq    skipAddrAssign  ;[2]
343
+    sts     usbDeviceAddr, x2; if not skipped: SE0 is one cycle longer
344
+skipAddrAssign:
345
+;end of usbDeviceAddress transfer
346
+    ldi     x2, 1<<USB_INTR_PENDING_BIT;[4] int0 occurred during TX -- clear pending flag
347
+    USB_STORE_PENDING(x2)   ;[5]
348
+    ori     x1, USBIDLE     ;[6]
349
+    in      x2, USBDDR      ;[7]
350
+    cbr     x2, USBMASK     ;[8] set both pins to input
351
+    mov     x3, x1          ;[9]
352
+    cbr     x3, USBMASK     ;[10] configure no pullup on both pins
353
+    ldi     x4, 5           ;[11]
354
+se0Delay:
355
+    dec     x4              ;[12] [15] [18] [21] [24]
356
+    brne    se0Delay        ;[13] [16] [19] [22] [25]
357
+    out     USBOUT, x1      ;[26] <-- out J (idle) -- end of SE0 (EOP signal)
358
+    out     USBDDR, x2      ;[27] <-- release bus now
359
+    out     USBOUT, x3      ;[28] <-- ensure no pull-up resistors are active
360
+    rjmp    doReturn

+ 140
- 0
usbportability.h View File

@@ -0,0 +1,140 @@
1
+/* Name: usbportability.h
2
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
3
+ * Author: Christian Starkjohann
4
+ * Creation Date: 2008-06-17
5
+ * Tabsize: 4
6
+ * Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
7
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
8
+ * This Revision: $Id: usbportability.h 740 2009-04-13 18:23:31Z cs $
9
+ */
10
+
11
+/*
12
+General Description:
13
+This header is intended to contain all (or at least most of) the compiler
14
+and library dependent stuff. The C code is written for avr-gcc and avr-libc.
15
+The API of other development environments is converted to gcc's and avr-libc's
16
+API by means of defines.
17
+
18
+This header also contains all system includes since they depend on the
19
+development environment.
20
+
21
+Thanks to Oleg Semyonov for his help with the IAR tools port!
22
+*/
23
+
24
+#ifndef __usbportability_h_INCLUDED__
25
+#define __usbportability_h_INCLUDED__
26
+
27
+/* We check explicitly for IAR and CodeVision. Default is avr-gcc/avr-libc. */
28
+
29
+/* ------------------------------------------------------------------------- */
30
+#if defined __IAR_SYSTEMS_ICC__ || defined __IAR_SYSTEMS_ASM__  /* check for IAR */
31
+/* ------------------------------------------------------------------------- */
32
+
33
+#ifndef ENABLE_BIT_DEFINITIONS
34
+#   define ENABLE_BIT_DEFINITIONS	1   /* Enable bit definitions */
35
+#endif
36
+
37
+/* Include IAR headers */
38
+#include <ioavr.h>
39
+#ifndef __IAR_SYSTEMS_ASM__
40
+#   include <inavr.h>
41
+#endif
42
+
43
+#define __attribute__(arg)  /* not supported on IAR */
44
+
45
+#ifdef __IAR_SYSTEMS_ASM__
46
+#   define __ASSEMBLER__    /* IAR does not define standard macro for asm */
47
+#endif
48
+
49
+#ifdef __HAS_ELPM__
50
+#   define PROGMEM __farflash
51
+#else
52
+#   define PROGMEM __flash
53
+#endif
54
+
55
+#define USB_READ_FLASH(addr)    (*(PROGMEM char *)(addr))
56
+
57
+/* The following definitions are not needed by the driver, but may be of some
58
+ * help if you port a gcc based project to IAR.
59
+ */
60
+#define cli()       __disable_interrupt()
61
+#define sei()       __enable_interrupt()
62
+#define wdt_reset() __watchdog_reset()
63
+#define _BV(x)      (1 << (x))
64
+
65
+/* assembler compatibility macros */
66
+#define nop2    rjmp    $+2 /* jump to next instruction */
67
+#define XL      r26
68
+#define XH      r27
69
+#define YL      r28
70
+#define YH      r29
71
+#define ZL      r30
72
+#define ZH      r31
73
+#define lo8(x)  LOW(x)
74
+#define hi8(x)  (((x)>>8) & 0xff)   /* not HIGH to allow XLINK to make a proper range check */
75
+
76
+/* Depending on the device you use, you may get problems with the way usbdrv.h
77
+ * handles the differences between devices. Since IAR does not use #defines
78
+ * for MCU registers, we can't check for the existence of a particular
79
+ * register with an #ifdef. If the autodetection mechanism fails, include
80
+ * definitions for the required USB_INTR_* macros in your usbconfig.h. See
81
+ * usbconfig-prototype.h and usbdrv.h for details.
82
+ */
83
+
84
+/* ------------------------------------------------------------------------- */
85
+#elif __CODEVISIONAVR__ /* check for CodeVision AVR */
86
+/* ------------------------------------------------------------------------- */
87
+/* This port is not working (yet) */
88
+
89
+/* #define F_CPU   _MCU_CLOCK_FREQUENCY_    seems to be defined automatically */
90
+
91
+#include <io.h>
92
+#include <delay.h>
93
+
94
+#define __attribute__(arg)  /* not supported on IAR */
95
+
96
+#define PROGMEM                 __flash
97
+#define USB_READ_FLASH(addr)    (*(PROGMEM char *)(addr))
98
+
99
+#ifndef __ASSEMBLER__
100
+static inline void  cli(void)
101
+{
102
+    #asm("cli");
103
+}
104
+static inline void  sei(void)
105
+{
106
+    #asm("sei");
107
+}
108
+#endif
109
+#define _delay_ms(t)    delay_ms(t)
110
+#define _BV(x)          (1 << (x))
111
+#define USB_CFG_USE_SWITCH_STATEMENT 1  /* macro for if() cascase fails for unknown reason */
112
+
113
+#define macro   .macro
114
+#define endm    .endmacro
115
+#define nop2    rjmp    .+0 /* jump to next instruction */
116
+
117
+/* ------------------------------------------------------------------------- */
118
+#else   /* default development environment is avr-gcc/avr-libc */
119
+/* ------------------------------------------------------------------------- */
120
+
121
+#include <avr/io.h>
122
+#ifdef __ASSEMBLER__
123
+#   define _VECTOR(N)   __vector_ ## N   /* io.h does not define this for asm */
124
+#else
125
+#   include <avr/pgmspace.h>
126
+#endif
127
+
128
+#define USB_READ_FLASH(addr)    pgm_read_byte(addr)
129
+
130
+#define macro   .macro
131
+#define endm    .endm
132
+#define nop2    rjmp    .+0 /* jump to next instruction */
133
+
134
+#endif  /* development environment */
135
+
136
+/* for conveniecne, ensure that PRG_RDB exists */
137
+#ifndef PRG_RDB
138
+#   define PRG_RDB(addr)    USB_READ_FLASH(addr)
139
+#endif
140
+#endif  /* __usbportability_h_INCLUDED__ */

Loading…
Cancel
Save