前言
今天是学习百问网智能家居项目的第4天,本文我们将会介绍如何使用ESP8266进行连接WIFI
一、ESP8266和WIFI的连接
STM32通过串口和ESP8266进行通信,发送指定的AT指令即可实现联网。ESP8266可以单独进行联网也可以通过上面方式进行联网。 注意:ESP8266只能连接2.4GHZ的WIFI,很多人可能因为连接到的是5GHZ的WIFI导致ESP8266无法和WIFI进行连接。
二、代码展示
main.c
USART3_StartRx();
esp8266_Init();
串口代码
static uint8_t rx_len;
static uint8_t rx_data;
static uint8_t usart_rx_buf[200];
void USART3_StartRx(void)
{
HAL_UART_Receive_IT(&huart3, (uint8_t*)&rx_data, 1);
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
usart_rx_buf[rx_len%200] = rx_data;
rx_len++;
HAL_UART_Receive_IT(&huart3, (uint8_t*)&rx_data, 1);
}
uint16_t USART3_Receive(uint8_t *pdata)
{
memcpy(pdata, (uint8_t*)usart_rx_buf, rx_len);
return rx_len;
}
void USART3_Transmit(uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
HAL_UART_Transmit(&huart3, pData, Size, Timeout);
}
void USART3_ClearBuf(void)
{
rx_len = 0;
memset((uint8_t*)usart_rx_buf, 0, 200);
}
ESP8266.c
#include "esp8266.h"
#include "log.h"
#include <string.h>
u8 esp8266_sendcmd(char *cmd,char *reply,u16 timeout)
{
u8 buf[256]={0};
strcat(buf,cmd);
if(0==strstr(buf,"\r\n"))
{
strcat(buf,"\r\n");
}
USART3_ClearBuf();
USART3_Transmit((u8*)buf,sizeof(buf),500);
memset(buf,0,256);
while(timeout!=0)
{
if(USART3_Receive((u8*)buf))
{
if(strstr(buf,reply))
{
PRINTF("%s Send ok!\r\n", cmd);
if (strstr(buf, "CIFSR"))
{
PRINTF("%s\r\n", buf);
}
return 0;
}
}
else
{
timeout--;
HAL_Delay(1);
}
}
PRINTF("%s send error\r\n",cmd);
return 1;
}
void esp8266_Init(void)
{
esp8266_sendcmd("AT+RST", "OK", 500);
HAL_Delay(1000);
esp8266_sendcmd("AT+CWMODE=1", "OK", 500);
esp8266_sendcmd("AT+CWJAP=\"MERCURY_2446\",\"740740740\"", "OK", 5000);
esp8266_sendcmd("AT+CIPMUX=1", "OK", 500);
esp8266_sendcmd("AT+CIPSERVER=1,9999", "OK", 500);
esp8266_sendcmd("AT+CIFSR", "OK", 500);
}
void esp8266_Task(void)
{
}
void esp8266_Handle(void)
{
}
ESP8266.h
#ifndef _ESP8266_H_
#define _ESP8266_H_
#include "main.h"
#define u8 unsigned char
#define u16 unsigned short
#define u32 unsigned int
#define WIFI_NAME "Dongsan201"
#define WIFI_PASSWORD "66666666"
u8 esp8266_sendcmd(char *cmd,char *reply,u16 time);
void esp8266_Init(void);
void esp8266_Task(void);
void esp8266_Handle(void);
#endif
main.c
esp8266_Init();
总结
感谢百问网让我了解到了如何使用ESP8266进行联网。
|