Skip to content

Instantly share code, notes, and snippets.

@threeaccents
Created September 8, 2016 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save threeaccents/9ecda1bf35e1ec86a3d48809aa7c3989 to your computer and use it in GitHub Desktop.
Save threeaccents/9ecda1bf35e1ec86a3d48809aa7c3989 to your computer and use it in GitHub Desktop.
goserial
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