bugst / go-serial

A cross-platform serial library for go-lang.
BSD 3-Clause "New" or "Revised" License
657 stars 199 forks source link

Serial.print() equivalent #91

Closed brentgracey closed 3 years ago

brentgracey commented 3 years ago

This is more of an "advice please" post than an issue; so please advise if there is a better forum to post it on.

Is there an equivalent to https://www.arduino.cc/reference/en/language/functions/communication/serial/print/?

I've seen a few notes regarding the potential for framing errors using https://www.arduino.cc/reference/en/language/functions/communication/serial/write/ which I assume is analogous to https://github.com/bugst/go-serial/blob/master/serial.go#L25

As I understand print also sends a few more bytes than write - so I'm trying to think through how to handle that correctly on the Arduino which receives the data.

What approach would be advisable to try and send the same data as in this python example (hope the question makes sense; as appreciate there might not be a direct equivalent) https://forum.arduino.cc/index.php?topic=225329.msg1810764#msg1810764 there is an attached file The python serial client has a method ser.write(sendStr) ComArduino2PY3.txt

kroppt commented 3 years ago

You should first define what character set you are using. UTF-8 would be the easiest I think. Go strings are encoded in UTF-8. So you can send them using the following:

str := "Hello, world!"
port.Write([]byte(str))

And of course to get a Go string that has properly formatted numbers, you can use Sprint:

str := fmt.Sprint(1.23)
// str is "1.23"

You can also create new strings from existing strings with the + operator:

str := "Hello" + ", " + "world!"
// str is "Hello, world!"

Use Go's playground to play around to make sure you're doing it right: https://play.golang.org/

I don't really have Python experience, so I hope this is enough for you.

brentgracey commented 3 years ago

Thanks for the pointers.

From some initial reading; I thought there was some additional "checksum" type data that was sent when doing "text" IO to help make the communication more reliable; but perhaps I was wrong on that and its just about sending the correct binary values.