我有一个简单的Python代码,可以正确地设置MFRC522设备:
import spidev
mode_reset = 0x0F
def spi_transfer(data):
r = spi.xfer2(data)
return r
def dev_write(address, value):
r = spi_transfer([(address << 1) & 0x7E, value])
print(">>",[(address << 1) & 0x7E, value], r)
return r
def reset():
dev_write(0x01, mode_reset)
spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 1000000
print(spi.mode, spi.bits_per_word, spi.lsbfirst)
reset()
完全正常 - 它返回命令代码15
,但在Go中实现的相同初始化例程确实不起作用:
package main
import (
"fmt"
"golang.org/x/exp/io/spi"
"log"
)
func main() {
spiDev, err := spi.Open(&spi.Devfs{
Dev: "/dev/spidev0.0",
Mode: spi.Mode(spi.Mode0),
MaxSpeed: int64(1000000),
})
spiDev.SetMode(spi.Mode0)
spiDev.SetBitOrder(spi.MSBFirst)
spiDev.SetBitsPerWord(8)
if err != nil {
log.Fatal(err)
}
writeSpiData := func(dataIn []byte) (out []byte, err error) {
out = make([]byte, len(dataIn))
err = spiDev.Tx(dataIn, out)
return
}
devWrite := func(address int, data byte) (err error) {
newData := [2]byte{(byte(address) << 1) & 0x7E, data}
readBuf, err := writeSpiData(newData[0:])
fmt.Println(">>", newData, readBuf)
return
}
if err != nil {
log.Fatal(err)
}
devWrite(0x01, 0x0F)
fmt.Println("Done")
}
这个返回[0 0]
这是错误的。有谁知道那里可能有什么问题?
答案 0 :(得分:2)
看起来Go发行版的SPI模块无法按预期工作。我使用一些逻辑分析器做了一些研究,发现exp / io / spi中的SPI命令层没有生成相应的命令。
源代码:
package main
import (
"fmt"
"golang.org/x/exp/io/spi"
"log"
)
func main() {
spiDev, err := spi.Open(&spi.Devfs{
Dev: "/dev/spidev0.0",
MaxSpeed: int64(1000000),
})
spiDev.SetMode(spi.Mode0)
spiDev.SetBitOrder(spi.MSBFirst)
spiDev.SetBitsPerWord(8)
if err != nil {
log.Fatal(err)
}
writeSpiData := func(dataIn []byte) (out []byte, err error) {
out = make([]byte, len(dataIn))
err = spiDev.Tx(dataIn, out)
return
}
devWrite := func(address int, data byte) (err error) {
newData := [2]byte{(byte(address) << 1) & 0x7E, data}
readBuf, err := writeSpiData(newData[0:])
fmt.Println(">>", newData, readBuf)
return
}
if err != nil {
log.Fatal(err)
}
devWrite(0x01, 0x0F)
fmt.Println("Done")
}
结果数据日志:
现在使用另一个驱动程序,https://github.com/ecc1/spi代码如下:
package main
import (
"fmt"
"log"
"github.com/ecc1/spi"
)
func main() {
spiDev, err := spi.Open("/dev/spidev0.0", 1000000, 0)
spiDev.SetMode(0)
spiDev.SetBitsPerWord(8)
spiDev.SetLSBFirst(false)
spiDev.SetMaxSpeed(1000000)
if err != nil {
log.Fatal(err)
}
writeSpiData := func(dataIn []byte) (err error) {
err = spiDev.Transfer(dataIn)
return
}
devWrite := func(address int, data byte) (err error) {
newData := [2]byte{(byte(address) << 1) & 0x7E, data}
fmt.Print("<< ", newData, " ")
err = writeSpiData(newData[0:])
fmt.Println(">>", newData)
return
}
if err != nil {
log.Fatal(err)
}
devWrite(0x01, 0x0F)
if err != nil {
log.Fatal(err)
}
}
结果协议转储是正确的: