2021年1月26日火曜日

micro:bitのBluetoothアドバタイズを使う

micro:bitで音を検出して通知するプログラム

 BBCのmicro:bit v2を入手したので、ちょっとためしてみた。作成したのは、Bluetoothをつかっで通知を送るもの。micro:bit v2にあるマイクで音を拾い、閾値以上であれば、「Bluetooth UIDをアドバタイズ」を実行する。これは、実は、EddyStone Beaconになっている。Windows10には、EddyStone Beaconを受信する機能がないので、別途作成した。「Windows10でEddyStone Beaconを受信する その1」を参照してほしい。

 List01が、上記のBeaconを送信するmicro:bit v2のプログラムのJavaScriptソースである。

List01
input.onButtonPressed(Button.A, function () {
    閾値 += 8
    if (閾値 >= 255) {
        閾値 = 255
    }
    input.setSoundThreshold(SoundThreshold.Loud, 閾値)
    bluetooth.advertiseUid(
    name_space,
    閾値,
    7,
    false
    )
    basic.showArrow(ArrowNames.North)
    basic.showNumber(Math.round(Math.map(閾値, 0, 255, 0, 9)))
    basic.pause(BeaconCycle)
    basic.clearScreen()
    bluetooth.stopAdvertising()
})
input.onLogoEvent(TouchButtonEvent.Pressed, function () {
    閾値 = 128
    input.setSoundThreshold(SoundThreshold.Loud, 閾値)
    bluetooth.advertiseUid(
    name_space,
    閾値,
    7,
    false
    )
    basic.showArrow(ArrowNames.East)
    basic.showNumber(Math.round(Math.map(閾値, 0, 255, 0, 9)))
    basic.pause(BeaconCycle)
    basic.clearScreen()
    bluetooth.stopAdvertising()
})
input.onSound(DetectedSound.Loud, function () {
    音 = input.soundLevel()
    Event_Time = input.runningTime()
    basic.showNumber(Math.round(Math.map(音, 0, 255, 0, 9)))
})
input.onButtonPressed(Button.B, function () {
    閾値 += -8
    if (閾値 <= 0) {
        閾値 = 0
    }
    input.setSoundThreshold(SoundThreshold.Loud, 閾値)
    bluetooth.advertiseUid(
    name_space,
    閾値,
    7,
    false
    )
    basic.showArrow(ArrowNames.South)
    basic.showNumber(Math.round(Math.map(閾値, 0, 255, 0, 9)))
    basic.pause(BeaconCycle)
    basic.clearScreen()
    bluetooth.stopAdvertising()
})
let 音 = 0
let Event_Time = 0
let BeaconCycle = 0
let name_space = 0
let 閾値 = 0
bluetooth.setTransmitPower(7)
閾値 = 128
let Instance = 0
name_space = 2155971203
BeaconCycle = 2000
Event_Time = input.runningTime()
input.setSoundThreshold(SoundThreshold.Loud, 閾値)
basic.showIcon(IconNames.Yes)
bluetooth.advertiseUid(
name_space,
Event_Time * 65536 + 65535,
7,
false
)
basic.pause(BeaconCycle)
bluetooth.stopAdvertising()
basic.forever(function () {
    if (音 > 0) {
        bluetooth.advertiseUid(
        name_space,
        Event_Time * 65536 + 音,
        7,
        false
        )
        if (Event_Time + BeaconCycle < input.runningTime()) {
            音 = 0
            bluetooth.stopAdvertising()
            basic.clearScreen()
        }
    }
})

 上記プログラムをmicro:bit v2で動作させると、音が鳴ったときに、Bluetooth UIDをアドバタイズが実行されるが、これは、EddyStoneというBeaconそのものだ。micro:bitの左右のボタンで音の閾値を上下でき、中央上のタッチボタンで閾値をデフォルト値(128)に戻す。音を検出したり、閾値を変更したときには、LEDで表示を行うようになっているほか、閾値の変更もBluetooth UIDアドバタイズで通知するようになっている。

0 件のコメント:

コメントを投稿