Teensy 4.1 core updated for C++20
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.

653 lines
17KB

  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. bool usb_midi_class::read(uint8_t channel)
  155. {
  156. uint8_t c, intr_state;
  157. uint8_t b0, b1, b2, b3, type1, type2;
  158. intr_state = SREG;
  159. cli();
  160. if (!usb_configuration) {
  161. SREG = intr_state;
  162. return false;
  163. }
  164. UENUM = MIDI_RX_ENDPOINT;
  165. retry:
  166. c = UEINTX;
  167. if (!(c & (1<<RWAL))) {
  168. if (c & (1<<RXOUTI)) {
  169. UEINTX = 0x6B;
  170. goto retry;
  171. }
  172. SREG = intr_state;
  173. return false;
  174. }
  175. b0 = UEDATX;
  176. b1 = UEDATX;
  177. b2 = UEDATX;
  178. b3 = UEDATX;
  179. if (!(UEINTX & (1<<RWAL))) UEINTX = 0x6B;
  180. SREG = intr_state;
  181. type1 = b0 & 0x0F;
  182. type2 = b1 & 0xF0;
  183. c = (b1 & 0x0F) + 1;
  184. if (type1 >= 0x08 && type1 <= 0x0E) {
  185. if (channel && channel != c) {
  186. // ignore other channels when user wants single channel read
  187. return false;
  188. }
  189. if (type1 == 0x08 && type2 == 0x80) {
  190. msg_type = 0x80; // 0x80 = usbMIDI.NoteOff
  191. if (handleNoteOff) (*handleNoteOff)(c, b2, b3);
  192. } else
  193. if (type1 == 0x09 && type2 == 0x90) {
  194. if (b3) {
  195. msg_type = 0x90; // 0x90 = usbMIDI.NoteOn
  196. if (handleNoteOn) (*handleNoteOn)(c, b2, b3);
  197. } else {
  198. msg_type = 0x80; // 0x80 = usbMIDI.NoteOff
  199. if (handleNoteOff) (*handleNoteOff)(c, b2, b3);
  200. }
  201. } else
  202. if (type1 == 0x0A && type2 == 0xA0) {
  203. msg_type = 0xA0; // 0xA0 = usbMIDI.AfterTouchPoly
  204. if (handleVelocityChange) (*handleVelocityChange)(c, b2, b3);
  205. } else
  206. if (type1 == 0x0B && type2 == 0xB0) {
  207. msg_type = 0xB0; // 0xB0 = usbMIDI.ControlChange
  208. if (handleControlChange) (*handleControlChange)(c, b2, b3);
  209. } else
  210. if (type1 == 0x0C && type2 == 0xC0) {
  211. msg_type = 0xC0; // 0xC0 = usbMIDI.ProgramChange
  212. if (handleProgramChange) (*handleProgramChange)(c, b2);
  213. } else
  214. if (type1 == 0x0D && type2 == 0xD0) {
  215. msg_type = 0xD0; // 0xD0 = usbMIDI.AfterTouchChannel
  216. if (handleAfterTouch) (*handleAfterTouch)(c, b2);
  217. } else
  218. if (type1 == 0x0E && type2 == 0xE0) {
  219. msg_type = 0xE0; // 0xE0 = usbMIDI.PitchBend
  220. if (handlePitchChange) (*handlePitchChange)(c,
  221. (b2 & 0x7F) | ((b3 & 0x7F) << 7));
  222. } else {
  223. return false;
  224. }
  225. return_message:
  226. // only update these when returning true for a parsed message
  227. // all other return cases will preserve these user-visible values
  228. msg_channel = c;
  229. msg_data1 = b2;
  230. msg_data2 = b3;
  231. return true;
  232. }
  233. if (type1 == 0x02 || type1 == 0x03 || (type1 == 0x05 && type2 == 0x0F)) {
  234. // system common or system realtime message
  235. system_common_or_realtime:
  236. switch (b1) {
  237. case 0xF1: // usbMIDI.TimeCodeQuarterFrame
  238. if (handleTimeCodeQuarterFrame) {
  239. (*handleTimeCodeQuarterFrame)(b2);
  240. }
  241. break;
  242. case 0xF2: // usbMIDI.SongPosition
  243. if (handleSongPosition) {
  244. (*handleSongPosition)(
  245. (uint16_t)(b2 & 0x7F) | (uint16_t)(b3 & 0x7F) << 7);
  246. }
  247. break;
  248. case 0xF3: // usbMIDI.SongSelect
  249. if (handleSongSelect) {
  250. (*handleSongSelect)(b2);
  251. }
  252. break;
  253. case 0xF6: // usbMIDI.TuneRequest
  254. if (handleTuneRequest) {
  255. (*handleTuneRequest)();
  256. }
  257. break;
  258. case 0xF8: // usbMIDI.Clock
  259. if (handleClock) {
  260. (*handleClock)();
  261. } else if (handleRealTimeSystem) {
  262. (*handleRealTimeSystem)(0xF8);
  263. }
  264. break;
  265. case 0xFA: // usbMIDI.Start
  266. if (handleStart) {
  267. (*handleStart)();
  268. } else if (handleRealTimeSystem) {
  269. (*handleRealTimeSystem)(0xFA);
  270. }
  271. break;
  272. case 0xFB: // usbMIDI.Continue
  273. if (handleContinue) {
  274. (*handleContinue)();
  275. } else if (handleRealTimeSystem) {
  276. (*handleRealTimeSystem)(0xFB);
  277. }
  278. break;
  279. case 0xFC: // usbMIDI.Stop
  280. if (handleStop) {
  281. (*handleStop)();
  282. } else if (handleRealTimeSystem) {
  283. (*handleRealTimeSystem)(0xFC);
  284. }
  285. break;
  286. case 0xFE: // usbMIDI.ActiveSensing
  287. if (handleActiveSensing) {
  288. (*handleActiveSensing)();
  289. } else if (handleRealTimeSystem) {
  290. (*handleRealTimeSystem)(0xFE);
  291. }
  292. break;
  293. case 0xFF: // usbMIDI.SystemReset
  294. if (handleSystemReset) {
  295. (*handleSystemReset)();
  296. } else if (handleRealTimeSystem) {
  297. (*handleRealTimeSystem)(0xFF);
  298. }
  299. break;
  300. default:
  301. return false; // unknown message, ignore it
  302. }
  303. msg_type = b1;
  304. goto return_message;
  305. }
  306. if (type1 == 0x04) {
  307. read_sysex_byte(b1);
  308. read_sysex_byte(b2);
  309. read_sysex_byte(b3);
  310. return false;
  311. }
  312. if (type1 >= 0x05 && type1 <= 0x07) {
  313. read_sysex_byte(b1);
  314. if (type1 >= 0x06) read_sysex_byte(b2);
  315. if (type1 == 0x07) read_sysex_byte(b3);
  316. uint16_t len = msg_sysex_len;
  317. msg_data1 = len;
  318. msg_data2 = len >> 8;
  319. msg_sysex_len = 0;
  320. msg_type = 0xF0; // 0xF0 = usbMIDI.SystemExclusive
  321. if (handleSysExPartial) {
  322. (*handleSysExPartial)(msg_sysex, len, 1);
  323. } else if (handleSysExComplete) {
  324. (*handleSysExComplete)(msg_sysex, len);
  325. }
  326. return true;
  327. }
  328. if (type1 == 0x0F) {
  329. if (b1 >= 0xF8) {
  330. // From Sebastian Tomczak, seb.tomczak at gmail.com
  331. // http://little-scale.blogspot.com/2011/08/usb-midi-game-boy-sync-for-16.html
  332. goto system_common_or_realtime;
  333. }
  334. if (msg_sysex_len > 0) {
  335. // From David Sorlien, dsorlien at gmail.com, http://axe4live.wordpress.com
  336. // OSX sometimes uses Single Byte Unparsed to
  337. // send bytes in the middle of a SYSEX message.
  338. read_sysex_byte(b1);
  339. }
  340. }
  341. return false;
  342. }
  343. void usb_midi_class::read_sysex_byte(uint8_t b)
  344. {
  345. if (handleSysExPartial && msg_sysex_len >= USB_MIDI_SYSEX_MAX) {
  346. // when buffer is full, send another chunk to partial handler.
  347. (*handleSysExPartial)(msg_sysex, msg_sysex_len, 0);
  348. msg_sysex_len = 0;
  349. }
  350. if (msg_sysex_len < USB_MIDI_SYSEX_MAX) {
  351. msg_sysex[msg_sysex_len++] = b;
  352. }
  353. }
  354. static volatile uint8_t prev_byte=0;
  355. void usb_serial_class::begin(long speed)
  356. {
  357. // make sure USB is initialized
  358. usb_init();
  359. uint16_t begin_wait = (uint16_t)millis();
  360. while (1) {
  361. if (usb_configuration) {
  362. delay(200); // a little time for host to load a driver
  363. return;
  364. }
  365. if (usb_suspended) {
  366. uint16_t begin_suspend = (uint16_t)millis();
  367. while (usb_suspended) {
  368. // must remain suspended for a while, because
  369. // normal USB enumeration causes brief suspend
  370. // states, typically under 0.1 second
  371. if ((uint16_t)millis() - begin_suspend > 250) {
  372. return;
  373. }
  374. }
  375. }
  376. // ... or a timout (powered by a USB power adaptor that
  377. // wiggles the data lines to keep a USB device charging)
  378. if ((uint16_t)millis() - begin_wait > 2500) return;
  379. }
  380. prev_byte = 0;
  381. }
  382. void usb_serial_class::end()
  383. {
  384. usb_shutdown();
  385. delay(25);
  386. }
  387. // number of bytes available in the receive buffer
  388. int usb_serial_class::available()
  389. {
  390. uint8_t c;
  391. c = prev_byte; // assume 1 byte static volatile access is atomic
  392. if (c) return 1;
  393. c = readnext();
  394. if (c) {
  395. prev_byte = c;
  396. return 1;
  397. }
  398. return 0;
  399. }
  400. // get the next character, or -1 if nothing received
  401. int usb_serial_class::read()
  402. {
  403. uint8_t c;
  404. c = prev_byte;
  405. if (c) {
  406. prev_byte = 0;
  407. return c;
  408. }
  409. c = readnext();
  410. if (c) return c;
  411. return -1;
  412. }
  413. int usb_serial_class::peek()
  414. {
  415. uint8_t c;
  416. c = prev_byte;
  417. if (c) return c;
  418. c = readnext();
  419. if (c) {
  420. prev_byte = c;
  421. return c;
  422. }
  423. return -1;
  424. }
  425. // get the next character, or 0 if nothing
  426. uint8_t usb_serial_class::readnext(void)
  427. {
  428. uint8_t c, intr_state;
  429. // interrupts are disabled so these functions can be
  430. // used from the main program or interrupt context,
  431. // even both in the same program!
  432. intr_state = SREG;
  433. cli();
  434. if (!usb_configuration) {
  435. SREG = intr_state;
  436. return 0;
  437. }
  438. UENUM = DEBUG_RX_ENDPOINT;
  439. try_again:
  440. if (!(UEINTX & (1<<RWAL))) {
  441. // no packet in buffer
  442. SREG = intr_state;
  443. return 0;
  444. }
  445. // take one byte out of the buffer
  446. c = UEDATX;
  447. if (c == 0) {
  448. // if we see a zero, discard it and
  449. // discard the rest of this packet
  450. UEINTX = 0x6B;
  451. goto try_again;
  452. }
  453. // if this drained the buffer, release it
  454. if (!(UEINTX & (1<<RWAL))) UEINTX = 0x6B;
  455. SREG = intr_state;
  456. return c;
  457. }
  458. // discard any buffered input
  459. void usb_serial_class::flush()
  460. {
  461. uint8_t intr_state;
  462. if (usb_configuration) {
  463. intr_state = SREG;
  464. cli();
  465. UENUM = DEBUG_RX_ENDPOINT;
  466. while ((UEINTX & (1<<RWAL))) {
  467. UEINTX = 0x6B;
  468. }
  469. SREG = intr_state;
  470. }
  471. prev_byte = 0;
  472. }
  473. // transmit a character.
  474. #if ARDUINO >= 100
  475. size_t usb_serial_class::write(uint8_t c)
  476. #else
  477. #define setWriteError()
  478. void usb_serial_class::write(uint8_t c)
  479. #endif
  480. {
  481. //static uint8_t previous_timeout=0;
  482. uint8_t timeout, intr_state;
  483. // if we're not online (enumerated and configured), error
  484. if (!usb_configuration) goto error;
  485. // interrupts are disabled so these functions can be
  486. // used from the main program or interrupt context,
  487. // even both in the same program!
  488. intr_state = SREG;
  489. cli();
  490. UENUM = DEBUG_TX_ENDPOINT;
  491. // if we gave up due to timeout before, don't wait again
  492. #if 0
  493. // this seems to be causig a lockup... why????
  494. if (previous_timeout) {
  495. if (!(UEINTX & (1<<RWAL))) {
  496. SREG = intr_state;
  497. return;
  498. }
  499. previous_timeout = 0;
  500. }
  501. #endif
  502. // wait for the FIFO to be ready to accept data
  503. timeout = UDFNUML + TRANSMIT_TIMEOUT;
  504. while (1) {
  505. // are we ready to transmit?
  506. if (UEINTX & (1<<RWAL)) break;
  507. SREG = intr_state;
  508. // have we waited too long? This happens if the user
  509. // is not running an application that is listening
  510. if (UDFNUML == timeout) {
  511. //previous_timeout = 1;
  512. goto error;
  513. }
  514. // has the USB gone offline?
  515. if (!usb_configuration) goto error;
  516. // get ready to try checking again
  517. intr_state = SREG;
  518. cli();
  519. UENUM = DEBUG_TX_ENDPOINT;
  520. }
  521. // actually write the byte into the FIFO
  522. UEDATX = c;
  523. // if this completed a packet, transmit it now!
  524. if (!(UEINTX & (1<<RWAL))) {
  525. UEINTX = 0x3A;
  526. debug_flush_timer = 0;
  527. } else {
  528. debug_flush_timer = TRANSMIT_FLUSH_TIMEOUT;
  529. }
  530. SREG = intr_state;
  531. #if ARDUINO >= 100
  532. return 1;
  533. #endif
  534. error:
  535. #if ARDUINO >= 100
  536. setWriteError();
  537. return 0;
  538. #else
  539. return;
  540. #endif
  541. }
  542. // These are Teensy-specific extensions to the Serial object
  543. // immediately transmit any buffered output.
  544. // This doesn't actually transmit the data - that is impossible!
  545. // USB devices only transmit when the host allows, so the best
  546. // we can do is release the FIFO buffer for when the host wants it
  547. void usb_serial_class::send_now(void)
  548. {
  549. uint8_t intr_state;
  550. intr_state = SREG;
  551. cli();
  552. if (debug_flush_timer) {
  553. UENUM = DEBUG_TX_ENDPOINT;
  554. while ((UEINTX & (1<<RWAL))) {
  555. UEDATX = 0;
  556. }
  557. UEINTX = 0x3A;
  558. debug_flush_timer = 0;
  559. }
  560. SREG = intr_state;
  561. }
  562. uint32_t usb_serial_class::baud(void)
  563. {
  564. return ((uint32_t)DEBUG_TX_SIZE * 10000 / DEBUG_TX_INTERVAL);
  565. }
  566. uint8_t usb_serial_class::stopbits(void)
  567. {
  568. return 1;
  569. }
  570. uint8_t usb_serial_class::paritytype(void)
  571. {
  572. return 0;
  573. }
  574. uint8_t usb_serial_class::numbits(void)
  575. {
  576. return 8;
  577. }
  578. uint8_t usb_serial_class::dtr(void)
  579. {
  580. return 1;
  581. }
  582. uint8_t usb_serial_class::rts(void)
  583. {
  584. return 1;
  585. }
  586. usb_serial_class::operator bool()
  587. {
  588. if (usb_configuration) return true;
  589. return false;
  590. }
  591. // Preinstantiate Objects //////////////////////////////////////////////////////
  592. usb_serial_class Serial = usb_serial_class();
  593. usb_midi_class usbMIDI = usb_midi_class();