近幾天 用微芯力科的板子 調試usb虛擬串口的程式,發現一些問題以及解決方案。和大家共用
主要問題是 串口有時收到亂碼 有時收到丟包資料:
關於 亂碼 我們其實很容易想到 同位的問題,而我們平常都是預設為沒有同位。
請看程式:
* USART1 default configuration */
/* USART1 configured as follow:
- BaudRate = 9600 baud
- Word Length = 8 Bits
- One Stop Bit
- Parity Odd
- Hardware flow control desabled
- Receive and transmit enabled
- USART Clock disabled
- USART CPOL: Clock is active low
- USART CPHA: Data is captured on the second edge
- USART LastBit: The clock pulse of the last data bit is not output to
the SCLK pin
*/
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_Odd;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_InitStructure.USART_Clock = USART_Clock_Disable;
USART_InitStructure.USART_CPOL = USART_CPOL_Low;
USART_InitStructure.USART_CPHA = USART_CPHA_2Edge;
USART_InitStructure.USART_LastBit = USART_LastBit_Disable;
只要改成odd 或者程式裡作修改即可
問題2 :既然是虛擬串口,那麼利用pc串口軟體 兩邊應該可以正常通訊,但是來源程式出現的情況是。
真--虛 ok
虛--真 則嚴重丟資料
看了一下程式 原來搗鬼的是這裡:
void USB_To_USART_Send_Data(u8* data_buffer, u8 Nb_bytes)
{
u32 i;
for (i = 0; i < Nb_bytes; i++)
{
USART_SendData(USART1, *(data_buffer + i));
}
}
串口發送資料後 沒有等待串口發送完成
改為下邊即可
void USB_To_USART_Send_Data(u8* data_buffer, u8 Nb_bytes)
{
u32 i;
for (i = 0; i < Nb_bytes; i++)
{
USART_SendData(USART1, *(data_buffer + i));
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}
}
原始碼 有需要的 請到 在路上 論壇下載 http://www.stmsky.com/bbs/