douzhi8488 2017-12-15 05:46
浏览 35

从串口获取输入

I am trying to write a program to read from an RFID card reader, I have configured the device to be a character input and end the input with enter. I am using GoLang. Here's the part of the code where I read the input:

//Using www.github.com/tarm/goserial and bufio

func getInput(input chan string) {
    c := &serial.Config{Name: "/dev/input/event5", Baud: 9600}
    s, err := serial.OpenPort(c)

    if err != nil {
        fmt.Println(err)
    }

    for {
        reader:= bufio.NewReader(s)
        result, err1:= reader.ReadBytes('\x0a')
        if err1!=nil {
            panic(err1)
        }
        input<-string(result)
    }
    s.Close()
}

However, as soon as it executes the function reader.ReadBytes, and sees there isn't an input, gives me this error:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x93e432]

goroutine 53 [running]:

vendor/github.com/tarm/serial.(*Port).Read(0x0, 0xc420292000, 0x1000,      
0x1000, 0x18, 0xc4201b4d00, 0xc4201793f0) 
    vendor/github.com/tarm/serial/serial_linux.go:135 +0x22
bufio.(*Reader).fill(0xc420036f18)
    /usr/local/go/src/bufio/bufio.go:97 +0x117
bufio.(*Reader).ReadSlice(0xc420036f18, 0xc42029200a, 0x7fac0a47fab0, 
0x1, 0x101000000000000, 0x0, 0x1000)
    /usr/local/go/src/bufio/bufio.go:338 +0xbb
bufio.(*Reader).ReadBytes(0xc420036f18, 0x100a, 0x1000, 0xc420292000, 
0x1000, 0x1000, 0x0)
    /usr/local/go/src/bufio/bufio.go:416 +0x66
getInput(0xc4201e8c00)
    /home/shivam/go/src/main.go:150 +0x172
created by main.go.ReadCard
    /home/shivam/go/src/main.go:164 +0x72

exit status 2

What can I do so that it waits for an input and sends it when it receives a '\x0a' byte (Return)?

Thanks!

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
    • ¥20 怎么用dlib库的算法识别小麦病虫害
    • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
    • ¥15 java写代码遇到问题,求帮助
    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?