WeMos D1 Connect to Firebase

ネットで検索すると、大抵はArduinoからFirebaseのAPIを叩くためのFirebaseArduinoというライブラリを利用する例が公開されている。しかしそのライブラリは、もう数年前からメンテナンス停止した。

試しにサンプルなど動かしてみたが、Firebaseに繋がらない。

色々と調べて、MobizTのライブラリを利用することで成功した。

https://github.com/mobizt/Firebase-ESP8266

いきなり参考リンクから本番プログラムを作ると動かないので、サンプルの Beginner_start_here をまずお試し。

https://github.com/mobizt/Firebase-ESP8266/tree/master/examples/Beginner_start_here

(誤り)API KEYを使う

(正しい)スークレドを使う

Firebaseから、LEDの色と明るさの制御はできた。

#include "FirebaseESP8266.h"
#include <ESP8266WiFi.h>
#include <Adafruit_NeoPixel.h>

#define PIN D1
#define NUM_LEDS 8

const char* ssid = "ssid003";
const char* password = "12345";

FirebaseData firebaseData;

Adafruit_NeoPixel leds(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);

// Current color values
int redValue = 0;
int greenValue = 0;
int blueValue = 0;

void setup() {
  Serial.begin(115200);
  connectWifi();
  leds.begin();
  
  Firebase.begin("https://test2-xxxxx-default-rtdb.firebaseio.com/", "9jBRxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxiCI");
}

void loop() {

  if (Firebase.getInt(firebaseData, "/red")) {
    if  (firebaseData.dataType() == "int") {
      int val = firebaseData.intData();
      if (val != redValue) {
        redValue = val;
         setLedColor();
      }
    }
  }

  if (Firebase.getInt(firebaseData, "/green")) {
    if  (firebaseData.dataType() == "int") {
      int val = firebaseData.intData();
      if (val != greenValue) {
        greenValue = val;
        setLedColor();
      }
    }
  }

  if (Firebase.getInt(firebaseData, "/blue")) {
    if  (firebaseData.dataType() == "int") {
      int val = firebaseData.intData();
      if (val != blueValue) {
        blueValue = val;
        setLedColor();
      }
    }
  }
}

void connectWifi() {
  // Let us connect to WiFi
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println(".......");
  Serial.println("WiFi Connected....IP Address:");
  Serial.println(WiFi.localIP());

}

void setLedColor() {
  Serial.printf("red=%d, green=%d, blue=%d\n", redValue, greenValue, blueValue);

  for (int i=0; i < NUM_LEDS; i++) 
    leds.setPixelColor(i, leds.Color(redValue, greenValue, blueValue));
  leds.show();
}

 

 

 

Ref:

https://www.survivingwithandroid.com/esp8266-firebase-realtime-database-iot-controlled-rgb-leds/

 

WeMos (e3) リレー制御

制御の試し

参考資料1そのまま。

/*
 * Relay Shield - Blink
 * Turns on the relay for two seconds, then off for two seconds, repeatedly.
 *
 * Relay Shield transistor closes relay when D1 is HIGH
 */

const int relayPin = D1;
const long interval = 2000;  // pause for two seconds

void setup() {
  pinMode(relayPin, OUTPUT);
}

void loop() {
  digitalWrite(relayPin, HIGH); // turn on relay with voltage HIGH
  delay(interval);              // pause
  digitalWrite(relayPin, LOW);  // turn off relay with voltage LOW
  delay(interval);              // pause
}

 

firebaseから制御

FAN_Onエントリーをみて、リレーを制御。

 

#include "Firebase_ESP_Client.h"
#include <ESP8266WiFi.h>

#define relayPin D1

#define FIREBASE_HOST "test2-***.firebaseio.com"                    // Enter the Firebase Database URL Without Https and backslash
#define API_KEY "AIzaSyDfl-s-7-**********"

FirebaseData fbdo;

FirebaseAuth auth;
FirebaseConfig config;

FirebaseJson json;

