Ⅰ、串口的初始化配置
Ⅱ、发送一个字节
Ⅲ、重定义“printf”和“scanf”
Ⅰ、串口的初始化配置
//串口配置函数
void USART_Config(void)
{
//定义GPIO初始化结构体
GPIO_InitTypeDef GPIO_InitStructure;
//定义串口初始化结构体
USART_InitTypeDef USART_InitStructure;
//打开GPIO时钟
RCC_APB2PeriphClockCmd(DEBUG_USART_GPIO_CLK, ENABLE);
//打开串口时钟
RCC_APB2PeriphClockCmd(DEBUG_USART_CLK, ENABLE);
//配置发送引脚
GPIO_InitStructure.GPIO_Pin = DEBUG_USART_TX_GPIO_PIN;
//复用推挽输出
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
//输出速率:50MHz
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(DEBUG_USART_TX_GPIO_PORT, &GPIO_InitStructure);
//配置接收引脚
GPIO_InitStructure.GPIO_Pin = DEBUG_USART_RX_GPIO_PIN;
//浮空输入
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
//输入速率:50MHz
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(DEBUG_USART_RX_GPIO_PORT, &GPIO_InitStructure);
//串口波特率
USART_InitStructure.USART_BaudRate = DEBUG_USART_BAUDRATE;
//非硬件流控制
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
//打开收发
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
//无校验
USART_InitStructure.USART_Parity = USART_Parity_No;
//停止位:1
USART_InitStructure.USART_StopBits = USART_StopBits_1;
//字长:8bit
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_Init(DEBUG_USARTx,&USART_InitStructure);
//使能串口
USART_Cmd(DEBUG_USARTx, ENABLE);
}
Ⅱ、发送一个字节
//发送一个字节
void Usart_SendByte(USART_TypeDef* pUSARTx, uint8_t data)
{
USART_SendData(pUSARTx, data);
//判断TXE标志位是否为空
while( USART_GetFlagStatus(pUSARTx, USART_FLAG_TXE) == RESET );
}
Ⅲ、重定义“printf”和“scanf”
int fputc(int ch, FILE *f)
{
/* 发送一个字节数据到串口 */
USART_SendData(DEBUG_USARTx, (uint8_t) ch);
/* 等待发送完毕 */
while (USART_GetFlagStatus(DEBUG_USARTx, USART_FLAG_TXE) == RESET);
return (ch);
}
///重定向c库函数scanf到串口
int fgetc(FILE *f)
{
/* 等待串口输入数据 */
while (USART_GetFlagStatus(DEBUG_USARTx, USART_FLAG_RXNE) == RESET);
return (int)USART_ReceiveData(DEBUG_USARTx);
}
网友评论