Last active
July 10, 2024 09:04
-
-
Save duanebester/5e3a29d89c5f24860bc0 to your computer and use it in GitHub Desktop.
Quick read of serial port in Go
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 ( | |
"bufio" | |
"flag" | |
"fmt" | |
"github.com/tarm/goserial" | |
"log" | |
"os" | |
) | |
// Command Line Args | |
// EX: ./serial -com=COM1 -baud=115200 | |
var ( | |
com string | |
baud int | |
) | |
// Set Defaults | |
func init() { | |
flag.StringVar(&com, "com", "COM1", "The COM port to read data from") | |
flag.IntVar(&baud, "baud", 115200, "The Baud Rate") | |
} | |
func main() { | |
flag.Parse() | |
// Program Info | |
log.Printf("Starting with port %s at baud rate %d", com, baud) | |
// Setup Serial Port | |
c := &serial.Config{Name: com, Baud: baud} | |
s, err := serial.OpenPort(c) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Print("Reading Bytes in...") | |
buf := make([]byte, 2048) | |
r, err := s.Read(buf) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// Print Bytes Read | |
log.Printf("% #x ", buf[:r]) | |
file, err := os.Create("test.txt") | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer file.Close() | |
w := bufio.NewWriter(file) | |
for _, abyte := range buf { | |
fmt.Fprintf(w, "% #x ", abyte) | |
} | |
write_err := w.Flush() | |
if write_err != nil { | |
log.Fatal(write_err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment