Multithreading in Serial Port


(Melissa) #1

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:

    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)

    }
}

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\r\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.

(Arny Logan) #2

Hi… I write multithreaded applications to manage ioT devices and others.So there are devices that send data slowly but others could send data using serial port at 1 Mb/s and I have to manage them simultineously.Each connection has got a thread and no one byte was missing.You should review your code.

pcb printing and assembly