Created
May 6, 2014 23:39
-
-
Save duanebester/2e9afbbaa3aac9c07274 to your computer and use it in GitHub Desktop.
Go Write Random Bytes to Serial Port
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 ( | |
"github.com/tarm/goserial" | |
"log" | |
"flag" | |
"math/rand" | |
. "time" | |
) | |
// Command Line Args | |
// EX: ./joystick-demo.exe -com=COM1 -baud=115200 -readBytes=true -count=10 -delay=5 | |
var ( | |
com string | |
baud int | |
count int | |
delay int | |
readBytes = flag.Bool("readBytes", false, "Whether to read bytes in on Rx") | |
) | |
// Set Defaults | |
func init() { | |
flag.StringVar(&com, "com", "COM4", "The COM port to write data to") | |
flag.IntVar(&baud, "baud", 230400, "The Baud Rate") | |
flag.IntVar(&count, "count", 20, "The Amount of times to send data") | |
flag.IntVar(&delay, "delay", 3, "The Amount of delay in seconds before writing out bytes") | |
} | |
func main() { | |
flag.Parse() | |
// Program Info | |
log.Printf("Starting with port %s at baud rate %d", com, baud) | |
log.Printf("Running program %d times, delay is %d seconds", count, delay) | |
log.Printf("Reading Bytes? %t", *readBytes) | |
// Set Seed | |
rand.Seed(Now().Unix()) | |
// Setup Serial Port | |
c := &serial.Config{Name: com, Baud: baud} | |
s, err := serial.OpenPort(c) | |
if err != nil { | |
log.Fatal(err) | |
} | |
Sleep(Duration(delay) * Second) | |
// Declarations | |
var start_byte, end_byte uint8 | |
// 0xBE | |
start_byte = 190 | |
// 0xEF | |
end_byte = 239 | |
buf := make([]uint8, 4) | |
// Write bytes | |
for i := 0; i < count; i++ { | |
buf[0] = start_byte | |
buf[1] = uint8(rand.Intn(255)) | |
buf[2] = uint8(rand.Intn(255)) | |
buf[3] = end_byte | |
n, err := s.Write(buf) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Printf("Wrote %d bytes", n) | |
log.Print(buf[:n]) | |
// Random Delay | |
Sleep(Millisecond * 10) | |
} | |
// Read Bytes In | |
if *readBytes { | |
Sleep(Millisecond * 1000) | |
log.Print("Reading Bytes in...") | |
buf2 := make([]uint8, 256) | |
r, err := s.Read(buf2) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// Print Bytes Read | |
log.Print(buf2[:r]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment