---
# System prepended metadata

title: Untitled

---

```
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title></title>
<script>

const UUID_UART_SERVICE = '6e400001-b5a3-f393-e0a9-e50e24dcca9e'
const UUID_TX_CHAR_CHARACTERISTIC = '6e400002-b5a3-f393-e0a9-e50e24dcca9e'
const UUID_RX_CHAR_CHARACTERISTIC = '6e400003-b5a3-f393-e0a9-e50e24dcca9e'
var targetDevice;
let tx = null
let rx = null
var arrayData=[];

/// 接続
async function getMicrobit() {
  ///constは書き換えを禁止した変数を宣言するところ→１回決めたら変えれない
  /// デバイスのスキャン
  ///promise構文

  const device = await navigator.bluetooth.requestDevice({
    filters: [
        { services: [UUID_UART_SERVICE] },
        { namePrefix: 'BBC micro:bit' }
    ]
  })
  /// GATT接続
    targetDevice = device;
    const server=await device.gatt.connect();
    const service=await server.getPrimaryService(UUID_UART_SERVICE);
    const characteristics=await Promise.all([
            service.getCharacteristic(UUID_TX_CHAR_CHARACTERISTIC),
            service.getCharacteristic(UUID_RX_CHAR_CHARACTERISTIC)])
     tx = characteristics[0];
     rx = characteristics[1];
     await tx.startNotifications();
     await tx.addEventListener('characteristicvaluechanged', event=>{
         var uint8=[];
         uint8=DataView.prototype.getUint8(tx.value);//txのuint8配列要素を取り出したい
         console.log(uint8);
          arrayData = arrayData.concat(uint8);
          console.log(arrayData);
          //const text = new TextDecoder().decode(tx.value);
          //document.getElementById('getMessage').value = document.getElementById('getMessage').value+text;

    })


}



/// 切断
function disconnect() {

  if (!targetDevice.gatt.connected){
    return;
  }
  targetDevice.gatt.disconnect();
  alert("切断しました。");

}


//データを送る
async function sendData(){
  var startTime = performance.now();
  const text=document.getElementById("sendText").value;
  const uint8=new TextEncoder().encode(text);
  for(let i=0;i<uint8.length;i+=19){
    await rx.writeValue(uint8.subarray(i, i+19)); //UTF-8を返してpromiseを返す
    console.log(uint8.subarray(i, i+19));
  }
  var endTime = performance.now();
  console.log(endTime-startTime);
}


//テキストエリアのリセット
function textClear(){
  document.getElementById("getMessage").value="";
  document.getElementById("sendText").value="";
  var arrayData=[];
}

</script>
</head>
<body>
<div >
  <div id="BLE_button">
    <input type="button" value="micro:bitと接続する" onclick="getMicrobit();"/>
    <input type="button" value="切断する" onclick="disconnect();"/>
    <textarea id ="sendText"  name="text" rows="20" cols="40" ></textarea>
    <input type="button"  value="送信する" onclick="sendData();"/>
    <textarea id="getMessage" name="name" rows="20" cols="40"></textarea>
    <input type="button"  value="クリア" onclick="textClear();">
  </div>
</div>
</body>
</html>

```