stm32串口通信(usart1)

参考:https://www.cnblogs.com/pertor/p/9488446.html
	  GPIO_InitTypeDef GPIO_InitStructure;

24 USART_InitTypeDef USART_InitStructure;
25 NVIC_InitTypeDef NVIC_InitStructure;

初始化gpio

30 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //PA.9
31 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
32 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
33 GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化GPIOA.9
34
35 //USART1_RX GPIOA.10初始化
36 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;//PA10
37 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//浮空输入
38 GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化GPIOA.10

Usart1 NVIC 配置
41 NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //设置NVIC中断分组2:2位抢占优先级,2位响应优先级 0-3;
42
43 NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
44 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;//抢占优先级3
45 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //子优先级3
46 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能
47 NVIC_Init(&NVIC_InitStructure); //根据指定的参数初始化VIC寄存器
48

USART 初始化设置
50
51 USART_InitStructure.USART_BaudRate = 115200;//串口波特率
52 USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字长为8位数据格式
53 USART_InitStructure.USART_StopBits = USART_StopBits_1;//一个停止位
54 USART_InitStructure.USART_Parity = USART_Parity_No;//无奇偶校验位
55 USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制
56 USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //收发模式
57
58 USART_Init(USART1, &USART_InitStructure); //初始化串口1
59 USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//开启串口接受中断
60 USART_Cmd(USART1, ENABLE); //使能串口1

// 发送一个字节
void usart_sendbyte(USART_TypeDef * pUSARTx, uint8_t ch)
{
// 第一步,发送一个字节
USART_SendData(USART1, ch);
// 等待发送完成
while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET) {
}
}

void usart_sendstring(USART_TypeDef * pUSARTx, char *data)
{
// 发送每个字符,不包括结束字符’\0’
while(*data != ‘\0’) {
usart_sendbyte(pUSARTx, *data);
data++;
}
}

// 实现fputc
int fputc(int ch, FILE *f)
{
usart_sendbyte(USART1, ch);
return ch;
}

// 禁止半主机模式,没有勾选MicroLib
#pragma import(__use_no_semihosting)
struct __FILE
{
int a;
};

FILE __stdout;
void _sys_exit(int x)
{

}

你可能感兴趣的:(stm32串口通信(usart1))