Skip to content

Commit 02660d0

Browse files
committed
[tinyusb] Only read from CDC if data is available
1 parent 8ca2f35 commit 02660d0

File tree

2 files changed

+47
-5
lines changed

2 files changed

+47
-5
lines changed

examples/generic/usb/main.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,12 @@ int main()
4646
tud_task();
4747
midi_task();
4848

49+
#if CFG_TUD_CDC
50+
// Do a loopback on the CDC
51+
if (char input; usb_stream0.get(input), input != modm::IOStream::eof) {
52+
usb_stream0 << input;
53+
}
54+
#endif
4955
if (tmr.execute())
5056
{
5157
Leds::toggle();

ext/hathach/uart.hpp

Lines changed: 41 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ class UsbUart : public modm::Uart
2929
return tud_cdc_n_connected(ITF);
3030
}
3131

32+
static inline void
33+
flushWriteBuffer()
34+
{
35+
tud_cdc_n_write_flush(ITF);
36+
}
37+
3238
static inline bool
3339
write(uint8_t c)
3440
{
@@ -45,22 +51,26 @@ class UsbUart : public modm::Uart
4551
return rc;
4652
}
4753

48-
static inline void
49-
flushWriteBuffer()
54+
static inline bool
55+
isWriteFinished()
5056
{
51-
tud_cdc_n_write_flush(ITF);
57+
return not transmitBufferSize();
5258
}
5359

5460
static inline bool
5561
read(uint8_t& c)
5662
{
57-
return tud_cdc_n_read(ITF, &c, sizeof(uint8_t));
63+
if (receiveBufferSize())
64+
return tud_cdc_n_read(ITF, &c, sizeof(uint8_t));
65+
return false;
5866
}
5967

6068
static inline std::size_t
6169
read(uint8_t *data, std::size_t length)
6270
{
63-
return tud_cdc_n_read(ITF, data, length);
71+
if (receiveBufferSize())
72+
return tud_cdc_n_read(ITF, data, length);
73+
return 0;
6474
}
6575

6676
static inline std::size_t
@@ -69,11 +79,37 @@ class UsbUart : public modm::Uart
6979
return tud_cdc_n_available(ITF);
7080
}
7181

82+
static inline std::size_t
83+
discardReceiveBuffer()
84+
{
85+
const std::size_t rxsize = receiveBufferSize();
86+
tud_cdc_n_read_flush(ITF);
87+
return rxsize;
88+
}
89+
7290
static inline std::size_t
7391
transmitBufferSize()
7492
{
7593
return tud_cdc_n_write_available(ITF);
7694
}
95+
96+
static inline std::size_t
97+
discardTransmitBuffer()
98+
{
99+
const std::size_t txsize = transmitBufferSize();
100+
tud_cdc_n_write_clear(ITF);
101+
return txsize;
102+
}
103+
104+
static inline bool
105+
hasError()
106+
{
107+
return false;
108+
}
109+
110+
static inline void
111+
clearError()
112+
{}
77113
};
78114

79115
using UsbUart0 = UsbUart<0>;

0 commit comments

Comments
 (0)