使用Arduino从串行端口读取以提供垃圾输出

I'm currently trying to read input from the serial port through an Arduino using multithreading. I have two threads reading from the serial port, and they are both reading the same thing (ignore their function names). Here is the code:

 func readFirstLine(scanner *bufio.Scanner, port *serial.Port){
    for scanner.Scan() {
        log.Printf("%q
", 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
", 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)
    }
}

I am expecting the output to look like this:

{"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"}

Yet I am getting garbage output in between the expected output:

"{\"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\x00\x00\x00"

I believe this garbage output appears because I am reading serial port input even when the Arduino hasn't outputted anything. Is there any ideas on how to fix this? Thanks.

dpbfb7119
dpbfb7119 请注意,true与for相同。也就是说,您可以省略“true”
2 年多之前 回复
dongshang6790
dongshang6790 注意,实际上,您实际上并不是在执行多线程。您正在并发。这可以在单个线程中以相同的方式发生。
2 年多之前 回复

1个回答



您正在同时读取和写入 bufio.Scanner </ code>,而没有同步机制。</ p>

参考资料:引入Go Race Detector </ p>
</ DIV>

展开原文

原文

You are concurrently reading from and writing to a bufio.Scanner with no synchronization mechanism.

Reference: Introducing the Go Race Detector

dqoeghe9452
dqoeghe9452 如果我只使用sync.WaitGroup就足够了吗? 抱歉,我还是该语言的新手,这是我第一次使用Go和串行端口。
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问