-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathusb.c
146 lines (118 loc) · 2.04 KB
/
usb.c
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
// SPDX-FileCopyrightText: 2023 Andreas Sig Rosvall
//
// SPDX-License-Identifier: GPL-3.0-or-later
#include "bsp/gpio.h"
#include "bsp/interrupts.h"
#include "bsp/usb.h"
#include "config/pins.h"
#include "int.h"
#include "log.h"
#include "radio.h"
#include "rx.h"
#include "sleep.h"
#include "tx.h"
#include "usb.h"
#include "usb_config.h"
#include "usb_control_ep.h"
extern __bit sleep_now;
static void
enable_usb_pll(void)
{
LOGI(__func__);
USB.ctrl = USBCTRL_USB_EN | USBCTRL_PLL_EN;
while (!(USB.ctrl & USBCTRL_PLL_LOCKED))
;
}
static void
disable_usb_pll(void)
{
LOGI(__func__);
USB.ctrl = USBCTRL_USB_EN;
while (USB.ctrl & USBCTRL_PLL_LOCKED)
;
}
inline void
usb_reset(void)
{
LOGI(__func__);
radio_stop();
USB.cie = USBCI_RST | USBCI_SUSPEND;
USB.pow = USBPOW_SUSPEND_EN;
usb_control_reset();
}
inline void
usb_suspend(void)
{
LOGI(__func__);
disable_usb_pll();
sleep_soon();
}
inline void
usb_resume(void)
{
LOGI(__func__);
enable_usb_pll();
}
inline void
check_wakeup_flag(void)
{
if (P2IFG & P2IFG_DPIF)
usb_resume();
P2IFG = 0;
}
inline void
check_common_flags(void)
{
// Cleared on read
u8 flags = USB.cif;
if (flags & USBCI_RST)
usb_reset();
if (flags & USBCI_SUSPEND)
usb_suspend();
}
inline void
check_in_ep_flags(void)
{
// Cleared on read
u8 flags = USB.iif;
if (flags & BIT(CTRL_EP))
usb_control_intr_handler();
if (flags & BIT(RXPKT_EP))
rx_usb_intr_handler();
if (flags & BIT(INT_EP))
tx_usb_intr_handler();
}
inline void
check_out_ep_flags(void)
{
// Cleared on read
u8 flags = USB.oif;
if (flags)
LOGWX8("oif", flags);
}
INTERRUPT(usb_intr_handler, INTR_P2INT_USB_I2C)
{
IRCON2_P2IF = 0;
check_common_flags();
check_in_ep_flags();
check_out_ep_flags();
check_wakeup_flag();
}
void
usb_init(void)
{
enable_usb_pll();
gpio_dir_out(USB_DPLUS);
gpio_set_high(USB_DPLUS);
// Clear interrupt flags
USB.iif = 0;
USB.cif = 0;
USB.oif = 0;
P2IFG = 0;
IRCON2_P2IF = 0;
// Enable D+ intr on wake up
P2IEN |= P2IEN_DPIEN;
// Enable P2 interrupt
IEN2 |= IEN2_P2IE;
usb_control_init();
}