SPI

rt thread spi 使用

发布于 2019-07-17 09:59:15
有没有尝试按照rt thread 官方文档的spi 案例敲代码,但是发现总线错误或者spi数据传输不成功的情况,那么下面可以看一下我的记录。

#include 
#include
#include "drv_spi.h" //注意添加这个头文件,不然rt_hw_spi_device_attach 无法调用

#define FLASH_DEVICE_NAME "spi12"

struct rt_spi_device *spi_dev_flash;


struct rt_spi_message msg1, msg2;


struct rt_spi_message *res;


struct rt_spi_configuration cfg;


rt_uint8_t flash_id[] = {0x90, 0x24};

//文档中提示使用rt_hw_spi_device_attach这个函数,但是没有码
static int rt_hw_spi_flash_init(void)
{
__HAL_RCC_GPIOC_CLK_ENABLE();
rt_hw_spi_device_attach("spi1", "spi12", GPIOC, GPIO_PIN_0); //我用的野火指南者开发板,CS片选引脚为PC0
return RT_EOK;
}


//测试代码,直接放在main 中了
int main(void)
{
//挂载spi12 到 spi1
rt_hw_spi_flash_init();

spi_dev_flash = (struct rt_spi_device *)rt_device_find(FLASH_DEVICE_NAME);

if(spi_dev_flash != RT_NULL)
{
rt_kprintf("find the flash on the spi bus\n");
}
else
{
rt_kprintf("can't find the device\n");
}

//配置spi
cfg.data_width = 8;
cfg.mode = RT_SPI_MASTER | RT_SPI_MODE_0 | RT_SPI_MSB;
cfg.max_hz = 20*1000*1000; //20Mhz

rt_spi_configure(spi_dev_flash, &cfg);

//向设备发送数据
msg1.send_buf = &flash_id[0];
msg1.recv_buf = RT_NULL;
msg1.length = 1;
msg1.cs_take = 1;
msg1.cs_release = 0;
msg1.next = &msg2;

msg2.send_buf = &flash_id[1];
msg2.recv_buf = RT_NULL;
msg2.length = 1;
msg2.cs_take = 0;
msg2.cs_release = 1;
msg2.next = RT_NULL;

res = rt_spi_transfer_message(spi_dev_flash, &msg1);

if(res == RT_NULL)
{
rt_kprintf("data transfer ok from spi12\n");
}

return 0;
}


最后的输出结果如下:
24 (2).png




0x90, 可以发现上面设置的20Mhz 是 spi 数据传输时的,clk 频率。
24 (1).png
0x24

spi12 设备 工作正常。


查看更多

关注者
0
被浏览
765
1 个回答

撰写答案

请登录后再发布答案,点击登录

发布
问题

分享
好友