【STM32】STM32串口配置的一般步骤(库函数)
2024-08-24 06:34:31
STM32串口配置的一般步骤(库函数)
(1)串口时钟使能:RCC_APBxPeriphClockCmd();
GPIO时钟使能:RCC_AHBxPeriphClockCmd();
(2)引脚复用映射:GPIO_PinAFConfig();
(3)GPIO端口模式配置:GPIO_Init(); 模式配置为GPIO_Mode_AF
(4)串口参数初始化:USART_Init();
(5)开启中断并且初始化NVIC(如果需要开启中断才需要这个步骤)
NVIC_Init();
USART_ITConfig();
(6)使能串口:USART_Cmd();
(7)编写中断处理函数:USARTx_IRQHandler();
(8)串口数据收发:
void USART_SendData();//发送数据到串口,DR
uint16_t USART_ReceiveData();//接收数据,从DR读取接收的数据
(9)串口传输状态获取:
FlagStatus USART_GetFlagStatus();
void USART_ClearITPendingBit();
范例代码:
#include "stm32f4xx.h"
#include "usart.h" /* 中断服务函数 */
void USART1_IRQHandler(void)
{
uint16_t recv; if (USART_GetFlagStatus(USART1,USART_IT_RXNE))
{
recv = USART_ReceiveData(USART1);
USART_SendData(USART1,recv);
}
} void Usart1_Demo_Init(void)
{
GPIO_InitTypeDef GPIOA_InitStruct;
USART_InitTypeDef USART1_InitStruct;
NVIC_InitTypeDef NVIC_InitStruct; RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); /* 使能USART1时钟 */
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); /* 使能GPIOA的时钟 */ /* 将PA9和PA10映射到串口1 */
GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_USART1);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_USART1); /* 设置GPIO端口模式 */
GPIOA_InitStruct.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10;
GPIOA_InitStruct.GPIO_Mode = GPIO_Mode_AF;
GPIOA_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIOA_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
GPIOA_InitStruct.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_Init(GPIOA, &GPIOA_InitStruct); /* 串口参数初始化 */
USART1_InitStruct.USART_BaudRate = ;
USART1_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART1_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART1_InitStruct.USART_Parity = USART_Parity_No;
USART1_InitStruct.USART_StopBits = USART_StopBits_1;
USART1_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_Init(USART1, &USART1_InitStruct); /* 使能USART1 */
USART_Cmd(USART1, ENABLE); /* 使能串口使用的中断 */
NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = ;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = ;
NVIC_Init(&NVIC_InitStruct);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
} int main(void)
{
/* 设置中断分组 */
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
Usart1_Demo_Init(); while ();
}
最新文章
- ZoomEye 钟馗之眼 搜索工具 基于API
- iOS 跳转至AppStore评分页面
- SCWS分词扩展在WINDOWS下的安装方法
- Empire C:Basic 3
- 关于OBJ/LIB格式,我以前有个总结
- [转]Rotate a table in reporting services
- SharePoint重置密码功能Demo
- UIPickerView自定义背景
- Java通过代理server上网
- 【转】设置SecureCRT会话的缓冲区大小
- Java NIO之内存映射文件——MappedByteBuffer
- Servlet 后台获取XML
- 银联在线 网关支付 (JAVA版)
- 注解配置spring
- spring 5.1.2 mvc RequestMappingHandlerMapping 源码初始化过程
- Oracle客户端连接数据库配置
- vim技巧4 删除/保留文本中匹配行
- 通过父元素的hover控制子元素的显示
- -bash: fork: Cannot allocate memory
- SOA, EDA, 和 ESB