源码:https://github.com/jimingkang/STM32L476_BSP
IDE里代码结构
1)stm32l4xx_it.c 设置NVIC的串口中断处理程序
extern UART_HandleTypeDef huart2;
void USART2_IRQHandler(void)
{
/* USER CODE BEGIN USART2_IRQn 0 */
/* USER CODE END USART2_IRQn 0 */
HAL_UART_IRQHandler(&huart2);
/* USER CODE BEGIN USART2_IRQn 1 */
/* USER CODE END USART2_IRQn 1 */
}
2)uart.c设置硬件,以及中断模式收发
void UART2_Init(void) {
// Enable the clock of USART 1 & 2
RCC->APB1ENR1 |= RCC_APB1ENR1_USART2EN; // Enable USART 2 clock
// Select the USART1 clock source
// 00: PCLK selected as USART2 clock
// 01: System clock (SYSCLK) selected as USART2 clock
// 10: HSI16 clock selected as USART2 clock
// 11: LSE clock selected as USART2 clock
RCC->CCIPR &= ~RCC_CCIPR_USART2SEL;
RCC->CCIPR |= RCC_CCIPR_USART2SEL_0;
UART2_GPIO_Init();
USART_Init(USART2);
//这里打开中断,上一篇文章没开中断(直接是阻塞模式),
NVIC_SetPriority(USART2_IRQn, 0); // Set Priority to 1
NVIC_EnableIRQ(USART2_IRQn); // Enable interrupt of USART1 peripheral
}
3)在main.c直接调用硬件初始化:
UART_HandleTypeDef huart2;
/**
* @brief Main program
* The program follows the following steps
* -1- LEDs initialization.
* -2- User-based LEDs management: all the LEDs are turned on and the user
* can next turn on/off/toggle the LEDs in resorting to the Wakeup/Tamper
* button or to the Joystick.
* Pressing the SEL joystick button turns on all the LEDs
* @retval None
*/
static void MX_USART2_UART_Init(void)
{
/* USER CODE BEGIN USART2_Init 0 */
/* USER CODE END USART2_Init 0 */
/* USER CODE BEGIN USART2_Init 1 */
/* USER CODE END USART2_Init 1 */
huart2.Instance = USART2;
huart2.Init.BaudRate = 9600;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
/* USER CODE END USART2_Init 2 */
}
int main(void)
{ uint8_t n=0;
uint8_t i = 0;
uint8_t menudisplay[DEMO_NAME_CHAR_NB + 5] = {0};
HAL_Init();
/*##-1- Configure the system clock #########################################*/
/* */
SystemClock_Config();
EXTI0_IRQHandler_Config();
/*##-2-Configure minimum hardware resources at boot ########################*/
SystemHardwareInit();
//这里借用上一篇文章的硬件初始化(https://blog.csdn.net/conjimmy/article/details/102657881)
UART2_Init();
//这里借用STM32Cubemx(见图2)生成,我拷贝过来放到main()上面,主要就是设置huart2结构体
MX_USART2_UART_Init();
//直接调用中断方式发送
uint8_t aTxStartMessages[] = "\r\ntest jimmy";
HAL_UART_Transmit_IT(&huart2 ,(uint8_t*)aTxStartMessages,sizeof(aTxStartMessages));
图2