#define WIFI_SSID "SSID003"                     // Change the name of your WIFI
#define WIFI_PASSWORD "12345"                        // Change the password of your WIFI

#define USER_EMAIL "xxx@yyy.net"
#define USER_PASSWORD "12345"

void setup() {
  pinMode(relayPin, OUTPUT);
    
  Serial.begin(115200);
  Serial.println("Relay for FAN Test");

  WiFi.begin (WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) 
  {
   delay(500);
   Serial.print(".");
  }

  Serial.println ("");
  Serial.println ("WiFi Connected!");
  
  /* Assign the project host and api key (required) */
  config.host = FIREBASE_HOST;
  config.api_key = API_KEY;

  /* Assign the user sign in credentials */
  auth.user.email = USER_EMAIL;
  auth.user.password = USER_PASSWORD;

  Firebase.begin(&config, &auth);
  Firebase.reconnectWiFi(true);
}


void loop() {
String target;

//  if (Firebase.RTDB.getBool(&fbdo, "Thermostat/FAN_On")) {
//    target = fbdo.boolData();
  if (Firebase.RTDB.getString(&fbdo, "Thermostat/FAN_On")) {
    target = fbdo.stringData();
    Serial.println(target);
    Serial.println(fbdo.dataType());
    digitalWrite(relayPin, target.equals("true"));
  }
  else
  {
    Serial.println("FAILED");
    Serial.println("REASON: " + fbdo.errorReason());
    Serial.println("------------------------------------");
    Serial.println();
  }
  delay(500);
}

 

 

参考

  1. https://www.wemos.cc/en/latest/d1_mini_shield/relay.html — リレーの情報

Thunkableで管理App

画面デザイン

Speechのお試しプログラムに、Realtime_DBモジュールを追加した。

プログラム

Thunkableには、Cloud変数は、Realtime_DBに対応するので、Cloud変数の読み書きで、簡単にRealtime_DBのデータの読み書きができる。

 

WordPressとの連携(1)

WordPressにFirebaseデータの公開

Integrate Firebaseプラグイン

The Integrate Firebase Plugin will help a Firebase user to login to your WordPress interface – not to WordPress dashboard – from Firebase authentication. You can show user info display data that is only available to your Firebase users.

You also can view Real Time Database and Firestore from your Dashboard in Version 0.5.3

Integrate Firebaseプラグインは、FirebaseユーザーがFirebase認証からWordPressダッシュボードではなくWordPressインターフェースにログインするのに役立ちます。 Firebaseユーザーのみが利用できるユーザー情報表示データを表示できます。

バージョン0.5.3のダッシュボードからリアルタイムデータベースとFirestoreを表示することもできます

インストール

Integrate Firebaseを検索して、インストールしてください。

Firebase SDKの追加

https://console.firebase.google.com/ を開き、「Webアプリ」を追加する。

適当なアプリのニックネーム を入れて、アプリを登録する。

「Firebase SDK の追加」をクリックして、次の画面になる。

Firebaseのデータ

テストデータ:test.json ファイルを用意して、Firebaseにインポートしてください。

WordPressでデータを確認 

 

Raspberry Piとの連携

Raspberry Piからデータの送信

PCのPythonからFirebase Realtime Database成功、Raspberry Piからも同じ方法で可能

1. Python インストール

  1. MacBook : homebrewから
  2. Windows : Python 公式サイトから
  3. Raspberry Pi: do nothing

2. Frebase-adminをインストール

$ sudo apt-get -y install python3-pip
$ sudo pip3 install firebase-admin

3. service accountの認証ファイルをダウンロード

service account の認証ファイル .json をダウンロード

4. Firebase Realtime Databaseにアクセス

プログラムは、参考1からコピー

chen@Hongs-MacBook-Pro firebase % python3 firebase.py 

{‘user001’: {‘date_of_birth’: ‘June 23, 1984’, ‘full_name’: ‘Sazae Isono’}, ‘user002’: {‘date_of_birth’: ‘December 9, 1995’, ‘full_name’: ‘Tama Isono’}, ‘user003’: {‘date_of_birth’: ‘Aug 23, 1980’, ‘full_name’: ‘Masuo Isono’}}

