tarm / serial

BSD 3-Clause "New" or "Revised" License
1.59k stars 451 forks source link

ReadLine / read a '\n' terminated line #93

Open scls19fr opened 5 years ago

scls19fr commented 5 years ago

Hello,

I'm looking for a way to read a string (or array of byte) from serial port until end of line (CRLF ie \r\n in fact). Is there a function for this? (or a work around) I noticed in https://godoc.org/github.com/argandas/serial#SerialPort.ReadLine that https://github.com/argandas/serial have such a ReadLine method but this fork doesn't seems to be maintained any more. Any idea?

Kind regards

scls19fr commented 5 years ago

I've found a workaround using bufio

package main

import (
    "github.com/tarm/serial"
    "bufio"
    "fmt"
)

const SERIAL_PORT_NAME = "COM5"
const SERIAL_PORT_BAUD = 9600

func main() {
    conf := &serial.Config{Name: SERIAL_PORT_NAME, Baud: SERIAL_PORT_BAUD}
    ser, err := serial.OpenPort(conf)
    if err != nil {
        log.Fatalf("serial.Open: %v", err)
    }
    reader := bufio.NewReader(ser)
    reply, _ := reader.ReadBytes('\x0a')
    fmt.Println(reply)
}

Not sure now if tarm/serial should have such a ReadLine method.

charles-d-burton commented 5 years ago

You could use this which is recommended by the Golang developers:

ser, err := serial.OpenPort(conf)
if err != nil {
  log.Fatal(err)
}
scanner := bufio.NewScanner(ser)
for scanner.Scan() {
  fmt.Println(scanner.Text())
}
if scanner.Err() != nil {
  log.Fatal(err)
}