我有简单的固件arduino uno,通过串口提供简单的API:
-
命令"read"返回当前状态
-
命令"on"将状态设置为"on"
-
命令"off"将状态设置为"off"
现在我想为这个设备实现一个客户端 . 如果我使用Arduino IDE串行监视器,则此API可按预期工作 . 如果我使用python与pySerial库,API工作 .
但是每当我尝试使用golang和go-serial从串口读取数据时,我的读取调用都会挂起(例如,与socat创建的/ dev / pts / X一起工作正常)
Python客户端
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)
去客户端(挂起永远读取通话):包主
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))
}
固件代码:
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代码
1 回答
您已将Go lang功能的波特率设置为19200,但在arduino中您使用的是9600 .
在python代码中,未设置波特率,因此默认值为9600 .
只需在go lang程序中设置正确的波特率,它就可以正常工作 .