之前将go语言的运行环境给搭建起来了,但是没有开始真正的试试Go 语言操作树莓派硬件的效果。

一、树莓派3B硬件介绍

树莓派3B采用了博通的BCM2837方案,而树莓派2采用的是博通的BCM2836方案,这两个方案 树莓派2采用32bit的 ARMv7指令集的 ARM Cortex-A7 内核,树莓派3B采用了 64bit的 ARMV8指令集的 AR Cortex-A53内核,看起来BCM2837似乎略胜一筹,毕竟升级到了64位处理器。一下是树莓派3B的样图:

树莓派3B.png

网上查阅了一圈资料,发现BCM2837的资料都没放出来,在官网上找到了一则说明:

This is the Broadcom chip used in the Raspberry Pi 3, and in later models of the Raspberry Pi 2. The underlying architecture of the BCM2837 is identical to the BCM2836. The only significant difference is the replacement of the ARMv7 quad core cluster with a quad-core ARM Cortex A53 (ARMv8) cluster.

The ARM cores run at 1.2GHz, making the device about 50% faster than the Raspberry Pi 2. The VideocoreIV runs at 400Mhz.

Also see the Raspberry Pi 2's chip BCM2836 and the Raspberry Pi 1's chip BCM2835

看样子官网说外设没差别,就核心换了一下,那大致可以认为外设包括I2C、GPIO、SPI、timer这些基本的东西都没有怎么变化才对。不过为了保险起见,还是查阅了相关文档。以下是树莓派3B GPIO引脚图。

树莓派3B 接口.png

对比一下树莓派2的相关引脚图:

树莓派2 接口.png

仔细查阅了下,这上面常用的GPIO,SPI,I2C,UART都提供了。这还算好,发现常用的PWM不见了,这可有点麻烦了,后面再继续研究PWM。

二、点亮LED灯

我们尝试下所有开发板的第一个例程,点亮LED灯。这里找寻了一会暂时觉得可以使用下 nathan-osman 大神的 go-rpigpio 库。

go get github.com/nathan-osman/go-rpigpio

安装好了敲入以下代码:

package main

import (
    "github.com/nathan-osman/go-rpigpio"
    "time"
    "fmt"
)

func main(){
    p,err := rpi.OpenPin(2,rpi.OUT)
    if err != nil {
        panic(err)
    }
    defer p.Close()

    //set high
    p.Write(rpi.HIGH)
    fmt.Println("start gpio test")

    go func() {
        for{
            time.Sleep(time.Millisecond * 100)
            p.Write(rpi.HIGH)
            fmt.Println("on")
            time.Sleep(time.Millisecond * 100)
            p.Write(rpi.LOW)
            fmt.Println("off")
        }
    }()

    time.Sleep(time.Hour * 2)
}

保存并编译:

go build gpio_test.go
sudo ./gpio_test.go

这时候我们在 GPIO2 和 GND 之间串上一个 LED 灯 和一个 1K的电阻,发现 LED灯已经开始以飞快的频率闪烁了。