tarm / serial

BSD 3-Clause "New" or "Revised" License
1.62k stars 452 forks source link

Can I use multiple Serial ports in one code for simultaneously reading? #118

Closed sushantdasputepatil closed 3 years ago

sushantdasputepatil commented 3 years ago

I am able to use two serial ports individually and they are working fine but when I use them combine Both serial ports not working. This is my code -

package main import ( "fmt" "log" "github.com/tarm/serial" ) // This example prints the list of serial ports and use the first one // to send a string "10,20,30" and prints the response on the screen. func main() { c1 := &serial.Config{Name: "/dev/ttyS1", Baud: 115200} port1, errc1 := serial.OpenPort(c1) if errc1 != nil { log.Fatal(errc1) } c2 := &serial.Config{Name: "/dev/ttyS2", Baud: 115200} port2, errc2 := serial.OpenPort(c2) if errc2 != nil { log.Fatal(errc2) } // Send the string "10,20,30\n\r" to the serial port n1, err := port1.Write([]byte("10,20,30\n\r")) if err != nil { log.Fatal(err) } fmt.Printf("Sent %v bytes\n", n1) n2, err := port2.Write([]byte("10,20,30\n\r")) if err != nil { log.Fatal(err) } fmt.Printf("Sent %v bytes\n", n2) // Read and print the response buff1 := make([]byte, 100) buff2 := make([]byte, 100) for { // Reads up to 100 bytes n2, err2 := port2.Read(buff2) if err2 != nil { log.Fatal(err2) } n1, err1 := port1.Read(buff1) if err1 != nil { log.Fatal(err1) } // if n1 == 0 { // fmt.Println("\nEOF") // break // } fmt.Printf("%s", string(buff1[:n1])) fmt.Printf("%s", string(buff2[:n2])) // If we receive a newline stop reading // if strings.Contains(string(buff1[:n1]), "\n") { // break // } } }

sushantdasputepatil commented 3 years ago

My issue got resolved by using library : https://github.com/albenik/go-serial/