SPI
提示
如下案例使用犀牛派 X1 的 树莓派 40PIN 引脚,具体位置请参见 硬件信息。
SPI 简介
串行外设接口(SPI)是同步串行通信的实际标准(有许多变体),主要用于嵌入式系统中集成电路之间的短距离有线通信。
准备
- 一块犀牛派 X1
- 一个母头杜邦线
连接
使用杜邦线短接 19 和 21
测试
- 查看 spidev 设备
shell
ls /dev/spidev*- 打开终端,在终端中输入命令安装必要的 Python 库。
shell
sudo pip3 install spidev- 新建一个名为 spitest.py 的文件,并将如下代码粘贴到其中:
shell
import spidev
import time
class SPILoopbackTester:
def __init__(self, bus=0, device=0, speed=1000000):
"""
初始化SPI回环测试器
:param bus: SPI总线编号
:param device: SPI设备编号
:param speed: 通信速度(Hz)
"""
self.spi = spidev.SpiDev()
self.bus = bus
self.device = device
self.speed = speed
self.connected = False
def connect(self):
"""连接到SPI设备"""
try:
self.spi.open(self.bus, self.device)
self.spi.max_speed_hz = self.speed
self.connected = True
print(f"成功连接到SPI总线 {self.bus}, 设备 {self.device}, 速度 {self.speed}Hz")
return True
except Exception as e:
print(f"SPI连接失败: {e}")
return False
def test_single_byte(self, test_byte):
"""测试单个字节的回环"""
if not self.connected:
print("请先连接SPI设备")
return False
try:
# 发送并接收数据
rx_data = self.spi.xfer2([test_byte])
received_byte = rx_data[0]
# 验证结果
if received_byte == test_byte:
print(f"测试通过 - 发送: 0x{test_byte:02X}, 接收: 0x{received_byte:02X}")
return True
else:
print(f"测试失败 - 发送: 0x{test_byte:02X}, 接收: 0x{received_byte:02X}")
return False
except Exception as e:
print(f"测试出错: {e}")
return False
def test_multiple_bytes(self, test_data):
"""测试多个字节的回环"""
if not self.connected:
print("请先连接SPI设备")
return False
try:
# 发送并接收数据
rx_data = self.spi.xfer2(test_data)
# 验证结果
success = True
print("多字节测试结果:")
print("发送\t接收\t结果")
print("-" * 30)
for tx, rx in zip(test_data, rx_data):
status = "通过" if tx == rx else "失败"
if tx != rx:
success = False
print(f"0x{tx:02X}\t0x{rx:02X}\t{status}")
return success
except Exception as e:
print(f"测试出错: {e}")
return False
def run_complete_test(self):
"""运行完整的测试套件"""
print("\n===== 开始SPI回环测试 =====")
print(f"测试配置: 总线={self.bus}, 设备={self.device}, 速度={self.speed}Hz")
# 测试单个特殊字节
test_bytes = [0x00, 0xFF, 0xAA, 0x55, 0x33, 0xCC]
single_byte_result = True
print("\n----- 单个字节测试 -----")
for b in test_bytes:
if not self.test_single_byte(b):
single_byte_result = False
# 测试随机序列
print("\n----- 多字节序列测试 -----")
sequence = list(range(0, 256, 16)) # 0x00, 0x10, 0x20, ..., 0xF0
multi_byte_result = self.test_multiple_bytes(sequence)
# 测试连续数据
print("\n----- 连续数据测试 -----")
continuous_data = list(range(10, 20)) # 10到19的连续数字
continuous_result = self.test_multiple_bytes(continuous_data)
# 总体结果
print("\n===== 测试总结 =====")
overall_result = single_byte_result and multi_byte_result and continuous_result
if overall_result:
print("✅ 所有SPI回环测试通过!")
else:
print("❌ 部分SPI回环测试失败!")
return overall_result
def close(self):
"""关闭SPI连接"""
if self.connected:
self.spi.close()
self.connected = False
print("\nSPI连接已关闭")
if __name__ == "__main__":
# 创建测试器实例 (默认使用SPI0, CE0)
tester = SPILoopbackTester(bus=1, device=0, speed=1000000)
try:
if tester.connect():
# 运行完整测试
tester.run_complete_test()
time.sleep(1)
finally:
# 确保资源正确释放
tester.close()- 保存后,输入以下命令进行测试
shell
sudo spitest.py- 检查输出结果
结果中会打印"所有 SPI 回环测试通过!"