stm32 esp8266自动获取IP代码
时间: 2023-08-20 07:24:02 浏览: 48
以下是基于STM32和ESP8266的自动获取IP地址的示例代码:
```c
#include <stdio.h>
#include <string.h>
#include "stm32f4xx.h"
#define ESP8266_USART USART6
void ESP8266_Init(void)
{
// 初始化ESP8266串口
USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOC, GPIO_PinSource6, GPIO_AF_USART6);
GPIO_PinAFConfig(GPIOC, GPIO_PinSource7, GPIO_AF_USART6);
USART_InitStructure.USART_BaudRate = 115200;
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(ESP8266_USART, &USART_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = USART6_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_ITConfig(ESP8266_USART, USART_IT_RXNE, ENABLE);
USART_Cmd(ESP8266_USART, ENABLE);
}
void ESP8266_SendCommand(char* command)
{
while(*command != 0)
{
USART_SendData(ESP8266_USART, *command++);
while(USART_GetFlagStatus(ESP8266_USART, USART_FLAG_TXE) == RESET);
}
}
void ESP8266_GetIP(void)
{
char buffer[100];
int i = 0;
ESP8266_SendCommand("AT+CIFSR\r\n");
while(1)
{
while(USART_GetFlagStatus(ESP8266_USART, USART_FLAG_RXNE) == RESET);
char c = USART_ReceiveData(ESP8266_USART);
buffer[i++] = c;
if(strstr(buffer, "192.168.1.") != NULL)
{
printf("IP address: %s\r\n", strstr(buffer, "192.168.1."));
break;
}
}
}
int main(void)
{
ESP8266_Init();
ESP8266_GetIP();
while(1);
}
```
在这个示例中,我们首先初始化ESP8266的串口,并设置为接收和发送模式。然后,我们发送AT+CIFSR命令来获取ESP8266的IP地址。在接收到ESP8266的响应后,我们检查响应是否包含“192.168.1.”字符串,如果包含,则打印IP地址并退出循环。