Reading from serial port with while-loop

前端 未结 2 1065
一个人的身影
一个人的身影 2021-01-05 10:03

I’ve written a short program in Go to communicate with a sensor through a serial port:

package main

import (
    \"fmt\"
    \"github.com/tarm/goserial\"
           


        
2条回答
  •  北海茫月
    2021-01-05 10:53

    Your problem is that Read() will return whenever it has some data - it won't wait for all the data. See the io.Reader specification for more info

    What you want to do is read until you reach some delimiter. I don't know exactly what format you are trying to use, but it looks like maybe \x0a is the end delimiter.

    In which case you would use a bufio.Reader like this

    reader := bufio.NewReader(s)
    reply, err := reader.ReadBytes('\x0a')
    if err != nil {
        panic(err)
    }
    fmt.Println(reply)
    

    Which will read data until the first \x0a.

提交回复
热议问题