main.c
#include "sys.h"
#include "usart.h"
int main(void)
{
delay_init();
Debug_Usart_Init();
while(1)
{
send_byte(0x12);
delay_ms(1000);
}
}
usart.c
#include "sys.h"
#include "usart.h"
/*
发送引脚:TX---复用推挽输出模式
接收引脚:RX---浮空输入模式
*/
void Debug_Usart_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
DEBUG_USART_GPIO_CLK_ENABLE(); //使能GPIO时钟
DEBUG_USART_CLK_ENABLE(); //使能USART时钟
DEBUG_USART_AFIO_CLK_ENABLE(); //使能AFIO时钟
GPIO_InitStructure.GPIO_Pin = DEBUG_USART_TX_GPIO_PIN; //USART_TX
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_Init(DEBUG_USART_TX_GPIO_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = DEBUG_USART_RX_GPIO_PIN; //USART_RX
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //浮空输入
GPIO_Init(DEBUG_USART_RX_GPIO_PORT, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = 115200; //串口波特率
USART_InitStructure.USART_WordLength = USART_WordLength_8b; //字长为8位数据格式
USART_InitStructure.USART_StopBits = USART_StopBits_1; //一个停止位
USART_InitStructure.USART_Parity = USART_Parity_No; //无奇偶校验位
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; //无硬件数据流控制
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //收发模式全双工
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE); //使能串口1
}
void send_byte(uint8_t byte)
{
USART_SendData(DEBUG_USART,byte);
while(USART_GetFlagStatus(DEBUG_USART,USART_FLAG_TXE)==RESET);
}
#ifndef __USART_H
#define __USART_H
#include "stdio.h"
#include "sys.h"
/* 引脚 定义 */
#define DEBUG_USART USART1
#define DEBUG_USART_TX_GPIO_PORT GPIOA
#define DEBUG_USART_TX_GPIO_PIN GPIO_Pin_9
#define DEBUG_USART_RX_GPIO_PORT GPIOA
#define DEBUG_USART_RX_GPIO_PIN GPIO_Pin_10
#define DEBUG_USART_GPIO_CLK_ENABLE() do{ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); }while(0) /* GPIOA口时钟使能 */
#define DEBUG_USART_CLK_ENABLE() do{ RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); }while(0) /* USART1口时钟使能 */
#define DEBUG_USART_AFIO_CLK_ENABLE() do{ RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE); }while(0) /* AFIO口时钟使能 */
/* 外部接口函数*/
void Debug_Usart_Init(void);
void send_byte(uint8_t byte);
#endif