Home  >  Article  >  Backend Development  >  How to Read Data from a Serial Port Non-Blockingly in Go?

How to Read Data from a Serial Port Non-Blockingly in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 18:38:30940browse

How to Read Data from a Serial Port Non-Blockingly in Go?

Non-Blocking Serial Port Reading Using a While-Loop

In this program, the goal is to communicate with a sensor via a serial port while avoiding the use of time.Sleep for reading data. Unfortunately, the initial attempt using a while-loop failed due to overwriting the data buffer with each loop iteration.

The solution lies in implementing a byte-oriented reading approach, spearheaded by the introduction of bufio.Reader. This stream-oriented reader provides a more sophisticated and robust mechanism for serial communication.

<code class="go">package main

import (
    "bufio"
    "fmt"
    "github.com/tarm/goserial"
)

func main() {
    c := &serial.Config{Name: "/dev/ttyUSB0", Baud: 9600}
    s, err := serial.OpenPort(c)

    if err != nil {
        fmt.Println(err)
    }

    _, err = s.Write([]byte("\x16\x02N0C0 G A\x03\x0d\x0a"))

    if err != nil {
        fmt.Println(err)
    }

    reader := bufio.NewReader(s)
    reply, err := reader.ReadBytes('\x0a') // Read until a newline character is encountered
    if err != nil {
        panic(err)
    }

    fmt.Println(reply)

    s.Close()
}</code>

With this modification, the program will continuously read incoming data until the specified delimiter (in this case, x0a) is encountered. This approach ensures reliable data retrieval without the need for blocking operations.

The above is the detailed content of How to Read Data from a Serial Port Non-Blockingly in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn