Serial Sample with golang

Serial Sample with golang

先安裝Package

go get github.com/goburrow/serial

Sample Code:

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/goburrow/serial"
)

func main() {
	//開啟SerialPort
	port, err := serial.Open(
		&serial.Config{
			Address:  "COM1",
			BaudRate: 9600,
			DataBits: 8,
			StopBits: 1,
			Parity:   "N",
			//Timeout時間決定port.read()的等待時間上限
			Timeout: 3 * time.Second,
		})
	if err != nil {
		log.Fatal("Comport open fail")
	}
	defer port.Close() //程式結束時關閉SerialPort

	wbuf := []byte("你好9527\n")
	fmt.Println(string(wbuf))
	_, err = port.Write(wbuf) //寫資料出去
	if err != nil {
		log.Fatal(err)
	}

	data := make([]byte, 1024)
	time.Sleep(1000 * time.Millisecond) //等待回傳所需的時間1000ms
	n, err := port.Read(data)           //讀資料回來
	if err != nil {
		log.Fatal(err)
	}
	log.Println(string(data[:n]))
}