<!DOCTYPE HTML> <html lang="ja"> <head> <meta charset="UTF-8"> <title>BLE Notify</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <h1>BLE Notify</h1> <p>Micro:bitに接続完了後、1秒間隔で温度を表示します。</p> <hr> <p><button type="button" id="connect">接続</button> <span id="msg"> </span></p> <div id="BLE_display"> <p>温度:<span id="temperature">取得温度を表示します。</span></p> <script> uuid1 = 'e95d6100-251d-470a-a062-fa1922dfa9a8' //TEMPERATURE_SERVICE uuid2 = 'e95d9250-251d-470a-a062-fa1922dfa9a8' //TEMPERATURE_SERVICE_CHARACTERISTIC_DATA uuid3 = 'e95d1b25-251d-470a-a062-fa1922dfa9a8' //TEMPERATURE_SERVICE_CHARACTERISTIC_PERIOD const INTERVAL = 1000 ; // 取得間隔(ミリ秒) document.getElementById('connect').addEventListener('click', function(e){ if (document.getElementById('connect').textContent == '接続') { start() ; } else { bluetoothDevice.gatt.disconnect() ; update(false) ; } }) function start() { navigator.bluetooth.requestDevice({ filters: [ { namePrefix: "BBC micro:bit" } ], optionalServices: [uuid1] }) .then(device => { bluetoothDevice = device; return device.gatt.connect(); }) .then(server => { server.getPrimaryService(uuid1) /// 温度の取得 .then(service => { /// 温度の取得間隔の設定 service.getCharacteristic(uuid3) .then(characteristic => { characteristic.writeValue(new Uint16Array([INTERVAL])); }) .catch(error => { msg.innerHTML = (error) ; }) /// 温度の取得開始 service.getCharacteristic(uuid2) .then(characteristic => { characteristic.startNotifications() .then(char => { characteristic.addEventListener('characteristicvaluechanged',onTemperatureChanged); update(true) ; }) }) .catch(error => { msg.innerHTML = (error); }) }) }) .catch(error => { msg.innerHTML = (error) ; }) ; /// 温度の表示 function onTemperatureChanged (event) { let temperature = event.target.value.getUint8(0, true); document.getElementById("temperature").innerText = temperature + '℃'; } } function update(connected) { connect.textContent = connected ? '切断' : '接続' msg.innerHTML = connected ? 'BLE connected' : 'BLE disconnected' //send.disabled = !connected ; } </script> </body> </html>