wifi连接
#include <Arduino.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include "../lib/PWMMOT/PWMMOT.h"
void WiFi_Connect()
{
Serial.print("goal,ESPro1,key:321654987");
WiFi.begin("ESPro1", "321654987");
while (WiFi.status() != WL_CONNECTED)
{
delay(300);
Serial.print(" waiting");
}
}
void setup()
{
Serial.begin(115200);
delay(100);
Serial.println("********Connecting**********");
WiFi_Connect();
Serial.println("WiFi connected");
Serial.println("Get IP address: ");
Serial.println(WiFi.localIP());
}
void loop()
{
delay(5000);
}
建立tcp client:
#include <Arduino.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include "../lib/PWMMOT/PWMMOT.h"
const IPAddress serverIP(192, 168, 19, 108);
uint16_t serverPort = 5001;
WiFiClient client;
void WiFi_Connect()
{
long iRetval = -1;
Serial.print("goal,ESPro1,key:321654987");
4个数值,第一个是目的WiFi名字,第二个是目的的WiFi密码,第三个是通道,第四个是mac地址,第五个是是否默认连接
WiFi.begin("ESPro1", "321654987", 0, NULL, true);
WiFi的返回值:
0连接中,
1(WL_NO_SSID_AVAIL)没找到,
2(WL_SCAN_COMPLETE)扫描完毕,
3(WL_CONNECTED)连接成功,
4(WL_CONNECT_FAIED)连接失败,
5(WL_CONNECT_LOST)连接丢失,
6(WL_DISCONNECTED)没有连接
while (WiFi.status() != 3)
{
iRetval = WiFi.status();
switch (iRetval)
{
case -1:
Serial.println("meet errors at begining");
break;
case 0:
Serial.print("connecting...");
break;
case 1:
Serial.println("connot find this SSID");
break;
case 2:
Serial.println("WIFI scan connected!!");
break;
case 4:
Serial.println("WIFI connect meet error!!");
break;
case 5:
Serial.println("lost WIFI connect");
break;
case 6:
Serial.println("status:no connected");
break;
}
delay(300);
}
Serial.println("WiFi Connected");
}
void TCP_Client_build()
{
String DATA_Client;
Serial.println("trying buuiding tcp client**");
if (client.connect(serverIP, serverPort))
{
Serial.println("success,tcp ip:127.0.0.1,port:5001");
client.print("hello,server!\r\n");
Serial.println("goal:server,send:hello,server!");
while (client.connected() || client.available())
已连接或者有没读取的数据
{
if (client.available())
{
DATA_Client = client.readStringUntil('\n');
Serial.print("receive:");
Serial.println(DATA_Client);
}
}
跳出循环说明连接断开,可以关闭
client.stop();
Serial.println("关闭当前连接");
}
else
{
Serial.println("访问失败");
client.stop();
}
}
void setup()
{
Serial.begin(115200);
delay(100);
Serial.println("********Connecting**********");
WiFi_Connect();
Serial.println("Get IP address: ");
Serial.println(WiFi.localIP());
}
void loop()
{
TCP_Client_build();
delay(5000);
}