chen@Hongs-MacBook-Pro firebase % 

参考:

  1. https://qiita.com/sai-san/items/24dbee74c5744033c330 — [python] Firebase Realtime Databaseのはじめ方 – Qiita

M5StickCからデータ送信

M5StickCからFirebaseへデータ送信。

M5StickC (4) Firebase
Arduinoを利用する

1. Setup Arduino IDE

Arduino IDEがまたインストールしてないの場合、つかうPCにより、下記の何れを参考にArduino IDEのインストールする。

2. USB-UARTドライバのインストール

Silicon Labsの以下のURLからドライバをダウンロード
USB – UART ブリッジ VCP ドライバ|Silicon Labs

3. Board ManagerにESP32追加

つい最近(20180728), ESP32 用 Arduino 開発環境 Arduino core for ESP32 WiFi chip の初の安定版 1.0.0 がリリース。インストールする際に, コマンドラインで色々する必要はなく Arduino IDE のメニューからインストールできるようになる。

Arduino-IDEを使ってWeMosにスケッチを書き込むには、こ ち らを参考にESP32用のAddOnを追加する必要がある。

  1.  [Arduino]-[環境設定]に、[ボードマネージャーURL]を追加
    https://dl.espressif.com/dl/package_esp32_index.json
  2. ボードマネージャーに、ESP32を検索して追加

4. ライブラリを管理にM5StickC

インストールが終わったらボードマネージャを閉じて、「スケッチ」->「ライブラリをインクルード」->「ライブラリを管理」。

5. HelloWorldプログラム

「ファイル」->「スケッチ例」->「M5StickC」->「Basics」->「HelloWorld」を書き込んでみます。
参考2の手順を参考する。

6. Blinkプログラム

参考1からソースコードを利用する。
#include <M5StickC.h>

#define BTN_A_PIN 37
#define BTN_B_PIN 39
#define LED_PIN   10

// このLEDは、GPIO10の電位を下げることで発光するタイプ
#define LED_ON  LOW
#define LED_OFF HIGH

// INPUT_PULLUPが有効かは不明だが、有効という前提で定義
#define BTN_ON  LOW
#define BTN_OFF HIGH

uint8_t prev_btn_a = BTN_OFF;
uint8_t btn_a      = BTN_OFF;
uint8_t prev_btn_b = BTN_OFF;
uint8_t btn_b      = BTN_OFF;

void setup() {
  // Initialize the M5StickC object
  M5.begin();
  pinMode(BTN_A_PIN, INPUT_PULLUP);
  pinMode(BTN_B_PIN, INPUT_PULLUP);
  pinMode(LED_PIN,   OUTPUT);
  digitalWrite(LED_PIN, LED_OFF);
  // LCD display
  M5.Lcd.setRotation(1); // ボタンBが上になるような向き
  M5.Lcd.setTextSize(2); // フォントサイズをデフォルトの2倍に
  M5.Lcd.print("BTN&LED Test.");
}

void loop() {
  btn_a = digitalRead(BTN_A_PIN);
  btn_b = digitalRead(BTN_B_PIN);

  if(prev_btn_a == BTN_OFF && btn_a == BTN_ON){
    // ボタンAが押されたとき。今回は1回発光
    digitalWrite(LED_PIN, LED_ON);
    delay(500);
    digitalWrite(LED_PIN, LED_OFF);
  }

  if(prev_btn_a == BTN_ON && btn_a == BTN_OFF){
    // ボタンAが離されたとき。今回は何もしない
    ;
  }

  if(prev_btn_b == BTN_OFF && btn_b == BTN_ON){
    // ボタンBが押されたとき。今回は2回点滅
    digitalWrite(LED_PIN, LED_ON);
    delay(500);
    digitalWrite(LED_PIN, LED_OFF);
    delay(500);
    digitalWrite(LED_PIN, LED_ON);
    delay(500);
    digitalWrite(LED_PIN, LED_OFF);
  }

  if(prev_btn_b == BTN_ON && btn_b == BTN_OFF){
    // ボタンBが離されたとき。今回は何もしない
    ;
  }

  prev_btn_a = btn_a;
  prev_btn_b = btn_b;
}

 

