You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

716 lines
18KB

  1. /* USB API for Teensy USB Development Board
  2. * http://www.pjrc.com/teensy/teensyduino.html
  3. * Copyright (c) 2008 PJRC.COM, LLC
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6. * of this software and associated documentation files (the "Software"), to deal
  7. * in the Software without restriction, including without limitation the rights
  8. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in
  13. * all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. * THE SOFTWARE.
  22. */
  23. #include <avr/io.h>
  24. #include <avr/pgmspace.h>
  25. #include <stdint.h>
  26. #include "usb_common.h"
  27. #include "usb_private.h"
  28. #include "usb_api.h"
  29. #include "wiring.h"
  30. void usb_midi_class::sendSysEx_BufferHasTerm(uint16_t length, const uint8_t *data)
  31. {
  32. while (length > 3) {
  33. send_raw(0x04, data[0], data[1], data[2]);
  34. data += 3;
  35. length -= 3;
  36. }
  37. if (length == 3) {
  38. send_raw(0x07, data[0], data[1], data[2]);
  39. } else if (length == 2) {
  40. send_raw(0x06, data[0], data[1], 0);
  41. } else if (length == 1) {
  42. send_raw(0x05, data[0], 0, 0);
  43. }
  44. }
  45. void usb_midi_class::sendSysEx_AddTermBytes(uint16_t length, const uint8_t *data)
  46. {
  47. if (length == 0) {
  48. send_raw(0x06, 0xF0, 0xF7, 0);
  49. return;
  50. } else if (length == 1) {
  51. send_raw(0x07, 0xF0, data[0], 0xF7);
  52. return;
  53. } else {
  54. send_raw(0x04, 0xF0, data[0], data[1]);
  55. data += 2;
  56. length -= 2;
  57. }
  58. while (length >= 3) {
  59. send_raw(0x04, data[0], data[1], data[2]);
  60. data += 3;
  61. length -= 3;
  62. }
  63. if (length == 2) {
  64. send_raw(0x07, data[0], data[1], 0xF7);
  65. } else if (length == 1) {
  66. send_raw(0x06, data[0], 0xF7, 0);
  67. } else {
  68. send_raw(0x05, 0xF7, 0, 0);
  69. }
  70. }
  71. void usb_midi_class::send_raw(uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3)
  72. {
  73. uint8_t intr_state, timeout;
  74. if (!usb_configuration) return;
  75. intr_state = SREG;
  76. cli();
  77. UENUM = MIDI_TX_ENDPOINT;
  78. timeout = UDFNUML + 2;
  79. while (1) {
  80. // are we ready to transmit?
  81. if (UEINTX & (1<<RWAL)) break;
  82. SREG = intr_state;
  83. if (UDFNUML == timeout) return;
  84. if (!usb_configuration) return;
  85. intr_state = SREG;
  86. cli();
  87. UENUM = MIDI_TX_ENDPOINT;
  88. }
  89. UEDATX = b0;
  90. UEDATX = b1;
  91. UEDATX = b2;
  92. UEDATX = b3;
  93. if (!(UEINTX & (1<<RWAL))) UEINTX = 0x3A;
  94. SREG = intr_state;
  95. }
  96. void usb_midi_class::send_now(void)
  97. {
  98. uint8_t intr_state;
  99. if (!usb_configuration) return;
  100. intr_state = SREG;
  101. cli();
  102. UENUM = MIDI_TX_ENDPOINT;
  103. if (UEBCLX != MIDI_TX_SIZE) {
  104. UEINTX = 0x3A;
  105. }
  106. SREG = intr_state;
  107. }
  108. // Convert 10 bit linear measurements to a logarthmic scale
  109. // suitable for sending as MIDI velocity numbers. The
  110. // "range" parameter should be probably be between 30 to 60,
  111. // with 36 probably a good default.
  112. //
  113. // This function uses fast 16 bit unsigned integer math. :-)
  114. //
  115. uint8_t usb_midi_class::analog2velocity(uint16_t val, uint8_t range)
  116. {
  117. #if 0
  118. if (val == 0) return 0;
  119. float scale = 1.0 + (20.0 / (float)range) * log10((float)val / 1023.0);
  120. if (scale < 0) return 0;
  121. return 127 * scale;
  122. #else
  123. uint8_t i, e, b;
  124. uint16_t s=0;
  125. static const uint8_t PROGMEM table[] = {225,124,65,34,17,9,4,2,1};
  126. if (val == 0) return 0;
  127. if (val >= 1023) return 127;
  128. for (e=0; (val & 512) == 0; e++) val <<= 1;
  129. for (i=0; i<9; i++) { // cordic algorithm
  130. uint16_t x = val + (val >> (i + 1));
  131. if (x < 1024) {
  132. val = x;
  133. s += pgm_read_byte(table + i);
  134. }
  135. }
  136. s += e * 385;
  137. s <<= 4;
  138. s += (range >> 1);
  139. s /= range;
  140. if (s >= 1024) return 0;
  141. s = 1024 - s;
  142. if (s > 511) {
  143. s -= 512;
  144. b = 64;
  145. } else if (s > 255) {
  146. s -= 256;
  147. b = 32;
  148. } else {
  149. b = 0;
  150. }
  151. return b + ((s * 127) >> 10);
  152. #endif
  153. }
  154. uint32_t usb_midi_class::midiusb_available()
  155. {
  156. uint8_t c, intr_state;
  157. intr_state = SREG;
  158. cli();
  159. if (!usb_configuration) {
  160. SREG = intr_state;
  161. return 0;
  162. }
  163. UENUM = MIDI_RX_ENDPOINT;
  164. retry:
  165. c = UEINTX;
  166. if (!(c & (1<<RWAL))) {
  167. if (c & (1<<RXOUTI)) {
  168. UEINTX = 0x6B;
  169. goto retry;
  170. }
  171. SREG = intr_state;
  172. return 0;
  173. }
  174. SREG = intr_state;
  175. return 4;
  176. }
  177. void usb_midi_class::midiusb_read(uint8_t *buf)
  178. {
  179. uint8_t c, intr_state;
  180. intr_state = SREG;
  181. cli();
  182. if (!usb_configuration) {
  183. SREG = intr_state;
  184. buf[0] = 0;
  185. buf[1] = 0;
  186. buf[2] = 0;
  187. buf[3] = 0;
  188. return;
  189. }
  190. UENUM = MIDI_RX_ENDPOINT;
  191. retry:
  192. c = UEINTX;
  193. if (!(c & (1<<RWAL))) {
  194. if (c & (1<<RXOUTI)) {
  195. UEINTX = 0x6B;
  196. goto retry;
  197. }
  198. SREG = intr_state;
  199. buf[0] = 0;
  200. buf[1] = 0;
  201. buf[2] = 0;
  202. buf[3] = 0;
  203. return;
  204. }
  205. buf[0] = UEDATX;
  206. buf[1] = UEDATX;
  207. buf[2] = UEDATX;
  208. buf[3] = UEDATX;
  209. if (!(UEINTX & (1<<RWAL))) UEINTX = 0x6B;
  210. SREG = intr_state;
  211. }
  212. bool usb_midi_class::read(uint8_t channel)
  213. {
  214. uint8_t c, intr_state;
  215. uint8_t b0, b1, b2, b3, type1, type2;
  216. intr_state = SREG;
  217. cli();
  218. if (!usb_configuration) {
  219. SREG = intr_state;
  220. return false;
  221. }
  222. UENUM = MIDI_RX_ENDPOINT;
  223. retry:
  224. c = UEINTX;
  225. if (!(c & (1<<RWAL))) {
  226. if (c & (1<<RXOUTI)) {
  227. UEINTX = 0x6B;
  228. goto retry;
  229. }
  230. SREG = intr_state;
  231. return false;
  232. }
  233. b0 = UEDATX;
  234. b1 = UEDATX;
  235. b2 = UEDATX;
  236. b3 = UEDATX;
  237. if (!(UEINTX & (1<<RWAL))) UEINTX = 0x6B;
  238. SREG = intr_state;
  239. type1 = b0 & 0x0F;
  240. type2 = b1 & 0xF0;
  241. c = (b1 & 0x0F) + 1;
  242. if (type1 >= 0x08 && type1 <= 0x0E) {
  243. if (channel && channel != c) {
  244. // ignore other channels when user wants single channel read
  245. return false;
  246. }
  247. if (type1 == 0x08 && type2 == 0x80) {
  248. msg_type = 0x80; // 0x80 = usbMIDI.NoteOff
  249. if (handleNoteOff) (*handleNoteOff)(c, b2, b3);
  250. } else
  251. if (type1 == 0x09 && type2 == 0x90) {
  252. if (b3) {
  253. msg_type = 0x90; // 0x90 = usbMIDI.NoteOn
  254. if (handleNoteOn) (*handleNoteOn)(c, b2, b3);
  255. } else {
  256. msg_type = 0x80; // 0x80 = usbMIDI.NoteOff
  257. if (handleNoteOff) (*handleNoteOff)(c, b2, b3);
  258. }
  259. } else
  260. if (type1 == 0x0A && type2 == 0xA0) {
  261. msg_type = 0xA0; // 0xA0 = usbMIDI.AfterTouchPoly
  262. if (handleVelocityChange) (*handleVelocityChange)(c, b2, b3);
  263. } else
  264. if (type1 == 0x0B && type2 == 0xB0) {
  265. msg_type = 0xB0; // 0xB0 = usbMIDI.ControlChange
  266. if (handleControlChange) (*handleControlChange)(c, b2, b3);
  267. } else
  268. if (type1 == 0x0C && type2 == 0xC0) {
  269. msg_type = 0xC0; // 0xC0 = usbMIDI.ProgramChange
  270. if (handleProgramChange) (*handleProgramChange)(c, b2);
  271. } else
  272. if (type1 == 0x0D && type2 == 0xD0) {
  273. msg_type = 0xD0; // 0xD0 = usbMIDI.AfterTouchChannel
  274. if (handleAfterTouch) (*handleAfterTouch)(c, b2);
  275. } else
  276. if (type1 == 0x0E && type2 == 0xE0) {
  277. msg_type = 0xE0; // 0xE0 = usbMIDI.PitchBend
  278. if (handlePitchChange) {
  279. int value = (b2 & 0x7F) | ((int)(b3 & 0x7F) << 7);
  280. value -= 8192; // 0 to 16383 --> -8192 to +8191
  281. (*handlePitchChange)(c, value);
  282. }
  283. } else {
  284. return false;
  285. }
  286. return_message:
  287. // only update these when returning true for a parsed message
  288. // all other return cases will preserve these user-visible values
  289. msg_channel = c;
  290. msg_data1 = b2;
  291. msg_data2 = b3;
  292. return true;
  293. }
  294. if (type1 == 0x02 || type1 == 0x03 || (type1 == 0x05 && type2 == 0x0F)) {
  295. // system common or system realtime message
  296. system_common_or_realtime:
  297. switch (b1) {
  298. case 0xF1: // usbMIDI.TimeCodeQuarterFrame
  299. if (handleTimeCodeQuarterFrame) {
  300. (*handleTimeCodeQuarterFrame)(b2);
  301. }
  302. break;
  303. case 0xF2: // usbMIDI.SongPosition
  304. if (handleSongPosition) {
  305. (*handleSongPosition)(
  306. (uint16_t)(b2 & 0x7F) | (uint16_t)(b3 & 0x7F) << 7);
  307. }
  308. break;
  309. case 0xF3: // usbMIDI.SongSelect
  310. if (handleSongSelect) {
  311. (*handleSongSelect)(b2);
  312. }
  313. break;
  314. case 0xF6: // usbMIDI.TuneRequest
  315. if (handleTuneRequest) {
  316. (*handleTuneRequest)();
  317. }
  318. break;
  319. case 0xF8: // usbMIDI.Clock
  320. if (handleClock) {
  321. (*handleClock)();
  322. } else if (handleRealTimeSystem) {
  323. (*handleRealTimeSystem)(0xF8);
  324. }
  325. break;
  326. case 0xFA: // usbMIDI.Start
  327. if (handleStart) {
  328. (*handleStart)();
  329. } else if (handleRealTimeSystem) {
  330. (*handleRealTimeSystem)(0xFA);
  331. }
  332. break;
  333. case 0xFB: // usbMIDI.Continue
  334. if (handleContinue) {
  335. (*handleContinue)();
  336. } else if (handleRealTimeSystem) {
  337. (*handleRealTimeSystem)(0xFB);
  338. }
  339. break;
  340. case 0xFC: // usbMIDI.Stop
  341. if (handleStop) {
  342. (*handleStop)();
  343. } else if (handleRealTimeSystem) {
  344. (*handleRealTimeSystem)(0xFC);
  345. }
  346. break;
  347. case 0xFE: // usbMIDI.ActiveSensing
  348. if (handleActiveSensing) {
  349. (*handleActiveSensing)();
  350. } else if (handleRealTimeSystem) {
  351. (*handleRealTimeSystem)(0xFE);
  352. }
  353. break;
  354. case 0xFF: // usbMIDI.SystemReset
  355. if (handleSystemReset) {
  356. (*handleSystemReset)();
  357. } else if (handleRealTimeSystem) {
  358. (*handleRealTimeSystem)(0xFF);
  359. }
  360. break;
  361. default:
  362. return false; // unknown message, ignore it
  363. }
  364. msg_type = b1;
  365. goto return_message;
  366. }
  367. if (type1 == 0x04) {
  368. read_sysex_byte(b1);
  369. read_sysex_byte(b2);
  370. read_sysex_byte(b3);
  371. return false;
  372. }
  373. if (type1 >= 0x05 && type1 <= 0x07) {
  374. read_sysex_byte(b1);
  375. if (type1 >= 0x06) read_sysex_byte(b2);
  376. if (type1 == 0x07) read_sysex_byte(b3);
  377. uint16_t len = msg_sysex_len;
  378. msg_data1 = len;
  379. msg_data2 = len >> 8;
  380. msg_sysex_len = 0;
  381. msg_type = 0xF0; // 0xF0 = usbMIDI.SystemExclusive
  382. if (handleSysExPartial) {
  383. (*handleSysExPartial)(msg_sysex, len, 1);
  384. } else if (handleSysExComplete) {
  385. (*handleSysExComplete)(msg_sysex, len);
  386. }
  387. return true;
  388. }
  389. if (type1 == 0x0F) {
  390. if (b1 >= 0xF8) {
  391. // From Sebastian Tomczak, seb.tomczak at gmail.com
  392. // http://little-scale.blogspot.com/2011/08/usb-midi-game-boy-sync-for-16.html
  393. goto system_common_or_realtime;
  394. }
  395. if (msg_sysex_len > 0) {
  396. // From David Sorlien, dsorlien at gmail.com, http://axe4live.wordpress.com
  397. // OSX sometimes uses Single Byte Unparsed to
  398. // send bytes in the middle of a SYSEX message.
  399. read_sysex_byte(b1);
  400. }
  401. }
  402. return false;
  403. }
  404. void usb_midi_class::read_sysex_byte(uint8_t b)
  405. {
  406. if (handleSysExPartial && msg_sysex_len >= USB_MIDI_SYSEX_MAX) {
  407. // when buffer is full, send another chunk to partial handler.
  408. (*handleSysExPartial)(msg_sysex, msg_sysex_len, 0);
  409. msg_sysex_len = 0;
  410. }
  411. if (msg_sysex_len < USB_MIDI_SYSEX_MAX) {
  412. msg_sysex[msg_sysex_len++] = b;
  413. }
  414. }
  415. static volatile uint8_t prev_byte=0;
  416. void usb_serial_class::begin(long speed)
  417. {
  418. // make sure USB is initialized
  419. usb_init();
  420. uint16_t begin_wait = (uint16_t)millis();
  421. while (1) {
  422. if (usb_configuration) {
  423. delay(200); // a little time for host to load a driver
  424. return;
  425. }
  426. if (usb_suspended) {
  427. uint16_t begin_suspend = (uint16_t)millis();
  428. while (usb_suspended) {
  429. // must remain suspended for a while, because
  430. // normal USB enumeration causes brief suspend
  431. // states, typically under 0.1 second
  432. if ((uint16_t)millis() - begin_suspend > 250) {
  433. return;
  434. }
  435. }
  436. }
  437. // ... or a timout (powered by a USB power adaptor that
  438. // wiggles the data lines to keep a USB device charging)
  439. if ((uint16_t)millis() - begin_wait > 2500) return;
  440. }
  441. prev_byte = 0;
  442. }
  443. void usb_serial_class::end()
  444. {
  445. usb_shutdown();
  446. delay(25);
  447. }
  448. // number of bytes available in the receive buffer
  449. int usb_serial_class::available()
  450. {
  451. uint8_t c;
  452. c = prev_byte; // assume 1 byte static volatile access is atomic
  453. if (c) return 1;
  454. c = readnext();
  455. if (c) {
  456. prev_byte = c;
  457. return 1;
  458. }
  459. return 0;
  460. }
  461. // get the next character, or -1 if nothing received
  462. int usb_serial_class::read()
  463. {
  464. uint8_t c;
  465. c = prev_byte;
  466. if (c) {
  467. prev_byte = 0;
  468. return c;
  469. }
  470. c = readnext();
  471. if (c) return c;
  472. return -1;
  473. }
  474. int usb_serial_class::peek()
  475. {
  476. uint8_t c;
  477. c = prev_byte;
  478. if (c) return c;
  479. c = readnext();
  480. if (c) {
  481. prev_byte = c;
  482. return c;
  483. }
  484. return -1;
  485. }
  486. // get the next character, or 0 if nothing
  487. uint8_t usb_serial_class::readnext(void)
  488. {
  489. uint8_t c, intr_state;
  490. // interrupts are disabled so these functions can be
  491. // used from the main program or interrupt context,
  492. // even both in the same program!
  493. intr_state = SREG;
  494. cli();
  495. if (!usb_configuration) {
  496. SREG = intr_state;
  497. return 0;
  498. }
  499. UENUM = DEBUG_RX_ENDPOINT;
  500. try_again:
  501. if (!(UEINTX & (1<<RWAL))) {
  502. // no packet in buffer
  503. SREG = intr_state;
  504. return 0;
  505. }
  506. // take one byte out of the buffer
  507. c = UEDATX;
  508. if (c == 0) {
  509. // if we see a zero, discard it and
  510. // discard the rest of this packet
  511. UEINTX = 0x6B;
  512. goto try_again;
  513. }
  514. // if this drained the buffer, release it
  515. if (!(UEINTX & (1<<RWAL))) UEINTX = 0x6B;
  516. SREG = intr_state;
  517. return c;
  518. }
  519. // discard any buffered input
  520. void usb_serial_class::flush()
  521. {
  522. uint8_t intr_state;
  523. if (usb_configuration) {
  524. intr_state = SREG;
  525. cli();
  526. UENUM = DEBUG_RX_ENDPOINT;
  527. while ((UEINTX & (1<<RWAL))) {
  528. UEINTX = 0x6B;
  529. }
  530. SREG = intr_state;
  531. }
  532. prev_byte = 0;
  533. }
  534. // transmit a character.
  535. #if ARDUINO >= 100
  536. size_t usb_serial_class::write(uint8_t c)
  537. #else
  538. #define setWriteError()
  539. void usb_serial_class::write(uint8_t c)
  540. #endif
  541. {
  542. //static uint8_t previous_timeout=0;
  543. uint8_t timeout, intr_state;
  544. // if we're not online (enumerated and configured), error
  545. if (!usb_configuration) goto error;
  546. // interrupts are disabled so these functions can be
  547. // used from the main program or interrupt context,
  548. // even both in the same program!
  549. intr_state = SREG;
  550. cli();
  551. UENUM = DEBUG_TX_ENDPOINT;
  552. // if we gave up due to timeout before, don't wait again
  553. #if 0
  554. // this seems to be causig a lockup... why????
  555. if (previous_timeout) {
  556. if (!(UEINTX & (1<<RWAL))) {
  557. SREG = intr_state;
  558. return;
  559. }
  560. previous_timeout = 0;
  561. }
  562. #endif
  563. // wait for the FIFO to be ready to accept data
  564. timeout = UDFNUML + TRANSMIT_TIMEOUT;
  565. while (1) {
  566. // are we ready to transmit?
  567. if (UEINTX & (1<<RWAL)) break;
  568. SREG = intr_state;
  569. // have we waited too long? This happens if the user
  570. // is not running an application that is listening
  571. if (UDFNUML == timeout) {
  572. //previous_timeout = 1;
  573. goto error;
  574. }
  575. // has the USB gone offline?
  576. if (!usb_configuration) goto error;
  577. // get ready to try checking again
  578. intr_state = SREG;
  579. cli();
  580. UENUM = DEBUG_TX_ENDPOINT;
  581. }
  582. // actually write the byte into the FIFO
  583. UEDATX = c;
  584. // if this completed a packet, transmit it now!
  585. if (!(UEINTX & (1<<RWAL))) {
  586. UEINTX = 0x3A;
  587. debug_flush_timer = 0;
  588. } else {
  589. debug_flush_timer = TRANSMIT_FLUSH_TIMEOUT;
  590. }
  591. SREG = intr_state;
  592. #if ARDUINO >= 100
  593. return 1;
  594. #endif
  595. error:
  596. #if ARDUINO >= 100
  597. setWriteError();
  598. return 0;
  599. #else
  600. return;
  601. #endif
  602. }
  603. // These are Teensy-specific extensions to the Serial object
  604. // immediately transmit any buffered output.
  605. // This doesn't actually transmit the data - that is impossible!
  606. // USB devices only transmit when the host allows, so the best
  607. // we can do is release the FIFO buffer for when the host wants it
  608. void usb_serial_class::send_now(void)
  609. {
  610. uint8_t intr_state;
  611. intr_state = SREG;
  612. cli();
  613. if (debug_flush_timer) {
  614. UENUM = DEBUG_TX_ENDPOINT;
  615. while ((UEINTX & (1<<RWAL))) {
  616. UEDATX = 0;
  617. }
  618. UEINTX = 0x3A;
  619. debug_flush_timer = 0;
  620. }
  621. SREG = intr_state;
  622. }
  623. uint32_t usb_serial_class::baud(void)
  624. {
  625. return ((uint32_t)DEBUG_TX_SIZE * 10000 / DEBUG_TX_INTERVAL);
  626. }
  627. uint8_t usb_serial_class::stopbits(void)
  628. {
  629. return 1;
  630. }
  631. uint8_t usb_serial_class::paritytype(void)
  632. {
  633. return 0;
  634. }
  635. uint8_t usb_serial_class::numbits(void)
  636. {
  637. return 8;
  638. }
  639. uint8_t usb_serial_class::dtr(void)
  640. {
  641. return 1;
  642. }
  643. uint8_t usb_serial_class::rts(void)
  644. {
  645. return 1;
  646. }
  647. usb_serial_class::operator bool()
  648. {
  649. if (usb_configuration) return true;
  650. return false;
  651. }
  652. // Preinstantiate Objects //////////////////////////////////////////////////////
  653. usb_serial_class Serial = usb_serial_class();
  654. usb_midi_class usbMIDI = usb_midi_class();