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

not clear buffer splitting when reading #129

Open
thedemoncat opened this issue Mar 18, 2023 · 4 comments
Open

not clear buffer splitting when reading #129

thedemoncat opened this issue Mar 18, 2023 · 4 comments

Comments

@thedemoncat
Copy link

HI!!!

arduino App (platformio - esp8266)

#include <Arduino.h>
#include <ESP8266WiFi.h>


void setup() {
  // initialize serial:
  Serial.begin(9600);

}

void loop() {
  Serial.print("Hello world");
  delay(10000);   
}

golang app

package main

import "fmt"
import "log"
import "github.com/tarm/serial"

func main() {
	config := &serial.Config{
		Name: "COM3",
		Baud: 9600,
	}

	stream, err := serial.OpenPort(config)
	if err != nil {
		log.Fatal(err)
	}

	buf := make([]byte, 1024)

	for {
		n, err := stream.Read(buf)
		if err != nil {
			log.Fatal(err)
		}
		s := string(buf[:n])
		if s == "" {
			continue
		}
		fmt.Println(s)
	}
}

in the console I get this result:

API server listening at: 127.0.0.1:57847
H
ello world
H
ello world

Why is the first character read separately in the stream?

How to read a line correctly?

Thank you in advance!

@orestonce
Copy link

bufio.NewReader(stream).ReadLine()

@FObersteiner
Copy link

FObersteiner commented Apr 20, 2023

bufio.Scanner is another option I find quite useful. You can also set your custom Spiltter function there if your input data is not newline-separated.

@slinky55
Copy link

Is there a way to set a custom timeout on bufio.NewReader()? I've set a timeout on the port itself as well

@FObersteiner
Copy link

FObersteiner commented Apr 21, 2024

Is there a way to set a custom timeout on bufio.NewReader()? I've set a timeout on the port itself as well

the underlying io.Reader does not implement a timeout - the idea here being that the reader finishes when the resource is closed or exhausted (EOF). So the correct way I think is to set the timeout on the port, which is your resource in this case. Note however that on Windows, this does not work with the original tarm/serial. There are a couple of forks that implement this feature (example from my fork).

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

4 participants