7. Firebaseに送信する

必要ライブラリ

  1. スケッチ – ライブラリを管理 – ライブラリをインクルードから、ArduinoJson 5.13.5をインストールする。
  2. もうひとつ、IOXhop_FirebaseESP32をインストールします。

参考3からソースコードを利用する。

#include <M5StickC.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#include <IOXhop_FirebaseESP32.h>
#include "ArduinoJson.h"
#define WIFI_SSID "WifiのSSIDをここに書いてね" // ①
#define WIFI_PASSWORD "Wifiのパスワードをここに書いてね"
#define FIREBASE_DB_URL "https://iot-sandbox-ea132.firebaseio.com/" // ②
WiFiMulti WiFiMulti;
int count = 1;  // ③
void setup() {
  M5.begin(); 
  M5.Lcd.setRotation(3);
  M5.Lcd.setCursor(0, 0, 2);
 WiFiMulti.addAP(WIFI_SSID,WIFI_PASSWORD);
  M5.Lcd.print("Connecting");
  while(WiFiMulti.run() != WL_CONNECTED) {
    M5.Lcd.print(".");
    delay(1000);
  }
  M5.Lcd.println("");
  M5.Lcd.println("Connected to");
  M5.Lcd.println(WiFi.localIP());
  delay(500);
  
  Firebase.begin(FIREBASE_DB_URL);   // ④
}
void loop() {
  M5.update();  // ⑤
  if (M5.BtnA.wasPressed() ) {  // ⑥
    M5.Lcd.println("Pushed");
    Firebase.setInt("/button", count);  // ⑦
    count ++;  // ⑧
  }
}

 

参考:

  1. https://make-muda.net/2019/09/6906/ ーーM5StickCであそぶ 〜ボタンとLEDを使う〜
  2. https://make-muda.net/2019/08/6891/ ーー M5StickCであそぶ 〜開発環境を構築する〜
  3. https://slanew.com/news/819 — M5StickCからFirebase Realtime Databaseに値を書き込んじゃうよ。

WeMos (e2) LED表示

IoT Study Kit 2のLEDは、FirebaseのLEDデータに従って表示。

プログラム1

単純に文字、パタンの表示。

3連ベースで、ESP8266, LED Matrix, SHT30を装着する。

 

 

Features

  • 8×8 dot matrix LED
  • 8 step adjustable intensity

Pins

D1 mini GPIO Shield
D5 14 CLK
D7 13 DIN

 

ライブラリから、WEMOS_Matrix_Adafruit_GFXを追加してください。

つぎは、ライブラリ付属のLED Matrix表示サンプルの修正版。

# コンパイルエラー発生した。

MLED matrix(7);  から

MLED matrix(7, D7, D5); に変更した。

 

#include <Adafruit_GFX.h>
#include <WEMOS_Matrix_GFX.h>

MLED matrix(7, D7, D5); //set intensity=7 (maximum)

void setup() {
  Serial.begin(9600);
  Serial.println("8x8 LED Matrix Test");
  
 
}

static const uint8_t PROGMEM
  smile_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10100101,
    B10011001,
    B01000010,
    B00111100 },
  neutral_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10111101,
    B10000001,
    B01000010,
    B00111100 },
  frown_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10011001,
    B10100101,
    B01000010,
    B00111100 };

