Reading Serial Port Data in Golang: A Complete Guide
In Go language, you can use the third-party library github.com/tarm/serial to read serial port data. First, you need to install this library.
go get github.com/tarm/serial
You can then use the following code to read serial data:
package main
import (
"fmt"
"log"
"github.com/tarm/serial"
)
func main() {
c := &serial.Config{Name: "/dev/ttyUSB0", Baud: 9600}
s, err := serial.OpenPort(c)
if err != nil {
log.Fatal(err)
}
defer s.Close()
buf := make([]byte, 128)
for {
n, err := s.Read(buf)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Received %v bytes: %v\n", n, buf[:n])
}
}
The code will continuously read serial port data and print the received byte data. You can modify the serial port name and baud rate based on specific serial port configuration.