# **ゼミナールB** ### 前回までにできたこと Micro:bitの温度センサーの結果を、Webページに表示できた ### **今回の目標** 温度センサーのプログラムを書き換えることで、プログラムへの理解を深める ### プログラムを書き換える 奥居先生がslackにあげたLEDとサイコロのコードを参考にasync/awaitを使って、前回のプログラムの簡略化を行った 参考資料 ・[【JavaScript入門】5分で理解!async / awaitの使い方と非同期処理の書き方](https://www.sejuku.net/blog/69618) ・[サイコロの簡単な例でPromiseを理解する](https://hackmd.io/@okuisatoshi/dice-and-promise) ### 書き換えたプログラム Micro:bitのコードは変更なし ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Web Bluetooth機能で温度を取得する</title> </head> <body> <button onclick="scan()">スキャン</button> <button onclick="connect()">接続</button> <button onclick="getTemp()">温度取得</button> <button onclick="disconnect()">切断</button> <p>温度:<span id="temperature">micro:bitと接続して、温度を取得してください。</span></p> <script> const UUID_TEMPERATURE_SERVICE = 'e95d6100-251d-470a-a062-fa1922dfa9a8' const UUID_TEMPERATURE_SERVICE_CHARACTERISTIC_DATA = 'e95d9250-251d-470a-a062-fa1922dfa9a8' const UUID_TEMPERATURE_SERVICE_CHARACTERISTIC_PERIOD = 'e95d1b25-251d-470a-a062-fa1922dfa9a8' const INTERVAL = 1000 let device = null; let service = null; let char_ = null; let char_period = null; async function scan() { device = await navigator.bluetooth.requestDevice({ filters: [ { namePrefix: "BBC micro:bit" } ], optionalServices: [UUID_TEMPERATURE_SERVICE] }) } async function connect() { const server = await device.gatt.connect(); alert('接続しました。'); service = await server.getPrimaryService(UUID_TEMPERATURE_SERVICE); char = await service.getCharacteristic(UUID_TEMPERATURE_SERVICE_CHARACTERISTIC_DATA); char_period = await service.getCharacteristic(UUID_TEMPERATURE_SERVICE_CHARACTERISTIC_PERIOD); } async function getTemp() { await char_period.writeValue(new Uint16Array([INTERVAL])); await char.startNotifications(); char.addEventListener('characteristicvaluechanged',onTemperatureChanged); } function onTemperatureChanged (event) { let temperature = event.target.value.getUint8(0, true); document.getElementById("temperature").innerText = temperature + '℃'; } function disconnect() { if (!device || !device.gatt.connected) return; device.gatt.disconnect(); alert("切断しました。"); } </script> </body> </html> ``` ### 結果 変更前のプログラムと同じように動くことが確認できた また、サヌキのプログラムでは「then」を使用していたが、「async/await」を使用した方が簡単で、プログラムの流れを理解しやすいと感じた ### 次回の目標 温度センサー以外の機能も使うWebページを作成することで、プログラムへの理解を深める
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up