stm32 usart 发送一段ascll并保存接收到的报文
时间: 2023-12-10 11:40:35 浏览: 65
下面是一个简单的示例代码,可以通过 USART 发送一段 ASCII 字符串,并接收并保存接收到的报文:
```c
#include "stm32f4xx.h"
#include <stdio.h>
#include <string.h>
#define USARTx USART2
#define USARTx_IRQn USART2_IRQn
#define USARTx_IRQHandler USART2_IRQHandler
#define USARTx_GPIO GPIOA
#define USARTx_TX_PIN GPIO_Pin_2
#define USARTx_RX_PIN GPIO_Pin_3
#define BAUDRATE 115200
void USART_Config(void);
void USART_SendString(char *str);
void USARTx_IRQHandler(void);
volatile uint8_t rx_buffer[256];
volatile uint8_t rx_count = 0;
volatile uint8_t rx_flag = 0;
int main(void)
{
USART_Config();
while (1)
{
if (rx_flag)
{
rx_flag = 0;
printf("Received message: %s\n", rx_buffer);
rx_count = 0;
memset(rx_buffer, 0, sizeof(rx_buffer));
}
USART_SendString("Hello, world!\r\n");
delay_ms(1000);
}
}
void USART_Config(void)
{
USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
// USARTx GPIO Configuration
GPIO_InitStructure.GPIO_Pin = USARTx_TX_PIN | USARTx_RX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(USARTx_GPIO, &GPIO_InitStructure);
GPIO_PinAFConfig(USARTx_GPIO, GPIO_PinSource2, GPIO_AF_USART2);
GPIO_PinAFConfig(USARTx_GPIO, GPIO_PinSource3, GPIO_AF_USART2);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
// USARTx Configuration
USART_InitStructure.USART_BaudRate = BAUDRATE;
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_Rx | USART_Mode_Tx;
USART_Init(USARTx, &USART_InitStructure);
USART_ITConfig(USARTx, USART_IT_RXNE, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = USARTx_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_Cmd(USARTx, ENABLE);
}
void USART_SendString(char *str)
{
while (*str)
{
while (USART_GetFlagStatus(USARTx, USART_FLAG_TXE) == RESET);
USART_SendData(USARTx, (uint16_t) (*str++));
}
}
void USARTx_IRQHandler(void)
{
if (USART_GetITStatus(USARTx, USART_IT_RXNE) != RESET)
{
rx_buffer[rx_count++] = USART_ReceiveData(USARTx);
if (rx_count >= sizeof(rx_buffer))
{
rx_count = 0;
memset(rx_buffer, 0, sizeof(rx_buffer));
}
rx_flag = 1;
}
}
```
这个程序配置了 USART2 来发送和接收数据。发送函数 `USART_SendString()` 通过轮询等待 USART 发送完成标志来发送字符串。接收函数 `USARTx_IRQHandler()` 中,每当 USART 接收到一个字节时,将它存储在接收缓冲区 `rx_buffer` 中。如果接收缓冲区已满,则清空它并重新开始接收。当接收到完整的报文时,将 `rx_flag` 置为 1,以通知主循环读取报文。
在主循环中,首先检查 `rx_flag`,如果它为 1,则读取接收到的报文,并将 `rx_count` 和 `rx_buffer` 清零。然后发送一条 “Hello, world!” 消息,并延迟 1 秒。
阅读全文