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

As result i am getting:

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 file (shell1.go) code is:

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)

}

Content of (gpio.bash) file is just one command to read gpio

 #!/bin/bash
gpio read 29
1
  • 3
    Change n, _ = strconv.ParseFloat(b, 10) to n, _ := strconv.ParseFloat(string(b), 10). Your compiler errors have the exact information you'd need to fix this. Mar 7, 2017 at 21:57

1 Answer 1

5

You are working with a command here, which can of course execute just about anything.

The function is purposely generic, as the true return type varies depending on what you executed. Thus, when you call the output method, you are given a slice of bytes (very generic!). Here is its signature:

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

If you know that the bytes will always be a string, then you simply have to do a type conversion to a string:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.