From b6e2790f15cdc27235175b42926c9389ee3c05fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=A0t=C4=9Bp=C3=A1n=20Daleck=C3=BD?= Date: Sat, 2 Jul 2022 12:03:45 +0200 Subject: [PATCH] Fix CDC_Send_FreeBytes --- src/main/vcpf4/usbd_cdc_vcp.c | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/src/main/vcpf4/usbd_cdc_vcp.c b/src/main/vcpf4/usbd_cdc_vcp.c index 6a0aaa60f4..7fbed99e78 100644 --- a/src/main/vcpf4/usbd_cdc_vcp.c +++ b/src/main/vcpf4/usbd_cdc_vcp.c @@ -44,7 +44,7 @@ __IO uint32_t bDeviceState = UNCONNECTED; /* USB device status */ /* This is the buffer for data received from the MCU to APP (i.e. MCU TX, APP RX) */ extern uint8_t APP_Rx_Buffer[]; -extern uint32_t APP_Rx_ptr_out; +extern volatile uint32_t APP_Rx_ptr_out; /* Increment this buffer position or roll it back to start address when writing received data in the buffer APP_Rx_Buffer. */ @@ -190,12 +190,8 @@ uint32_t CDC_Send_FreeBytes(void) { /* return the bytes free in the circular buffer - - functionally equivalent to: - (APP_Rx_ptr_out > APP_Rx_ptr_in ? APP_Rx_ptr_out - APP_Rx_ptr_in : APP_RX_DATA_SIZE - APP_Rx_ptr_in + APP_Rx_ptr_in) - but without the impact of the condition check. */ - return ((APP_Rx_ptr_out - APP_Rx_ptr_in) + (-((int)(APP_Rx_ptr_out <= APP_Rx_ptr_in)) & APP_RX_DATA_SIZE)) - 1; + return (APP_Rx_ptr_out > APP_Rx_ptr_in ? APP_Rx_ptr_out - APP_Rx_ptr_in : APP_RX_DATA_SIZE + APP_Rx_ptr_out - APP_Rx_ptr_in); } /** @@ -212,15 +208,13 @@ static uint16_t VCP_DataTx(const uint8_t* Buf, uint32_t Len) could just check for: USB_CDC_ZLP, but better to be safe and wait for any existing transmission to complete. */ - while (USB_Tx_State != 0); - for (uint32_t i = 0; i < Len; i++) { - APP_Rx_Buffer[APP_Rx_ptr_in] = Buf[i]; - APP_Rx_ptr_in = (APP_Rx_ptr_in + 1) % APP_RX_DATA_SIZE; - - while (CDC_Send_FreeBytes() == 0) { + while ((APP_Rx_ptr_in + 1) % APP_RX_DATA_SIZE == APP_Rx_ptr_out || APP_Rx_ptr_out == APP_RX_DATA_SIZE || USB_Tx_State != 0) { delay(1); } + + APP_Rx_Buffer[APP_Rx_ptr_in] = Buf[i]; + APP_Rx_ptr_in = (APP_Rx_ptr_in + 1) % APP_RX_DATA_SIZE; } return USBD_OK;