#include #include #include #include #include #include "../uart/uart.h" #include "usb.h" #include "bdt.h" #include "endpt0.h" #include "endpt1.h" #define USBFRAC_VAL 1 /* 72 MHz * 2 = 144 MHz (Top of Fraction) */ #define USBDIV_VAL 2 /* 144 MHz / 3 = 48 MHz (Bottom of Fraction) */ /* TODO: Only use the number of endpoints that are needed */ /* TODO: Try using static */ __attribute__ ((aligned(512))) struct usb0_bd usb_bdt[16 * 4]; /* usb_setup: Setup function for USB subsystem */ void usb_setup(void) { /* Clock Setup */ SET_BIT(SIM_SOPT2, SOPT2_USBSRC); SET_MASKED(SIM_CLKDIV2, CLKDIV2_USBDIV_M | BV(CLKDIV2_USBFRAC), USBDIV_VAL << CLKDIV2_USBDIV | USBFRAC_VAL << CLKDIV2_USBFRAC); SET_BIT(SIM_SCGC4, SCGC4_USBOTG); /* Reset USB and wait more than 2 USB clock cycles */ SET_BIT(USB0_USBTRC0, USBTRC0_USBRESET); for (int i = 0; i < 5; i++) ; /* 512 bit aligned BDT address */ USB0_BDTPAGE1 = (uintptr_t)usb_bdt >> 8 & 0xff; USB0_BDTPAGE2 = (uintptr_t)usb_bdt >> 16 & 0xff; USB0_BDTPAGE3 = (uintptr_t)usb_bdt >> 24 & 0xff; /* Initial Configuration */ SET_MASKED(USB0_USBCTRL, BV(USBCTRL_SUSP) | BV(USBCTRL_PDE), 0); SET_BIT(USB0_CONTROL, CONTROL_DPPULLUPNONOTG); SET_BIT(USB0_INTEN, INTEN_USBRSTEN); /* NVIC Enable interrupt */ ISR_CLRPEND(73); ISR_SETENA(73); INTPRI(73) = 0x00; /* Enable USB */ USB0_CTL = BV(CTL_USBENSOFEN); } /* i_usbrst: Handler for USBRST USB interrupt */ static void i_usbrst(void) { SET_BIT(USB0_CTL, CTL_ODDRST); usb_endpt0_enable(); usb_endpt1_disable(); USB0_ADDR = 0; SET_BIT(USB0_INTEN, INTEN_TOKDNEEN); } /* i_tokdne: Handler for TOKDNE USB interrupt */ static void i_tokdne(void) { uint8_t stat = USB0_STAT; switch (GET_BITS(stat, STAT_ENDP)) { case 0: usb_endpt0_token(stat); break; case 1: usb_endpt1_token(stat); break; } } /* usb_isr: interrupt service routine for the USB FS SIE */ void usb_isr(void) { uint8_t stat = USB0_ISTAT; if (IS_BIT_SET(stat, ISTAT_TOKDNE)) { uart_puts("tokdne"); i_tokdne(); USB0_ISTAT = BV(ISTAT_TOKDNE); } if (IS_BIT_SET(stat, ISTAT_USBRST)) { uart_puts("usbrst"); i_usbrst(); USB0_ISTAT = BV(ISTAT_USBRST); } }