Skip to content

Commit ae709cd

Browse files
committed
usbd: Add cdc example and a basic read function.
1 parent 64e98c9 commit ae709cd

File tree

2 files changed

+40
-5
lines changed

2 files changed

+40
-5
lines changed

micropython/usbd/cdc.py

+26-5
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
)
1111
from micropython import const
1212
import ustruct
13+
import time
1314

1415
_DEV_CLASS_MISC = const(0xef)
1516
_CS_DESC_TYPE = const(0x24) # CS Interface type communication descriptor
@@ -69,18 +70,38 @@ def get_endpoint_descriptors(self, ep_addr, str_idx):
6970
class CDCDataInterface(USBInterface):
7071
# Implements the CDC Data Interface
7172

72-
def __init__(self, interface_str):
73+
def __init__(self, interface_str, timeout=1):
7374
super().__init__(_CDC_ITF_DATA_CLASS, _CDC_ITF_DATA_SUBCLASS,
7475
_CDC_ITF_DATA_PROT)
76+
self.rx_buf = bytearray(256)
77+
self.mv_buf = memoryview(self.rx_buf)
78+
self.rx_done = False
79+
self.rx_nbytes = 0
80+
self.timeout = timeout
7581

7682
def get_endpoint_descriptors(self, ep_addr, str_idx):
7783
# XXX OUT = 0x00 but is defined as 0x80?
7884
self.ep_in = (ep_addr + 2) | EP_OUT_FLAG
7985
self.ep_out = (ep_addr + 2) & ~EP_OUT_FLAG
80-
print("cdc in={} out={}".format(self.ep_in, self.ep_out))
8186
# one IN / OUT Endpoint
8287
e_out = endpoint_descriptor(self.ep_out, "bulk", 64, 0)
8388
e_in = endpoint_descriptor(self.ep_in, "bulk", 64, 0)
84-
desc = e_out + e_in
85-
return (desc, [], (self.ep_out, self.ep_in))
86-
89+
return (e_out + e_in, [], (self.ep_out, self.ep_in))
90+
91+
def write(self, data):
92+
super().submit_xfer(self.ep_in, data)
93+
94+
def read(self, nbytes=0):
95+
# XXX PoC.. When returning, it should probably
96+
# copy it to a ringbuffer instead of leaving it here
97+
super().submit_xfer(self.ep_out, self.rx_buf, self._cb_rx)
98+
now = time.time()
99+
self.rx_done = False
100+
self.rx_nbytes = 0
101+
while ((time.time() - now) < self.timeout) and not self.rx_done:
102+
time.sleep_ms(10)
103+
return bytes(self.mv_buf[:self.rx_nbytes]) if self.rx_done else None
104+
105+
def _cb_rx(self, ep, res, num_bytes):
106+
self.rx_done = True
107+
self.rx_nbytes = num_bytes

micropython/usbd/cdc_example.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from usbd import device, cdc
2+
3+
ud = device.get_usbdevice()
4+
cdc.setup_CDC_device()
5+
ctrl_cdc = cdc.CDCControlInterface('')
6+
data_cdc = cdc.CDCDataInterface('')
7+
ud.add_interface(ctrl_cdc)
8+
ud.add_interface(data_cdc)
9+
ud.reenumerate()
10+
11+
# sending something over CDC
12+
data_cdc.write(b'Hello World')
13+
# receiving something..
14+
print(data_cdc.read(10))

0 commit comments

Comments
 (0)