UART串口通信

时间:2023-03-08 22:23:17

UART串口通信

UART串口通信

UART串口通信

UART串口通信

UART串口通信

UART串口通信

UART串口通信

UART串口通信

UART串口通信

UART串口通信

UART串口通信

UART串口通信

UART串口通信

UART串口通信

#include "sys.h"
#include "delay.h"
#include "usart.h" u8 rdata[]; UART_HandleTypeDef usart1_handler; //UART¾ä±ú void uart1_init()
{
usart1_handler.Instance=USART1; //USART1
usart1_handler.Init.BaudRate=; //²¨ÌØÂÊ
usart1_handler.Init.WordLength=UART_WORDLENGTH_8B; //×Ö³¤Îª8λÊý¾Ý¸ñʽ
usart1_handler.Init.StopBits=UART_STOPBITS_1; //Ò»¸öֹͣλ
usart1_handler.Init.Parity=UART_PARITY_NONE; //ÎÞÆæżУÑéλ
usart1_handler.Init.HwFlowCtl=UART_HWCONTROL_NONE; //ÎÞÓ²¼þÁ÷¿Ø
usart1_handler.Init.Mode=UART_MODE_TX_RX; //ÊÕ·¢Ä£Ê½
HAL_UART_Init(&usart1_handler); //HAL_UART_Init()»áʹÄÜUART1 } void HAL_UART_MspInit(UART_HandleTypeDef *huart)
{ GPIO_InitTypeDef GPIO_Initure; if(huart->Instance==USART1)//Èç¹ûÊÇ´®¿Ú1£¬½øÐд®¿Ú1 MSP³õʼ»¯
{
__HAL_RCC_GPIOA_CLK_ENABLE(); //ʹÄÜGPIOAʱÖÓ
__HAL_RCC_USART1_CLK_ENABLE(); //ʹÄÜUSART1ʱÖÓ GPIO_Initure.Pin=GPIO_PIN_9; //PA9
GPIO_Initure.Mode=GPIO_MODE_AF_PP; //¸´ÓÃÍÆÍìÊä³ö
GPIO_Initure.Pull=GPIO_PULLUP; //ÉÏÀ­
GPIO_Initure.Speed=GPIO_SPEED_FREQ_HIGH; //¸ßËÙ
GPIO_Initure.Alternate=GPIO_AF7_USART1; //¸´ÓÃΪUSART1
HAL_GPIO_Init(GPIOA,&GPIO_Initure); //³õʼ»¯PA9 GPIO_Initure.Pin=GPIO_PIN_10; //PA10
HAL_GPIO_Init(GPIOA,&GPIO_Initure); //³õʼ»¯PA10 HAL_NVIC_EnableIRQ(USART1_IRQn); //ʹÄÜUSART1ÖжÏͨµÀ
HAL_NVIC_SetPriority(USART1_IRQn,,); //ÇÀÕ¼ÓÅÏȼ¶3£¬×ÓÓÅÏȼ¶3
} } void USART1_IRQHandler(void)
{
HAL_UART_IRQHandler(&usart1_handler);
while (HAL_UART_GetState(&usart1_handler) != HAL_UART_STATE_READY);//ÅжÏUARTÊÇ·ñ³õʼ»¯
while(HAL_UART_Receive_IT(&usart1_handler, (u8 *)rdata, ) != HAL_OK); //ÖØдò¿ªÖÐ¶Ï } void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
u8 rec;
if(huart->Instance==USART1)//Èç¹ûÊÇ´®¿Ú1
{
rec=*(--(huart->pRxBuffPtr));//°ÑÖ¸Õëµ¹ÍË»ØÔ­À´µÄ×Ö·ûλÖÃ
HAL_UART_Transmit(&usart1_handler,&rec,,);
} } int main(void)
{ HAL_Init(); //³õʼ»¯HAL¿â
Stm32_Clock_Init(,,,); //ÉèÖÃʱÖÓ,180Mhz
delay_init(); uart1_init();//³õʼ»¯´®¿Ú²ÎÊý HAL_UART_Receive_IT(&usart1_handler, (u8 *)rdata, );//¸Ãº¯Êý»á¿ªÆô½ÓÊÕÖжϣº±ê־λUART_IT_RXNE£¬²¢ÇÒÉèÖýÓÊÕ»º³åÒÔ¼°½ÓÊÕ»º³å½ÓÊÕ×î´óÊý¾ÝÁ¿ while()
{ } }