仔细读ST支持文档 UM0560,按步骤操作。
程序准备工作:
1.开串口接收中断,发送。
/* ********************************************
UART2 configured as follow:
- BaudRate = 115200 baud
- Word Length = 8 Bits
- One Stop Bit
- No parity
- Receive and transmit enabled
- Receive interrupt
- UART2 Clock disabled
*********************************************/
void Uart_Init(void)
{
UART2_DeInit();
UART2_Init((u32)115200, UART2_WORDLENGTH_8D, UART2_STOPBITS_1,
UART2_PARITY_NO , UART2_SYNCMODE_CLOCK_DISABLE , UART2_MODE_TXRX_ENABLE);
UART2_ITConfig(UART2_IT_RXNE_OR,ENABLE );
UART2_Cmd(ENABLE );
}
void UART2_SendByte(u8 data)
{
/* Loop until the end of transmission */
while ((UART2_GetFlagStatus(UART2_FLAG_TXE) == RESET));
UART2_SendData8((unsigned char)data);
}
/**
* @brief UART2 RX interrupt routine.
* @param None
* @retval None
*/
#define C_UartRxMaxInx 40
uint8_t V_RxDataInx = 0;
uint8_t V_UartEndTime = 0;
uint8_t VT_RxUartData[C_UartRxMaxInx+1] = {0};
uint8_t B_RxFirts = 0;
INTERRUPT_HANDLER(UART2_RX_IRQHandler, 21)
{
/* In order to detect unexpected events during development,
it is recommended to set a breakpoint on the following instruction.
*/
if(SET == UART2_GetITStatus(UART2_IT_RXNE)) //接收到数据中断
{
UART2_ClearITPendingBit(UART2_IT_RXNE);
if(B_RxFirts == 0)
{
B_RxFirts = 1;
V_UartEndTime =0;
V_RxDataInx = 0;
}
if(V_RxDataInx < C_UartRxMaxInx)//接收串口数据,最多接收40字节
{
V_UartEndTime=0;
VT_RxUartData[V_RxDataInx] = UART2_ReceiveData8();
V_RxDataInx++;
}
else
{
V_UartEndTime = 0; //超过缓存了,不在往里面写数
}
}
else if(SET == UART2_GetITStatus(UART2_IT_OR)) //过载错误
{
UART2->SR = UART2->SR;
UART2_ReceiveData8(); //读状态寄存器,读数据寄存器,清除中断标志
}
}
uint8_t B_HaveRxData = 0;
//************************************************************************
void UartRxScan(void)
{
if(B_RxFirts)
{
V_UartEndTime++;
if(V_UartEndTime>10)//大于50ms认为是新的指令来了
{
B_RxFirts = 0; //下次来数据就覆盖
V_UartEndTime = 0;
B_HaveRxData = 1; //接收到真确的UART数据
VT_RxUartData[C_UartRxMaxInx-1]='