Created
September 8, 2016 17:33
-
-
Save threeaccents/9ecda1bf35e1ec86a3d48809aa7c3989 to your computer and use it in GitHub Desktop.
goserial
This file contains hidden or 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 ( | |
"bytes" | |
"encoding/binary" | |
"flag" | |
"fmt" | |
"io" | |
"log" | |
"time" | |
"github.com/tarm/serial" | |
) | |
func main() { | |
postPtr := flag.Int("pos", 0, "position") | |
namePtr := flag.String("name", "/dev/tty.usbmodem1421", "dev location") | |
flag.Parse() | |
c := &serial.Config{Name: *namePtr, Baud: 9600} | |
s, err := serial.OpenPort(c) | |
if err != nil { | |
log.Fatalf("Erro opening serial port %v", err) | |
} | |
time.Sleep(2 * time.Second) // sleep because when a connection is made with an Arudino it reboots | |
send('s', int8(*postPtr), s) | |
} | |
func send(cmd byte, val int8, s io.ReadWriteCloser) error { | |
buf := new(bytes.Buffer) | |
if err := binary.Write(buf, binary.LittleEndian, val); err != nil { | |
return fmt.Errorf("binary.Write failed: %v", err) | |
} | |
for _, b := range [][]byte{[]byte{cmd}, buf.Bytes()} { | |
n, err := s.Write(b) | |
if err != nil { | |
return err | |
} | |
fmt.Printf("sent %d byte(s)\n", n) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment