UART通信协议实践--stm32串口通信(一)

基于UART通信协议写的串口通信程序

本文章只是写了stm32通过串口向上位机发送数据的程序,程序简单易懂,最适合刚学完UART协议的小伙伴练手。

开发环境和新建工程这个我就不罗嗦了,芯片是stm32f407ZG,可自行百度查找如何搭建开发环境和新建工程

以下是usart.c和usart.h以及mian.c文件中的程序。

usart.c文件

#include "usart.h"

void Usart1_Init()
{
	GPIO_InitTypeDef GPIO_InitStructure;
	USART_InitTypeDef USART_InitStructure; //定义结构体变量
	//初始化引脚
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE); //使能GPIOA时钟
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);//使能USART1时钟
	
//USART1端口配置

 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10; //GPIOA9与GPIOA10
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;//复用功能
 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度50MHz
 GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //推挽复用输出
 GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; //上拉
 GPIO_Init(GPIOA,&GPIO_InitStructure); //初始化PA9,PA10
	

	//串口1对应引脚复用映射
  GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1); //GPIOA9复用为USART1
  GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1); //GPIOA10复用为USART1
	

	
	USART_InitStructure.USART_BaudRate = 9600;  // 波特率
	USART_InitStructure.USART_WordLength = USART_WordLength_8b; //8bit数据位
	USART_InitStructure.USART_StopBits = USART_StopBits_1; // 1个停止位
	USART_InitStructure.USART_Parity = USART_Parity_No; // 禁止奇偶校验
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; //禁止硬件控制流
	USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx; //全双工通信
	USART_Init(USART1, &USART_InitStructure);  //调用初始化函数
	

	USART_Cmd(USART1, ENABLE); //使能串口1
	}

usart.h文件

#ifndef _USART_H
#define _USART_H

#include "stm32f4xx.h"
#include "stm32f4xx_conf.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_usart.h"


void Usart1_Init(void); 

#endif

main.c文件

#include "stm32f4xx.h"
#include "usart.h"
#include "delay.h"

int main(void)
{
	

		Usart1_Init(); 
		delay_init(168);		
		while(1)	//死循环
	{
		USART_SendData(USART1,'w'); //串口1发送数据
		delay_ms(1000);   
		//uint16_t USART_ReceiveData(USART_TypeDef* USARTx);

}
}


x下面是串口电脑助手助手接受到的数据
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值