6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

obniz+距離センサー+MP3モジュールでAmazon Echoを起動させる

Last updated at Posted at 2019-04-16

Amazon Echo買ったらやっぱり音声受付システム作りたいですよね?
そして、センサー使って自動でスキル起動させたいですよね?

ということで、周回遅れのネタですが、以下の記事にインスパイアされて、obnizでやってみました

使ったもの

IMG_2067.JPG
※配線汚くてごめんなさい

動画

alexaとgoogle homeでAPL対応音声受付システムをvoiceflowで作ってみた+距離センサーによるスキル自動起動付き

コード

50cmの距離で5秒間というのが基準です。配線はコードを参照してください。

とりあえず手元のMacで動かしてます。そのうちRPi Zero Wに移す予定。

ロジックはM5Stackと超音波距離センサーでAmazon Echoを起動させるを大いに参考にさせてもらいました。ありがとうこざいます。

$ npm init
$ npm install obniz —-save
index.js
var Obniz = require("obniz");
var obniz = new Obniz("OBNIZ_ID_HERE");

const DISTANCE = 500; 
const DETECT_COUNT = 5;

obniz.onconnect = async function () {

  // mp3初期化
  const mp3 = obniz.wired("Grove_MP3", { gnd: 5, vcc: 6, mp3_rx: 7, mp3_tx: 8 });
  await mp3.initWait();

  // 距離センサー初期化
  const hcsr04 = obniz.wired("HC-SR04", {gnd:0, echo:1, trigger:2, vcc:3});
  hcsr04.temp = 20;

  let sayFlg = false;
  let count = 0;

  // ループ
  while(true) {

    let avg = 0;
    let cnt = 0;

    for (let i=0; i<3; i++) { // measure three time. and calculate average
      const val = await hcsr04.measureWait();
      if (val) {
        cnt++;
        avg += val;
      }
    }
    if (cnt > 1) {
      avg /= cnt;
    }

    if (!sayFlg) {
      if (avg < DISTANCE) {
        count++;
        if (count >= DETECT_COUNT) {
          sayFlg = true;
          count = 0;
          await mp3.play(1);
        }
      } else {
        count = 0;
      }
    } else {
      if (avg > DISTANCE) {
        count++;
        if (count >= DETECT_COUNT) {
          sayFlg = false;
          count = 0;
        }
      } else {
        count = 0;
      }
    }

    console.log("----------------")
    console.log(`DISTANCE: ${avg}`);
    console.log(`COUNT: ${count}`);
    console.log(`SAYFLG: ${sayFlg}`);

    await obniz.wait(1000);
  }
}

実行

$ node index.js
DISTANCE: 307.03373200276
COUNT: 0
SAYFLG: true
----------------
DISTANCE: 308.4072286603679
COUNT: 0
SAYFLG: true
・・・

Alexaスキルはこの話の本質ではないので割愛します。詳細は以下をご覧ください。

その他

  • Amazon Echoを起動するための音声はAmazon Pollyで作りました。
  • 思いのほかスピーカーからの音声が小さかったので、ffmpegでmp3ファイルの音量を上げてます。
  • 距離センサーの精度は少し微妙ですが、こんなものなのかなという印象です。

まとめ

Alexaスキルと同じNode.jsで書けるので違うこと覚えなくて良いですし(とはいいつつ今回はノンコーディングで作ったスキルですが)、公式にサンプルコードもたくさんあるので、私のような見よう見まねでコード書いてるレベルだと非常に助かります。

他のセンサーとかもそのうち試してみたいと思います。

6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?