go - 不能在 strconv.ParseFloat 问题的参数中使用 (type []byte) 作为类型字符串

标签 go gpio

pi@raspberrypi:~/Desktop/go $ go run shell1.go

结果我得到:

pi@raspberrypi:~/Desktop/go $ go run shell1.go
# command-line-arguments
./shell1.go:29: undefined: n
./shell1.go:29: cannot use b (type []byte) as type string in argument to strconv.ParseFloat
./shell1.go:32: undefined: n

Go文件(shell1.go)代码为:

package main

import (
    //    "net/http"
    //    "github.com/julienschmidt/httprouter"
    "fmt"
    "log"
    "os/exec"
    "strconv"
    "time"
    //"bytes"
    //"encoding/binary"
)
import _ "github.com/go-sql-driver/mysql"
import _ "database/sql"

func main() {
    for {
        time.Sleep(10 * time.Millisecond)
        cmd := exec.Command("gpio.bash")

        b, err := cmd.Output()
        if err != nil {
            log.Fatal(err)
        }
        n, _ = strconv.ParseFloat(b, 10)
        fmt.Println(string(b))
        break
    }

    fmt.Println("Button pressed!!! ", n)

}

(gpio.bash)文件的内容只是读取gpio的一条命令

 #!/bin/bash
gpio read 29

最佳答案

您正在使用 command在这里,它当然可以执行任何事情。

该函数特意是通用的,因为真正的返回类型因您执行的内容而异。因此,当您调用 output方法,您将获得一段字节(非常通用!)。这是它的签名:

func (c *Cmd) Output() ([]byte, error)

如果你知道字节总是一个字符串,那么你只需要做一个字符串类型转换:

n, _ := strconv.ParseFloat(string(b), 10)

关于go - 不能在 strconv.ParseFloat 问题的参数中使用 (type []byte) 作为类型字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42659045/

相关文章:

ajax - 检测是否是AJAX请求

pointers - 在 Go 中比较指针

regex - 如何在 Go 正则表达式中获取捕获组功能

linux - 更改 gpio 值时通知

python - RPi 在启动时运行 GPIO 脚本

c - 需要 "hello world"才能用 C 语言写入 Intel Edison gpio

ios - gomobile:ObjC 的绑定(bind)回调

json - 使用嵌套的 map[string] 接口(interface)解码 JSON

linux - 在带有 DAS U-Boot 的 Raspberry Pi 计算模块上使用 GPIO-Poweroff 关闭 PSU

stm32 - 使用显示总线接口(interface)将 TFT 屏幕与 STM32F446 接口(interface)