目录
1.ESP8266连接热点
2.ESP8266创建热点
创建热点的ESP8266
连接热点的ESP8266
3.发送网络请求
案例一
案例二
4.连接服务器
接收信息开关灯
发布消息开关灯
5.ESP8266创建HTTP服务
编辑
编辑
编辑
6.ESP8266HTTP请求控制灯
编辑
7.ESP8266接收后端数据
1.ESP8266连接热点
基于WiFi-client示例
/*
This sketch establishes a TCP connection to a "quote of the day" service.
It sends a "hello" message, and then prints received data.
*/
#include <ESP8266WiFi.h>
#ifndef STASSID
#define STASSID "hello"
#define STAPSK "12345679"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
void setup() {
Serial.begin(9600);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("连接 to ");
Serial.println(ssid);
/* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
would try to act as both a client and an access-point and could cause
network-issues with your other WiFi-devices on your WiFi-network. */
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("wifi连接成功");
Serial.println("IP 地址: ");
Serial.println(WiFi.localIP());
}
void loop()
{}
2.ESP8266创建热点
创建热点的ESP8266
基于WiFi-AccessPoint示例
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#ifndef APSSID
//热点名
#define APSSID "ESP8266_AP"
//热点密码
#define APPSK "123456"
#endif
/* Set these to your desired credentials. */
const char *ssid = "ESP8266_AP";
const char *password = APPSK;
int number=0;
void setup() {
delay(1000);
Serial.begin(9600);
Serial.println();
Serial.print("创建热点...");
Serial.print(ssid);
/* You can remove the password parameter if you want the AP to be open. */
//创建热点
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
}
void loop() {
number=WiFi.softAPgetStationNum();
if(number)
{
Serial.print("设备连接数:");
Serial.print(number);
}
}
2.
#include <ESP8266WiFi.h>
// 热点名称和密码
const char *ap_ssid = "ESP8266_AP";
const char *ap_password = "12345678";
void setup() {
Serial.begin(9600);
// 等待串口初始化完成
delay(1000);
// 打印启动信息
Serial.println("Starting AP...");
// 创建热点
WiFi.softAP(ap_ssid, ap_password);
// 获取热点的IP地址
IPAddress ip = WiFi.softAPIP();
// 打印热点的IP地址
Serial.print("AP IP address: ");
Serial.println(ip);
}
void loop() {
// 获取连接到热点的设备数量
int numberOfClients = WiFi.softAPgetStationNum();
// 如果有设备连接,打印设备数量
if (numberOfClients) {
Serial.print("Number of connected devices: ");
Serial.println(numberOfClients);
}
// 适当延时,避免频繁打印
delay(5000);
}
连接热点的ESP8266
#include <ESP8266WiFi.h>
#ifndef STASSID
#define STASSID "ESP8266_AP"
#define STAPSK "12345678"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
void setup() {
Serial.begin(9600);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("连接 to ");
Serial.println(ssid);
/* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
would try to act as both a client and an access-point and could cause
network-issues with your other WiFi-devices on your WiFi-network. */
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("wifi连接成功");
Serial.println("IP 地址: ");
Serial.println(WiFi.localIP());
}
void loop()
{}
3.发送网络请求
案例一
https://www.juhe.cn/
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#ifndef STASSID
#define STASSID "hello"
#define STAPSK "12345679"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
String url = "http://apis.juhe.cn/simpleWeather/query";
String city = "上海";
String key = "dbbdc4f89228d7281fbbbde5ccddf395";
void setup() {
Serial.begin(9600);
Serial.println();
Serial.println();
Serial.print("正在连接到 ");
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已连接");
Serial.print("IP地址: ");
Serial.println(WiFi.localIP());
HTTPClient http;
// 构造完整的URL和参数
String requestUrl = url + "?city=" + city + "&key=" + key;
http.begin(requestUrl);
int http_code = http.GET();
Serial.printf("HTTP状态码: %d\n", http_code);
String response = http.getString();
Serial.print("响应数据:");
Serial.println(response);
http.end();
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, response);
if (error) {
Serial.print("deserializeJson() 失败: ");
Serial.println(error.c_str());
return;
}
unsigned int temp = doc["result"]["realtime"]["temperature"].as<unsigned int>();
String info = doc["result"]["realtime"]["info"].as<String>();
int aqi = doc["result"]["realtime"]["aqi"].as<int>();
Serial.printf("温度: %u, 天气: %s, 空气质量指数: %d\n", temp, info.c_str(), aqi);
}
void loop() {
// 空循环
}
案例二
http://www.tianqiapi.com/
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
const char* ssid = "hello";
const char* password = "12345679";
String url = "http://v1.yiketianqi.com/free/day";
String appid = "看个人";
String appsecret = "看个人";
int unescape = 1;
void setup() {
Serial.begin(9600);
Serial.println();
Serial.println("Connecting to WiFi");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
HTTPClient http;
String requestUrl = url + "?appid=" + appid + "&appsecret=" + appsecret + "&unescape=" + String(unescape)+"&city="+"金华";
http.begin(requestUrl);
int http_code = http.GET();
if (http_code != HTTP_CODE_OK) {
Serial.printf("HTTP GET failed, error code: %d\n", http_code);
http.end();
return;
}
String response = http.getString();
http.end();
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, response);
if (error) {
Serial.print("deserializeJson() failed: ");
Serial.println(error.c_str());
return;
}
const char* city = doc["city"];
const char* date = doc["date"];
const char* wea = doc["wea"];
Serial.printf("City: %s, Date: %s, Weather: %s\n", city, date, wea);
}
void loop() {
// Empty loop
}
4.连接服务器
在浏览器输入你的ip:18083
初始的用户名 admin
密码 public
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "ming‘s iPhone";
const char* password = "123321123";
const char* mqtt_server = "ip";
const int mqtt_port = 1883; //一般是1883
const char* mqtt_client_id = "esp8266-client";
const char* mqtt_user = "esp8266-client"; // 替换为你的MQTT服务器用户名
const char* mqtt_password = "123456"; // 替换为你的MQTT服务器密码
WiFiClient espClient;
PubSubClient client(espClient);
void callback(char* topic, byte* payload, unsigned int length);
void setup() {
Serial.begin(9600);
Serial.println("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
// Attempt to connect with username and password
if (!client.connect(mqtt_client_id, mqtt_user, mqtt_password)) {
Serial.println("Failed to connect to MQTT server");
return;
}
Serial.println("Connected to MQTT server");
client.subscribe("led"); // Subscribe to "led" topic
}
void loop() {
client.loop(); // Maintain MQTT connection
// Other loop code here
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
接收信息开关灯
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const int ledPin = D8; // LED连接到的GPIO引脚
const char* ssid = "ming‘s iPhone";
const char* password = "123321123";
const char* mqtt_server = "ip";
const int mqtt_port = 1883;
const char* mqtt_client_id = "esp8266-client";
const char* mqtt_user = "esp8266-client";
const char* mqtt_password = "123456";
WiFiClient espClient;
PubSubClient client(espClient);
void callback(char* topic, byte* payload, unsigned int length);
void setup() {
Serial.begin(9600);
Serial.println("Connecting to WiFi");
// 设置D8引脚为输出模式
pinMode(ledPin, OUTPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
if (!client.connect(mqtt_client_id, mqtt_user, mqtt_password)) {
Serial.println("Failed to connect to MQTT server");
return;
}
Serial.println("Connected to MQTT server");
client.subscribe("led");
}
void loop() {
client.loop();
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
char message[length + 1];
for (int i = 0; i < length; i++) {
message[i] = (char)payload[i];
}
message[length] = '\0';
Serial.println(message);
// 检查消息内容,如果为"1"则打开LED灯
if (strcmp(message, "1") == 0) {
digitalWrite(ledPin, HIGH);
} else {
// 如果消息不是"1",可以保持LED状态不变或关闭
digitalWrite(ledPin, LOW);
}
}
如果连接不上,就试一下下面的代码
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const int ledPin = D8; // LED连接到的GPIO引脚
const char* ssid = "hello";
const char* password = "12345679";
const char* mqtt_server_ip = "ip"; // 直接使用 IP 地址
const int mqtt_port = 1883;
const char* mqtt_client_id = "pc";
const char* mqtt_user = "pc";
const char* mqtt_password = "12345";
WiFiClient espClient;
PubSubClient client(espClient);
void callback(char* topic, byte* payload, unsigned int length);
void setup() {
Serial.begin(9600);
Serial.println("Connecting to WiFi");
// 设置D8引脚为输出模式
pinMode(ledPin, OUTPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
client.setServer(mqtt_server_ip, mqtt_port); // 使用 IP 地址代替域名
client.setCallback(callback);
// 尝试连接到 MQTT 服务器
while (!client.connect(mqtt_client_id, mqtt_user, mqtt_password)) {
Serial.println("Failed to connect to MQTT server, retrying...");
delay(5000); // 重试连接前等待5秒
}
Serial.println("Connected to MQTT server");
client.subscribe("led");
}
void loop() {
if (!client.connected()) {
Serial.println("Reconnecting to MQTT server...");
while (!client.connect(mqtt_client_id, mqtt_user, mqtt_password)) {
delay(5000); // 重试连接前等待5秒
}
Serial.println("Connected to MQTT server");
client.subscribe("led");
}
client.loop();
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
char message[length + 1];
for (int i = 0; i < length; i++) {
message[i] = (char)payload[i];
}
message[length] = '\0';
Serial.println(message);
// 检查消息内容,如果为"1"则打开LED灯
if (strcmp(message, "1") == 0) {
digitalWrite(ledPin, HIGH);
} else {
// 如果消息不是"1",可以保持LED状态不变或关闭
digitalWrite(ledPin, LOW);
}
}
在WebSocket客户端发布主题
发布消息开关灯
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const int ledPin = D8; // LED连接到的GPIO引脚
const int buttonPin = D7; // 按键连接到的GPIO引脚
const char* ssid = "dbabeb";
const char* password = "12345678";
const char* mqtt_server = "ip";
const int mqtt_port = 1883;
const char* mqtt_client_id = "esp8266-publisher";
const char* mqtt_user = "esp8266-publisher";
const char* mqtt_password = "123456";
bool ledState = false; // 跟踪 LED 状态
bool previousButtonState = HIGH; // 上次按键的状态
WiFiClient espClient;
PubSubClient client(espClient);
void callback(char* topic, byte* payload, unsigned int length);
void setup() {
Serial.begin(9600);
Serial.println("Connecting to WiFi");
// 设置D8引脚为输出模式
pinMode(ledPin, OUTPUT);
// 设置D7引脚为输入模式,启用内部上拉电阻
pinMode(buttonPin, INPUT_PULLUP);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
if (!client.connect(mqtt_client_id, mqtt_user, mqtt_password)) {
Serial.println("Failed to connect to MQTT server");
return;
}
Serial.println("Connected to MQTT server");
client.subscribe("led");
}
void loop() {
client.loop();
bool currentButtonState = digitalRead(buttonPin); // 当前按键状态
// 检测按键状态变化
if(currentButtonState == LOW && previousButtonState == HIGH) {
// 如果按键被按下
ledState = !ledState; // 切换 LED 状态
// 发送 MQTT 消息来控制 LED 灯
char state[2];
state[0] = ledState ? '1' : '0';
state[1] = '\0';
client.publish("led", state);
delay(100); // 防止重复触发
}
previousButtonState = currentButtonState; // 更新上次按键的状态
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
char message[length + 1];
for (int i = 0; i < length; i++) {
message[i] = (char)payload[i];
}
message[length] = '\0';
Serial.println(message);
}
5.ESP8266创建HTTP服务
#include <ESP8266WiFi.h>
#include <ESPAsyncWebServer.h>
#ifndef STASSID
#define STASSID "dbabeb"
#define STAPSK "12345678"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
AsyncWebServer server(80); // 使用 AsyncWebServer 类
void handleRoot(AsyncWebServerRequest *request)
{
String html = "<!DOCTYPE html><html><head><meta charset='utf-8'></head><body>"
"你好呀好呀好呀"
"</body></html>";
request->send(200, "text/html", html);
}
void handleHello(AsyncWebServerRequest *request)
{
request->send(200, "text/html", "hello");
}
void handleNotFound(AsyncWebServerRequest *request)
{
request->send(404, "text/html;charset=utf-8", "没有找到页面!");
}
void setup() {
Serial.begin(9600);
// 连接到WiFi网络
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi连接成功");
Serial.println("IP地址: ");
Serial.println(WiFi.localIP());
// 设置路由处理函数
server.on("/", handleRoot);
server.on("/hello", HTTP_GET, handleHello);
server.onNotFound(handleNotFound);
// 启动Web服务器
server.begin();
}
void loop() {
// 主循环可以留空,除非有其他任务需要处理
}
6.ESP8266HTTP请求控制灯
#include <ESP8266WiFi.h>
#include <ESPAsyncWebServer.h>
#ifndef STASSID
#define STASSID "dbabeb"
#define STAPSK "12345678"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
const int ledPin = D8; // LED连接到的GPIO引脚
AsyncWebServer server(80); // 使用 AsyncWebServer 类
void handleRoot(AsyncWebServerRequest *request)
{
String html = "<!DOCTYPE html><html><head><meta charset='utf-8'></head><body>"
"你好呀好呀好呀"
"</body></html>";
request->send(200, "text/html", html);
}
void handleHello(AsyncWebServerRequest *request)
{
request->send(200, "text/html", "hello");
}
void handleNotFound(AsyncWebServerRequest *request)
{
request->send(404, "text/html;charset=utf-8", "没有找到页面!");
}
void handleLed(AsyncWebServerRequest *request)
{
String state = request->arg("led");
if (state == "off") {
digitalWrite(ledPin, LOW);
}
else if (state == "on") {
digitalWrite(ledPin, HIGH);
}
request->send(200, "text/html", "LED is <b>" + state + "</b>");
}
void setup() {
Serial.begin(9600);
// 设置D8引脚为输出模式
pinMode(ledPin, OUTPUT);
// 连接到WiFi网络
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi连接成功");
Serial.println("IP地址: ");
Serial.println(WiFi.localIP());
// 设置路由处理函数
server.on("/", handleRoot);
server.on("/hello", HTTP_GET, handleHello);
server.on("/ledctr", HTTP_GET, handleLed);
server.onNotFound(handleNotFound);
// 启动Web服务器
server.begin();
}
void loop() {
// 主循环可以留空,除非有其他任务需要处理
}
7.ESP8266网页按钮控制灯
#include <ESP8266WiFi.h>
#include <ESPAsyncWebServer.h>
#ifndef STASSID
#define STASSID "dbabeb"
#define STAPSK "12345678"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
const int ledPin = D8; // LED连接到的GPIO引脚
AsyncWebServer server(80); // 使用 AsyncWebServer 类
void handleRoot(AsyncWebServerRequest *request)
{
String html = "<!DOCTYPE html><html><head><meta charset='utf-8'></head><body>"
"你好呀好呀好呀"
"<script>"
"var xhttp = new XMLHttpRequest();"
"function ledctr(arg) {"
" xhttp.open('GET', '/ledctr?led=' + arg, true);"
" xhttp.send();"
"}"
"</script>"
"<button onclick='ledctr(\"on\")'>开灯</button>"
"<button onclick='ledctr(\"off\")'>关灯</button>"
"</body></html>";
request->send(200, "text/html", html);
}
void handleHello(AsyncWebServerRequest *request)
{
request->send(200, "text/html", "hello");
}
void handleNotFound(AsyncWebServerRequest *request)
{
request->send(404, "text/html;charset=utf-8", "没有找到页面!");
}
void handleLed(AsyncWebServerRequest *request)
{
String state = request->arg("led");
if (state == "off") {
digitalWrite(ledPin, LOW);
}
else if (state == "on") {
digitalWrite(ledPin, HIGH);
}
request->send(200, "text/html", "LED is <b>" + state + "</b>");
}
void setup() {
Serial.begin(9600);
// 设置D8引脚为输出模式
pinMode(ledPin, OUTPUT);
// 连接到WiFi网络
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi连接成功");
Serial.println("IP地址: ");
Serial.println(WiFi.localIP());
// 设置路由处理函数
server.on("/", handleRoot);
server.on("/hello", HTTP_GET, handleHello);
server.on("/ledctr", HTTP_GET, handleLed);
server.onNotFound(handleNotFound);
// 启动Web服务器
server.begin();
}
void loop() {
// 主循环可以留空,除非有其他任务需要处理
}
7.ESP8266接收后端数据
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#ifndef STASSID
#define STASSID "2022"
#define STAPSK "WQ1371480"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
String url = "http://192.168.43.33:9001/single";
String city = "123456";
String key = "999999";
void setup() {
Serial.begin(9600);
Serial.println();
Serial.println();
Serial.print("正在连接到 ");
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已连接");
Serial.print("IP地址: ");
Serial.println(WiFi.localIP());
HTTPClient http;
// 构造完整的URL和参数
String requestUrl = url + "?appid=" + city + "&appsecret=" + key;
http.begin(requestUrl);
int http_code = http.GET();
Serial.printf("HTTP状态码: %d\n", http_code);
String response = http.getString();
Serial.print("响应数据:");
Serial.println(response);
http.end();
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, response);
if (error) {
Serial.print("deserializeJson() 失败: " + response);
Serial.println(error.c_str());
return;
}
// 正确的JSON字段类型转换和打印
String cityId = doc["cityid"].as<String>();
String date = doc["date"].as<String>();
String week = doc["week"].as<String>();
Serial.printf("城市: %s\n时间: %s\n星期几: %s\n", cityId.c_str(), date.c_str(), week.c_str());
}
void loop() {
// 空循环
}