Continuing from the previous section, the control of buttons and LED lights has been configured
From this section, the code generated by Cubemx will be ported to the previous project
1 Cubemx serial port configuration
Copy the last example to a new folder
then open
Check the schematic diagram of the board, the serial port 1 pins used are PB6 (RX), PB7 (TX)
PB7 is the same
Enable serial port (receive) interrupt
generate code
2 serial port code
In the serial header file add
Add an interrupt callback function to the serial port file , and change the input and output interface functions
/* USER CODE BEGIN 1 */
//清空接收缓冲
void uart_FlushRxBuffer(void)
{
UART_RxPtr = 0;
UART_RxBuffer[UART_RxPtr] = 0;
}
//接受中断回调函数
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
//测试是否进入接受中断
HAL_GPIO_WritePin(LED_2_GPIO_Port, LED_2_Pin, GPIO_PIN_RESET);
HAL_UART_Receive_IT(&huart1, &UART_RxPtr, 1);
}
/***************** 发送字符 **********************/
void Usart_SendByte(uint8_t str)
{
HAL_UART_Transmit(&huart1, &str, 1, 1000);
}
/***************** 发送字符串 **********************/
void Usart_SendString(uint8_t *str)
{
unsigned int k=0;
do
{
HAL_UART_Transmit(&huart1,(uint8_t *)(str + k) ,1,1000);
k++;
} while(*(str + k)!='\0');
}
///重定向c库函数printf到串口DEBUG_USART,重定向后可使用printf函数
int fputc(int ch, FILE *f)
{
/* 发送一个字节数据到串口DEBUG_USART */
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 1000);
return (ch);
}
///重定向c库函数scanf到串口DEBUG_USART,重写向后可使用scanf、getchar等函数
int fgetc(FILE *f)
{
int ch;
HAL_UART_Receive(&huart1, (uint8_t *)&ch, 1, 1000);
return (ch);
}
/* USER CODE END 1 */
Remember to define the array and header file
Compile + Burn Use Wildfire’s serial port debugging assistant, after sending data and enter the serial port interrupt LED will light up, the configuration is successful
3 Serial port program transplantation + liquid crystal display program transplantation (optional)
The file of the LCD display has been transplanted (optional) . Since transplanting the LCD display is too troublesome, I directly use the LCD display routine as the project source file, and transplant the previous configuration into it
Add the usart interrupt in the interrupt file
Replace the header file, make up for the missing ones, and add the previous functions to the initialization function. After the compilation is passed, the LCD, KEY, LED, and serial port functions run normally, and the porting is successful.