📜  带有NodeMCU的IoT Google Firebase控制LED

📅  最后修改于: 2021-01-04 01:04:59             🧑  作者: Mango

物联网(IoT)项目:Google Firebase通过NodeMCU控制LED

在本节中,我们将使用Firebase数据库通过NodeMCU控制LED。在该项目的上一部分中,我们介绍了如何使用NodeMCU ESP8266的Google Firebase,以及如何在Firebase上创建项目以及如何使用NodeMCU进行配置。建议您先阅读本教程,然后再进行本项目。

一个使用Google Firebase数据库和NodeMCU控制LED(ON / OFF)的程序

打开之前的代码并进行一些更改:添加引脚连接,设置Firebase状态。

#include 
#include 
#include 
#include 
#include 
#include 

//
// Copyright 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

// FirebaseDemo_ESP8266 is a sample that demo the different functions
// of the FirebaseArduino API.

#include 
#include 

// Set these to run example.
#define FIREBASE_HOST "nodemcu-demo-697d8.firebaseio.com"
#define FIREBASE_AUTH "YOUR_FIREBASE_AUTH"
#define WIFI_SSID "NETGEAR64"
#define WIFI_PASSWORD "*JAVATPOINT#"

void setup() {
  Serial.begin(9600);

  // connect to wifi.
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("connected: ");
  Serial.println(WiFi.localIP());
  
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  pinMode(D1,OUTPUT);
  Firebase.set("LED_STATUS",0);
}

int n = 0;

void loop() {
  // set value
  n=Firebase.getInt("LED_STATUS");
  // handle error
  if (n==1) {
      Serial.print("LED is ON");
      digitalWrite(D1,HIGH);
      Serial.println(Firebase.error());  
      return;
       delay(100);
  }
 else{
   Serial.print("LED is OFF");
   digitalWrite(D1,LOW);
 }
  
  // update value
  
}

编译并将代码上传到NodeMCU ESP8266。打开串行监视器并查看状态,其当前状态为0,并且LED熄灭。

在数据库中,我们获得了LED_STATUS:0且LED已熄灭。


现在,手动将led状态更改为1,它会点亮LED。