英文:
Write binary integer byte to a serial connection with GO
问题
这段代码是用来向串口发送字节00000100
(十进制为4)吗?
buf := make([]byte, 4)
d, err := connection.Write(buf)
因为似乎有东西被发送了,但是我在另一端的代码中期望接收到的是4,但并没有触发。我有另一种语言的代码向Arduino发送4,它可以正常响应。而且当上述代码运行时,我可以看到灯在闪烁,但它不是我期望的字节。
那么如何通过串口发送字节00000100
呢?
完整代码如下:
package main
import (
"github.com/tarm/goserial"
"log"
"time"
)
func main() {
config := &serial.Config{Name: "/dev/tty.usbmodem1421", Baud: 9600}
connection, err := serial.OpenPort(config)
if err != nil {
log.Fatal(err)
}
// 等待Arduino
time.Sleep(5 * time.Second)
// 向串口发送二进制整数4
buf := make([]byte, 4)
_, err = connection.Write(buf)
if err != nil {
log.Fatal(err)
}
// 等待Arduino
time.Sleep(1 * time.Second)
// 清理
connection.Close()
}
英文:
Does this write a 4
(the byte 00000100
) to the serial port?
buf := make([]byte, 4)
d, err := connection.Write(buf)
Because it seems like something is getting sent, but my code on the other end that is expecting a 4 does not get triggered. I have other code in another language that sends a 4 to the Arduino, and it responds fine. And I can see the light blink when the above code runs, but it's somehow not he byte I'm expecting.
So how do send the byte 00000100
over the serial port?
Full code here:
package main
import (
"github.com/tarm/goserial"
"log"
"time"
)
func main() {
config := &serial.Config{Name: "/dev/tty.usbmodem1421", Baud: 9600}
connection, err := serial.OpenPort(config)
if err != nil {
log.Fatal(err)
}
// Wait for Arduino
time.Sleep(5 * time.Second)
// Send the binary integer 4 to the serial port
buf := make([]byte, 4)
_, err = connection.Write(buf)
if err != nil {
log.Fatal(err)
}
// Wait for Arduino
time.Sleep(1 * time.Second)
// Cleanup
connection.Close()
}
答案1
得分: 0
看起来我完全误解了make
函数的第二个参数...
buf := make([]byte, 1) // 第二个参数是数组的长度,而不是数组中的值
binary.PutUvarint(buf, 8) // 将我的整数值添加到缓冲区
connection.Write(buf) // 发送它!
英文:
It looks like I totally misunderstood the second argument to make
...
buf := make([]byte, 1) // second arg is lenght of array, not a value in the array
binary.PutUvarint(buf, 8) // add my int value to the buffer
connection.Write(buf) // send it!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论