[N32L43X评测]8.USB CDC 自定义传输内容
<p>N32的USB部分自己走了点弯路,本来HSI内部RC晶振是完全可以给USB用的,但是N32的Boot必须使用HSE才能工作,这样不得已还要在板子上加上晶振才行,请小伙伴们注意这一点。</p><p> </p>
<p>N32的USB使用时要先确认主频,内部分频可以是1、1.5、2、3,即主频可以是48MHz,72MHz,96MHz,144MHz 。官方提供的例程是96MHz</p>
<p> </p>
<p>USB转串口的程序厂家已经提供了,我的项目主要想通过USB传输自己的内容,并不需要Uart。所以需要找到USB和Uart通讯的代码进行修改。</p>
<p lang="en-US"> </p>
<p>先找到USB接收到数据然后通过串口发出的位置,这是通过端口3实现的</p>
<p lang="en-US">usb_endp.c Line:113</p>
<pre>
<code class="language-cpp">/**
* @brief EP3 OUT Callback Routine.
*/
void EP3_OUT_Callback(void)
{
uint16_t USB_Rx_Cnt;
/* Get the received data buffer and update the counter */
USB_Rx_Cnt = USB_SilRead(EP3_OUT, USB_Rx_Buffer);
/* USB data will be immediately processed, this allow next USB traffic being
NAKed till the end of the USART Xfer */
//USB_To_USART_Send_Data(USB_Rx_Buffer, USB_Rx_Cnt);
UsbToUserData(USB_Rx_Buffer,USB_Rx_Cnt);
/* Enable the receive of data on EP3 */
USB_SetEpRxValid(ENDP3);
}
</code></pre>
<p lang="en-US"> </p>
<p>然后找到Uart接收到数据通过USB发送的位置,这是通过端口1实现的</p>
<p lang="en-US">usb_endp.c Line:64</p>
<pre>
<code class="language-cpp">/**
* @briefEP1 IN Callback Routine.
*/
void EP1_IN_Callback (void)
{
uint16_t USB_Tx_ptr;
uint16_t USB_Tx_length;
if (USB_Tx_State == 1)
{
if (USART_Rx_length == 0)
{
USB_Tx_State = 0;
}
else
{
if (USART_Rx_length > VIRTUAL_COM_PORT_DATA_SIZE)
{
USB_Tx_ptr = USART_Rx_ptr_out;
USB_Tx_length = VIRTUAL_COM_PORT_DATA_SIZE;
USART_Rx_ptr_out += VIRTUAL_COM_PORT_DATA_SIZE;
USART_Rx_length -= VIRTUAL_COM_PORT_DATA_SIZE;
}
else
{
USB_Tx_ptr = USART_Rx_ptr_out;
USB_Tx_length = USART_Rx_length;
USART_Rx_ptr_out += USART_Rx_length;
USART_Rx_length = 0;
}
USB_CopyUserToPMABuf(&USART_Rx_Buffer, ENDP1_TXADDR, USB_Tx_length);
USB_SetEpTxCnt(ENDP1, USB_Tx_length);
USB_SetEpTxValid(ENDP1);
}
}
}
</code></pre>
<p lang="en-US"> </p>
<p lang="en-US"> </p>
<p>然后我精简了一下</p>
<p> </p>
<p>typedef struct{</p>
<p>uint8_t Buf;</p>
<p>uint16_t Len;</p>
<p>bool isRecived;</p>
<p>}USB_TO_USER_S;</p>
<p>extern USB_TO_USER_S UsbToUser;</p>
<p> </p>
<p>USB_TO_USER_S UsbToUser;</p>
<p>//通过USB发送数据</p>
<p>void UserDataToUsb(uint8_t *buf,uint16_t len){</p>
<p>USB_CopyUserToPMABuf(buf, ENDP1_TXADDR, len);</p>
<p>USB_SetEpTxCnt(ENDP1, len);</p>
<p>USB_SetEpTxValid(ENDP1);</p>
<p>}</p>
<p> </p>
<p>void UsbToUserData(uint8_t* data_buffer, uint8_t Nb_bytes){</p>
<p>memcpy(UsbToUser.Buf,data_buffer,Nb_bytes);</p>
<p>UsbToUser.Len = Nb_bytes;</p>
<p>UsbToUser.isRecived = true;</p>
<p>}</p>
<p lang="en-US"> </p>
<p>这样就可以实现自定义内容的收发了</p>
<p> </p>
<p lang="en-US"> </p>
<p> </p>
<p> </p>
<p>下载看看</p>
<p> </p>
页:
[1]