找到特定的定界符后,如何从串行中读取数据并进行处理

I have a device, which continues to send data over a serial port. Now I want to read this and process it. The data send this delimiter "!" and as soon as this delimiter appears I want to pause reading to processing the data thats already been received. How can I do that? Is there any documentation or examples that I can read or follow.

For reading data from a serial port you can find a few packages on Github, e.g. tarm/serial.

You can use this package to read data from your serial port. In order to read until a specific delimiter is reached, you can use something like:

config := &serial.Config{Name: "/dev/ttyUSB", Baud: 9600}

s, err := serial.OpenPort(config)
if err != nil {
    // stops execution
    log.Fatal(err)
}

// golang reader interface
r := bufio.NewReader(s)

// reads until delimiter is reached
data, err := r.ReadBytes('\x21')
if err != nil {
    // stops execution
    log.Fatal(err)
}
// or use fmt.Printf() with the right verb
// https://golang.org/pkg/fmt/#hdr-Printing
fmt.Println(data)

See also: Reading from serial port with while-loop

For everybody coming here... I had a similar task and bufio did NOT work for me. It kept crashing after a while! This was an absolute no-go since I needed a very stable solution for a low-performance system.

My suggestion would be to implement this suggestion with a small tweek. As noted, if you don't use bufio, the buffer gets overwritten every time you call

n, err := s.Read(buf0)

To fix this, append the bytes from buf0 to a second buffer:

if n > 0 {
    for _, b := range buf0[:n] {
    buf1 = append(buf1, b)
    }

Then parse the string stored in buf1. If you find a substring you are looking for, process it further. (!) make sure to clear the buffer after a successful parse (!) make sure to clear the buffer if it reaches a certain size to avoid memory issues. Now, I know this is not exactly an elegant solution but it creates minimal overhead, you imediately see what's going on and it works perfectly fine in my application.

Check out this post to get some ideas how you can do the string parsing.