串口 电脑接收stm32传来的字符

usart串口模块 

usart.c
#include "stm32f10x.h"                  // Device header
#include "usart.h"

void Usart_Init(void)
{
	//2. 配置GPIO的结构体
	GPIO_InitTypeDef GpioInitStructure; //初始化GPIO结构体命名
	USART_InitTypeDef UsartInitStructure;//初始化USART结构体命名
	//1. 配置时钟:GPIO口的时钟,引脚复用的时钟,串口的时钟
		RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
		RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
		RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);

	//2.1 配置PA9 TX
	GpioInitStructure.GPIO_Mode  = GPIO_Mode_AF_PP;//复用推挽输出
	GpioInitStructure.GPIO_Pin   = GPIO_Pin_9;
	GpioInitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	
	GPIO_Init(GPIOA,&GpioInitStructure);
	//2.2 配置PA10 RX
	GpioInitStructure.GPIO_Mode  = GPIO_Mode_IN_FLOATING;//浮空输入
	GpioInitStructure.GPIO_Pin   = GPIO_Pin_10;
	GPIO_Init(GPIOA,&GpioInitStructure);
	//3.配置串口结构体
	UsartInitStructure.USART_BaudRate =   115200;        //波特率
	UsartInitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;   //硬件流
	UsartInitStructure.USART_Mode = USART_Mode_Rx| USART_Mode_Tx;					//模式
	UsartInitStructure.USART_Parity = USART_Parity_No;						//校验位
	UsartInitStructure.USART_StopBits =	USART_StopBits_1;					//停止位
	UsartInitStructure.USART_WordLength =	USART_WordLength_8b;				//字节长度
	
	USART_Init(USART1, &UsartInitStructure);
	USART_Cmd(USART1, ENABLE);//打开串口 比配置GPIO多这一步


	
}
usart.h
#include "stm32f10x.h" 
void Usart_Init(void);

主函数 

main.c
#include "stm32f10x.h" 
#include "usart.h"
void delay(uint16_t time)
{
		uint16_t i = 0;
		while(time--)
		{
			i=12000;
			while(i--);
		}
}
int main(void)
{
		Usart_Init();

		while(1)
		{
			
			
			USART_SendData(USART1, 'O');
			while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);      //USART_GetFlagStatus是判断标志位 USART_FLAG_TXE 去usart.h  FLAG找
						USART_SendData(USART1, 'K');
			while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);   //USART_GetFlagStatus是判断标志位 USART_FLAG_TXE 去usart.h  FLAG找
						USART_SendData(USART1, '\n');
			while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);  //右键USART_GetFlagStatus去goto找到RESET
						delay(1000);
		}
}

猜你喜欢

转载自blog.csdn.net/weixin_46016743/article/details/114446072