Using Web Serial API to realize serial communication between Vue and microcontroller

1. Introduction to Web Serial API

        The Web Serial API is a web technology for accessing and communicating with serial port devices (such as Arduino, sensors, etc.) in a browser. It provides a set of JavaScript interfaces, so that Web applications can connect to hardware devices through USB serial ports, and perform data sending and receiving operations.

2. Software environment introduction

        Browser version: Google Chrome version 113.0.5672.127

        Node.js version: Node.js v16.9.1

        Vue scaffolding version: @vue/cli 5.0.8

        Vue version: vue: 3.2.13

        Element-plus version: element-plus: 2.3.5

3. Introduction to Web Serial API interface functions

        The Web Serial API provides some interface functions for accessing and communicating with serial port devices in a browser. The following are commonly used Web Serial API interface functions:

  1. navigator.serial.requestPort () : pops up a selection dialog box, allowing the user to select a serial port device .

  2. port.open(baudrate): Open the specified serial port with the specified baudrate.

  3. port.write(data): Write data to an open serial port.

  4. port.readable.getReader(): Get a readable stream.

  5. reader.read(): Read data from the serial port.

  6. reader.cancel(): cancel the current read operation.

  7. port.close(): closes an open serial port.

4. Function realization

4.1 Determine whether the current browser supports the API

/* 
生命周期函数
当挂载完成之后,对浏览器是否支持本网页进行检查
*/
onMounted(() => {
    if ("serial" in navigator) {
    } else {
        ElNotification({
            title: '浏览器版本低',
            message: '您的浏览器版本太低,可能不支持浏览器串口的使用',
            type: 'error',
            duration: 20000
        })
    }
})

4.2 Select serial port

Response function of button click

// 选择串口
const chooseSerial = async () => {
    // 提示用户选择一个串口
    try {
        port.value = await navigator.serial.requestPort();
        console.log(port.value);
    } catch (error) {
        // 错误提示弹窗
        ElNotification({title: '选择串口失败',message: '错误信息:' + error,type: 'warning',duration: 2000})
        return;
    }
    ElNotification({title: '选择串口成功',message: '打开串口接收信息',type: 'success',duration: 2000})
}

4.3 Serial configuration information

// 串口配置
const port = ref(null)
const reader = ref(null)
const message = ref(null)
const connected = ref(null)
const serialOptions = {
    baudRate: 9600,
    flowControl: 'none',
    dataBits: 8
};

4.4 Open the serial port to receive information

// 2.打开串口
const openSerial = async () => {
    try {
        await port.value.open(serialOptions)
        reader.value = port.value.readable.getReader()
        connected.value = true
    } catch (error) {
        ElNotification({title: '打开串口失败',message: error,type: 'warning',duration: 2000})
        return;
    }
    ElNotification({title: '打开串口成功',message: '串口等待接收信息中',type: 'success',duration: 2000})
    readLoop()
}
// readLoop()串口读取函数
async function readLoop() {
    try {
        while (connected.value) {
            const { value, done } = await reader.value.read()
            if (done) {
                reader.value.releaseLock()
                break
            }
            message.value = new TextDecoder().decode(value)
        }
    } catch (error) {
        ElNotification({title: '读取串口失败',message: `串口读取信息失败:${error}`,type: 'error',duration: 2000})
    }
}

4.5 Close the serial port

// 3.关闭串口
const closeSerial = async () => {
    try {
        await reader.value.cancel()
        await port.value.close()
        connected.value = false
    } catch (error) {
        ElNotification({title: '关闭串口失败',message: '请检查后重新关闭串口',type: 'warning',duration: 2000})
        return;
    }
    ElNotification({title: '关闭串口成功',message: `已关闭串口:${port.value.name}`,type: 'success',duration: 2000})
}

4.6 Realize the effect

         The function is perfectly realized, you can select the serial port, open the serial port, receive information, and close the serial port after not in use. The fly in the ointment is that the function of serial port configuration has not been realized, and there can only be as many codes as there are written.

Five, complete code

        Link: Click to enter 
        the extraction code: ea9d
        

Guess you like

Origin blog.csdn.net/Stanford_sun/article/details/131016379