利用STM32单片机串口发送字符串

最近由于要调试一个SMS发送短信的模块,该模块需要发送一系列AT指令,且需要字符串发送,但是STM32官方给的usart.c中并没有直接发送字符串的函数,因此写了一个发送字符串的函数。

其实发送字符串的本质还是发送一个个字符,所以只需在字符串结束标志之前,循环发送字符即可。不罗嗦,上程序。

//程序功能:利用串口发送一个字符串

// 参数:USARTx USART编号 可取 USART1、USART2、USART3、USART4、 USART5(STM32F103ZET6)

str 需要发送的字符串

#include “stm32f10x.h”

void Usart_SendString(USART_TypeDef* USARTx,char *str)

{

while(*str)

{

while(!USART_GetFlagStatus(USARTx,USART_FLAG_TXE)); //判断是否可以发送

USART_SendData(USARTx,*str);

while(USART_GetFlagStatus(USARTx, USART_FLAG_TC)); //判断是否发送完成,此句必须有,否则会造

//成只发送最后一个字符(覆盖)

str++;

}

}

方法二:
const u8 TEXT_Buffer[]={“Explorer STM32F4 SPI TEST”};
#define SIZE sizeof(TEXT_Buffer) ;

for(i=0;i<SIZE;i++)
{
USART2->DR =TEXT_Buffer[i];
delay_ms(10);
}

  • 12
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
首先,你需要在单片机上配置串口,然后通过按键触发送数据。下面是一个简单的代码示例: ```c #include "stm32f10x.h" #include <stdio.h> void USART1_Init(void); void USART1_Send(char c); void USART1_SendString(char* str); int main(void) { USART1_Init(); GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; GPIO_Init(GPIOA, &GPIO_InitStructure); while(1) { if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == RESET) { USART1_SendString("Button was pressed!\r\n"); while(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == RESET); // 等待按键释放 } } } void USART1_Init(void) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE); GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOA, &GPIO_InitStructure); USART_InitStructure.USART_BaudRate = 9600; USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode = USART_Mode_Tx; USART_Init(USART1, &USART_InitStructure); USART_Cmd(USART1, ENABLE); } void USART1_Send(char c) { while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET); USART_SendData(USART1, c); } void USART1_SendString(char* str) { while(*str) { USART1_Send(*str++); } } ``` 在这个例子中,我们使用PA0作为按键输入,USART1作为串口输出。在主循环中,我们检测按键是否被按下,并发送一条字符串数据。要注意的是,如果按键一直被按下,我们需要等待它被释放才能进行下一次发送。 在你的具体应用中,你需要根据需要进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值