Skip to content

Instantly share code, notes, and snippets.

@ryochack
Created November 8, 2020 21:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryochack/16f747af86ff4bb6da97b76fcec36c8c to your computer and use it in GitHub Desktop.
Save ryochack/16f747af86ff4bb6da97b76fcec36c8c to your computer and use it in GitHub Desktop.
Serial Write/Read sample using golang
package main
import (
"fmt"
"log"
"os"
"time"
"github.com/tarm/serial"
)
func main() {
comname := os.Args[1]
fmt.Println("Start communication with ", comname)
c := &serial.Config{
Name: comname,
Baud: 115200,
ReadTimeout: time.Millisecond * 100,
}
s, err := serial.OpenPort(c)
if err != nil {
log.Fatal(err)
}
n, err := s.Write([]byte{0, 1, 2, 3, 4, 5, 6, 7})
if err != nil {
log.Fatal(err)
}
log.Println("Sent data size =", n)
buf := make([]byte, 128)
for {
n, err := s.Read(buf)
if n == 0 {
break
}
if err != nil {
log.Fatal(err)
}
log.Println("Received data size = ", n)
log.Println(buf[:n])
}
log.Println("exit")
}
@ryochack
Copy link
Author

ryochack commented Nov 8, 2020

build for Windows on Linux.

$ GOOS=windows GOARCH=amd64 go build

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment