Arduino笔记-WeMos D1通过HTTP亮熄灯
作者:互联网
程序运行截图如下:
低位:
对应的演示:
熄灯:
源码如下:
#include <ESP8266WiFi.h>
const char* ssid = "FAST_8482";
const char* password = "123456";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(2, OUTPUT);
digitalWrite(2, 0);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.println(WiFi.localIP());
}
void loop() {
//判断是否有客户端连接
WiFiClient client = server.available();
if (!client) {
return;
}
//等待用户发送数据
Serial.println("new client");
while(!client.available()){
delay(1);
}
//获取数据
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
//匹配
int val;
if (req.indexOf("/gpio/0") != -1)
val = 0;
else if (req.indexOf("/gpio/1") != -1)
val = 1;
else {
Serial.println("invalid request");
client.stop();
return;
}
digitalWrite(2, val);
client.flush();
//设置响应
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
s += (val)?"high":"low";
s += "</html>\n";
// Send the response to the client
client.print(s);
delay(1);
Serial.println("Client disonnected");
// client将会被释放
// 当这个函数结束后client连接将会被消耗
}
标签:HTTP,val,Arduino,WiFi,WeMos,server,client,println,Serial 来源: https://blog.csdn.net/qq78442761/article/details/105240756