1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
#include <cm4.h>
#include <reg/gpio.h>
#include <reg/sim.h>
#include <reg/usbotg.h>
#include <stddef.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);
/* 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)) {
i_tokdne();
USB0_ISTAT = BV(ISTAT_TOKDNE);
}
if (IS_BIT_SET(stat, ISTAT_USBRST)) {
i_usbrst();
USB0_ISTAT = BV(ISTAT_USBRST);
}
}
|