SPI 驅(qū)動(dòng)程序可以使用多個(gè) SPI 外設(shè)實(shí)例。 可以使用 menuconfig 工具為每個(gè)項(xiàng)目選擇外設(shè)和 DMA 支持配置的實(shí)例,通常保存在 C 頭文件中。 默認(rèn)情況下,配置保存為 rtconfig.h。
適配器層注冊(cè) RT-Thread 請(qǐng)求的硬件支持功能,并使用 HAL 實(shí)現(xiàn)這些功能。 對(duì)于 SPI HAL 公開的 API,請(qǐng)參考 SPI。 對(duì)于使用 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);
}