之前的文章提到以前购买的ReSpeaker扩展板,用Python控制总觉得有点不爽,于是搜索Golang的实现方法。
另外还有一个库,没有仔细看:https://github.com/kidoman/embd
再就是GPIO控制 https://github.com/stianeikeland/go-rpio
这是本程序使用的库https://github.com/goiot/devices
以下代码实现了对SPI设备的控制。
import (
"bytes"
"encoding/binary"
"github.com/goiot/devices/dotstar"
"golang.org/x/exp/io/spi"
)
const n = 3 // LED数量,看起来它是可以控制一个灯带的
// 要将整形变为Byte型。这里只用了一位,所以作了修改。
func IntToBytes(n int) byte {
x := int32(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, x)
return bytesBuffer.Bytes()[3]
}
func main() {
d, err := dotstar.Open(&spi.Devfs{Dev: "/dev/spidev0.1", Mode: spi.Mode3}, n) // 这个/dev可以用ls查看
if err != nil {
panic(err)
}
for i := 0; i < n; i++ {
d.SetRGBA(i, dotstar.RGBA{0, IntToBytes(i*30+100), 0, 100}) // 颜色控制
}
if err := d.Draw(); err != nil {
panic(err)
}
}
改个版,命令行控制三个LED
package main
import (
"fmt"
"flag"
"bytes"
"strconv"
"encoding/binary"
"github.com/goiot/devices/dotstar"
"golang.org/x/exp/io/spi"
)
func Hex2Dec(val string) int {
n, err := strconv.ParseUint(val, 16, 32)
if err != nil {
fmt.Println(err)
}
return int(n)
}
func IntToBytes(n int) byte {
x := int32(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, x)
return bytesBuffer.Bytes()[3]
}
func ColorSplit(s string) (r,g,b,a byte){
m := []rune(s)
r = IntToBytes(Hex2Dec(string(m[0:2])))
g = IntToBytes(Hex2Dec(string(m[2:4])))
b = IntToBytes(Hex2Dec(string(m[4:6])))
a = IntToBytes(Hex2Dec(string(m[6:8])))
return
}
func main() {
var Led0,Led1,Led2 string
flag.StringVar(&Led0,"l1","00000000","1灯值: RRGGBBAA(AA=01-1F)")
flag.StringVar(&Led1,"l2","00000000","2灯值:RRGGBBAA(AA=01-1F)")
flag.StringVar(&Led2,"l3","00000000","3灯值:RRGGBBAA(AA=01-1F)")
flag.Parse()
d, err := dotstar.Open(&spi.Devfs{Dev: "/dev/spidev0.1", Mode: spi.Mode3}, 3)
if err != nil {
panic(err)
}
r0,g0,b0,a0:= ColorSplit(Led0)
d.SetRGBA(0, dotstar.RGBA{r0, g0, b0, a0})
r1,g1,b1,a1:= ColorSplit(Led1)
d.SetRGBA(1, dotstar.RGBA{r1, g1, b1, a1})
r2,g2,b2,a2:= ColorSplit(Led2)
d.SetRGBA(2, dotstar.RGBA{r2, g2, b2, a2})
d.Draw()
}