html获取蓝牙设备,Web Bluetooth 读写蓝牙串口

本文介绍了如何在HTML页面中通过Web Bluetooth API获取并连接蓝牙设备,进行串口读写操作。首先,通过navigator.bluetooth.requestDevice获取设备,并在用户触发的事件中执行。接着,连接设备,获取服务和特性,监听特性值变化并发送数据。同时,文章还提到了在Node.js中使用Express创建服务器来配合Web应用。需要注意的是,虽然MDN建议在HTTPS环境下使用Web Bluetooth,但Chrome 87开始也支持HTTP环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HTML 定义触发按钮

www/index.html

Web Bluetooth

Send And Receive!

navigator.bluetooth.requestDevice 必须在某个用户触发的回调内执行,例如在 button 元素的 onclick 事件中调用。在其它环境下调用将产生错误:

Must be handling a user gesture to show a permission request

JS 操作 Web Bluetooth

www/js/web-bluetooth.js

async function sendAndReceive() {

let device = await navigator.bluetooth.requestDevice({

filters: [

{services: [0xffe0]},

]

});

let server = await device.gatt.connect();

let service = await server.getPrimaryService(0xffe0);

let characteristic = await service.getCharacteristic(0xffe1);

characteristic.addEventListener(

'characteristicvaluechanged', e => {

console.log(e.target.value);

}

);

characteristic.startNotifications();

await characte

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值