如果使用串口,一定要打开Use Micro LIB!!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 STM32 串口打印字符串之前,需要先配置串口。通常需要配置波特率、数据位、停止位、奇偶校验等参数。以 STM32F4 为例,可以使用以下代码进行串口配置和初始化: ```c #include "stm32f4xx.h" #include "stdio.h" void USART_Config(void) { GPIO_InitTypeDef GPIO_InitStruct; USART_InitTypeDef USART_InitStruct; // 打开 GPIO 时钟和 USART 时钟 RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); // 配置 USART2 引脚 GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_USART2); // PA2 -> USART2_TX GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_USART2); // PA3 -> USART2_RX GPIO_InitStruct.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStruct.GPIO_OType = GPIO_OType_PP; GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOA, &GPIO_InitStruct); // 配置 USART2 USART_InitStruct.USART_BaudRate = 115200; USART_InitStruct.USART_WordLength = USART_WordLength_8b; USART_InitStruct.USART_StopBits = USART_StopBits_1; USART_InitStruct.USART_Parity = USART_Parity_No; USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx; USART_Init(USART2, &USART_InitStruct); // 使能 USART2 USART_Cmd(USART2, ENABLE); } int main(void) { char buffer[32]; int num = 12345; USART_Config(); // 使用 sprintf 将整数转换为字符串 sprintf(buffer, "The number is %d.\r\n", num); // 使用 USART 发送字符串 for (int i = 0; i < strlen(buffer); i++) { USART_SendData(USART2, buffer[i]); while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET); } while (1); } ``` 在上述代码中,我们首先需要调用 `USART_Config()` 函数配置和初始化 USART2。然后使用 `sprintf()` 将需要打印的字符串格式化到一个字符数组中,最后通过 `USART_SendData()` 逐个发送字符。在发送字符的过程中,需要判断 USART 发送寄存器是否为空,以避免数据丢失。 需要注意的是,为了使用 `sprintf()` 函数,需要在编译选项中启用支持浮点数格式化的库函数,例如在 Keil MDK 中需要勾选 `Use MicroLIB` 选项。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值