RT-Thread Studio学习(五)nrf24L01软件包
简介
本文将基于STM32F407VET芯片介绍如何在RT-Thread Studio开发环境下使用nrf24L01软件包。
新建RT-Thread项目并使用外部时钟
详细步骤参考文档《RT-Thread Studio学习之使用外部时钟系统》。
使能SPI
在使用nrf24L01软件包之前,要使能SPI驱动。具体参考官方文档《基于 RT-Thread Studio 的 SPI 驱动开发文档》
使用nrf24L01软件包
在 RT-Thread Setting
文件中借助图形化配置工具打开软件的软件包设置,如下图所示:
测试
在本文里,nrf24L01的CE引脚接芯片的PD1,IRQ引脚接芯片的PD11,CS引脚接芯片的PA8,模块为发送方。
main.c测试代码如下:
......
const static char *ROLE_TABLE[] = {"PTX", "PRX"};
static void rx_ind(nrf24_t nrf24, uint8_t *data, uint8_t len, int pipe)
{
/*! Don't need to care the pipe if the role is ROLE_PTX */
rt_kprintf("(p%d): ", pipe);
rt_kprintf((char *)data);
}
static void tx_done(nrf24_t nrf24, int pipe)
{
static int cnt = 0;
static char tbuf[32];
cnt++;
/*! Here just want to tell the user when the role is ROLE_PTX
the pipe have no special meaning except indicating (send) FAILED or OK
However, it will matter when the role is ROLE_PRX*/
if (nrf24->cfg.role == ROLE_PTX)
{
if (pipe == NRF24_PIPE_NONE)
rt_kprintf("tx_done failed");
else
rt_kprintf("tx_done ok");
}
else
{
rt_kprintf("tx_done ok");
}
rt_kprintf(" (pipe%d)\n", pipe);
rt_sprintf(tbuf, "My role is %s [%dth]\n", ROLE_TABLE[nrf24->cfg.role], cnt);
nrf24_send_data(nrf24, (uint8_t *)tbuf, rt_strlen(tbuf), pipe);
if(NRF24_DEMO_ROLE==ROLE_PTX)
rt_thread_mdelay(NRF24_DEMO_SEND_INTERVAL*300);
}
const static struct nrf24_callback _cb = {
.rx_ind = rx_ind,
.tx_done = tx_done,
};
static void thread_entry(void *param)
{
nrf24_t nrf24;
rt_kprintf("[nrf24/demo] Version:%s\n", PKG_NRF24L01_VERSION);
if(NRF24_DEMO_ROLE==ROLE_PRX)
rt_kprintf("[nrf24] configure in RX mode.\n");
else
rt_kprintf("[nrf24] configure in TX mode.\n");
nrf24 = nrf24_default_create(NRF24_DEMO_SPI_DEV_NAME, NRF24_DEMO_CE_PIN, NRF24_DEMO_IRQ_PIN, &_cb, NRF24_DEMO_ROLE);
if (nrf24 == RT_NULL)
{
rt_kprintf("\n[nrf24/demo] Failed to create nrf24. stop!\n");
for(;;) rt_thread_mdelay(10000);
}
else
{
rt_kprintf("[nrf24/demo] running.\n");
}
nrf24_send_data(nrf24, "Hi\n", 3, NRF24_DEFAULT_PIPE);
while (1)
{
nrf24_run(nrf24);
if(!nrf24->flags.using_irq)
rt_thread_mdelay(10);
}
}
static int nrf24l01_sample_init(void)
{
struct rt_spi_device *spi_dev_nrf24;
/* 查找 spi 设备获取设备句柄 */
rt_hw_spi_device_attach("spi1", NRF24_DEMO_SPI_DEV_NAME, GPIOA, GPIO_PIN_8);
spi_dev_nrf24 = (struct rt_spi_device *)rt_device_find(NRF24_DEMO_SPI_DEV_NAME);
if (!spi_dev_nrf24)
{
rt_kprintf("spi sample run failed! can't find %s device!\n", NRF24_DEMO_SPI_DEV_NAME);
}
rt_thread_t thread;
thread = rt_thread_create("nrfDemo", thread_entry, RT_NULL, 1024, RT_THREAD_PRIORITY_MAX/2, 20);
rt_thread_startup(thread);
return RT_EOK;
}
测试结果如下:
也就是发送失败了,原因在于软件包的通信过程是这样的:
也就是24L01必须成对调试,一个为接收端,一个为发送端。
接收端的为:
发送端的为
不论是接收端还是发送端,都会出现2个字节的乱码。因为这2个字节的乱码不在tbuf
中,可能是软件包的bug,所以不用管。只要记住,要发送的数据在tbuf
中,接收到的数据在(char *)data
中,
在串口shell中先运行nrf24 probe
,再运行nrf24 report
可以查看与nrf24模块相关的信息,如下图所示:
在这里,可以看到发送地址为默认值,即0x040302100
。该地址可以在nrf24l01.c
文件的nrf24_fill_default_config_on
函数中设置,要注意高低位字节顺序。