开发环境
操作系统:OpenEuler
硬件:树莓派4B,PCF8591
开发语言:Golang
Openeuler 启用I2C
相关配置文件
/boot/config.txt
dtparam=i2c_arm=on
dtparam=i2c_baudrate=10000
相关命令
sudo modprobe i2c-core
sudo modprobe i2c-dev
I2C工具安装
下载地址
https://mirrors.edge.kernel.org/pub/software/utils/i2c-tools/
操作命令
sudo i2cdetect -l # 列出所有I2C总线
sudo i2cdetect -y 0 # 假设你的I2C设备连接在总线0上
sudo i2cdump -y 0 0x38 # 假设你的I2C设备地址是0x38
测试代码
pcf8591.go
package pcf8591
import (
"periph.io/x/conn/v3"
"periph.io/x/conn/v3/i2c"
)
// Channel 模拟信号输入
type Channel uint8
// AIN0~AIN3 模拟信号输入端
const (
AIO0 Channel = 0
AIO1 Channel = 1
AIO2 Channel = 2
AIO3 Channel = 3
)
// Dev is a handle to an initialized PCF8591 device.
type Dev struct {
d conn.Conn
name string
}
// NewI2C returns an object that communicates over I²C to PCF8591
func NewI2C(b i2c.Bus, addr uint16) (*Dev, error) {
d := &Dev{d: &i2c.Dev{Bus: b, Addr: addr}}
return d, nil
}
// Read 读取结果
func (d *Dev) Read(channel Channel) (result byte) {
tmp := make([]byte, 1)
switch channel {
case AIO0:
d.d.Tx([]byte{0x40}, tmp)
case AIO1:
d.d.Tx([]byte{0x41}, tmp)
case AIO2:
d.d.Tx([]byte{0x42}, tmp)
case AIO3:
d.d.Tx([]byte{0x43}, tmp)
}
result = tmp[0]
return
}
// Write 写入数据
func (d *Dev) Write(val byte) {
d.d.Tx([]byte{0x40, val}, nil)
}
main.go
package main
import (
"ez-pi/pcf8591"
"log"
"periph.io/x/conn/v3/i2c/i2creg"
"periph.io/x/host/v3"
"time"
)
func main() {
// 加载所有驱动
if _, err := host.Init(); err != nil {
log.Fatal(err)
}
// 打开第一个可用I²C总线的handle
//bus, err := i2creg.Open("/dev/i2c/1")
bus, err := i2creg.Open("")
if err != nil {
log.Fatal(err)
}
defer bus.Close()
// 通过执行命令 'sudo i2cdetect -y 1' 查看 PCF8591 设备地址
dev, err := pcf8591.NewI2C(bus, 0x48)
if err != nil {
log.Fatal(err)
}
var tmp1 byte
var tmp2 uint16
for {
// 读取可调电阻值
tmp1 = dev.Read(pcf8591.AIO0)
tmp2 = BytesToUint16([]byte{tmp1})
// LED灯亮度值125~255
tmp2 = tmp2*(255-125)/255 + 125
// 调节LED灯的亮度
dev.Write(Uint16ToBytes(tmp2)[0])
log.Println(tmp1)
// 亮度为0时退出程序
if tmp1 == 0 {
break
}
time.Sleep(50)
}
}
// Uint16ToBytes unit16 -> bytes
func Uint16ToBytes(n uint16) []byte {
return []byte{
byte(n),
byte(n >> 8),
}
}
// BytesToUint16 bytes -> unit16
func BytesToUint16(array []byte) uint16 {
var data uint16 = 0
for i := 0; i < len(array); i++ {
data = data + uint16(uint(array[i])<<uint(8*i))
}
return data
}