NodeMCU 使用 App(iOS Swift) 点亮 LED 小灯

转载来源

这是我转载的老外的教程,视频来源:跳转到 Youtube 查看

视频教程

视频简介

在这个视频中,我们学习了如何使用 esp8266-12e 和 iOS 来控制 led。 模块本身不到 10 美元,所以与其他物联网设备相比,制作这个项目并不需要太多的费用。

视频中的程序代码(不包含 IOS APP 代码)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <ESP8266WiFi.h>

//////////////////////
// WiFi Definitions //
//////////////////////
const char WiFiAPPSK[] = "esp8266-12e";

/////////////////////
// Pin Definitions //
/////////////////////
const int LED_PIN = 16; // Thing's onboard, green LED

WiFiServer server(80);

void setupWiFi()
{
WiFi.mode(WIFI_AP);

// Do a little work to get a unique-ish name. Append the
// last two bytes of the MAC (HEX'd) to "ThingDev-":
uint8_t mac[WL_MAC_ADDR_LENGTH];
WiFi.softAPmacAddress(mac);
String macID = String(mac[WL_MAC_ADDR_LENGTH - 2], HEX) +
String(mac[WL_MAC_ADDR_LENGTH - 1], HEX);
macID.toUpperCase();
String AP_NameString = "ESP-" + macID;

char AP_NameChar[AP_NameString.length() + 1];
memset(AP_NameChar, 0, AP_NameString.length() + 1);

for (int i=0; i<AP_NameString.length(); i++)
AP_NameChar[i] = AP_NameString.charAt(i);

WiFi.softAP(AP_NameChar, WiFiAPPSK);
}

void initHardware()
{
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
// Don't need to set ANALOG_PIN as input,
// that's all it can be.
}

void setup()
{
initHardware();
setupWiFi();
server.begin();
}

void loop()
{
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}

// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();

// Match the request
int val = -1; // We'll use'val'to keep track of both the
// request type (read/set) and value if set.
if (req.indexOf("/led/0") != -1)
val = 1; // Will write LED high
else if (req.indexOf("/led/1") != -1)
val = 0; // Will write LED low

// Set GPIO5 according to the request
if (val >= 0)
digitalWrite(LED_PIN, val);

client.flush();

// Prepare the response. Start with the common header:
String s = "HTTP/1.1 200 OK\r\n";
s += "Content-Type: text/html\r\n\r\n";
s += "<!DOCTYPE HTML>\r\n<html>\r\n";
// If we're setting the LED, print out a message saying we did
if (val >= 0)
{
s += "LED is now";
s += (val)?"off":"on";
}
else
{
s += "Invalid Request.<br> Try /led/1, /led/0, or /read.";
}
s += "</html>\n";

// Send the response to the client
client.print(s);
delay(1);
Serial.println("Client disonnected");

// The client will actually be disconnected
// when the function returns and 'client' object is detroyed
}
坚持原创技术分享,您的支持将鼓励我继续创作!