105 lines
2.4 KiB
C++
105 lines
2.4 KiB
C++
#include <WiFi.h>
|
||
#include <WebServer.h>
|
||
#include <WiFiUdp.h>
|
||
#include "page.h"
|
||
|
||
// 创建Web服务器对象,监听端口80
|
||
WebServer server(80);
|
||
|
||
// 存储用户输入的SSID和密码
|
||
String ssid;
|
||
String password;
|
||
String target_ip;
|
||
|
||
bool flag = true;
|
||
bool isConnected = false;
|
||
|
||
WiFiUDP udp;
|
||
const char* udpAddress = "255.255.255.255";
|
||
const int udpPort = 8000;
|
||
|
||
// 定义ADC通道
|
||
const int adcPins[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
|
||
|
||
// 处理根路径的请求,显示配网页面
|
||
void handleRoot() {
|
||
String html = page1;
|
||
server.send(200, "text/html", html);
|
||
}
|
||
|
||
// 处理配置请求,获取用户输入的SSID和密码
|
||
void handleConfigure() {
|
||
ssid = server.arg("ssid");
|
||
password = server.arg("password");
|
||
target_ip = server.arg("target_ip");
|
||
server.send(200, "text/html", "<html><body><h1>Configuration Successful</h1></body></html>");
|
||
|
||
// 关闭AP模式并连接到用户指定的Wi-Fi
|
||
WiFi.softAPdisconnect();
|
||
WiFi.begin(ssid.c_str(), password.c_str());
|
||
|
||
// 等待Wi-Fi连接
|
||
while (WiFi.status() != WL_CONNECTED) {
|
||
delay(1000);
|
||
Serial.print(".");
|
||
}
|
||
Serial.println("Connected to WiFi");
|
||
Serial.print("IP address: ");
|
||
Serial.println(WiFi.localIP());
|
||
Serial.print("Target IP: ");
|
||
Serial.println(target_ip);
|
||
// udpAddress = target_ip.c_str();
|
||
udp.begin(udpPort); // 启动UDP
|
||
isConnected = true;
|
||
}
|
||
|
||
void setup() {
|
||
Serial.begin(115200);
|
||
|
||
// 配置AP模式
|
||
WiFi.softAP("ESP32_Config", "12345678");
|
||
|
||
// 配置Web服务器的路由
|
||
server.on("/", handleRoot);
|
||
server.on("/configure", HTTP_POST, handleConfigure);
|
||
|
||
// 启动Web服务器
|
||
server.begin();
|
||
|
||
Serial.println("AP Mode Started");
|
||
}
|
||
|
||
void loop() {
|
||
// 处理客户端请求
|
||
while (!isConnected) {
|
||
server.handleClient();
|
||
}
|
||
if (flag) {
|
||
Serial.println("Now is connected to WiFi!");
|
||
flag = false;
|
||
}
|
||
|
||
while (isConnected) {
|
||
uint16_t adcData[8] = { 0 };
|
||
uint8_t adcByteData[16] = { 0 };
|
||
|
||
// 读取ADC值
|
||
for (int i = 0; i < 8; i++) {
|
||
adcData[i] = analogRead(adcPins[i]);
|
||
}
|
||
|
||
for (int i = 0; i < 8; i++) {
|
||
adcByteData[2 * i] = (uint8_t)(adcData[i] & 0x00FF); // 低字节
|
||
adcByteData[2 * i + 1] = (uint8_t)((adcData[i] >> 8) & 0x00FF); // 高字节
|
||
}
|
||
|
||
// 发送UDP数据
|
||
udp.beginPacket(udpAddress, udpPort);
|
||
udp.write(adcByteData, 16);
|
||
udp.endPacket();
|
||
|
||
// Serial.println("Sent: " + adcData); // 打印发送的数据
|
||
delay(25); // 每25ms发送一次数据
|
||
}
|
||
}
|