1.硬件
2.软件

#include "sys.h"
#include "delay.h"
#include "led.h"
#include "uart1.h"
int main(void)
{
HAL_Init();
stm32_clock_init(RCC_PLL_MUL9);
led_init();
uart1_init(115200);
while(1)
{
led1_on();
led2_off();
delay_ms(500);
led1_off();
led2_on();
delay_ms(500);
}
}
#include "uart1.h"
UART_HandleTypeDef uart1_handle = {0};
void uart1_init(uint32_t baudrate)
{
uart1_handle.Instance = USART1;
uart1_handle.Init.BaudRate = baudrate;
uart1_handle.Init.WordLength = UART_WORDLENGTH_8B;
uart1_handle.Init.StopBits = UART_STOPBITS_1;
uart1_handle.Init.Parity = UART_PARITY_NONE;
uart1_handle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
uart1_handle.Init.Mode = UART_MODE_TX_RX;
HAL_UART_Init(&uart1_handle);
}
void HAL_UART_MspInit(UART_HandleTypeDef *huart)
{
if(huart->Instance == USART1)
{
__HAL_RCC_USART1_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
GPIO_InitTypeDef gpio_initstruct;
gpio_initstruct.Pin = GPIO_PIN_9;
gpio_initstruct.Mode = GPIO_MODE_AF_PP;
gpio_initstruct.Pull = GPIO_PULLUP;
gpio_initstruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOA, &gpio_initstruct);
gpio_initstruct.Pin = GPIO_PIN_10;
gpio_initstruct.Mode = GPIO_MODE_AF_INPUT;
HAL_GPIO_Init(GPIOA, &gpio_initstruct);
HAL_NVIC_EnableIRQ(USART1_IRQn);
HAL_NVIC_SetPriority(USART1_IRQn, 2, 2);
__HAL_UART_ENABLE_IT(huart, UART_IT_RXNE);
}
}
void USART1_IRQHandler(void)
{
uint8_t receive_data = 0;
if(__HAL_UART_GET_FLAG(&uart1_handle, UART_FLAG_RXNE) != RESET)
{
HAL_UART_Receive(&uart1_handle, &receive_data, 1, 1000);
HAL_UART_Transmit(&uart1_handle, &receive_data, 1, 1000);
}
#ifndef __USART_H__
#define __USART_H__
#include "sys.h"
void uart1_init(uint32_t baudrate);
#endif
3.实物效果
USB转TTL | STM32 |
---|
TX | PA10 |
RX | PA9 |
VCC | 5V |
GND | GND |
ST-Link下载方式
- 实验现象
通过USB转TTL串口模块,将STM32单片机与电脑连接,打开串口软件,设置波特率115200,通过串口软件发送数据,可以看到串口软件接收到数据。
