stm32第十三天串口发送数据
一:串口发送软件流程设计
#include "stm32f10x.h"
#include "usart.h"void my_usart_Init()//千万不要和32库里面串口定于的名字一样,不然会报错
{GPIO_InitTypeDef my_usart_Initstruct;USART_InitTypeDef USART_Initstruct;RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);my_usart_Initstruct.GPIO_Pin=GPIO_Pin_9;my_usart_Initstruct.GPIO_Mode=GPIO_Mode_AF_PP;my_usart_Initstruct.GPIO_Speed=GPIO_Speed_10MHz;GPIO_Init(GPIOA, &my_usart_Initstruct);my_usart_Initstruct.GPIO_Pin=GPIO_Pin_10;my_usart_Initstruct.GPIO_Mode=GPIO_Mode_IN_FLOATING;GPIO_Init(GPIOA, &my_usart_Initstruct);USART_Initstruct.USART_BaudRate=115200;USART_Initstruct.USART_HardwareFlowControl=USART_HardwareFlowControl_None;USART_Initstruct.USART_Mode=USART_Mode_Rx | USART_Mode_Tx ;USART_Initstruct.USART_Parity=USART_Parity_No;USART_Initstruct.USART_StopBits=USART_StopBits_1;USART_Initstruct.USART_WordLength=USART_WordLength_8b;USART_Init(USART1,&USART_Initstruct);USART_Cmd(USART1, ENABLE);}
usart.h
#ifndef USART_H_
#define USART_H_void my_usart_Init(void);#endif
main.c
#include "stm32f10x.h"
#include "main.h"
#include "led.h"
#include "Bear.h"
#include "key.h"
#include "relay.h"
#include "shake.h"
#include "wireless.h"
#include "exti_key.h"
#include "usart.h"void delay(uint16_t time)//延时1ms 软件延时粗延时
{uint16_t i=0;while(time --){i=12000;while(i --);}}int main()
{my_usart_Init();while(1){USART_SendData( USART1, 1);}}
二:代码心得
1:在写usart.c的初始化串口引脚时为什么用复用模式?
3:或(|)和与(&)的原理
一、符号 |
(按位或)
1. 作用
-
用于组合多个使能标志位(每个标志位对应一个外设)。
-
将多个二进制位中至少有一个为1的位设为1。
2. 原理
-
假设:
-
RCC_APB2Periph_GPIOA = 0x00000004
(二进制:0000 0100
) -
RCC_APB2Periph_USART1 = 0x00000010
(二进制:0001 0000
)
-
-
按位或操作:
text
0000 0100 (GPIOA) OR 0001 0000 (USART1) ---------- 0001 0100 (结果:0x14)
-
结果同时保留了GPIOA和USART1的使能位。
-
总结:
-
按位或(|)的使用:按位或的规则是:两个位中只要有一个为1,结果位就为1。
-
按位与(&)的使用:两个位都为1时,结果位才为1
4:USART_WordLength_8b 和 USART_WordLength_9b
为什么用8位不用9位?
-
字节对齐:
-
计算机系统基本单位是8位字节
-
所有字符编码(ASCII/UTF-8)基于8位
-
何时使用9位?
-
多机通信中的地址/数据区分
-
定制协议需要额外标志位
-
奇偶校验+8位数据等效于9位帧
5:USART_Cmd(USART1,ENABLE)的使用
1. 时钟使能 RCC_APB2PeriphClockCmd()
c
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);
-
作用对象:RCC(Reset and Clock Control)时钟控制器
-
功能:打开USART1和GPIOA的时钟门控
-
原理:
-
STM32为降低功耗,默认关闭所有外设时钟
-
此操作相当于给USART1和GPIOA模块"通电"
-
-
必要性:
-
没有时钟时,无法访问USART寄存器
-
未使能时钟时操作USART会导致HardFault错误
-
2. 外设使能 USART_Cmd()
c
USART_Cmd(USART1, ENABLE); // 关键步骤!
-
作用对象:USART外设本身
-
功能:激活USART的核心收发功能
-
原理:
-
设置USART控制寄存器(CR1)的UE位(USART Enable)
-
UE位=0时:USART处于休眠状态(即使有时钟)
-
UE位=1时:启动USART的串行引擎
-
-
必要性:
-
没有此操作,USART不会处理任何数据
-
发送/接收缓冲区将无法工作
-
总结:RCC_APB2PeriphClockCmd
是给外设"供电",USART_Cmd
是"开机按钮"。二者缺一不可,共同确保USART正常工作。