STM32 Arduino使用RF24库存在的问题

在使用Arduino在STM32F4芯片上对NRF24L01+模块进行操作时,我使用了经典的RF24库,可是发现无论是设置参数,还有收/发数据都有问题。

NRF24L01+模块支持的最大SPI速度为10Mhz。而分析RF24库数据后发现,它会根据芯片F_CPU的值去设置SPI的速度:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
_SPI.setBitOrder(MSBFIRST);
_SPI.setDataMode(SPI_MODE0);
#if !defined(F_CPU) || F_CPU < 20000000
_SPI.setClockDivider(SPI_CLOCK_DIV2);
#elif F_CPU < 40000000
_SPI.setClockDivider(SPI_CLOCK_DIV4);
#elif F_CPU < 80000000
_SPI.setClockDivider(SPI_CLOCK_DIV8);
#elif F_CPU < 160000000
_SPI.setClockDivider(SPI_CLOCK_DIV16);
#elif F_CPU < 320000000
_SPI.setClockDivider(SPI_CLOCK_DIV32);
#elif F_CPU < 640000000
_SPI.setClockDivider(SPI_CLOCK_DIV64);
#elif F_CPU < 1280000000
_SPI.setClockDivider(SPI_CLOCK_DIV128);
#else
#error "Unsupported CPU frequency. Please set correct SPI divider."
#endif

我们使用Arduino_Core_STM32库来让STM32支持Arduino环境,其中有定义:

1
2
3
4
5
6
7
8
9
  /* This variable is updated in three ways:
1) by calling CMSIS function SystemCoreClockUpdate()
2) by calling HAL API function HAL_RCC_GetHCLKFreq()
3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency
Note: If you use this function to configure the system clock; then there
is no need to call the 2 first functions listed above, since SystemCoreClock
variable is updated automatically.
*/
uint32_t SystemCoreClock = 16000000;
1
#define F_CPU SystemCoreClock

可是STM32F4的真实F_CPU应该是168Mhz,而RF24库设置SPI速度时,F_CPU值为16Mhz,使用两分频SPI_CLOCK_DIV2,使得SPI的速度过高。

在头文件中重新定义F_CPU的速度#define F_CPU 168000000后,终于能正确设置NRF24L01+模块参数,收/发数据了。