—— 阿尔伯特·爱因斯坦

程序员の奇妙冒险

ESP32物联网
2026-04-14 23:49阅读:评论:

esp32-s3 开发板扫描Wi-Fi网络已经播放音频

需求:烧录程序,第一次运行需要移动设备访问http://192.168.4.1配置连接Wi-Fi。Wi-Fi连接成功后记住Wi-Fi并自动播放音频。下次运行自动连接Wi-Fi并播放音频 扫描界面 源码 #include <WiFi.h> #include <WebServer.h> #in

  • 需求:烧录程序,第一次运行需要移动设备访问___PROTECTED_4__0___PROTECTED_5__3___PROTECTED_6__1___PROTECTED_7__20260414__PROTECTED_8____PROTECTED_9__2__
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
#include <WiFi.h>
#include <WebServer.h>
#include <Preferences.h>
#include <Audio.h>
 
Audio audio;
Preferences prefs;
WebServer server(80);
 
const char* ap_ssid = "ESP32_Audio_Config";
const char* streamUrl = "http://music.163.com/song/media/outer/url?id=1980818176.mp3";
 
// 添加Wi-Fi连接函数
bool connectToWiFi(String ssid, String password) {
Serial.printf("正在连接: %s\n", ssid.c_str());
WiFi.begin(ssid.c_str(), password.c_str());
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 20) {
delay(500);
Serial.print(".");
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\n✓ WiFi连接成功!");
Serial.printf("IP地址: %s\n", WiFi.localIP().toString().c_str());
return true;
} else {
Serial.println("\n✗ WiFi连接失败");
return false;
}
}
 
// 正常模式:初始化音频并开始播放
void setupAudio() {
Serial.println("正在初始化音频...");
audio.setPinout(15, 16, 7); // BCLK, LRCLK, DIN
audio.setVolume(6);
audio.connecttohost(streamUrl);
Serial.println("音频已启动");
}
 
