登录
首页 >  文章 >  前端

WebUSB与Arduino连接教程

时间:2025-11-04 08:21:51 171浏览 收藏

小伙伴们对文章编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《WebUSB与Arduino通信教程》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

WebUSB API使浏览器能直接与Arduino通信,用户需授权连接,通过指定vendorId请求设备,打开并配置CDC接口,利用transferOut和transferIn实现数据收发,简化了Web与物理设备交互流程。

如何用WebUSB API与Arduino等微控制器通信?

WebUSB API提供了一种在浏览器中直接与Arduino等微控制器进行通信的强大方式,它让网页能够发现、连接并交换数据,无需安装额外驱动或桌面应用,极大地简化了设备交互的门槛,为Web应用打开了通往物理世界的大门。

解决方案

要让WebUSB与Arduino对话,这可不是点一下按钮那么简单,它涉及硬件固件和Web应用两端的协作,并且需要一套清晰的步骤。

首先,你的Arduino微控制器得准备好。大多数Arduino板子默认通过USB暴露一个CDC(Communication Device Class)串行接口。你只需要在Arduino草图中像往常一样使用Serial.begin()Serial.print()Serial.read()函数即可。如果用的是非标准板或自定义固件,确保它能正确地作为USB串行设备被识别。

接着,我们来看Web端的实现,这通常是一个异步操作序列:

  1. 请求设备: 出于安全考量,浏览器不会让你随意连接任何USB设备。用户必须通过一个弹窗明确授权。你用navigator.usb.requestDevice()来发起这个请求,并提供filters来指定你想要连接的设备类型,比如通过vendorId(厂商ID)和productId(产品ID)。Arduino Uno的厂商ID通常是0x2341

    async function connectDevice() {
        try {
            const device = await navigator.usb.requestDevice({
                filters: [{ vendorId: 0x2341 }] // 示例:Arduino的VID
            });
            console.log("已连接设备:", device.productName);
            // 接下来就可以打开并配置设备了
            return device;
        } catch (error) {
            console.error("连接失败:", error);
        }
    }
  2. 打开并配置设备: 拿到device对象后,你需要打开它,选择一个配置,然后声明(claim)它提供串行通信的接口。USB设备可能有多个配置和接口,你需要找到那个用于CDC(通常是串行通信)的接口。

    async function setupArduinoConnection(device) {
        await device.open(); // 打开设备
        if (device.configuration === null) {
            await device.selectConfiguration(1); // 选择一个配置,通常是1
        }
    
        // 寻找CDC数据接口,interfaceClass 0x0A 通常代表CDC数据
        const cdcInterface = device.configuration.interfaces.find(i =>
            i.alternates.some(alt => alt.interfaceClass === 0x0A)
        );
    
        if (!cdcInterface) {
            throw new Error("未找到CDC接口。");
        }
    
        await device.claimInterface(cdcInterface.interfaceNumber); // 声明接口
    
        // 找到输入和输出端点
        const alternate = cdcInterface.alternates[0]; // 假设使用第一个备用设置
        const endpointIn = alternate.endpoints.find(e => e.direction === 'in');
        const endpointOut = alternate.endpoints.find(e => e.direction === 'out');
    
        if (!endpointIn || !endpointOut) {
            throw new Error("未找到输入或输出端点。");
        }
    
        console.log("设备接口已声明,端点已识别。");
        return { device, endpointIn, endpointOut, interfaceNumber: cdcInterface.interfaceNumber };
    }
  3. 数据传输: 现在可以进行数据读写了。发送数据用device.transferOut(),接收数据用device.transferIn()。记住,WebUSB处理的是ArrayBufferDataView格式的二进制数据,所以你需要进行字符串和二进制数据的转换。

    写入数据:

    async function writeToArduino(device, endpointOut, dataString) {
        const encoder = new TextEncoder(); // 默认UTF-8编码
        const dataBuffer = encoder.encode(dataString);
        await device.transferOut(endpointOut.endpointNumber, dataBuffer);
        console.log("数据已发送:", dataString);
    }

    读取数据: 读取通常需要一个循环来持续监听。

    let isReading = false;
    async function readFromArduino(device, endpointIn, callback) {
        isReading = true;
        const decoder = new TextDecoder(); // 默认UTF-8解码
        while (device.opened && isReading) {
            try {
                const result = await device.transferIn(endpointIn.endpointNumber, 64); // 读取最多64字节
                if (result.data && result.data.byteLength > 0) {
                    const receivedData = decoder.decode(result.data);
                    callback(receivedData);
                }
            } catch (error) {
                if (error.message.includes("The device was disconnected")) {
                    console.log("设备在读取时断开。");

终于介绍完啦!小伙伴们,这篇关于《WebUSB与Arduino连接教程》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>