Skip to content

Golang与树莓派

最近买了个树莓派3b,本来是做下载机用的,但是发现在上面写Go代码,编译,其实和在一般机器上的体验是一样的。

不过树莓派本身有其他电脑没有的玩法,那就是GPIO的支持,配合Go-gpio库,就可以控制这些接口

下面是一个简单的跑马灯+CPU温度探测程序

因为没加散热片……所以温度有点高┐( ̄ヮ ̄)┌

代码如下,根据/sys下的温度文件读数值,另一个是根据负载改变闪烁的频率。

很简单,所以我就不加注释了:)至于为啥叫jurassic,因为侏罗纪公园的电网就是蓝橙指示灯,然后写代码的胖子就被吃掉了

package main
import (
"fmt"
"io/ioutil"
"strconv"
"time"
"runtime"
"github.com/stianeikeland/go-rpio"
"github.com/shirou/gopsutil/load"
)
const (
BLUE = 20
ORANGE = 21
CORE_TEMP_PATH = "/sys/class/thermal/thermal_zone0/temp"
)
func init(){
runtime.GOMAXPROCS(1)
}
func main() {
fmt.Printf("System initial...")
if rpio.Open() == nil{
fmt.Println("[OK]")
} else {
fmt.Println("[ERROR]")
}
defer rpio.Close()
orange := rpio.Pin(ORANGE)
blue := rpio.Pin(BLUE)
orange.Output()
blue.Output()
orange.Low()
blue.High()
for {
stat, err := load.Avg()
if err != nil {
fmt.Println(err)
break
}
interval := int(stat.Load1)
if stat.Load1 < 1 {
interval = 1
}
fmt.Printf("Load1:%.2f Temp:%.2f'C", stat.Load1, loadTemp())
time.Sleep(time.Millisecond * time.Duration(interval * 900))
blue.Toggle()
orange.Toggle()
fmt.Printf("\r")
}
}
func loadTemp() float64 {
b, err := ioutil.ReadFile(CORE_TEMP_PATH)
if err != nil {
return -1000
}
raw, err := strconv.ParseFloat(string(b[:len(b)-2]), 64)
if err != nil {
fmt.Println(err)
return -1001
}
return raw/100
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.