Arduino---ESP8266 WIFI模块
阅读原文时间:2023年07月12日阅读:1

一:Arduino安装ESP8266

https://www.arduino.cn/thread-76029-1-1.html(内容截图如下:最简单方法)

选用NodeMCU .0即可

二:简单测试

void setup() {
// put your setup code here, to run once:
pinMode(LED_BUILTIN,OUTPUT); //测试灯
}

void loop() {
// put your main code here, to run repeatedly:
digitalWrite(LED_BUILTIN,LOW);
delay();
digitalWrite(LED_BUILTIN,HIGH);
delay();
}

LED_BUILTIN中builtin是内建意思,为内建LED灯,可直接用于测试

三:引脚对应

引脚编号

对应数字

D0

16

D1

5

D2

4

D3

0

D4

2

D5

14

D6

12

D7

13

D8

15

D9

3

D10

1

四:简单使用案例:无线控制LED开关

#include //引入模块

#ifndef STASSID
#define STASSID "Tenda_064E38"
#define STAPSK "YM123456789"
#endif

const char* ssid = STASSID;
const char* password = STAPSK;

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80); //开启板子的80端口

void setup() {
//https://blog.csdn.net/rong81590509/article/details/77010216 //在波特率为9600~38400之间,波特率的增长倍数与传输速率的增长倍数基本相同,但是在波特率大于192000以上时,传输速率基本没有任何提高。 //从115200开始实际与理论相差较大 11.25kb/s //不要9600,因为9600下速率太慢0.9kb/s Serial.begin(115200); //开启电脑的序列埠,设置为115200 // 测试D4接口
pinMode(, OUTPUT);
digitalWrite(, ); //设置为低电压

//告诉电脑连接到那个wifi了
Serial.println();
Serial.println();
Serial.print(F("Connecting to "));
Serial.println(ssid);

//开始连接
WiFi.mode(WIFI_STA); //WIFI模块的STA模式和AP模式有什么区别:AP是接入点,可以让用户接入。STA--Station无线终端,不接受无线接入,可以连接到无线AP,无线网卡工作在STA下
WiFi.begin(ssid, password); //开启WIFI //若是没有连接上:则一直打印….
while (WiFi.status() != WL_CONNECTED) {
delay();
Serial.print(F("."));
}

//打印连线成功
Serial.println();
Serial.println(F("WiFi connected"));

//开启伺服器
server.begin();
Serial.println(F("Server started"));

//告诉电脑自己的IP
Serial.println(WiFi.localIP());
}

void loop() {
//每次循环进入:都需要确认本板子是否有效(是否连上AP),成功则返回客户端连接自己的句柄 WiFiClient client = server.available(); if (!client) {
return;
}

//成功就打印成功
Serial.println(F("new client"));
//若是客户端一直连接没有信息传入,则等待

//设置客户端连接超时时间。若在指定时间连接不上的为超时
client.setTimeout(); // default is 1000
**//看客户端是否发送信息,不然一直等待
while(!client.available())
{
delay(1);
}

//读取第一行\r为换行符--->为请求
String req = client.readStringUntil('\r'**);
Serial.println(F("request: "));
Serial.println(req);
//client.flush(); //刷新流

// Match the request
int val;
if (req.indexOf(F("/gpio/0")) != -) { //若是匹配到/gpio/0
val = ; //关闭
} else if (req.indexOf(F("/gpio/1")) != -) { //若是匹配到/gpio/1
val = ; //打开
} else {
Serial.println(F("invalid request"));
val = digitalRead(); //若是无用,则读取当前状态不变
}

//修改状态
digitalWrite(, val);

//向客户端句柄写入数据
client.print(F("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n\r\n\r\nGPIO is now ")); client.print((val) ? F("high") : F("low")); client.print(F("

Click here to switch LED GPIO on, or here to switch LED GPIO off."));

//客户端断开连接(对象释放了)
Serial.println(F("Disconnecting from client"));
}

本程序为单进程,不支持同步处理连接,易出现客户端死等。待改进

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章