终于开始接触网络了,基础不行,这个摸索了有点久,还好网上资料多,有些细节还是没有怎么吃透。哈哈,开始联网了。
ESP8266有三种模式:
- station模式:0x01
- soft-AP模式:0x02
- soft-AP&station模式:0x03
简单的介绍一下这三个模式:
- station模式
只能连接其他的路由器,不能被其他设备连接(自己可以连别人,别人不能连自己,简称‘攻’) - soft-AP模式
这个模式可以看做是一个路由器,只能让其他设备连接本模块,自己不能去连其他路由器(别人可以连自己,自己不能连别人,简称‘受’) - soft-AP&station模式
顾名思义,这个模式即可以连其他设备,也可以被其他设备连,一般用得最多的就是这个模式(自己连别人,别人连自己都ok,这个就不可描述了=_=凸)
连接wifi
根据手册(手册是个好东西呀)总体思路是这样的:
- 将8266设置为soft-AP&station模式,默认是soft-AP模式,有一点要注意一下,不过现在0.9.2以前版本基本没人用了吧。
wifi_set_opmode(0x03);//设置为soft-AP兼station模式
- 用wifi_station_scan获取AP信息,扫描wifi,我这里是扫描所有可用AP信息。
void to_scan(void) {
wifi_station_scan(NULL,scan_done);
}
- 用wifi_station_connect连接wifi
wifi_station_connect();//在非user_init()入口函数中连接WiFi,需要调用这个函数
上代码
// 头文件引用
//==================================================================================
#include "user_config.h" // 用户配置
#include "driver/uart.h" // 串口
#include "c_types.h" // 变量类
#include "eagle_soc.h" // GPIO函数、宏定义
#include "ets_sys.h" // 回调函数
#include "os_type.h" // os_XXX
#include "osapi.h" // os_XXX、软件定时器
#include "user_interface.h" // 系统接口、system_param_xxx接口、WIFI、RateContro
#include "pwm.h"
#include "ip_addr.h"
#include "espconn.h"
#include "mem.h"
#include "smartconfig.h"
#include "airkiss.h"
//==================================================================================
ETSTimer connect_timer;
void ICACHE_FLASH_ATTR Wifi_conned(void *arg)
{
static uint8 count = 0;
uint8 status;
os_timer_disarm(&connect_timer);
count++;
status = wifi_station_get_connect_status();
if (status == STATION_GOT_IP)
{
os_printf("Wifi connect success!");
return;
}
else
{
if (count >= 7)
{
os_printf("Wifi connect fail!");
return;
}
}
os_timer_arm(&connect_timer, 2000, false);
}
void ICACHE_FLASH_ATTR scan_done(void *arg, STATUS status)
{
uint8 ssid[33];
char temp[128];
struct station_con