LWIFI学习
这个里面可以 Post a JSON object to a server and receive a response 本人是小白,以下程序又不专业的地方尽情谅解,同时欢迎大神来一起讨论~
#include "LTask.h"
#include "LWiFi.h"
#include "LWiFiClient.h"
#define SITE_URL "httpbin.org"//配置主机名SITE_URL “httpbin.org” //配置主机名
#define WIFI_AP "your_ap_ssid"
#define WIFI_PASSWORD "your_password"
#define WIFI_AUTH LWIFI_WPA // choose from LWIFI_OPEN, LWIFI_WPA, or LWIFI_WEP.
#define SITE_URL "labs.mediatek.com"
int tempF = 50;
int tempC = 15;
int pressure = 15;
int humidity = 15;
LWiFiClient c;
void setup()
{
LWiFi.begin();
Serial.begin(115200);
// keep retrying until connected to AP
Serial.println("Connecting to AP");
while (0 == LWiFi.connect(WIFI_AP, LWiFiLoginInfo(WIFI_AUTH, WIFI_PASSWORD)))
{
delay(1000);
}
// keep retrying until connected to website
Serial.println("Connecting to WebSite");
while (0 == c.connect(SITE_URL, 80))
{
Serial.println("Re-Connecting to WebSite");
delay(1000);
}
// send HTTP request, ends with 2 CR/LF
Serial.println("send HTTP GET request");
c.println("GET / HTTP/1.1");
c.println("Host: " SITE_URL);
c.println("Connection: close");
c.println();
//发送HTTP请求,以2 CR / LF结束//发送HTTP请求,以2 CR / LF结束
String PostData = buildJson();
Serial.println("Connected. Sending HTTP GET Request ....");
c.println("POST /post HTTP/1.1"); //modify the POST path.println("POST /post HTTP/1.1"); //modify the POST path
c.println("Host: " SITE_URL);
c.println("Connection: close");
c.print("Content-Length: ");
c.println(PostData.length());
c.println();
c.println(PostData); //send the HTTP POST body.println(PostData); //send the HTTP POST body
// waiting for server response
Serial.println("waiting HTTP response:");
while (!c.available())
{
delay(1000);
}
}
//构建JSON方法
String buildJson()
{
String data = "{";
data+="\n";
data+= "\"d\": {";
data+="\n";
data+="\"temperature (F)\": ";
data+=tempF;
data+= ",";
data+="\n";
data+="\"temperature (C)\": ";
data+=tempC;
data+= ",";
data+="\n";
data+="\"pressure\": ";
data+=pressure;
data+= ",";
data+="\n";
data+="\"humidity\": ";
data+=humidity;
data+="\n";
data+="}";
data+="\n";
data+="}";
return data;
}
boolean disconnectedMsg = false;
void loop()
{
// Make sure we are connected, and dump the response content to Serial
while (c)
{
int v = c.read();
if (v != -1)
{
Serial.print((char)v);
}
else
{
Serial.println("no more content, disconnect");
c.stop();
while (1)
{
delay(10);
}
}
}
if (!disconnectedMsg)
{
Serial.println("disconnected by server");
disconnectedMsg = true;
}
delay(1000);
}
于是现在应该呈现的是如官网图所示,然而我这个编完串口监视器只能显示Connecting to AP,具体原因不清楚,请各位大神指正!
PS:这块板子刷程序的时候总会出现“打开串行端口COM10出错”,我之前一直是多刷几次,有一次就行,一般程序刚编出来第一次都是好使的,错误的具体原因也不太清楚。