我正在尝试使用多线程通过Arduino从串口读取输入。我有两个线程从串口读取,他们都在读相同的东西(忽略他们的函数名)。这是代码:
func readFirstLine(scanner *bufio.Scanner, port *serial.Port){
for scanner.Scan() {
log.Printf("%q\n", scanner.Text())
}
time.Sleep(time.Duration(1)*time.Second)
}
func readSecondLine(scanner *bufio.Scanner, port *serial.Port){
time.Sleep(time.Duration(1)*time.Second)
for scanner.Scan() {
log.Printf("%q\n", scanner.Text())
}
}
func main() {
usbRead := &serial.Config{Name: "COM5", Baud: 9600, ReadTimeout: 0}
port, err := serial.OpenPort(usbRead)
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(port)
for true {
go readFirstLine(scanner, port)
go readSecondLine(scanner, port)
time.Sleep(time.Duration(2)*time.Second)
}
}
我希望输出看起来像这样:
{"temperature":[26,26],"humidity":[54.2,54.2],"sensor":"DHT22"}
{"temperature":[23.46041,23.46041],"sensor":"LM35DZ"}
{"blink":["true","true"],"actuator":"arduinoLED"}
{"temperature":[26,26],"humidity":[54.2,54.2],"sensor":"DHT22"}
{"temperature":[23.46041,23.46041],"sensor":"LM35DZ"}
{"blink":["true","true"],"actuator":"arduinoLED"}
然而,我在预期输出之间得到了垃圾输出:
"{\"temperature\":[23.46041,23.46041,23.46041],\"sensor\":\"LM35DZ\"}"
"{\"blink\":[\"true\",\"true\",\"true\"],\"actuator\":\"arduinoLED\"}"
"mpeer\x00\x00re\"u:\x00\x00[]6\x00midhui\x00\x00[54\":.\x00\x00sen,\"s\x00\x00:or\"\"TH\x00"
{\"}\"\x00\x00ptemurrate\x003.4[26\x00\x00,\"s1]e\x00\x00\":\"orL\x00\x00Z\"}5D\r\x00\x00\x00"
我相信这个垃圾输出出现是因为我正在读取串口输入,即使Arduino没有输出任何东西。有没有关于如何解决这个问题的想法?谢谢。