我有带有简单固件的arduino uno,它通过串行端口提供简单的API:
- 命令"read"返回当前状态 命令"on">
- 将状态设置为"on"> 命令"off">
- 将状态设置为"off">
现在我想为此设备实现一个客户端。 如果我使用 Arduino IDE 串行监视器,此 API 将按预期工作。 如果我将python与pySerial库一起使用,API就可以工作。
但是每当我尝试使用 golang 和 go-serial 从串行端口读取数据时,我的读取调用都会挂起(但与 socat 创建的/dev/pts/X 一起工作,例如(
蟒蛇客户端
import serial
s = serial.Serial("/dev/ttyACM0")
s.write("readn")
resp = []
char = None
while char != "r":
char = s.read()
resp.append(char)
print "".join(resp)
Go 客户端(永远挂在读取调用上(: 包主
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("readn"))
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))
}
固件代码:
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 == "onn") {
state = "on";
} else if (inputString == "offn") {
state = "off";
} else if (inputString == "readn") {
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;
}
}
}
蟒蛇代码
您已将Go lang 函数的波特率设置为 19200,但在 arduino 中您使用了 9600。
在 python 代码中,波特率未设置,因此采用默认值 9600。
只需在您的 go lang 程序中设置正确的波特率,它应该可以工作。