串口配置:
main.c(以串口3为例)
/* USER CODE BEGIN 0 */
//***********************************
uint16_t UART3_BlueTooth_Rx_Sta=0;
uint8_t uart_data=0;
#define UART3_REC_LEN 200
uint8_t UART3_RX_Buffer[UART3_REC_LEN];
/* 回调函数 *///********************************************
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance == USART3)
{
if((UART3_BlueTooth_Rx_Sta & 0x8000) == 0)
{
if(UART3_BlueTooth_Rx_Sta & 0x4000)
{
if(uart_data == 0x0a)
UART3_BlueTooth_Rx_Sta |= 0x8000;
else
UART3_BlueTooth_Rx_Sta = 0;
}
else
{
if(uart_data == 0x0d)
{
UART3_BlueTooth_Rx_Sta |= 0x4000;
}
else
{
UART3_RX_Buffer[UART3_BlueTooth_Rx_Sta & 0X3FFF] = uart_data;
UART3_BlueTooth_Rx_Sta++;
if(UART3_BlueTooth_Rx_Sta > UART3_REC_LEN - 1)
UART3_BlueTooth_Rx_Sta = 0;
}
}
}
HAL_UART_Receive_IT(&huart3, &uart_data, 1);
}
}
//*************************
//串口/蓝牙输出
void uart_mainloop(void)
{
if(!f_1s)return;
f_1s=0;
if(UART3_BlueTooth_Rx_Sta & 0x8000)
{
printf("收到数据:");
HAL_UART_Transmit(&huart3, UART3_RX_Buffer, UART3_BlueTooth_Rx_Sta & 0x3fff, 0xffff);
while(huart3.gState != HAL_UART_STATE_READY);
printf("\r\n");
//********************蓝牙控制***************************
//以电机控制为例//
if((strstr((const char *)UART3_RX_Buffer,"open")))
{
HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_RESET);
Motor_SPeed = 100;
printf("Motor_SPeed = %d\r\n",Motor_SPeed);
printf("距离 = %.2f cm\r\n",Distance_Data);
}
else if((strstr((const char *)UART3_RX_Buffer,"stop")))
{
HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);
Motor_SPeed = 0;
printf("Motor_SPeed = %d\r\n",Motor_SPeed);
}
else if((strstr((const char *)UART3_RX_Buffer,"up")))
{
HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);
Motor_SPeed += 10;
printf("Motor_SPeed = %d\r\n",Motor_SPeed);
}
else if((strstr((const char *)UART3_RX_Buffer,"down")))
{
HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);
Motor_SPeed -= 10;
printf("Motor_SPeed = %d\r\n",Motor_SPeed);
}
else if((strstr((const char *)UART3_RX_Buffer,"back")))
{
HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);
Motor_SPeed = -100;
printf("Motor_SPeed = %d\r\n",Motor_SPeed);
}
//********************END******************************
UART3_BlueTooth_Rx_Sta = 0;
}
}
//**********************************
int fputc(int ch, FILE *f)
{
unsigned char temp[1]={ch};
//串口打印printf,此处注意几号串口
HAL_UART_Transmit(&huart3,temp,1,0xffff);
return ch;
}
//***********************************
/* USER CODE END 0 */
/* 建议放在while(1)上面 蓝牙*/
HAL_UART_Receive_IT(&huart3, &uart_data, sizeof(uart_data));//开启中断接收数据