tarm / serial

BSD 3-Clause "New" or "Revised" License
1.62k stars 452 forks source link

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

Open s-celles opened 5 years ago

s-celles 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

s-celles 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)
}