问题描述
我在Go上写了一个简短程序,通过串口与传感器进行通信:
package main
导入(
fmt
github.com/tarm/goserial
时间
)
func main (){
c:=& serial.Config {名称:/ dev / ttyUSB0,波特:9600}
s,err:= serial.OpenPort(c)
如果err!= nil {
fmt.Println(err)
}
_,err = s.Write([] byte(\x16\x02N0C0 GA\\ \\ x03 \x0d\x0a))
if err!= nil {
fmt.Println(err)
}
时间。 Sleep(time.Second / 2)
buf:= make([] byte,40)
n,err:= s.Read(buf)
if err!= nil {
fmt.Println(err)
}
fmt.Println(string(buf [:n]))
s .Close()
}
它可以正常工作,但写入端口后,等待大约半秒后才能开始从它读取。我想用while循环代替 time.Sleep
来读取所有传入数据。我的尝试不起作用:
$ $ p $ $ $ $ $ $ buf:make([] byte,40)
n:= 0
为{
n,_:= s.Read(buf)
if n> 0 {
break
}
}
fmt.Println(string(buf [:n]))
我猜在每次循环之后会覆盖 buf
。任何建议?
您的问题是 Read()
将会返回只要它有一些数据 - 它不会等待所有的数据。有关详情,请参阅
什么你想要做的是读直到你达到某个分隔符。我不知道你想要使用什么格式,但它看起来可能 \x0a
是结束分隔符。
在这种情况下,您可以像这样使用
reader:= bufio.NewReader(s)
回复,err:= reader.ReadBytes('\x0a')
if err!= nil {
panic(err)
}
fmt.Println(reply)
它将读取数据直到第一个 \x0a
。
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"
"time"
)
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)
}
time.Sleep(time.Second/2)
buf := make([]byte, 40)
n, err := s.Read(buf)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(buf[:n]))
s.Close()
}
It works fine, but after writing to the port I have to wait about half a second before I can start reading from it. I would like to use a while-loop instead of time.Sleep
to read all incoming data. My attempt doesn’t work:
buf := make([]byte, 40)
n := 0
for {
n, _ := s.Read(buf)
if n > 0 {
break
}
}
fmt.Println(string(buf[:n]))
I guess buf
gets overwritten after every loop pass. Any suggestions?
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
.
这篇关于使用while循环从串口读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!