void loop() {
  matrix.clear();
  matrix.drawBitmap(0, 0, smile_bmp, 8, 8, LED_ON);
  matrix.writeDisplay();
  delay(500);

  matrix.clear();
  matrix.drawBitmap(0, 0, neutral_bmp, 8, 8, LED_ON);
  matrix.writeDisplay();
  delay(500);

  matrix.clear();
  matrix.drawBitmap(0, 0, frown_bmp, 8, 8, LED_ON);
  matrix.writeDisplay();
  delay(500);

  matrix.clear();      // clear display
  matrix.drawPixel(0, 0, LED_ON);  
  matrix.writeDisplay();  // write the changes we just made to the display
  delay(500);

  matrix.clear();
  matrix.drawLine(0,0, 7,7, LED_ON);
  matrix.writeDisplay();  // write the changes we just made to the display
  delay(500);

  matrix.clear();
  matrix.drawRect(0,0, 8,8, LED_ON);
  matrix.fillRect(2,2, 4,4, LED_ON);
  matrix.writeDisplay();  // write the changes we just made to the display
  delay(500);

  matrix.clear();
  matrix.drawCircle(3,3, 3, LED_ON);
  matrix.writeDisplay();  // write the changes we just made to the display
  delay(500);

  matrix.setTextSize(1);
  matrix.setTextWrap(false);  // we dont want text to wrap so it scrolls nicely
  matrix.setTextColor(LED_ON);
  for (int8_t x=0; x>=-36; x--) {
    matrix.clear();
    matrix.setCursor(x,0);
    matrix.print("Hello");
    matrix.writeDisplay();
    delay(100);
  }
  matrix.setRotation(3);
  for (int8_t x=7; x>=-36; x--) {
    matrix.clear();
    matrix.setCursor(x,0);
    matrix.print("World");
    matrix.writeDisplay();
    delay(100);
  }
  matrix.setRotation(0);
}

 

プログラム2

Firebaseのデータ(/Speech) をLEDに表示する

Firebaseへのコンタクトは、MobizTのライブラリを利用することで成功した。

https://github.com/mobizt/Firebase-ESP8266

#include <Adafruit_GFX.h>
#include <WEMOS_Matrix_GFX.h>
#include "FirebaseESP8266.h"
#include <ESP8266WiFi.h>

MLED matrix(7, D7, D5); //set intensity=7 (maximum)

#define PIN D1
#define NUM_LEDS 8

const char* ssid = "ssid003";
const char* password = "12345";

FirebaseData firebaseData;

// Current color values
int redValue = 0;
int greenValue = 0;
int blueValue = 0;

void setup() {
  Serial.begin(115200);
  Serial.println("8x8 LED Matrix Test");

  connectWifi();
  
  Firebase.begin("https://test2.firebaseio.com/", "********4WxzwiCI");
}


void loop() {
String target;

  if (Firebase.getString(firebaseData, "/Speech")) {
    target = firebaseData.stringData();
    Serial.println(target);
    Serial.println(firebaseData.dataType());
    matrix.setTextSize(1);
    matrix.setTextWrap(false);  // we dont want text to wrap so it scrolls nicely
    matrix.setTextColor(LED_ON);
    for (int8_t x=0; x>=-56; x--) {
      matrix.clear();
      matrix.setCursor(x,0);
      matrix.print(target);
      matrix.writeDisplay();
      delay(100);
    }
  }
  else
  {
    Serial.println("FAILED");
    Serial.println("REASON: " + firebaseData.errorReason());
    Serial.println("------------------------------------");
    Serial.println();
  }
  delay(500);
}

void connectWifi() {
  // Let us connect to WiFi
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println(".......");
  Serial.println("WiFi Connected....IP Address:");
  Serial.println(WiFi.localIP());

}

 

 

WeMos (e1) 温度の送信

IoT Study Kit 2からFirebaseへ温度データの送信。

 

IoT Sensor

UbiSense Ver2を利用。

結線

プログラム1

3連ベースで、ESP8266, LED Matrix, SHT30を装着。温度と湿度を計測。

WEMOS_SHT3x_Arduino_Libraryを使用。

https://github.com/wemos/WEMOS_SHT3x_Arduino_Library

ただの温度と湿度の表示サンプル。

#include <WEMOS_SHT3X.h>

