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

ESP8266调用Firestore的getDocument接口后无法控制LED开关问题求助

Firestore控制LED不工作修复方案

核心问题定位

  • 直接逻辑错误:代码中用于过滤字段的变量mask被固定赋值为"pump",后续判断直接拿mask和"on"/"off"比较,条件永远不成立,LED自然不会切换状态
  • 逻辑冲突:每次循环都调用createDocument接口,且本地固定firebaseStatus = "on",会反复覆盖云端的pump字段值,你在云端手动改的状态会被立刻刷回on
  • 缺少JSON解析步骤:Firestore返回的文档数据是JSON格式,你没有从中提取pump的实际值,直接用固定变量判断自然无效

修复代码

你可以直接替换原有setup和loop部分的代码:

void setup()
{
    Serial.begin(115200);
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print("Connecting to Wi-Fi");
    while (WiFi.status() != WL_CONNECTED)
    {
        Serial.print(".");
        delay(300);
    }
    Serial.println();
    Serial.print("Connected with IP: ");
    Serial.println(WiFi.localIP());
    Serial.println();
    Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION);
    config.api_key = API_KEY;
    auth.user.email = USER_EMAIL;
    auth.user.password = USER_PASSWORD;
    config.token_status_callback = tokenStatusCallback;
    Firebase.begin(&config, &auth);
    Firebase.reconnectWiFi(true);
    pinMode(D1, OUTPUT); 
    Serial.println("Getting User UID");
    while ((auth.token.uid) == "") {
        Serial.print('.');
        delay(1000);
    }
    uid = auth.token.uid.c_str();
    Serial.print("User UID: ");
    Serial.println(uid);
    // 文档创建逻辑挪到setup,只执行一次,避免循环覆盖云端值
    FirebaseJson content;
    content.set("fields/pump/stringValue", firebaseStatus);
    path = "esp/"+uid;
    Serial.print("Create document if not exist... ");
    if (Firebase.Firestore.createDocument(&fbdo, FIREBASE_PROJECT_ID, "", path.c_str(), content.raw()))
        Serial.println("ok");
    else
        Serial.println(fbdo.errorReason());
}
          
void loop()
{      
    path = "esp/"+uid;
    String mask = "pump";
    Serial.print("Get a document... ");
    if (Firebase.Firestore.getDocument(&fbdo, FIREBASE_PROJECT_ID, "", path.c_str(), mask.c_str())){
        Serial.printf("ok\n%s\n\n", fbdo.payload().c_str());
        // 解析返回的JSON数据
        FirebaseJson docJson;
        docJson.setJsonData(fbdo.payload().c_str());
        FirebaseJsonData jsonData;
        docJson.get(jsonData, "fields/pump/stringValue");
        if(jsonData.success){
            String pumpStatus = jsonData.stringValue;
            if(pumpStatus == "on"){
              digitalWrite(D1, HIGH);
            }else if(pumpStatus == "off"){
              digitalWrite(D1, LOW);
            }
        }
    }else{
        Serial.println(fbdo.errorReason());
    } 
    // 加2秒延时,避免频繁请求Firestore触发限流
    delay(2000);
}

额外注意

如果修改后还是不工作,可以先测量D1引脚的电平变化,确认是代码逻辑问题还是硬件接线问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 08:15:04