1.接线图
2.代码展示
第一步RCC时钟赋能,初始化GPIO口,选择复用推挽输出,通过接口关系表查看USART1的串口号为PA9
//时钟赋能
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
//初始化GPIOA
// GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
第二步,初始化USART,并且赋能USART
//初始化USART
// USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate=9600;//波特率
USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;//不使用流控
USART_InitStructure.USART_Mode=USART_Mode_Tx;//选择发送模式
USART_InitStructure.USART_Parity=USART_Parity_No;//选择校验位,无校验
USART_InitStructure.USART_StopBits=USART_StopBits_1;//停止位长度
USART_InitStructure.USART_WordLength=USART_WordLength_8b;//字长,8位
USART_Init(USART1,&USART_InitStructure);
USART_Cmd(USART1,ENABLE);
第三步,包装发送一个字节的函数
void Serial_SendByte(uint8_t Data)
{
USART_SendData(USART1,Data);
while(USART_GetFlagStatus(USART1,USART_FLAG_TXE) == RESET);//等待TDR中的数据全部传到移位寄存器中
}
第四步,包装发送一个数组的函数
void Serial_SendArray(uint8_t *Array,uint16_t Lenth)
{
uint16_t i;
for(i=0;i<Lenth;i++)
{
Serial_SendByte(Array[i]);
}
}
第五步,包装发送一个字符串的函数
void Serial_SendString(uint8_t *String)
{
uint8_t i;
for(i=0;String[i] != '\0';i++)
{
Serial_SendByte(String[i]);
}
}
第六步,包装一个发送数字的函数
首先我们写一个函数,此函数当x=10,y=3时的意思为,10的3次方。
uint32_t Serial_Pow(uint32_t x,uint32_t y)//x的y次方
{
uint32_t Result=1;
while(y--)
{
Result*=x;
}
return Result;
}
然后我们写提取一个数字每一位的函数,此函数的思路是列如:我们有一个数字1234,我们要取千位时是1234/1000%10.
void Serial_SendNumber(uint32_t Number,uint8_t Length)
{
uint8_t i;
for(i=Length;i>0;i--)
{
Serial_SendByte(Number/Serial_Pow(10,i-1)%10+'0');
}
}
这样我们可以将数字从高位到低位一位一位取出来。+’0‘是因为我们要将数字表示为字符模式。
第七步,我们将printf函数包装进来
首先点击魔法棒将此选项勾选
然后将fputc函数包含到USART中
int fputc(int ch,FILE *f)
{
Serial_SendByte(ch);
return ch;
}
注意头文件需要包含原函数
#include "stdio.h"
主函数
int main(void)
{
Serial_Init();
// Serial_SendByte(0x41);
// Serial_SendArray(Array,4);
// Serial_SendString("HELLOWORLD!");
// Serial_SendNumber(12345,5);
printf("Num=%d\r\n",666);
while(1)
{
}
}