SHT3X sht30(0x45);

void setup() {

  Serial.begin(115200);

}

void loop() {

  if(sht30.get()==0){
    Serial.print("Temperature in Celsius : ");
    Serial.println(sht30.cTemp);
    Serial.print("Temperature in Fahrenheit : ");
    Serial.println(sht30.fTemp);
    Serial.print("Relative Humidity : ");
    Serial.println(sht30.humidity);
    Serial.println();
  }
  else
  {
    Serial.println("Error!");
  }
  delay(1000);

}

参考

  1. http://stigern.net/blog/using-wemos-d1-mini-sht30-sensor-shield/

プログラム2

検出した温度をFirebaseに送信。

#include "Firebase_ESP_Client.h"
#include  <ESP8266WiFi.h>

#define FIREBASE_HOST "test2-***.firebaseio.com"                    // Enter the Firebase Database URL Without Https and backslash
#define API_KEY "AIzaSyDfl-s-**** "

FirebaseData fbdo;

FirebaseAuth auth;
FirebaseConfig config;

FirebaseJson json;

#define WIFI_SSID "SSID003"                     // Change the name of your WIFI
#define WIFI_PASSWORD "12345"                        // Change the password of your WIFI

#define USER_EMAIL "xxx@yyy.net"
#define USER_PASSWORD "12345"

#include <WEMOS_SHT3X.h>
SHT3X sht30(0x45);

void setup() 
{
  Serial.begin(115200);
  WiFi.begin (WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) 
  {
   delay(500);
   Serial.print(".");
  }
  Serial.println ("");
  Serial.println ("WiFi Connected!");

  /* Assign the project host and api key (required) */
  config.host = FIREBASE_HOST;
  config.api_key = API_KEY;

  /* Assign the user sign in credentials */
  auth.user.email = USER_EMAIL;
  auth.user.password = USER_PASSWORD;

  Firebase.begin(&config, &auth);
  Firebase.reconnectWiFi(true);
}

void loop() 
{
 float h =0;
 float t = 0;         // Reading temperature as Celsius (the default)

  if(sht30.get()==0){
    t = sht30.cTemp;
    h = sht30.humidity;
    Serial.print("Temperature in Celsius : ");
    Serial.println(sht30.cTemp);
    Serial.print("Temperature in Fahrenheit : ");
    Serial.println(sht30.fTemp);
    Serial.print("Relative Humidity : ");
    Serial.println(sht30.humidity);
    Serial.println();
  }
  else
  {
    Serial.println("SHT30 Error!");
  }

  
  Firebase.RTDB.setFloat (&fbdo, "Temperature",t);
  Serial.println(t);
  Firebase.RTDB.setFloat (&fbdo, "Humidity",h);
  Serial.println(h);
  delay(200);
}

 

Firebaseアカウント作成

Firebaseアカウント

「Firebase」は、2011年にシリコンバレー発のスタートアップ・Firebase社がサービスを開始したMobile Backend as a Service(MBaas)です。その後、2014年にGoogleが買収し、Googleの持つクラウドプラットフォームに統合されました。

MBaasはBaaS(Backend as a Service)とも呼ばれており、クラウドデータベースでけではなく、Webアプリケーションやモバイルアプリケーションのバックエンドで行う機能を提供するクラウドサービスです。「Firebase」はアプリ開発者向けのサービスで、バックエンドの処理を代行することで開発にかかる時間・手間の省略が可能で、コスト節約にもつながります。

1)使ってみるをクリック

Create your free Firebase project and account
無料 Firebase アカウント作成

image

2)プロジェクト追加をクリック

 

 

3)プロジェクト名と国を選択

4)データベース作成中

5)作成するアプリ種類の選択

 

スクリーンショット 2018-06-20 22.46.48.png

「ウェブアプリに Firebase を追加」を選択すると。

apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",     
authDomain: "chen420.firebaseapp.com",     
databaseURL: "https://chen420.firebaseio.com",

上記のapiKeyが表示される。