|
一直想试用ESP8266做一个和商业WIFI能媲美的项目但是总是做不好。网上看了很多例程后来还是觉得arduino IDE好懂一点;
想要达到商业WIFI项目基本上要能有以下功能:
设备开机之后默认进入smartconfig模式,手机打开APP能很快配网;
配网结束之后,进入连接WiFi模式,联网结束之后,连接服务器,之后就能传输数据,还有发送指令了,
目前网上很多代码都是基本里程,没有很完整的,那个大神能写一个完整的啊;
#include <ESP8266WiFi.h>
WiFiClient client;
#define relay1 4
#define key 5//将dht11的data口接在8266的GPIO2上
const char *host = "121.42.180.30";
char flag=0;
int temp=0;
bool autoConfig()
{
int a=0;
pinMode(key,INPUT);
if(digitalRead(key) == LOW)
flag=1;
else
flag=0;
WiFi.begin();
while (WiFi.status() != WL_CONNECTED)
{
Serial.println("AutoConfig Success");
Serial.printf("SSID:%s\r\n", WiFi.SSID().c_str());
Serial.printf("PSW:%s\r\n", WiFi.psk().c_str());
WiFi.printDiag(Serial);
delay(1000);
a++;
if(a==30)
{
a=0;
return false;
break;
}
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
const int httpPort =8181;
if (!client.connect(host, httpPort))
{
Serial.println("connection failed");
}
else
{
Serial.print("connecting to ");
Serial.println(host);
client.write("{\"M\":\"checkin\",\"ID\":\"8434\",\"K\":\"7f051cda9\"}\r\n");//登陆设备,修改成自己的ID和key
delay(100);
}
return true;
}
void smartConfig()
{
WiFi.mode(WIFI_STA);
Serial.println("\r\nWait for Smartconfig");
WiFi.beginSmartConfig();
while (1)
{
Serial.print("Wait soft line..\r\n");
if (WiFi.smartConfigDone())
{
Serial.println("SmartConfig Success");
Serial.printf("SSID:%s\r\n", WiFi.SSID().c_str());
Serial.printf("PSW:%s\r\n", WiFi.psk().c_str());
WiFi.setAutoConnect(true); // 设置自动连接
break;
}
delay(1000);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void setup()
{
Serial.begin(115200);
if (!autoConfig())
{
Serial.println("Start AP mode");
smartConfig();
}
}
void loop()
{
char valueread;
while(client.available())
{
String line = client.readStringUntil('\r');
Serial.print(line);
int i;
for(i=0;i<=150;i++)
{
if((line[i]=='p') &&( line[i+1]=='l'))
{
digitalWrite(relay1,HIGH);
client.write("{\"M\":\"say\",\"ID\":\"ALL\",\"C\":\"LED1 is on\",\"SIGN\":\"ok\"}\r\n");
}
if((line[i]=='s') && (line[i+1]=='t'))
{
digitalWrite(relay1,LOW);
client.write("{\"M\":\"say\",\"ID\":\"ALL\",\"C\":\"LED1 is off\",\"SIGN\":\"ok\"}\r\n");
}
}
}
client.write("{\"M\":\"say\",\"ID\":\"8434\",\"C\":\"123456\"}\r\n");//修改自己的ID,向设备发送信息,防止掉线
String str1="{\"M\":\"update\",\"ID\":\"8434\",\"V\":{\"7341\":\"";//修改成你自己的ID和数据接口ID1存温度
str1+=flag;
str1+="\",\"7342\":\"";//修改成你自己的数据接口ID2存湿度
str1+=temp;
str1+="\"}}\n";
temp++;
Serial.print("temp:"); //打印字符串
Serial.println(temp); //输出实际值
client.print(str1); //发送数据给服务器
delay(3000);
}
|
|