package util import ( "bytes" "encoding/hex" "fmt" "time" "github.com/tarm/serial" ) // ReadSerial read from serial func ReadSerial(name string, baudrate int, bits byte) (data []byte, err error) { s := &serial.Port{} c := &serial.Config{} c.Name = name c.Baud = baudrate c.Size = bits c.StopBits = serial.Stop1 c.ReadTimeout = 100 * time.Microsecond c.Parity = serial.ParityNone s, err = serial.OpenPort(c) if err != nil { return } defer s.Close() var ss bytes.Buffer buf := make([]byte, 1024) for { n, err := s.Read(buf) if err != nil { if ss.Len() > 0 { break } continue } if n > 0 { if n == 1 { if buf[0] == 0x0d { continue } if buf[0] == 0x0a { break } } else if n == 2 { if buf[0] == 0x0d && buf[1] == 0x0a { break } } ss.Write(buf[:n]) fmt.Println("Read", n, "bytes", string(buf[:n]), hex.EncodeToString(buf[:n])) } else { break } } if ss.Len() > 0 { data = ss.Bytes() } return }