dongqin1819 2018-05-28 21:42
浏览 47

使用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.

  • 写回答

1条回答 默认 最新

  • dream543211 2018-05-28 22:51
    关注

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

    Reference: Introducing the Go Race Detector

    评论

报告相同问题?

悬赏问题

  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符