使用GO将二进制整数字节写入串行连接。

huangapple go评论88阅读模式
英文:

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!

huangapple
  • 本文由 发表于 2014年1月24日 15:38:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/21327013.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定