I have arduino uno with simple firmware which provides simple API over serial port:
- Command "read" returns the current state
- Command "on" sets the state to "on"
- Command "off" sets the state to "off"
Now I want to implement a client for this device. If I use Arduino IDE serial monitor, this API works as expected. If I use python with pySerial library, API works.
But whenever I try to read data from the serial port using golang and go-serial, my read calls hangs (but works fine with /dev/pts/X created by socat, for example)
Python client
import serial
s = serial.Serial("/dev/ttyACM0")
s.write("read\n")
resp = []
char = None
while char != "\r":
char = s.read()
resp.append(char)
print "".join(resp)
Go client (hangs on Read call forever): package main
import "fmt"
import "github.com/jacobsa/go-serial/serial"
func check(err error) {
if err != nil {
panic(err.Error())
}
}
func main() {
options := serial.OpenOptions{
PortName: "/dev/ttyACM0",
BaudRate: 19200,
DataBits: 8,
StopBits: 1,
MinimumReadSize: 4,
}
port, err := serial.Open(options)
check(err)
n, err := port.Write([]byte("read\n"))
check(err)
fmt.Println("Written", n)
buf := make([]byte, 100)
n, err = port.Read(buf)
check(err)
fmt.Println("Readen", n)
fmt.Println(string(buf))
}
Firmware code:
String inputString = ""; // a String to hold incoming data
boolean stringComplete = false; // whether the string is complete
String state = "off";
void setup() {
// initialize serial:
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
pinMode(13, OUTPUT);
}
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
blink();
if (inputString == "on\n") {
state = "on";
} else if (inputString == "off\n") {
state = "off";
} else if (inputString == "read\n") {
Serial.println(state );
}
// clear the string:
inputString = "";
stringComplete = false;
}
}
void blink() {
digitalWrite(13, HIGH); // set the LED on
delay(1000); // wait for a second
digitalWrite(13, LOW); // set the LED off
delay(1000); // wait for a second
}
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag so the main loop can
// do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}
Python code
ser.readline()
(so your delimiter is\n
) another point is : C++ and python no diference, like ` while (Serial.available())(ardu) == while True: while ser.inWaiting() > 0: (python)` – dsgdfg"/dev/ttyACM0"
and"/dev/ttyACM1"
I hope it's a joke. – dsgdfg