<!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に接続完了後、加速センサーの情報をリアルタイムに表示します。</p> <hr> <p><button type="button" id="connect">接続</button> <span id="msg"> </span></p> <textarea id="dsp" rows="5" cols="30"></textarea> <p><button type="button" id="clear">クリア</button></p> <script> var bluetoothDevice; uuid1 ='e95d0753-251d-470a-a062-fa1922dfa9a8' uuid2 ='e95dca4b-251d-470a-a062-fa1922dfa9a8' document.getElementById('connect').addEventListener('click', function(e){ if (document.getElementById('connect').textContent == '接続') { navigator.bluetooth.requestDevice({ filters: [{ namePrefix: 'BBC micro:bit', }],optionalServices: [uuid1] }) .then(device => { bluetoothDevice=device; return device.gatt.connect(); }) .then(server => { return server.getPrimaryService(uuid1); }) .then(service => { return service.getCharacteristic(uuid2);}) .then(chara => { characteristic=chara; characteristic.startNotifications(); characteristic.addEventListener('characteristicvaluechanged', accelerometerChanged) update(true) ; }) .catch(error => { msg.innerHTML = (error) ; }); } else { bluetoothDevice.gatt.disconnect() ; update(false) ; } }) function accelerometerChanged(event) { x = event.target.value.getInt16(0, true) ; y = event.target.value.getInt16(2, true) ; z = event.target.value.getInt16(4, true) ; str ="x:"+ x + "y:"+y +"z:"+ z ; dsp.value = str + "\n" + dsp.value ; } function update(connected) { connect.textContent = connected ? '切断' : '接続' msg.innerHTML = connected ? 'BLE connected' : 'BLE disconnected' //send.disabled = !connected ; } clear.addEventListener('click', function(e) { dsp.value = '' ; }) </script> </body> </html>