Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
s-celles opened this issue Nov 29, 2018 · 2 comments
Open

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

s-celles opened this issue Nov 29, 2018 · 2 comments

Comments

@s-celles
Copy link

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
Copy link
Author

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
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants