Hi, I'm trying to set up go-serial to communicate with my arduino uno via usb.
I've got this go code that's pretty much lifted straight from the go library docs.
package main
import (
"fmt"
"log"
"go.bug.st/serial"
)
func main() {
ports, err := serial.GetPortsList()
if err != nil {
log.Fatal(err)
}
if len(ports) == 0 {
log.Fatal("No serial ports found!")
}
for _, port := range ports {
fmt.Printf("Found port: %v\n", port)
}
mode := &serial.Mode{}
port, err := serial.Open("/dev/ttyACM0", mode)
if err != nil {
log.Fatal(err)
}
n, err := port.Write([]byte("10,20,30\n\r"))
if err != nil {
log.Fatal(err)
}
fmt.Printf("Sent %v bytes\n", n)
buff := make([]byte, 100)
for {
n, err := port.Read(buff)
if err != nil {
log.Fatal(err)
break
}
if n == 0 {
fmt.Println("\nEOF")
break
}
fmt.Printf("%v", string(buff[:n]))
}
}
on the arduino I have the following.
const int BUFFER_SIZE = 50;
byte buf[BUFFER_SIZE];
int counter = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
// read the incoming bytes:
int rlen = Serial.readBytes(buf, BUFFER_SIZE);
// prints the received data
if (rlen > 0) {
Serial.print("I received: ");
for(int i = 0; i < rlen; i++){
Serial.print(char(buf[i]));
}
Serial.println("!");
}
Serial.println(counter++);
delay(500);
}
when I run the go program I get this output in my terminal
Found port: /dev/ttyACM0
Sent 10 bytes
0
0
1
2
3
4
If I send the same input to my arduino via the arduino-ide serial monitor I get the following.
0
1
I received: 10,20,30\n\r!
2
3
A poke around the internet (arch wiki) suggests there are issues with the arduino resetting upon connection, which might explain the multiple 0 log. Could this be what's happening between write and read in the Go code or does the call to open constitute a single connection?
The other issue I thought could be causing problems is that the go package sends an array of bytes. I don't have a good grasp of what this is coming from a webdev background, I'm not sure if this differs from what is sent via the arduino-ide.
Lastly, I wasn't sure if because the read loop starts after the call to write if it's just missing the response, perhaps they need to be run concurrently somehow?
Ultimately my goal is to send an array of JSON so I can configure an array of LEDs but It would be really helpful if I could get some basic communication/feedback loop going.
Thanks very much for any insights or pointers to resources that might clarify where I'm going wrong.