2014-01-24 54 views
1

這是否寫入4(字節00000100)串口?寫入二進制整數字節到串行連接與GO

buf := make([]byte, 4) 
d, err := connection.Write(buf) 

因爲它看起來像東西是越來越發送,但我對那期待一個4的另一端代碼不會被觸發。我有另一種語言的其他代碼發送一個4到Arduino,它的響應很好。當上面的代碼運行時,我可以看到燈閃爍,但它不知道他是我期望的字節。

那麼如何通過串口發送字節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) 
    } 

    // 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() 
} 

回答

0

它看起來像我完全誤解的第二個參數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! 
+2

這不太可能你想要varint。只要'寫([]字節{4})' – Dustin

+0

這似乎不工作,只要我做'8'一個'int'變量而不是:( –

+0

'八:= 8';'寫([]字節{字節(8)})' – Dustin