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.

713 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) (*handlePitchChange)(c,
  279. (b2 & 0x7F) | ((b3 & 0x7F) << 7));
  280. } else {
  281. return false;
  282. }
  283. return_message:
  284. // only update these when returning true for a parsed message
  285. // all other return cases will preserve these user-visible values
  286. msg_channel = c;
  287. msg_data1 = b2;
  288. msg_data2 = b3;
  289. return true;
  290. }
  291. if (type1 == 0x02 || type1 == 0x03 || (type1 == 0x05 && type2 == 0x0F)) {
  292. // system common or system realtime message
  293. system_common_or_realtime:
  294. switch (b1) {
  295. case 0xF1: // usbMIDI.TimeCodeQuarterFrame
  296. if (handleTimeCodeQuarterFrame) {
  297. (*handleTimeCodeQuarterFrame)(b2);
  298. }
  299. break;
  300. case 0xF2: // usbMIDI.SongPosition
  301. if (handleSongPosition) {
  302. (*handleSongPosition)(
  303. (uint16_t)(b2 & 0x7F) | (uint16_t)(b3 & 0x7F) << 7);
  304. }
  305. break;
  306. case 0xF3: // usbMIDI.SongSelect
  307. if (handleSongSelect) {
  308. (*handleSongSelect)(b2);
  309. }
  310. break;
  311. case 0xF6: // usbMIDI.TuneRequest
  312. if (handleTuneRequest) {
  313. (*handleTuneRequest)();
  314. }
  315. break;
  316. case 0xF8: // usbMIDI.Clock
  317. if (handleClock) {
  318. (*handleClock)();
  319. } else if (handleRealTimeSystem) {
  320. (*handleRealTimeSystem)(0xF8);
  321. }
  322. break;
  323. case 0xFA: // usbMIDI.Start
  324. if (handleStart) {
  325. (*handleStart)();
  326. } else if (handleRealTimeSystem) {
  327. (*handleRealTimeSystem)(0xFA);
  328. }
  329. break;
  330. case 0xFB: // usbMIDI.Continue
  331. if (handleContinue) {
  332. (*handleContinue)();
  333. } else if (handleRealTimeSystem) {
  334. (*handleRealTimeSystem)(0xFB);
  335. }
  336. break;
  337. case 0xFC: // usbMIDI.Stop
  338. if (handleStop) {
  339. (*handleStop)();
  340. } else if (handleRealTimeSystem) {
  341. (*handleRealTimeSystem)(0xFC);
  342. }
  343. break;
  344. case 0xFE: // usbMIDI.ActiveSensing
  345. if (handleActiveSensing) {
  346. (*handleActiveSensing)();
  347. } else if (handleRealTimeSystem) {
  348. (*handleRealTimeSystem)(0xFE);
  349. }
  350. break;
  351. case 0xFF: // usbMIDI.SystemReset
  352. if (handleSystemReset) {
  353. (*handleSystemReset)();
  354. } else if (handleRealTimeSystem) {
  355. (*handleRealTimeSystem)(0xFF);
  356. }
  357. break;
  358. default:
  359. return false; // unknown message, ignore it
  360. }
  361. msg_type = b1;
  362. goto return_message;
  363. }
  364. if (type1 == 0x04) {
  365. read_sysex_byte(b1);
  366. read_sysex_byte(b2);
  367. read_sysex_byte(b3);
  368. return false;
  369. }
  370. if (type1 >= 0x05 && type1 <= 0x07) {
  371. read_sysex_byte(b1);
  372. if (type1 >= 0x06) read_sysex_byte(b2);
  373. if (type1 == 0x07) read_sysex_byte(b3);
  374. uint16_t len = msg_sysex_len;
  375. msg_data1 = len;
  376. msg_data2 = len >> 8;
  377. msg_sysex_len = 0;
  378. msg_type = 0xF0; // 0xF0 = usbMIDI.SystemExclusive
  379. if (handleSysExPartial) {
  380. (*handleSysExPartial)(msg_sysex, len, 1);
  381. } else if (handleSysExComplete) {
  382. (*handleSysExComplete)(msg_sysex, len);
  383. }
  384. return true;
  385. }
  386. if (type1 == 0x0F) {
  387. if (b1 >= 0xF8) {
  388. // From Sebastian Tomczak, seb.tomczak at gmail.com
  389. // http://little-scale.blogspot.com/2011/08/usb-midi-game-boy-sync-for-16.html
  390. goto system_common_or_realtime;
  391. }
  392. if (msg_sysex_len > 0) {
  393. // From David Sorlien, dsorlien at gmail.com, http://axe4live.wordpress.com
  394. // OSX sometimes uses Single Byte Unparsed to
  395. // send bytes in the middle of a SYSEX message.
  396. read_sysex_byte(b1);
  397. }
  398. }
  399. return false;
  400. }
  401. void usb_midi_class::read_sysex_byte(uint8_t b)
  402. {
  403. if (handleSysExPartial && msg_sysex_len >= USB_MIDI_SYSEX_MAX) {
  404. // when buffer is full, send another chunk to partial handler.
  405. (*handleSysExPartial)(msg_sysex, msg_sysex_len, 0);
  406. msg_sysex_len = 0;
  407. }
  408. if (msg_sysex_len < USB_MIDI_SYSEX_MAX) {
  409. msg_sysex[msg_sysex_len++] = b;
  410. }
  411. }
  412. static volatile uint8_t prev_byte=0;
  413. void usb_serial_class::begin(long speed)
  414. {
  415. // make sure USB is initialized
  416. usb_init();
  417. uint16_t begin_wait = (uint16_t)millis();
  418. while (1) {
  419. if (usb_configuration) {
  420. delay(200); // a little time for host to load a driver
  421. return;
  422. }
  423. if (usb_suspended) {
  424. uint16_t begin_suspend = (uint16_t)millis();
  425. while (usb_suspended) {
  426. // must remain suspended for a while, because
  427. // normal USB enumeration causes brief suspend
  428. // states, typically under 0.1 second
  429. if ((uint16_t)millis() - begin_suspend > 250) {
  430. return;
  431. }
  432. }
  433. }
  434. // ... or a timout (powered by a USB power adaptor that
  435. // wiggles the data lines to keep a USB device charging)
  436. if ((uint16_t)millis() - begin_wait > 2500) return;
  437. }
  438. prev_byte = 0;
  439. }
  440. void usb_serial_class::end()
  441. {
  442. usb_shutdown();
  443. delay(25);
  444. }
  445. // number of bytes available in the receive buffer
  446. int usb_serial_class::available()
  447. {
  448. uint8_t c;
  449. c = prev_byte; // assume 1 byte static volatile access is atomic
  450. if (c) return 1;
  451. c = readnext();
  452. if (c) {
  453. prev_byte = c;
  454. return 1;
  455. }
  456. return 0;
  457. }
  458. // get the next character, or -1 if nothing received
  459. int usb_serial_class::read()
  460. {
  461. uint8_t c;
  462. c = prev_byte;
  463. if (c) {
  464. prev_byte = 0;
  465. return c;
  466. }
  467. c = readnext();
  468. if (c) return c;
  469. return -1;
  470. }
  471. int usb_serial_class::peek()
  472. {
  473. uint8_t c;
  474. c = prev_byte;
  475. if (c) return c;
  476. c = readnext();
  477. if (c) {
  478. prev_byte = c;
  479. return c;
  480. }
  481. return -1;
  482. }
  483. // get the next character, or 0 if nothing
  484. uint8_t usb_serial_class::readnext(void)
  485. {
  486. uint8_t c, intr_state;
  487. // interrupts are disabled so these functions can be
  488. // used from the main program or interrupt context,
  489. // even both in the same program!
  490. intr_state = SREG;
  491. cli();
  492. if (!usb_configuration) {
  493. SREG = intr_state;
  494. return 0;
  495. }
  496. UENUM = DEBUG_RX_ENDPOINT;
  497. try_again:
  498. if (!(UEINTX & (1<<RWAL))) {
  499. // no packet in buffer
  500. SREG = intr_state;
  501. return 0;
  502. }
  503. // take one byte out of the buffer
  504. c = UEDATX;
  505. if (c == 0) {
  506. // if we see a zero, discard it and
  507. // discard the rest of this packet
  508. UEINTX = 0x6B;
  509. goto try_again;
  510. }
  511. // if this drained the buffer, release it
  512. if (!(UEINTX & (1<<RWAL))) UEINTX = 0x6B;
  513. SREG = intr_state;
  514. return c;
  515. }
  516. // discard any buffered input
  517. void usb_serial_class::flush()
  518. {
  519. uint8_t intr_state;
  520. if (usb_configuration) {
  521. intr_state = SREG;
  522. cli();
  523. UENUM = DEBUG_RX_ENDPOINT;
  524. while ((UEINTX & (1<<RWAL))) {
  525. UEINTX = 0x6B;
  526. }
  527. SREG = intr_state;
  528. }
  529. prev_byte = 0;
  530. }
  531. // transmit a character.
  532. #if ARDUINO >= 100
  533. size_t usb_serial_class::write(uint8_t c)
  534. #else
  535. #define setWriteError()
  536. void usb_serial_class::write(uint8_t c)
  537. #endif
  538. {
  539. //static uint8_t previous_timeout=0;
  540. uint8_t timeout, intr_state;
  541. // if we're not online (enumerated and configured), error
  542. if (!usb_configuration) goto error;
  543. // interrupts are disabled so these functions can be
  544. // used from the main program or interrupt context,
  545. // even both in the same program!
  546. intr_state = SREG;
  547. cli();
  548. UENUM = DEBUG_TX_ENDPOINT;
  549. // if we gave up due to timeout before, don't wait again
  550. #if 0
  551. // this seems to be causig a lockup... why????
  552. if (previous_timeout) {
  553. if (!(UEINTX & (1<<RWAL))) {
  554. SREG = intr_state;
  555. return;
  556. }
  557. previous_timeout = 0;
  558. }
  559. #endif
  560. // wait for the FIFO to be ready to accept data
  561. timeout = UDFNUML + TRANSMIT_TIMEOUT;
  562. while (1) {
  563. // are we ready to transmit?
  564. if (UEINTX & (1<<RWAL)) break;
  565. SREG = intr_state;
  566. // have we waited too long? This happens if the user
  567. // is not running an application that is listening
  568. if (UDFNUML == timeout) {
  569. //previous_timeout = 1;
  570. goto error;
  571. }
  572. // has the USB gone offline?
  573. if (!usb_configuration) goto error;
  574. // get ready to try checking again
  575. intr_state = SREG;
  576. cli();
  577. UENUM = DEBUG_TX_ENDPOINT;
  578. }
  579. // actually write the byte into the FIFO
  580. UEDATX = c;
  581. // if this completed a packet, transmit it now!
  582. if (!(UEINTX & (1<<RWAL))) {
  583. UEINTX = 0x3A;
  584. debug_flush_timer = 0;
  585. } else {
  586. debug_flush_timer = TRANSMIT_FLUSH_TIMEOUT;
  587. }
  588. SREG = intr_state;
  589. #if ARDUINO >= 100
  590. return 1;
  591. #endif
  592. error:
  593. #if ARDUINO >= 100
  594. setWriteError();
  595. return 0;
  596. #else
  597. return;
  598. #endif
  599. }
  600. // These are Teensy-specific extensions to the Serial object
  601. // immediately transmit any buffered output.
  602. // This doesn't actually transmit the data - that is impossible!
  603. // USB devices only transmit when the host allows, so the best
  604. // we can do is release the FIFO buffer for when the host wants it
  605. void usb_serial_class::send_now(void)
  606. {
  607. uint8_t intr_state;
  608. intr_state = SREG;
  609. cli();
  610. if (debug_flush_timer) {
  611. UENUM = DEBUG_TX_ENDPOINT;
  612. while ((UEINTX & (1<<RWAL))) {
  613. UEDATX = 0;
  614. }
  615. UEINTX = 0x3A;
  616. debug_flush_timer = 0;
  617. }
  618. SREG = intr_state;
  619. }
  620. uint32_t usb_serial_class::baud(void)
  621. {
  622. return ((uint32_t)DEBUG_TX_SIZE * 10000 / DEBUG_TX_INTERVAL);
  623. }
  624. uint8_t usb_serial_class::stopbits(void)
  625. {
  626. return 1;
  627. }
  628. uint8_t usb_serial_class::paritytype(void)
  629. {
  630. return 0;
  631. }
  632. uint8_t usb_serial_class::numbits(void)
  633. {
  634. return 8;
  635. }
  636. uint8_t usb_serial_class::dtr(void)
  637. {
  638. return 1;
  639. }
  640. uint8_t usb_serial_class::rts(void)
  641. {
  642. return 1;
  643. }
  644. usb_serial_class::operator bool()
  645. {
  646. if (usb_configuration) return true;
  647. return false;
  648. }
  649. // Preinstantiate Objects //////////////////////////////////////////////////////
  650. usb_serial_class Serial = usb_serial_class();
  651. usb_midi_class usbMIDI = usb_midi_class();