<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>BLE UART read</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <h1>BLE UART read</h1> <p>Micro:bitに接続完了後、ボタンA・B、タッチセンサーを操作してください。 ボタン・タッチセンサーの情報を取得します。</p> <hr> <p><button type="button" id="connect">接続</button> <span id="msg"></span></p> <textarea id="dsp" rows="5" cols="30"></textarea><br> <p><button type="button" id="clear">クリア</button></p> <script> uuid1 ='6e400001-b5a3-f393-e0a9-e50e24dcca9e';//["UART_SERVICE"] uuid2 ='6e400002-b5a3-f393-e0a9-e50e24dcca9e';//["UART_SERVICE_CHARACTERISTICS"] 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 => { msg.innerHTML = "BLE connected" ; characteristic=chara; characteristic.startNotifications(); characteristic.addEventListener('characteristicvaluechanged',onCharacteristicValueChanged); update(true) ; }) .catch(error => { msg.innerHTML = "BLE error" ; }); } else { bluetoothDevice.gatt.disconnect() ; update(false) ; } }) function onCharacteristicValueChanged(e) { var str_arr=[]; for(var i=0;i<this.value.byteLength;i++){ str_arr[i]=this.value.getUint8(i); } var str=String.fromCharCode.apply(null,str_arr); 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>