单片机型号为STM32L433,该单片机的USART2连接ESP8266外设,usart1连接串口调试助手,写一个AT命令封装函数,要调用上面的函数,
时间: 2024-04-22 19:28:02 浏览: 26
你可以使用以下代码来封装一个AT命令发送函数:
```c
#include "stm32l4xx_hal.h"
UART huart1;
UART_HandleTypeDef huart2;
void USART1_Init(void)
{
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
HAL_UART_Init(&huart1);
}
void USART2_Init(void)
{
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
HAL_UART_Init(&huart2);
}
void AT_Command(char* command, UART_HandleTypeDef* huart)
{
HAL_UART_Transmit(huart, (uint8_t*)command, strlen(command), HAL_MAX_DELAY);
// 等待接收AT命令回复
uint8_t rxData;
while (1)
{
HAL_UART_Receive(huart, &rxData, 1, HAL_MAX_DELAY);
// 处理接收到的数据,例如判断是否收到了期望的回复
// 如果接收到了期望的回复,跳出循环
// 如果超时或者接收到了错误的回复,进行相应的处理
}
}
```
你可以调用 `AT_Command` 函数来发送AT命令,示例代码如下:
```c
int main(void)
{
HAL_Init();
USART1_Init();
USART2_Init();
// 发送AT命令给ESP8266
AT_Command("AT\r\n", &huart2);
// 发送AT命令给串口调试助手
AT_Command("AT\r\n", &huart1);
while (1)
{
// 主循环
}
}
```
这是一个简单的封装函数,你可以根据自己的需求进行扩展和优化。希望对你有所帮助!
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)