SPI 驱动程序可以使用多个 SPI 外设实例。 可以使用 menuconfig 工具为每个项目选择外设和 DMA 支持配置的实例,通常保存在 C 头文件中。 默认情况下,配置保存为 rtconfig.h。
适配器层注册 RT-Thread 请求的硬件支持功能,并使用 HAL 实现这些功能。 对于 SPI HAL 公开的 API,请参考 SPI。 对于使用 RT-Thread 的用户,可以使用以下代码作为示例:
rt_device_t rt_device_find(const char *name);
name: spi1 / spi2
rt_err_t rt_hw_spi_device_attach(const char *bus_name, const char *device_name);
bus_name: spi1 / spi2
rt_err_t rt_device_open(rt_device_t dev, rt_uint16_t oflag);
oflag: dma mode: RT_DEVICE_FLAG_RDWR|RT_DEVICE_FLAG_DMA_RX|RT_DEVICE_FLAG_DMA_TX
int mode: RT_DEVICE_FLAG_RDWR|RT_DEVICE_FLAG_INT_RX|RT_DEVICE_FLAG_INT_TX
normal mode: RT_DEVICE_FLAG_RDWR
rt_err_t rt_spi_configure(struct rt_spi_device *device, struct rt_spi_configuration *cfg)
cfg: use struct rt_spi_configuration as following:
struct rt_spi_configuration
{
rt_uint8_t mode;
rt_uint8_t data_width;
rt_uint16_t frameMode;
rt_uint32_t max_hz;
};
rt_size_t rt_spi_transfer(struct rt_spi_device *device,
const void *send_buf,
void *recv_buf,
rt_size_t length);
void spi_trans_test()
{
rt_device_t spi_bus = RT_NULL;
struct rt_spi_device *spi_dev = RT_NULL;
struct rt_spi_configuration cfg;
rt_err_t err_code;
rt_uint8_t *rx_buff = RT_NULL;
rt_uint8_t *tx_buff = RT_NULL;
spi_bus = rt_device_find("spi1");
if (RT_NULL == spi_bus)
{
return;
}
spi_dev = (struct rt_spi_device *)rt_device_find("spi1_dev");
if (RT_NULL == spi_dev)
{
err_code = rt_hw_spi_device_attach("spi1", "spi1_dev");
if (RT_EOK != err_code)
{
return;
}
spi_dev = (struct rt_spi_device *) rt_device_find("spi1_dev");
}
if (RT_NULL == spi_dev)
{
return;
}
err_code = rt_device_open(&(spi_dev->parent), RT_DEVICE_FLAG_RDWR);
if (RT_EOK != err_code)
{
return;
}
cfg.data_width = 8;
cfg.max_hz = 4000000;
cfg.mode = RT_SPI_MSB | RT_SPI_MASTER | RT_SPI_MODE_1;
cfg.frameMode = RT_SPI_MOTO;
err_code = rt_spi_configure(spi_dev, &cfg);
uassert_int_equal(RT_EOK, err_code);
err_code = rt_spi_take_bus(spi_dev);
uassert_int_equal(RT_EOK, err_code);
err_code = rt_spi_take(spi_dev);
uassert_int_equal(RT_EOK, err_code);
rx_buff = rt_malloc(rw_len + 2);
tx_buff = rt_malloc(rw_len + 2);
uassert_true((RT_NULL != tx_buff) && (RT_NULL != rx_buff));
if ((RT_NULL != tx_buff) && (RT_NULL != rx_buff))
{
for (int m = 0; m < rw_len; m++)
{
tx_buff[m] = m;
}
memset(rx_buff, 0x5a, rw_len + 2);
rt_spi_transfer(spi_dev, tx_buff, rx_buff, rw_len / (data_size / 8));
}
if (RT_NULL != tx_buff)
{
rt_free(tx_buff);
}
if (RT_NULL != rx_buff)
{
rt_free(rx_buff);
}
err_code = rt_spi_release(spi_dev);
uassert_int_equal(RT_EOK, err_code);
err_code = rt_spi_release_bus(spi_dev);
uassert_int_equal(RT_EOK, err_code);
err_code = rt_device_close(&(spi_dev->parent));
uassert_true_ret(RT_EOK == err_code);
}