Close

Hints for using the CDC USB Serial

A project log for Notes on Using SystemWorkbench with STM32 BluePill

I finally succumb to IDE madness... for awhile.

Al WilliamsAl Williams 04/11/2017 at 03:050 Comments

When you add the USB CDC serial to your project, you don't get much help about what to do next. The CDC_Transmit_FS call is pretty obvious. Give it a message and a length and it sends it. Fair enough.

Receive, though is via a callback named CDC_Receive_FS. You don't call this. The framework calls it for you.

Here's my version:

static int8_t CDC_Receive_FS (uint8_t* Buf, uint32_t *Len)

{

  /* USER CODE BEGIN 6 */
uint32_t len=*Len;
if (hUsbDeviceFS.dev_state != USBD_STATE_CONFIGURED)
{
   return USBD_FAIL;
}

if (((Buf == NULL) || (Len == NULL)) || (*Len <= 0))
{
   return USBD_FAIL;
}

/* Get data */
uint8_t result = USBD_OK;
    do
    {
        result = USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
    }
    while(result != USBD_OK);

    do
    {
       result = USBD_CDC_ReceivePacket(&hUsbDeviceFS);
    }
    while(result != USBD_OK);

// add data to FIFO
    while (len--)
       if (FIFO_INCR(RX_FIFO.head)==RX_FIFO.tail)
             return USBD_FAIL;  // overrun
       else
        {
        RX_FIFO.data[RX_FIFO.head]=*Buf++;
       RX_FIFO.head=FIFO_INCR(RX_FIFO.head);
       }
   return (USBD_OK);

  /* USER CODE END 6 */ 

}

This in in one of the headers:

#define  FIFO_SIZE 32  // must be 2^N

#define FIFO_INCR(x) (((x)+1)&((FIFO_SIZE)-1))

/* Structure of FIFO*/

typedef struct FIFO

{
uint32_t head;
uint32_t tail;
    uint8_t data[FIFO_SIZE];
} FIFO;

extern FIFO RX_FIFO;

Then you need a way to read it out, too

/* Create FIFO*/
FIFO RX_FIFO = {.head=0, .tail=0};

// returns bytes read (could be zero)
// would be easy to make it end early on a stop char (e.g., \r or \n)
uint8_t VCP_read(uint8_t* Buf, uint32_t Len)
{
  uint32_t count=0;
/* Check inputs */
  if ((Buf == NULL) || (Len == 0))
 {
  return 0;
 }

while (Len--)
{
if (RX_FIFO.head==RX_FIFO.tail) return count;
count++;
*Buf++=RX_FIFO.data[RX_FIFO.tail];
RX_FIFO.tail=FIFO_INCR(RX_FIFO.tail);
}

return count;
}

Discussions