目录
一、USART串口发送
1、电路图

![]()
要交叉连接,所以RX接TX
2、printf函数的移植方法
使用printf之前,先打开工程选项

再serial.c中,添加#include <stdio.h>,再在文件中重写fputc函数
int fputc(int ch, FILE *f)
{
Serial_SendByte(ch);
return ch;
}
fputc是printf函数的底层,printf在打印的时候,就是不断调用fputc函数一个个打印的,现在把fputc函数重定向到了串口,则printf自然就输出到串口
在serial.h文件中要包含头文件
#include <stdio.h>
这种方法printf只能有一个,若重定向到串口1了,则串口2不能使用
若多个串口都想用printf,则使用sprintf,sprintf可以把格式化字符输出到一个字符串中
3、serial.c
#include "stm32f10x.h" // Device header
#include <stdio.h>
#include <stdarg.h>
void Serial_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
//TX引脚是USART外设控制的输出引脚,所以要选复用推挽输出
//RX引脚是USART外设数据输入脚,所以要选择输入模式
//一根线只能有一个输出,可以有多个输入,故输入脚,外设和GPIO都可以用
//一般RX配置是浮空输入或者上拉输入,因为串口波形空闲状态是高电平,故不选择下拉输入
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_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = 9600;//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;//1位停止位
USART_InitStructure.USART_WordLength = USART_WordLength_8b;//8位字长
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
}
void Serial_SendByte(uint8_t Byte)
{
USART_SendData(USART1, Byte);//发送数据
while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}
void Serial_SendArray(uint8_t *Array, uint16_t Length)
{
uin
3779




被折叠的 条评论
为什么被折叠?



