本帖最后由 阿源玩电子 于 2025-6-23 22:20 编辑
串口1收发
2.编辑相应的驱动文件
usart_dsp.C #include "usart_dsp.h"
void USART1_InitConsole(uint32_t Baudrate)
{
GPIO_InitTypeDef GPIO_InitStruct;
USART_InitTypeDef USART_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
USART_StructInit(&USART_InitStruct);
USART_InitStruct.USART_BaudRate = Baudrate;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_Init(USART1, &USART_InitStruct);
RCC_AHBPeriphClockCmd(RCC_AHBENR_GPIOB, ENABLE);
GPIO_StructInit(&GPIO_InitStruct);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_0);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_FLOATING;
GPIO_Init(GPIOB, &GPIO_InitStruct);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_0);
GPIO_StructInit(&GPIO_InitStruct);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_High;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOB, &GPIO_InitStruct);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
USART_Cmd(USART1, ENABLE);
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPriority = 1;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
}
int fputc(int ch, FILE *f)
{
USART_SendData(USART1, (uint8_t)ch);
while (RESET == USART_GetFlagStatus(USART1, USART_FLAG_TC))
{
}
return (ch);
}
void USART1_IRQHandler(void)
{
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
uint8_t data = USART_ReceiveData(USART1);
USART_SendData(USART1, data);
while(USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
}
}
usart_dsp.h
#include "hal_conf.h"
#include <stdio.h>
void USART1_InitConsole(uint32_t Baudrate);
3.main函数部分
#include "main.h"
int main(void)
{
GPIO_Configure();
InitDelay();
USART1_InitConsole(115200);
while (1)
{
GPIOB->ODR ^= GPIO_Pin_14 | GPIO_Pin_15;
Delay_MS(300);
printf("Hello 21ic, HelloMM32F0121 \r\n");
}
}
4.试验现象
每300毫秒发送一次“Hello 21ic, HelloMM32F0121”
收数据并且回发
|