void startAPMode() {
Serial.println(">>> 正在启动配置模式...");
// 完全重置Wi-Fi
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
delay(1000);
// 设置为AP模式
WiFi.mode(WIFI_AP);
delay(100);
// 配置AP参数
IPAddress local_ip(192, 168, 4, 1);
IPAddress gateway(192, 168, 4, 1);
IPAddress subnet(255, 255, 255, 0);
if (!WiFi.softAPConfig(local_ip, gateway, subnet)) {
Serial.println("✗ AP IP配置失败");
return;
}
// 启动AP热点
if (WiFi.softAP(ap_ssid, NULL, 1, 0, 4)) {
Serial.printf("✓ 热点 '%s' 创建成功!\n", ap_ssid);
Serial.printf("✓ 热点IP地址: %s\n", WiFi.softAPIP().toString().c_str());
Serial.printf("✓ 热点MAC地址: %s\n", WiFi.softAPmacAddress().c_str());
} else {
Serial.println("✗ 热点创建失败!");
return;
}
 
// Web服务器路由
server.on("/", []() {
String html = R"rawliteral(
 
<html>
<head>
<meta charset="UTF-8">
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>ESP32 WiFi</title>
<style>
body { font-family: Arial; margin: 20px; }
input, button { margin: 5px; padding: 8px; width: 90%; }
.ssid-list { list-style: none; padding: 0; }
.ssid-list li { background: #eee; margin: 5px; padding: 8px; cursor: pointer; }
.status { margin-top: 20px; padding: 10px; background: #f0f0f0; }
</style>
</head>
<body>
<h2>ESP32 WiFi</h2>
<div>
<label>WiFi(SSID):</label>
<input type='text' id='ssid' placeholder='点击下方网络自动填充'><br>
<label>:</label>
<input type='password' id='password' placeholder='请输入密码'><br>
<button onclick='connectWiFi()'></button>
</div>
<h3>WiFi</h3>
<button onclick='scanNetworks()'></button>
<ul></ul>
<div id='status' class='status'></div>
<script>
function scanNetworks() {
// 显示 Loading
document.getElementById('status').innerHTML = "正在扫描WiFi,请稍候...";
fetch('/scan')
.then(response => response.json())
.then(data => {
let list = document.getElementById('networks');
list.innerHTML = '';
data.forEach(net => {
let li = document.createElement('li');
li.textContent = net.ssid + ' (信号: ' + net.rssi + ' dBm)';
li.onclick = () => {
document.getElementById('ssid').value = net.ssid;
document.getElementById('status').innerHTML = '已选择: ' + net.ssid;
};
list.appendChild(li);
});
// 扫描完成,关闭 Loading
document.getElementById('status').innerHTML = "扫描完成!共找到 " + data.length + " 个WiFi";
});
}
function connectWiFi() {
let ssid = document.getElementById('ssid').value;
let password = document.getElementById('password').value;
if (!ssid) {
alert('请选择或输入WiFi名称');
return;
}
document.getElementById('status').innerHTML = '正在连接 ' + ssid + '...';
fetch('/connect', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'ssid=' + encodeURIComponent(ssid) + '&password=' + encodeURIComponent(password)
})
.then(response => {
if (response.ok) {
// 连接成功 → 清空页面只显示 提示
document.body.innerHTML = '<h3>Wi-Fi连接成功!正在重启,请稍后...</h3>';
}
});
}
scanNetworks();
</script>
</body>
</html>
)rawliteral";
server.send(200, "text/html", html);
});
 
server.on("/scan", []() {
Serial.println("开始扫描Wi-Fi...");
WiFi.scanNetworks(false); // 异步扫描
int n = WiFi.scanComplete();
if (n >= 0) {
String json = "[";
for (int i = 0; i < n; i++) {
if (i > 0) json += ",";
json += "{\"ssid\":\"" + WiFi.SSID(i) + "\",\"rssi\":" + String(WiFi.RSSI(i)) + "}";
}
json += "]";
server.send(200, "application/json", json);
WiFi.scanDelete();
} else {
server.send(200, "application/json", "[]");
}
});
 
server.on("/connect", HTTP_POST, []() {
if (server.hasArg("ssid") && server.hasArg("password")) {
String ssid = server.arg("ssid");
String password = server.arg("password");
Serial.printf("收到连接请求: %s\n", ssid.c_str());
prefs.begin("wifi", false);
prefs.putString("ssid", ssid);
prefs.putString("password", password);
prefs.end();
// 立即响应前端,触发页面显示 Done!
server.send(200, "text/plain", "OK");
delay(500);
if (connectToWiFi(ssid, password)) {
Serial.println("连接成功,3秒后重启");
delay(3000);
ESP.restart();
} else {
Serial.println("连接失败");
prefs.begin("wifi", false);
prefs.clear();
prefs.end();
}
} else {
server.send(400, "text/plain", "缺少SSID或密码");
}
});
 
server.begin();
Serial.println("✓ Web服务器已启动");
Serial.println("======================================");
Serial.println("请连接热点: ESP32_Audio_Config");
Serial.println("然后访问: http://192.168.4.1");
Serial.println("======================================");
}
 
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("\n\n=== ESP32 音频播放器启动 ===");
Serial.printf("固件大小: %d bytes\n", ESP.getSketchSize());
Serial.printf("空闲内存: %d bytes\n", ESP.getFreeHeap());
// 检查是否已保存Wi-Fi配置
prefs.begin("wifi", false);
String savedSsid = prefs.getString("ssid", "");
String savedPassword = prefs.getString("password", "");
prefs.end();
if (savedSsid.length() > 0) {
Serial.printf("发现已保存的Wi-Fi: %s\n", savedSsid.c_str());
Serial.println("尝试自动连接...");
if (connectToWiFi(savedSsid, savedPassword)) {
Serial.println("✓ 已连接到Wi-Fi");
Serial.println("准备播放音频...");
setupAudio();
return;
} else {
Serial.println("自动连接失败,5秒后启动配置模式");
delay(5000);
}
}
// 没有保存的配置或连接失败,启动AP模式
startAPMode();
}
 
void loop() {
if (WiFi.getMode() == WIFI_AP || WiFi.getMode() == WIFI_AP_STA) {
server.handleClient();
} else {
audio.loop();
}
}
 
评论(0,共 null 条回复)
暂无评论来抢沙发吧~