tarm / serial

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ReadLine / read a '\n' terminated line

scls19fr opened this issue · comments

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

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.

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