8 years ago.

STM32L4 Random rumber generator

Has somebody figured out how to use the RNG random number generator of the STM32L4 (Nucleo). I tried the following but it does not work. I found the functions in the HAL layer of the mbed source.

Regards Helmut

unsigned int TestRNG(void) { static RNG_HandleTypeDef rng_inst;

rng_inst.Instance = RNG;

if (HAL_RNG_Init(&rng_inst) != HAL_OK) return 0xffffffff;

uint32_t rnd = 0xff; if (HAL_RNG_GenerateRandomNumber(&rng_inst, &rnd) != HAL_OK) return 0xfffffffE;

HAL_RNG_DeInit(&rng_inst);

return rnd; }

1 Answer

8 years ago.

You are missing at the beginning:

__HAL_RCC_RNG_CLK_ENABLE ();

Thanks for the advise, unfortunulaty this does not solve the problem, The call to HAL_RNG_GenerateRandomNumber returns HAL_RNG_STATE_TIMEOUT (0x03). I also tried HAL_RNG_GetRandomNumber which always returns 0.

posted by Helmut Tschemernjak 02 May 2016

This sequence looks ok, but there is one more important thing. RNG unit needs to work RNG_CLK. I'm afraid that in the library mbed this clock is not turned on.
I used (successfully) RNG in another STM32 by HAL functions as you use, but I do not have Nucleo L476 and I can not test how well I suspect the reasons for your problem.

Maybe try at the beginning:

RCC_PeriphCLKInitTypeDef PeriphClkInitStruct;

  /*Select PLLQ output as RNG clock source */
  PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RNG;
  PeriphClkInitStruct.RngClockSelection = RCC_RNGCLKSOURCE_PLL;
  HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct);


( this is fragment of STM RNG demo for L476)

posted by Nothing Special 02 May 2016

Thanks for the idea, the problem stays the same -3 (Timeout).

posted by Helmut Tschemernjak 14 May 2016

Using both HAL_RCC_RNG_CLK_ENABLE () and HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) worked for me. I get random bits at the rate of 31.37 million bits/second. The ref manual says you should get 32-bits every 40 ticks of RNG_CLK, so RNG_CLK appears to be 40MHz in this case. (on a crystal-clocked STM32L4, the RNG_CLK runs at 48mhz, and i get 37.2 million random bits/sec)

posted by tom dunigan 30 May 2016