在上一篇中我们主要了了解micro:bit的的服务特性,今天我们主要用micro:bit的几个特性来读取以及改写
在上篇我们已经将我们所需的UUID写入,接下来只要对代码进行小部分修改以及增添就行
首先我们要添加读写按钮 接着再添加读取型号函数,之后添加改变led的写函数。
读取micro:bit开发板的名称
function readModelNumber()
 {
 console.log(“readModelNumber”);
 if (!connected)
 {
 alert(“Error: Discover and connect to a device before using this function”);
 return
 }
 if (!services_discovered)
 {
 alert(“Error: Service discovery has not yet completed”);
 return
 }
 if (!has_device_information_service)
 {
 alert(“Error: The connected device does not contain the device information service”);
 return
 }
 if (!has_model_name_string)
 {
 alert(“Error: The connected device does not contain the model name string”);
 return;
 }
 model_number_string.readValue()
 .then(value => {
 data = new Uint8Array(value.buffer);
 model_number_string = new TextDecoder(“utf-8”).decode(data);
 console.log(model_number_string);
 document.getElementById(“model_number”).innerHTML =
 model_number_string;
 })
 .catch(error => {
 console.log(‘Error: ‘ + error);
 alert(‘Error: ‘ + error);
 return;
 });
 }
控制LED灯的亮灭
function randomLEDs()
 {
 console.log(“randomLEDs”);
 if (!connected)
 {
 alert(“Error: Discover and connect to a device before using this function”);
 return
 }
 if (!services_discovered)
 {
 alert(“Error: Service discovery has not yet completed”);
 return
 }
 if (!has_led_service)
 {
 alert(“Error: The connected device does not contain the LED service”);
 return
 }
 if (!has_led_matrix_state)
 {
 alert(“Error: The connected device does not contain the LED matrix state characteristic”);
 return;
 }
 var led_array = [0, 0, 0, 0, 0];
 led_array[0] = Math.floor(Math.random() * 32);
 led_array[1] = 1;
 led_array[2] = 2;
 led_array[3] = 3;
 led_array[4] = 4;
 var led_matrix_data = new Uint8Array(led_array);
 led_matrix_state.writeValue(led_matrix_data.buffer)
 .then(_ => {
 console.log(‘LED matrix state changed’);
 })
 .catch(error =>{
 console.log(‘Error ‘+ error);
 alert(‘Error: ‘ + error); return;
 });
 }
填加控制小灯和读取开发板名称的按钮
Reading and Writing
Write Charateristic - Randomise Lights
Read Charateristic - Model number
效果如下图:
当我们点击Read Model Number执行读取型号函数在下方显示型号
当我们点击Randomise LEDs执行改变led函数,板子上led灯发生改变
