1.硬件图
2.读取spi设备的寄存器值(方法1)
from driver import SPI
from driver import GPIO
print("-------------------spi test--------------------")
spi = SPI()
cs = GPIO()
spi.open("SPI0")
cs.open('cs')
readBuf = bytearray(3)
writeBuf = bytearray([0x9f])
print(writeBuf)
print(readBuf)
cs.write(0)
value1 = spi.write(writeBuf,1)
value2=spi.read(readBuf,3)
print(value1)
print(value2)
cs.write(1)
print(writeBuf)
print(readBuf)
cs.close()
spi.close()
print("-------------------spi test--------------------")
{
"version": "1.0.0",
"io": {
"ADS1115": {
"type": "I2C",
"port": 1,
"addrWidth": 7,
"freq": 400000,
"mode": "master",
"devAddr": 72
},
"cs":{
"type":"GPIO",
"port": 15,
"dir": "output",
"pull":"pullup"
},
"mosi":{
"type":"GPIO",
"port": 16,
"dir": "output",
"pull":"pullup"
},
"miso":{
"type":"GPIO",
"port": 17,
"dir": "output",
"pull":"pullup"
},
"clk":{
"type":"GPIO",
"port": 18,
"dir": "output",
"pull":"pullup"
},
"SPI0": {
"type": "SPI",
"port": 0,
"mode": "master",
"freq": 2000000
}
},
"debugLevel": "ERROR"
}
-------------------spi test--------------------
bytearray(b'\x9f')
bytearray(b'\x00\x00\x00')
1
3
bytearray(b'\x9f')
bytearray(b'\xef@\x16')
-------------------spi test--------------------
3.读取spi设备的寄存器值(方法2)
from driver import SPI
from driver import GPIO
print("-------------------spi test--------------------")
spi = SPI()
cs = GPIO()
spi.open("SPI0")
cs.open('cs')
readBuf = bytearray(4)
writeBuf = bytearray([0x9f,0x00,0x00,0x00])
temp=bytearray(4)
print(writeBuf)
print(readBuf)
cs.write(0)
value=spi.writeRead(writeBuf,readBuf)
temp[0]=readBuf[0]
temp[1]=readBuf[1]
temp[2]=readBuf[2]
temp[3]=readBuf[3]
cs.write(1)
print(value)
print(temp)
print(temp[1:])
cs.close()
spi.close()
print("-------------------spi test--------------------")
{
"version": "1.0.0",
"io": {
"ADS1115": {
"type": "I2C",
"port": 1,
"addrWidth": 7,
"freq": 400000,
"mode": "master",
"devAddr": 72
},
"cs":{
"type":"GPIO",
"port": 15,
"dir": "output",
"pull":"pullup"
},
"mosi":{
"type":"GPIO",
"port": 16,
"dir": "output",
"pull":"pullup"
},
"miso":{
"type":"GPIO",
"port": 17,
"dir": "output",
"pull":"pullup"
},
"clk":{
"type":"GPIO",
"port": 18,
"dir": "output",
"pull":"pullup"
},
"SPI0": {
"type": "SPI",
"port": 0,
"mode": "master",
"freq": 2000000
}
},
"debugLevel": "DEBUG"
}
-------------------spi test--------------------
bytearray(b'\x9f\x00\x00\x00')
bytearray(b'\x00\x00\x00\x00')
4
bytearray(b'\xff\xef@\x16')
bytearray(b'\xef@\x16')
-------------------spi test--------------------
4.Class-SPI
SPI
open
打开spi
write
spi写操作,往指定寄存器内写数据
read
spi读操作,从指定寄存器中读取数据
writeRead
spi写和读操作,往寄存器写数据、从寄存器中取数据
close
关闭spi
5.总结
??本节介绍了如何使用haas506的driver库中的SPI模块。需要注意的有:
- 在进行spi的读写操作时,需要对cs引脚进行一些处理,即先置cs脚为低电平,待数据读取/写入完毕后置cs脚为高电平。
|