本示例用在linux上,用在windows上的话,要修改串口号为COM之类。
要使用goserial要先安装

go get github.com/tarm/goserial

直接上代码

package main

import (
    "encoding/hex"
    "fmt"
    "io"
    "net"
    "os"
    "strings"
    "time"

    serial "github.com/tarm/goserial"
)

var g_serial_rwc io.ReadWriteCloser
func main() {
    //com3 ttymxc2 ok.
    cfg := &serial.Config{Name: "/dev/ttymxc2", Baud: 115200, ReadTimeout: 10 * time.Millisecond /*毫秒*/}

    g_serial_rwc, err := serial.OpenPort(cfg)
    if err != nil {
        Info.Printf("open serial fail. %s", err)
        os.Exit(1)
        return
    }

    defer g_serial_rwc.Close()
    buffer := make([]byte, MAXRWLEN)

    //发命令之前清空缓冲区
    Info.Printf("发命令之前清空缓冲区")
    num, _ := g_serial_rwc.Read(buffer)

    Info.Printf("发命令数据类型为[]byte")
    //发命令数据类型为[]byte
    init_rsu(g_serial_rwc)

    Info.Printf("Read 10 times")
    var tmpstr string = ""
    for i := 0; i < 10; i++ {
        Info.Printf("read %d", i)
        num, err = g_serial_rwc.Read(buffer)
        if num > 0 {
            tmpstr += fmt.Sprintf("%s", strings.ToUpper(hex.EncodeToString(buffer[:num])))
            Info.Printf(tmpstr)
        } //查找读到信息的结尾标志
        if strings.LastIndex(tmpstr, "FF") > 0 {
            break
        }
    }

    Info.Printf("打印输出读到的信息")
    //打印输出读到的信息
    fmt.Println(tmpstr)

    return
}
本文链接地址:https://const.net.cn/380.html

标签: none

添加新评论