You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求ESP-Touch V2及安卓APP场景下Arduino获取自定义数据的SmartConfig示例代码

基于ESP-Touch V2的Arduino SmartConfig自定义数据获取示例代码

是的,你可以通过ESP-IDF提供的ESP-Touch V2组件在Arduino环境中实现该功能,以下是完整示例代码:

#include <WiFi.h>
#include <esp_wifi.h>
#include <esp_smartconfig.h>

// 自定义数据存储变量
String customData;

// SmartConfig回调函数,处理配网结果和自定义数据
void smartConfigCallback(sc_status_t status, void *pdata) {
  switch (status) {
    case SC_STATUS_WAIT:
      Serial.println("等待配网数据...");
      break;
    case SC_STATUS_FIND_CHANNEL:
      Serial.println("正在查找WiFi信道...");
      break;
    case SC_STATUS_GETTING_SSID_PSWD:
      Serial.println("正在获取WiFi信息...");
      break;
    case SC_STATUS_LINK:
      {
        sc_callback_data_t *data = (sc_callback_data_t *)pdata;
        // 获取WiFi SSID和密码
        String ssid = (char *)data->ssid;
        String password = (char *)data->password;
        Serial.printf("WiFi SSID: %s, Password: %s\n", ssid.c_str(), password.c_str());

        // 检查是否存在自定义数据(ESP-Touch V2 APP支持传入自定义字段)
        if (data->custom_data_len > 0) {
          customData = String((char *)data->custom_data, data->custom_data_len);
          Serial.printf("获取到自定义数据: %s\n", customData.c_str());
        }

        // 连接WiFi
        WiFi.begin(ssid.c_str(), password.c_str());
        while (WiFi.status() != WL_CONNECTED) {
          delay(500);
          Serial.print(".");
        }
        Serial.println("\nWiFi连接成功");
        break;
      }
    case SC_STATUS_LINK_OVER:
      Serial.println("配网完成");
      if (status == SC_STATUS_LINK_OVER) {
        esp_smartconfig_stop(); // 停止SmartConfig服务
      }
      break;
    default:
      break;
  }
}

void setup() {
  Serial.begin(115200);
  Serial.println("\n启动ESP-Touch V2配网");

  // 初始化WiFi为Station模式
  WiFi.mode(WIFI_STA);

  // 配置SmartConfig参数,启用ESP-Touch V2
  smartconfig_start_config_t cfg = SMARTCONFIG_START_CONFIG_DEFAULT();
  cfg.type = SC_TYPE_ESPTOUCH_V2; // 指定使用ESP-Touch V2协议
  esp_smartconfig_start(&cfg, smartConfigCallback);
}

void loop() {
  // 主循环无需额外操作,回调函数会处理配网流程
  delay(1000);
}

关键说明:

  • 自定义数据获取:在SC_STATUS_LINK状态下,通过sc_callback_data_t结构体的custom_data和custom_data_len字段读取APP传入的自定义数据。
  • ESP-Touch V2 APP设置:在安卓APP中,除了输入WiFi SSID和密码,还需在自定义数据栏填写你需要传递的内容,APP会将该数据与WiFi信息一起发送给ESP设备。
  • 停止配网:配网完成后调用esp_smartconfig_stop()释放资源,避免不必要的功耗。

内容的提问来源于stack exchange,提问作者Smarta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 06:40:54