Created
November 8, 2020 21:43
-
-
Save ryochack/16f747af86ff4bb6da97b76fcec36c8c to your computer and use it in GitHub Desktop.
Serial Write/Read sample using golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
build for Windows on Linux.