My Marlin configs for Fabrikator Mini and CTC i3 Pro B
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.

USB_HOST_SHIELD_INLINE.h 31KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. /*
  2. * Copyright (C) 2015-2016 Andrew J. Kroll
  3. * and
  4. * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
  5. *
  6. * This software may be distributed and modified under the terms of the GNU
  7. * General Public License version 2 (GPL2) as publishe7d by the Free Software
  8. * Foundation and appearing in the file GPL2.TXT included in the packaging of
  9. * this file. Please note that GPL2 Section 2[b] requires that all works based
  10. * on this software must also be made publicly available under the terms of
  11. * the GPL2 ("Copyleft").
  12. *
  13. * Contact information
  14. * -------------------
  15. *
  16. * Circuits At Home, LTD
  17. * Web : https://www.circuitsathome.com
  18. * e-mail : support@circuitsathome.com
  19. *
  20. */
  21. #if defined(USB_HOST_SHIELD_H) && !defined(USB_HOST_SHIELD_LOADED)
  22. #define USB_HOST_SHIELD_LOADED
  23. #include <Arduino.h>
  24. #ifndef digitalPinToInterrupt
  25. #error digitalPinToInterrupt not defined, complain to your board maintainer.
  26. #endif
  27. #if USB_HOST_SHIELD_USE_ISR
  28. // allow two slots. this makes the maximum allowed shield count TWO
  29. // for AVRs this is limited to pins 2 and 3 ONLY
  30. // for all other boards, one odd and one even pin number is allowed.
  31. static MAX3421E_HOST *ISReven;
  32. static MAX3421E_HOST *ISRodd;
  33. static void UHS_NI call_ISReven() {
  34. ISReven->ISRTask();
  35. }
  36. static void UHS_NI call_ISRodd() {
  37. UHS_PIN_WRITE(LED_BUILTIN, HIGH);
  38. ISRodd->ISRTask();
  39. }
  40. #endif
  41. void UHS_NI MAX3421E_HOST::resume_host() {
  42. // Used on MCU that lack control of IRQ priority (AVR).
  43. // Resumes ISRs.
  44. // NOTE: you must track the state yourself!
  45. #ifdef __AVR__
  46. noInterrupts();
  47. if (irq_pin & 1) {
  48. ISRodd = this;
  49. attachInterrupt(UHS_GET_DPI(irq_pin), call_ISRodd, IRQ_SENSE);
  50. } else {
  51. ISReven = this;
  52. attachInterrupt(UHS_GET_DPI(irq_pin), call_ISReven, IRQ_SENSE);
  53. }
  54. interrupts();
  55. #endif
  56. }
  57. /* write single byte into MAX3421e register */
  58. void UHS_NI MAX3421E_HOST::regWr(uint8_t reg, uint8_t data) {
  59. SPIclass.beginTransaction(MAX3421E_SPI_Settings);
  60. MARLIN_UHS_WRITE_SS(LOW);
  61. SPIclass.transfer(reg | 0x02);
  62. SPIclass.transfer(data);
  63. MARLIN_UHS_WRITE_SS(HIGH);
  64. SPIclass.endTransaction();
  65. }
  66. /* multiple-byte write */
  67. /* returns a pointer to memory position after last written */
  68. uint8_t* UHS_NI MAX3421E_HOST::bytesWr(uint8_t reg, uint8_t nbytes, uint8_t *data_p) {
  69. SPIclass.beginTransaction(MAX3421E_SPI_Settings);
  70. MARLIN_UHS_WRITE_SS(LOW);
  71. SPIclass.transfer(reg | 0x02);
  72. //printf("%2.2x :", reg);
  73. while (nbytes) {
  74. SPIclass.transfer(*data_p);
  75. //printf("%2.2x ", *data_p);
  76. nbytes--;
  77. data_p++; // advance data pointer
  78. }
  79. MARLIN_UHS_WRITE_SS(HIGH);
  80. SPIclass.endTransaction();
  81. //printf("\r\n");
  82. return (data_p);
  83. }
  84. /* GPIO write */
  85. /*GPIO byte is split between 2 registers, so two writes are needed to write one byte */
  86. /* GPOUT bits are in the low nybble. 0-3 in IOPINS1, 4-7 in IOPINS2 */
  87. void UHS_NI MAX3421E_HOST::gpioWr(uint8_t data) {
  88. regWr(rIOPINS1, data);
  89. data >>= 4;
  90. regWr(rIOPINS2, data);
  91. return;
  92. }
  93. /* single host register read */
  94. uint8_t UHS_NI MAX3421E_HOST::regRd(uint8_t reg) {
  95. SPIclass.beginTransaction(MAX3421E_SPI_Settings);
  96. MARLIN_UHS_WRITE_SS(LOW);
  97. SPIclass.transfer(reg);
  98. uint8_t rv = SPIclass.transfer(0);
  99. MARLIN_UHS_WRITE_SS(HIGH);
  100. SPIclass.endTransaction();
  101. return (rv);
  102. }
  103. /* multiple-byte register read */
  104. /* returns a pointer to a memory position after last read */
  105. uint8_t* UHS_NI MAX3421E_HOST::bytesRd(uint8_t reg, uint8_t nbytes, uint8_t *data_p) {
  106. SPIclass.beginTransaction(MAX3421E_SPI_Settings);
  107. MARLIN_UHS_WRITE_SS(LOW);
  108. SPIclass.transfer(reg);
  109. while (nbytes) {
  110. *data_p++ = SPIclass.transfer(0);
  111. nbytes--;
  112. }
  113. MARLIN_UHS_WRITE_SS(HIGH);
  114. SPIclass.endTransaction();
  115. return ( data_p);
  116. }
  117. /* GPIO read. See gpioWr for explanation */
  118. /* GPIN pins are in high nybbles of IOPINS1, IOPINS2 */
  119. uint8_t UHS_NI MAX3421E_HOST::gpioRd() {
  120. uint8_t gpin = 0;
  121. gpin = regRd(rIOPINS2); // pins 4-7
  122. gpin &= 0xF0; // clean lower nybble
  123. gpin |= (regRd(rIOPINS1) >> 4); // shift low bits and OR with upper from previous operation.
  124. return (gpin);
  125. }
  126. /* reset MAX3421E. Returns number of microseconds it took for PLL to stabilize after reset
  127. or zero if PLL haven't stabilized in 65535 cycles */
  128. uint16_t UHS_NI MAX3421E_HOST::reset() {
  129. uint16_t i = 0;
  130. // Initiate chip reset
  131. regWr(rUSBCTL, bmCHIPRES);
  132. regWr(rUSBCTL, 0x00);
  133. int32_t now;
  134. uint32_t expires = micros() + 65535;
  135. // Enable full-duplex SPI so we can read rUSBIRQ
  136. regWr(rPINCTL, bmFDUPSPI);
  137. while ((int32_t)(micros() - expires) < 0L) {
  138. if ((regRd(rUSBIRQ) & bmOSCOKIRQ)) {
  139. break;
  140. }
  141. }
  142. now = (int32_t)(micros() - expires);
  143. if (now < 0L) {
  144. i = 65535 + now; // Note this subtracts, as now is negative
  145. }
  146. return (i);
  147. }
  148. void UHS_NI MAX3421E_HOST::VBUS_changed() {
  149. /* modify USB task state because Vbus changed or unknown */
  150. uint8_t speed = 1;
  151. //printf("\r\n\r\n\r\n\r\nSTATE %2.2x -> ", usb_task_state);
  152. switch (vbusState) {
  153. case LSHOST: // Low speed
  154. speed = 0;
  155. // Intentional fall-through
  156. case FSHOST: // Full speed
  157. // Start device initialization if we are not initializing
  158. // Resets to the device cause an IRQ
  159. // usb_task_state == UHS_USB_HOST_STATE_RESET_NOT_COMPLETE;
  160. //if ((usb_task_state & UHS_USB_HOST_STATE_MASK) != UHS_USB_HOST_STATE_DETACHED) {
  161. ReleaseChildren();
  162. if (!doingreset) {
  163. if (usb_task_state == UHS_USB_HOST_STATE_RESET_NOT_COMPLETE) {
  164. usb_task_state = UHS_USB_HOST_STATE_WAIT_BUS_READY;
  165. } else if (usb_task_state != UHS_USB_HOST_STATE_WAIT_BUS_READY) {
  166. usb_task_state = UHS_USB_HOST_STATE_DEBOUNCE;
  167. }
  168. }
  169. sof_countdown = 0;
  170. break;
  171. case SE1: // illegal state
  172. sof_countdown = 0;
  173. doingreset = false;
  174. ReleaseChildren();
  175. usb_task_state = UHS_USB_HOST_STATE_ILLEGAL;
  176. break;
  177. case SE0: // disconnected
  178. default:
  179. sof_countdown = 0;
  180. doingreset = false;
  181. ReleaseChildren();
  182. usb_task_state = UHS_USB_HOST_STATE_IDLE;
  183. break;
  184. }
  185. usb_host_speed = speed;
  186. //printf("0x%2.2x\r\n\r\n\r\n\r\n", usb_task_state);
  187. return;
  188. }
  189. /**
  190. * Probe bus to determine device presence and speed,
  191. * then switch host to detected speed.
  192. */
  193. void UHS_NI MAX3421E_HOST::busprobe() {
  194. uint8_t bus_sample;
  195. uint8_t tmpdata;
  196. bus_sample = regRd(rHRSL); // Get J,K status
  197. bus_sample &= (bmJSTATUS | bmKSTATUS); // zero the rest of the byte
  198. switch (bus_sample) { // start full-speed or low-speed host
  199. case bmJSTATUS:
  200. // Serial.println("J");
  201. if ((regRd(rMODE) & bmLOWSPEED) == 0) {
  202. regWr(rMODE, MODE_FS_HOST); // start full-speed host
  203. vbusState = FSHOST;
  204. } else {
  205. regWr(rMODE, MODE_LS_HOST); // start low-speed host
  206. vbusState = LSHOST;
  207. }
  208. #ifdef USB_HOST_MANUAL_POLL
  209. enable_frame_irq(true);
  210. #endif
  211. tmpdata = regRd(rMODE) | bmSOFKAENAB; // start SOF generation
  212. regWr(rHIRQ, bmFRAMEIRQ); // see data sheet.
  213. regWr(rMODE, tmpdata);
  214. break;
  215. case bmKSTATUS:
  216. // Serial.println("K");
  217. if ((regRd(rMODE) & bmLOWSPEED) == 0) {
  218. regWr(rMODE, MODE_LS_HOST); // start low-speed host
  219. vbusState = LSHOST;
  220. } else {
  221. regWr(rMODE, MODE_FS_HOST); // start full-speed host
  222. vbusState = FSHOST;
  223. }
  224. #ifdef USB_HOST_MANUAL_POLL
  225. enable_frame_irq(true);
  226. #endif
  227. tmpdata = regRd(rMODE) | bmSOFKAENAB; // start SOF generation
  228. regWr(rHIRQ, bmFRAMEIRQ); // see data sheet.
  229. regWr(rMODE, tmpdata);
  230. break;
  231. case bmSE1: // illegal state
  232. // Serial.println("I");
  233. regWr(rMODE, bmDPPULLDN | bmDMPULLDN | bmHOST);
  234. vbusState = SE1;
  235. // sofevent = false;
  236. break;
  237. case bmSE0: // disconnected state
  238. // Serial.println("D");
  239. regWr(rMODE, bmDPPULLDN | bmDMPULLDN | bmHOST);
  240. vbusState = SE0;
  241. // sofevent = false;
  242. break;
  243. } // end switch ( bus_sample )
  244. }
  245. /**
  246. * Initialize USB hardware, turn on VBUS
  247. *
  248. * @param mseconds Delay energizing VBUS after mseconds, A value of INT16_MIN means no delay.
  249. * @return 0 on success, -1 on error
  250. */
  251. int16_t UHS_NI MAX3421E_HOST::Init(int16_t mseconds) {
  252. usb_task_state = UHS_USB_HOST_STATE_INITIALIZE; //set up state machine
  253. //Serial.print("MAX3421E 'this' USB Host @ 0x");
  254. //Serial.println((uint32_t)this, HEX);
  255. //Serial.print("MAX3421E 'this' USB Host Address Pool @ 0x");
  256. //Serial.println((uint32_t)GetAddressPool(), HEX);
  257. Init_dyn_SWI();
  258. UHS_printf_HELPER_init();
  259. noInterrupts();
  260. #ifdef ARDUINO_AVR_ADK
  261. // For Mega ADK, which has a Max3421e on-board,
  262. // set MAX_RESET to output mode, and then set it to HIGH
  263. // PORTJ bit 2
  264. if (irq_pin == 54) {
  265. DDRJ |= 0x04; // output
  266. PORTJ |= 0x04; // HIGH
  267. }
  268. #endif
  269. SPIclass.begin();
  270. #ifdef ARDUINO_AVR_ADK
  271. if (irq_pin == 54) {
  272. DDRE &= ~0x20; // input
  273. PORTE |= 0x20; // pullup
  274. } else
  275. #endif
  276. pinMode(irq_pin, INPUT_PULLUP);
  277. //UHS_PIN_WRITE(irq_pin, HIGH);
  278. pinMode(ss_pin, OUTPUT);
  279. MARLIN_UHS_WRITE_SS(HIGH);
  280. #ifdef USB_HOST_SHIELD_TIMING_PIN
  281. pinMode(USB_HOST_SHIELD_TIMING_PIN, OUTPUT);
  282. // My counter/timer can't work on an inverted gate signal
  283. // so we gate using a high pulse -- AJK
  284. UHS_PIN_WRITE(USB_HOST_SHIELD_TIMING_PIN, LOW);
  285. #endif
  286. interrupts();
  287. #if USB_HOST_SHIELD_USE_ISR
  288. int intr = digitalPinToInterrupt(irq_pin);
  289. if (intr == NOT_AN_INTERRUPT) {
  290. #ifdef ARDUINO_AVR_ADK
  291. if (irq_pin == 54)
  292. intr = 6;
  293. else
  294. #endif
  295. return (-2);
  296. }
  297. SPIclass.usingInterrupt(intr);
  298. #else
  299. SPIclass.usingInterrupt(255);
  300. #endif
  301. #ifndef NO_AUTO_SPEED
  302. // test to get to reset acceptance.
  303. uint32_t spd = UHS_MAX3421E_SPD;
  304. again:
  305. MAX3421E_SPI_Settings = SPISettings(spd, MSBFIRST, SPI_MODE0);
  306. if (reset() == 0) {
  307. MAX_HOST_DEBUG(PSTR("Fail SPI speed %lu\r\n"), spd);
  308. if (spd > 1999999) {
  309. spd -= 1000000;
  310. goto again;
  311. }
  312. return (-1);
  313. } else {
  314. // reset passes, does 64k?
  315. uint8_t sample_wr = 0;
  316. uint8_t sample_rd = 0;
  317. uint8_t gpinpol_copy = regRd(rGPINPOL);
  318. for (uint16_t j = 0; j < 65535; j++) {
  319. regWr(rGPINPOL, sample_wr);
  320. sample_rd = regRd(rGPINPOL);
  321. if (sample_rd != sample_wr) {
  322. MAX_HOST_DEBUG(PSTR("Fail SPI speed %lu\r\n"), spd);
  323. if (spd > 1999999) {
  324. spd -= 1000000;
  325. goto again;
  326. }
  327. return (-1);
  328. }
  329. sample_wr++;
  330. }
  331. regWr(rGPINPOL, gpinpol_copy);
  332. }
  333. MAX_HOST_DEBUG(PSTR("Pass SPI speed %lu\r\n"), spd);
  334. #endif
  335. if (reset() == 0) { // OSCOKIRQ hasn't asserted in time
  336. MAX_HOST_DEBUG(PSTR("OSCOKIRQ hasn't asserted in time"));
  337. return ( -1);
  338. }
  339. /* MAX3421E - full-duplex SPI, interrupt kind, vbus off */
  340. regWr(rPINCTL, (bmFDUPSPI | bmIRQ_SENSE | GPX_VBDET));
  341. // Delay a minimum of 1 second to ensure any capacitors are drained.
  342. // 1 second is required to make sure we do not smoke a Microdrive!
  343. if (mseconds != INT16_MIN) {
  344. if (mseconds < 1000) mseconds = 1000;
  345. delay(mseconds); // We can't depend on SOF timer here.
  346. }
  347. regWr(rMODE, bmDPPULLDN | bmDMPULLDN | bmHOST); // set pull-downs, Host
  348. // Enable interrupts on the MAX3421e
  349. regWr(rHIEN, IRQ_CHECK_MASK);
  350. // Enable interrupt pin on the MAX3421e, set pulse width for edge
  351. regWr(rCPUCTL, (bmIE | bmPULSEWIDTH));
  352. /* check if device is connected */
  353. regWr(rHCTL, bmSAMPLEBUS); // sample USB bus
  354. while (!(regRd(rHCTL) & bmSAMPLEBUS)); // wait for sample operation to finish
  355. busprobe(); // check if anything is connected
  356. VBUS_changed();
  357. // GPX pin on. This is done here so that a change is detected if we have a switch connected.
  358. /* MAX3421E - full-duplex SPI, interrupt kind, vbus on */
  359. regWr(rPINCTL, (bmFDUPSPI | bmIRQ_SENSE));
  360. regWr(rHIRQ, bmBUSEVENTIRQ); // see data sheet.
  361. regWr(rHCTL, bmBUSRST); // issue bus reset to force generate yet another possible IRQ
  362. #if USB_HOST_SHIELD_USE_ISR
  363. // Attach ISR to service IRQ from MAX3421e
  364. noInterrupts();
  365. if (irq_pin & 1) {
  366. ISRodd = this;
  367. attachInterrupt(UHS_GET_DPI(irq_pin), call_ISRodd, IRQ_SENSE);
  368. } else {
  369. ISReven = this;
  370. attachInterrupt(UHS_GET_DPI(irq_pin), call_ISReven, IRQ_SENSE);
  371. }
  372. interrupts();
  373. #endif
  374. //printf("\r\nrPINCTL 0x%2.2X\r\n", rPINCTL);
  375. //printf("rCPUCTL 0x%2.2X\r\n", rCPUCTL);
  376. //printf("rHIEN 0x%2.2X\r\n", rHIEN);
  377. //printf("irq_pin %i\r\n", irq_pin);
  378. return 0;
  379. }
  380. /**
  381. * Setup UHS_EpInfo structure
  382. *
  383. * @param addr USB device address
  384. * @param ep Endpoint
  385. * @param ppep pointer to the pointer to a valid UHS_EpInfo structure
  386. * @param nak_limit how many NAKs before aborting
  387. * @return 0 on success
  388. */
  389. uint8_t UHS_NI MAX3421E_HOST::SetAddress(uint8_t addr, uint8_t ep, UHS_EpInfo **ppep, uint16_t &nak_limit) {
  390. UHS_Device *p = addrPool.GetUsbDevicePtr(addr);
  391. if (!p)
  392. return UHS_HOST_ERROR_NO_ADDRESS_IN_POOL;
  393. if (!p->epinfo)
  394. return UHS_HOST_ERROR_NULL_EPINFO;
  395. *ppep = getEpInfoEntry(addr, ep);
  396. if (!*ppep)
  397. return UHS_HOST_ERROR_NO_ENDPOINT_IN_TABLE;
  398. nak_limit = (0x0001UL << (((*ppep)->bmNakPower > UHS_USB_NAK_MAX_POWER) ? UHS_USB_NAK_MAX_POWER : (*ppep)->bmNakPower));
  399. nak_limit--;
  400. /*
  401. USBTRACE2("\r\nAddress: ", addr);
  402. USBTRACE2(" EP: ", ep);
  403. USBTRACE2(" NAK Power: ",(*ppep)->bmNakPower);
  404. USBTRACE2(" NAK Limit: ", nak_limit);
  405. USBTRACE("\r\n");
  406. */
  407. regWr(rPERADDR, addr); // set peripheral address
  408. uint8_t mode = regRd(rMODE);
  409. //Serial.print("\r\nMode: ");
  410. //Serial.println( mode, HEX);
  411. //Serial.print("\r\nLS: ");
  412. //Serial.println(p->speed, HEX);
  413. // Set bmLOWSPEED and bmHUBPRE in case of low-speed device, reset them otherwise
  414. regWr(rMODE, (p->speed) ? mode & ~(bmHUBPRE | bmLOWSPEED) : mode | bmLOWSPEED | hub_present);
  415. return 0;
  416. }
  417. /**
  418. * Receive a packet
  419. *
  420. * @param pep pointer to a valid UHS_EpInfo structure
  421. * @param nak_limit how many NAKs before aborting
  422. * @param nbytesptr pointer to maximum number of bytes of data to receive
  423. * @param data pointer to data buffer
  424. * @return 0 on success
  425. */
  426. uint8_t UHS_NI MAX3421E_HOST::InTransfer(UHS_EpInfo *pep, uint16_t nak_limit, uint16_t *nbytesptr, uint8_t *data) {
  427. uint8_t rcode = 0;
  428. uint8_t pktsize;
  429. uint16_t nbytes = *nbytesptr;
  430. MAX_HOST_DEBUG(PSTR("Requesting %i bytes "), nbytes);
  431. uint8_t maxpktsize = pep->maxPktSize;
  432. *nbytesptr = 0;
  433. regWr(rHCTL, (pep->bmRcvToggle) ? bmRCVTOG1 : bmRCVTOG0); // set toggle value
  434. // use a 'break' to exit this loop
  435. while (1) {
  436. rcode = dispatchPkt(MAX3421E_tokIN, pep->epAddr, nak_limit); // IN packet to EP-'endpoint'. Function takes care of NAKS.
  437. #if 0
  438. // This issue should be resolved now.
  439. if (rcode == UHS_HOST_ERROR_TOGERR) {
  440. //MAX_HOST_DEBUG(PSTR("toggle wrong\r\n"));
  441. // yes, we flip it wrong here so that next time it is actually correct!
  442. pep->bmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1;
  443. regWr(rHCTL, (pep->bmRcvToggle) ? bmRCVTOG1 : bmRCVTOG0); // set toggle value
  444. continue;
  445. }
  446. #endif
  447. if (rcode) {
  448. //MAX_HOST_DEBUG(PSTR(">>>>>>>> Problem! dispatchPkt %2.2x\r\n"), rcode);
  449. break; // should be 0, indicating ACK. Else return error code.
  450. }
  451. /* check for RCVDAVIRQ and generate error if not present */
  452. /* the only case when absence of RCVDAVIRQ makes sense is when toggle error occurred. Need to add handling for that */
  453. if ((regRd(rHIRQ) & bmRCVDAVIRQ) == 0) {
  454. //MAX_HOST_DEBUG(PSTR(">>>>>>>> Problem! NO RCVDAVIRQ!\r\n"));
  455. rcode = 0xF0; // receive error
  456. break;
  457. }
  458. pktsize = regRd(rRCVBC); // number of received bytes
  459. MAX_HOST_DEBUG(PSTR("Got %i bytes \r\n"), pktsize);
  460. if (pktsize > nbytes) { // certain devices send more than asked
  461. //MAX_HOST_DEBUG(PSTR(">>>>>>>> Warning: wanted %i bytes but got %i.\r\n"), nbytes, pktsize);
  462. pktsize = nbytes;
  463. }
  464. int16_t mem_left = (int16_t)nbytes - *((int16_t*)nbytesptr);
  465. if (mem_left < 0)
  466. mem_left = 0;
  467. data = bytesRd(rRCVFIFO, ((pktsize > mem_left) ? mem_left : pktsize), data);
  468. regWr(rHIRQ, bmRCVDAVIRQ); // Clear the IRQ & free the buffer
  469. *nbytesptr += pktsize; // add this packet's byte count to total transfer length
  470. /* The transfer is complete under two conditions: */
  471. /* 1. The device sent a short packet (L.T. maxPacketSize) */
  472. /* 2. 'nbytes' have been transferred. */
  473. if ((pktsize < maxpktsize) || (*nbytesptr >= nbytes)) { // have we transferred 'nbytes' bytes?
  474. // Save toggle value
  475. pep->bmRcvToggle = ((regRd(rHRSL) & bmRCVTOGRD)) ? 1 : 0;
  476. //MAX_HOST_DEBUG(PSTR("\r\n"));
  477. rcode = 0;
  478. break;
  479. } // if
  480. } // while( 1 )
  481. return (rcode);
  482. }
  483. /**
  484. * Transmit a packet
  485. *
  486. * @param pep pointer to a valid UHS_EpInfo structure
  487. * @param nak_limit how many NAKs before aborting
  488. * @param nbytes number of bytes of data to send
  489. * @param data pointer to data buffer
  490. * @return 0 on success
  491. */
  492. uint8_t UHS_NI MAX3421E_HOST::OutTransfer(UHS_EpInfo *pep, uint16_t nak_limit, uint16_t nbytes, uint8_t *data) {
  493. uint8_t rcode = UHS_HOST_ERROR_NONE;
  494. uint8_t retry_count;
  495. uint8_t *data_p = data; // local copy of the data pointer
  496. uint16_t bytes_tosend;
  497. uint16_t nak_count;
  498. uint16_t bytes_left = nbytes;
  499. uint8_t maxpktsize = pep->maxPktSize;
  500. if (maxpktsize < 1 || maxpktsize > 64)
  501. return UHS_HOST_ERROR_BAD_MAX_PACKET_SIZE;
  502. unsigned long timeout = millis() + UHS_HOST_TRANSFER_MAX_MS;
  503. regWr(rHCTL, (pep->bmSndToggle) ? bmSNDTOG1 : bmSNDTOG0); // set toggle value
  504. while (bytes_left) {
  505. SYSTEM_OR_SPECIAL_YIELD();
  506. retry_count = 0;
  507. nak_count = 0;
  508. bytes_tosend = (bytes_left >= maxpktsize) ? maxpktsize : bytes_left;
  509. bytesWr(rSNDFIFO, bytes_tosend, data_p); // filling output FIFO
  510. regWr(rSNDBC, bytes_tosend); // set number of bytes
  511. regWr(rHXFR, (MAX3421E_tokOUT | pep->epAddr)); // dispatch packet
  512. while (!(regRd(rHIRQ) & bmHXFRDNIRQ)); // wait for the completion IRQ
  513. regWr(rHIRQ, bmHXFRDNIRQ); // clear IRQ
  514. rcode = (regRd(rHRSL) & 0x0F);
  515. while (rcode && ((long)(millis() - timeout) < 0L)) {
  516. switch (rcode) {
  517. case UHS_HOST_ERROR_NAK:
  518. nak_count++;
  519. if (nak_limit && (nak_count == nak_limit))
  520. goto breakout;
  521. break;
  522. case UHS_HOST_ERROR_TIMEOUT:
  523. retry_count++;
  524. if (retry_count == UHS_HOST_TRANSFER_RETRY_MAXIMUM)
  525. goto breakout;
  526. break;
  527. case UHS_HOST_ERROR_TOGERR:
  528. // yes, we flip it wrong here so that next time it is actually correct!
  529. pep->bmSndToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1;
  530. regWr(rHCTL, (pep->bmSndToggle) ? bmSNDTOG1 : bmSNDTOG0); // set toggle value
  531. break;
  532. default:
  533. goto breakout;
  534. } // switch (rcode
  535. /* process NAK according to Host out NAK bug */
  536. regWr(rSNDBC, 0);
  537. regWr(rSNDFIFO, *data_p);
  538. regWr(rSNDBC, bytes_tosend);
  539. regWr(rHXFR, (MAX3421E_tokOUT | pep->epAddr)); // dispatch packet
  540. while (!(regRd(rHIRQ) & bmHXFRDNIRQ)); // wait for the completion IRQ
  541. regWr(rHIRQ, bmHXFRDNIRQ); // clear IRQ
  542. rcode = (regRd(rHRSL) & 0x0F);
  543. SYSTEM_OR_SPECIAL_YIELD();
  544. } // while (rcode && ....
  545. bytes_left -= bytes_tosend;
  546. data_p += bytes_tosend;
  547. } // while (bytes_left...
  548. breakout:
  549. pep->bmSndToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 1 : 0; // bmSNDTOG1 : bmSNDTOG0; // update toggle
  550. return (rcode); // should be 0 in all cases
  551. }
  552. /**
  553. * Send the actual packet.
  554. *
  555. * @param token
  556. * @param ep Endpoint
  557. * @param nak_limit how many NAKs before aborting, 0 == exit after timeout
  558. * @return 0 on success, 0xFF indicates NAK timeout. @see
  559. */
  560. /* Assumes peripheral address is set and relevant buffer is loaded/empty */
  561. /* If NAK, tries to re-send up to nak_limit times */
  562. /* If nak_limit == 0, do not count NAKs, exit after timeout */
  563. /* If bus timeout, re-sends up to USB_RETRY_LIMIT times */
  564. /* return codes 0x00-0x0F are HRSLT( 0x00 being success ), 0xFF means timeout */
  565. uint8_t UHS_NI MAX3421E_HOST::dispatchPkt(uint8_t token, uint8_t ep, uint16_t nak_limit) {
  566. unsigned long timeout = millis() + UHS_HOST_TRANSFER_MAX_MS;
  567. uint8_t tmpdata;
  568. uint8_t rcode = UHS_HOST_ERROR_NONE;
  569. uint8_t retry_count = 0;
  570. uint16_t nak_count = 0;
  571. for (;;) {
  572. regWr(rHXFR, (token | ep)); // launch the transfer
  573. while (long(millis() - timeout) < 0L) { // wait for transfer completion
  574. SYSTEM_OR_SPECIAL_YIELD();
  575. tmpdata = regRd(rHIRQ);
  576. if (tmpdata & bmHXFRDNIRQ) {
  577. regWr(rHIRQ, bmHXFRDNIRQ); // clear the interrupt
  578. //rcode = 0x00;
  579. break;
  580. } // if (tmpdata & bmHXFRDNIRQ
  581. } // while (millis() < timeout
  582. rcode = (regRd(rHRSL) & 0x0F); // analyze transfer result
  583. switch (rcode) {
  584. case UHS_HOST_ERROR_NAK:
  585. nak_count++;
  586. if (nak_limit && (nak_count == nak_limit))
  587. return (rcode);
  588. delayMicroseconds(200);
  589. break;
  590. case UHS_HOST_ERROR_TIMEOUT:
  591. retry_count++;
  592. if (retry_count == UHS_HOST_TRANSFER_RETRY_MAXIMUM)
  593. return (rcode);
  594. break;
  595. default:
  596. return (rcode);
  597. } // switch (rcode)
  598. }
  599. }
  600. //
  601. // NULL is error, we don't need to know the reason.
  602. //
  603. UHS_EpInfo * UHS_NI MAX3421E_HOST::ctrlReqOpen(uint8_t addr, uint64_t Request, uint8_t *dataptr) {
  604. uint8_t rcode;
  605. UHS_EpInfo *pep = NULL;
  606. uint16_t nak_limit = 0;
  607. rcode = SetAddress(addr, 0, &pep, nak_limit);
  608. if (!rcode) {
  609. bytesWr(rSUDFIFO, 8, (uint8_t*)(&Request)); // transfer to setup packet FIFO
  610. rcode = dispatchPkt(MAX3421E_tokSETUP, 0, nak_limit); // dispatch packet
  611. if (!rcode) {
  612. if (dataptr != NULL) {
  613. if (((Request)/* bmReqType*/ & 0x80) == 0x80) {
  614. pep->bmRcvToggle = 1; //bmRCVTOG1;
  615. } else {
  616. pep->bmSndToggle = 1; //bmSNDTOG1;
  617. }
  618. }
  619. } else {
  620. pep = NULL;
  621. }
  622. }
  623. return pep;
  624. }
  625. uint8_t UHS_NI MAX3421E_HOST::ctrlReqRead(UHS_EpInfo *pep, uint16_t *left, uint16_t *read, uint16_t nbytes, uint8_t *dataptr) {
  626. *read = 0;
  627. uint16_t nak_limit = 0;
  628. MAX_HOST_DEBUG(PSTR("ctrlReqRead left: %i\r\n"), *left);
  629. if (*left) {
  630. again:
  631. *read = nbytes;
  632. uint8_t rcode = InTransfer(pep, nak_limit, read, dataptr);
  633. if (rcode == UHS_HOST_ERROR_TOGERR) {
  634. // yes, we flip it wrong here so that next time it is actually correct!
  635. pep->bmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1;
  636. goto again;
  637. }
  638. if (rcode) {
  639. MAX_HOST_DEBUG(PSTR("ctrlReqRead ERROR: %2.2x, left: %i, read %i\r\n"), rcode, *left, *read);
  640. return rcode;
  641. }
  642. *left -= *read;
  643. MAX_HOST_DEBUG(PSTR("ctrlReqRead left: %i, read %i\r\n"), *left, *read);
  644. }
  645. return 0;
  646. }
  647. uint8_t UHS_NI MAX3421E_HOST::ctrlReqClose(UHS_EpInfo *pep, uint8_t bmReqType, uint16_t left, uint16_t nbytes, uint8_t *dataptr) {
  648. uint8_t rcode = 0;
  649. //MAX_HOST_DEBUG(PSTR("Closing"));
  650. if (((bmReqType & 0x80) == 0x80) && pep && left && dataptr) {
  651. MAX_HOST_DEBUG(PSTR("ctrlReqRead Sinking %i\r\n"), left);
  652. // If reading, sink the rest of the data.
  653. while (left) {
  654. uint16_t read = nbytes;
  655. rcode = InTransfer(pep, 0, &read, dataptr);
  656. if (rcode == UHS_HOST_ERROR_TOGERR) {
  657. // yes, we flip it wrong here so that next time it is actually correct!
  658. pep->bmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1;
  659. continue;
  660. }
  661. if (rcode) break;
  662. left -= read;
  663. if (read < nbytes) break;
  664. }
  665. }
  666. if (!rcode) {
  667. //Serial.println("Dispatching");
  668. rcode = dispatchPkt(((bmReqType & 0x80) == 0x80) ? MAX3421E_tokOUTHS : MAX3421E_tokINHS, 0, 0); //GET if direction
  669. //} else {
  670. //Serial.println("Bypassed Dispatch");
  671. }
  672. return rcode;
  673. }
  674. /**
  675. * Bottom half of the ISR task
  676. */
  677. void UHS_NI MAX3421E_HOST::ISRbottom() {
  678. uint8_t x;
  679. // Serial.print("Enter ");
  680. // Serial.print((uint32_t)this,HEX);
  681. // Serial.print(" ");
  682. // Serial.println(usb_task_state, HEX);
  683. DDSB();
  684. if (condet) {
  685. VBUS_changed();
  686. #if USB_HOST_SHIELD_USE_ISR
  687. noInterrupts();
  688. #endif
  689. condet = false;
  690. #if USB_HOST_SHIELD_USE_ISR
  691. interrupts();
  692. #endif
  693. }
  694. switch (usb_task_state) {
  695. case UHS_USB_HOST_STATE_INITIALIZE:
  696. // should never happen...
  697. MAX_HOST_DEBUG(PSTR("UHS_USB_HOST_STATE_INITIALIZE\r\n"));
  698. busprobe();
  699. VBUS_changed();
  700. break;
  701. case UHS_USB_HOST_STATE_DEBOUNCE:
  702. MAX_HOST_DEBUG(PSTR("UHS_USB_HOST_STATE_DEBOUNCE\r\n"));
  703. // This seems to not be needed. The host controller has debounce built in.
  704. sof_countdown = UHS_HOST_DEBOUNCE_DELAY_MS;
  705. usb_task_state = UHS_USB_HOST_STATE_DEBOUNCE_NOT_COMPLETE;
  706. break;
  707. case UHS_USB_HOST_STATE_DEBOUNCE_NOT_COMPLETE:
  708. MAX_HOST_DEBUG(PSTR("UHS_USB_HOST_STATE_DEBOUNCE_NOT_COMPLETE\r\n"));
  709. if (!sof_countdown) usb_task_state = UHS_USB_HOST_STATE_RESET_DEVICE;
  710. break;
  711. case UHS_USB_HOST_STATE_RESET_DEVICE:
  712. MAX_HOST_DEBUG(PSTR("UHS_USB_HOST_STATE_RESET_DEVICE\r\n"));
  713. busevent = true;
  714. usb_task_state = UHS_USB_HOST_STATE_RESET_NOT_COMPLETE;
  715. regWr(rHIRQ, bmBUSEVENTIRQ); // see data sheet.
  716. regWr(rHCTL, bmBUSRST); // issue bus reset
  717. break;
  718. case UHS_USB_HOST_STATE_RESET_NOT_COMPLETE:
  719. MAX_HOST_DEBUG(PSTR("UHS_USB_HOST_STATE_RESET_NOT_COMPLETE\r\n"));
  720. if (!busevent) usb_task_state = UHS_USB_HOST_STATE_WAIT_BUS_READY;
  721. break;
  722. case UHS_USB_HOST_STATE_WAIT_BUS_READY:
  723. MAX_HOST_DEBUG(PSTR("UHS_USB_HOST_STATE_WAIT_BUS_READY\r\n"));
  724. usb_task_state = UHS_USB_HOST_STATE_CONFIGURING;
  725. break; // don't fall through
  726. case UHS_USB_HOST_STATE_CONFIGURING:
  727. usb_task_state = UHS_USB_HOST_STATE_CHECK;
  728. x = Configuring(0, 1, usb_host_speed);
  729. usb_error = x;
  730. if (usb_task_state == UHS_USB_HOST_STATE_CHECK) {
  731. if (x) {
  732. MAX_HOST_DEBUG(PSTR("Error 0x%2.2x"), x);
  733. if (x == UHS_HOST_ERROR_JERR) {
  734. usb_task_state = UHS_USB_HOST_STATE_IDLE;
  735. } else if (x != UHS_HOST_ERROR_DEVICE_INIT_INCOMPLETE) {
  736. usb_error = x;
  737. usb_task_state = UHS_USB_HOST_STATE_ERROR;
  738. }
  739. } else
  740. usb_task_state = UHS_USB_HOST_STATE_CONFIGURING_DONE;
  741. }
  742. break;
  743. case UHS_USB_HOST_STATE_CHECK:
  744. // Serial.println((uint32_t)__builtin_return_address(0), HEX);
  745. break;
  746. case UHS_USB_HOST_STATE_CONFIGURING_DONE:
  747. usb_task_state = UHS_USB_HOST_STATE_RUNNING;
  748. break;
  749. #ifdef USB_HOST_MANUAL_POLL
  750. case UHS_USB_HOST_STATE_RUNNING:
  751. case UHS_USB_HOST_STATE_ERROR:
  752. case UHS_USB_HOST_STATE_IDLE:
  753. case UHS_USB_HOST_STATE_ILLEGAL:
  754. enable_frame_irq(false);
  755. break;
  756. #else
  757. case UHS_USB_HOST_STATE_RUNNING:
  758. Poll_Others();
  759. for (x = 0; (usb_task_state == UHS_USB_HOST_STATE_RUNNING) && (x < UHS_HOST_MAX_INTERFACE_DRIVERS); x++) {
  760. if (devConfig[x]) {
  761. if (devConfig[x]->bPollEnable) devConfig[x]->Poll();
  762. }
  763. }
  764. // fall thru
  765. #endif
  766. default:
  767. // Do nothing
  768. break;
  769. } // switch ( usb_task_state )
  770. DDSB();
  771. #if USB_HOST_SHIELD_USE_ISR
  772. if (condet) {
  773. VBUS_changed();
  774. noInterrupts();
  775. condet = false;
  776. interrupts();
  777. }
  778. #endif
  779. #ifdef USB_HOST_SHIELD_TIMING_PIN
  780. // My counter/timer can't work on an inverted gate signal
  781. // so we gate using a high pulse -- AJK
  782. UHS_PIN_WRITE(USB_HOST_SHIELD_TIMING_PIN, LOW);
  783. #endif
  784. //usb_task_polling_disabled--;
  785. EnablePoll();
  786. DDSB();
  787. }
  788. /* USB main task. Services the MAX3421e */
  789. #if !USB_HOST_SHIELD_USE_ISR
  790. void UHS_NI MAX3421E_HOST::ISRTask() {}
  791. void UHS_NI MAX3421E_HOST::Task()
  792. #else
  793. void UHS_NI MAX3421E_HOST::Task() {
  794. #ifdef USB_HOST_MANUAL_POLL
  795. if (usb_task_state == UHS_USB_HOST_STATE_RUNNING) {
  796. noInterrupts();
  797. for (uint8_t x = 0; x < UHS_HOST_MAX_INTERFACE_DRIVERS; x++)
  798. if (devConfig[x] && devConfig[x]->bPollEnable)
  799. devConfig[x]->Poll();
  800. interrupts();
  801. }
  802. #endif
  803. }
  804. void UHS_NI MAX3421E_HOST::ISRTask()
  805. #endif
  806. {
  807. DDSB();
  808. #ifndef SWI_IRQ_NUM
  809. suspend_host();
  810. #if USB_HOST_SHIELD_USE_ISR
  811. // Enable interrupts
  812. interrupts();
  813. #endif
  814. #endif
  815. counted = false;
  816. if (!MARLIN_UHS_READ_IRQ()) {
  817. uint8_t HIRQALL = regRd(rHIRQ); // determine interrupt source
  818. uint8_t HIRQ = HIRQALL & IRQ_CHECK_MASK;
  819. uint8_t HIRQ_sendback = 0x00;
  820. if ((HIRQ & bmCONDETIRQ) || (HIRQ & bmBUSEVENTIRQ)) {
  821. MAX_HOST_DEBUG
  822. (PSTR("\r\nBEFORE CDIRQ %s BEIRQ %s resetting %s state 0x%2.2x\r\n"),
  823. (HIRQ & bmCONDETIRQ) ? "T" : "F",
  824. (HIRQ & bmBUSEVENTIRQ) ? "T" : "F",
  825. doingreset ? "T" : "F",
  826. usb_task_state
  827. );
  828. }
  829. // ALWAYS happens BEFORE or WITH CONDETIRQ
  830. if (HIRQ & bmBUSEVENTIRQ) {
  831. HIRQ_sendback |= bmBUSEVENTIRQ;
  832. if (!doingreset) condet = true;
  833. busprobe();
  834. busevent = false;
  835. }
  836. if (HIRQ & bmCONDETIRQ) {
  837. HIRQ_sendback |= bmCONDETIRQ;
  838. if (!doingreset) condet = true;
  839. busprobe();
  840. }
  841. #if 1
  842. if ((HIRQ & bmCONDETIRQ) || (HIRQ & bmBUSEVENTIRQ)) {
  843. MAX_HOST_DEBUG
  844. (PSTR("\r\nAFTER CDIRQ %s BEIRQ %s resetting %s state 0x%2.2x\r\n"),
  845. (HIRQ & bmCONDETIRQ) ? "T" : "F",
  846. (HIRQ & bmBUSEVENTIRQ) ? "T" : "F",
  847. doingreset ? "T" : "F",
  848. usb_task_state
  849. );
  850. }
  851. #endif
  852. if (HIRQ & bmFRAMEIRQ) {
  853. HIRQ_sendback |= bmFRAMEIRQ;
  854. if (sof_countdown) {
  855. sof_countdown--;
  856. counted = true;
  857. }
  858. sofevent = false;
  859. }
  860. //MAX_HOST_DEBUG(PSTR("\r\n%s%s%s\r\n"),
  861. // sof_countdown ? "T" : "F",
  862. // counted ? "T" : "F",
  863. // usb_task_polling_disabled? "T" : "F");
  864. DDSB();
  865. regWr(rHIRQ, HIRQ_sendback);
  866. #ifndef SWI_IRQ_NUM
  867. resume_host();
  868. #if USB_HOST_SHIELD_USE_ISR
  869. // Disable interrupts
  870. noInterrupts();
  871. #endif
  872. #endif
  873. if (!sof_countdown && !counted && !usb_task_polling_disabled) {
  874. DisablePoll();
  875. //usb_task_polling_disabled++;
  876. #ifdef USB_HOST_SHIELD_TIMING_PIN
  877. // My counter/timer can't work on an inverted gate signal
  878. // so we gate using a high pulse -- AJK
  879. UHS_PIN_WRITE(USB_HOST_SHIELD_TIMING_PIN, HIGH);
  880. #endif
  881. #ifdef SWI_IRQ_NUM
  882. //MAX_HOST_DEBUG(PSTR("--------------- Doing SWI ----------------"));
  883. exec_SWI(this);
  884. #else
  885. #if USB_HOST_SHIELD_USE_ISR
  886. // Enable interrupts
  887. interrupts();
  888. #endif
  889. ISRbottom();
  890. #endif /* SWI_IRQ_NUM */
  891. }
  892. }
  893. }
  894. #if 0
  895. DDSB();
  896. #endif
  897. #else
  898. #error "Never include USB_HOST_SHIELD_INLINE.h, include UHS_host.h instead"
  899. #endif