gaylord wrote on Monday, February 18, 2019:
Hello. I created a usRand() function to use the RNG in the STMF32429. According to the manual, this generates a random number once it’s enabled. I would expect that after enabling the RNG, i can just read the register.
Using HAL_RNG_GenerateRandomNumber from stm32f4xx_hal_rng.c, it does just read the register.
HAL_StatusTypeDef HAL_RNG_GenerateRandomNumber(RNG_HandleTypeDef *hrng, uint32_t *random32bit)
{
uint32_t tickstart = 0U;
HAL_StatusTypeDef status = HAL_OK;
/* Process Locked */
__HAL_LOCK(hrng);
/* Check RNG peripheral state */
if(hrng->State == HAL_RNG_STATE_READY)
{
/* Change RNG peripheral state */
hrng->State = HAL_RNG_STATE_BUSY;
/* Get tick */
tickstart = HAL_GetTick();
/* Check if data register contains valid random data */
while(__HAL_RNG_GET_FLAG(hrng, RNG_FLAG_DRDY) == RESET)
{
if((HAL_GetTick() - tickstart ) > RNG_TIMEOUT_VALUE)
{
hrng->State = HAL_RNG_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hrng);
return HAL_TIMEOUT;
}
}
/* Get a 32bit Random number */
hrng->RandomNumber = hrng->Instance->DR;
*random32bit = hrng->RandomNumber;
hrng->State = HAL_RNG_STATE_READY;
}
else
{
status = HAL_ERROR;
}
/* Process Unlocked */
__HAL_UNLOCK(hrng);
return status;
}
But, when I get a random number using this, I keep getting the same number, as if the RNG isn’t running.
Seeing how it’s used in the http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/TCP-IP_FAT_Examples_ST_STM32F407.html sample, the value from the RNG seems to be being used as a seed, rather than a random number. This seems wrong, but it’s not working as I expect, so I’m missing something. Can anyone explain how uxRand should be written for an STMF32 with an RNG?
UBaseType_t uxRand( void )
{
const uint32_t ulMultiplier = 0x015a4e35UL, ulIncrement = 1UL;
static BaseType_t xInitialised = pdFALSE;
/* Don't initialise until the scheduler is running, as the timeout in the
random number generator uses the tick count. */
if( xInitialised == pdFALSE )
{
if( xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED )
{
RNG_HandleTypeDef xRND;
uint32_t ulSeed;
/* Generate a random number with which to seed the local pseudo random
number generating function. */
HAL_RNG_Init( &xRND );
HAL_RNG_GenerateRandomNumber( &xRND, &ulSeed );
prvSRand( ulSeed );
xInitialised = pdTRUE;
}
}
/* Utility function to generate a pseudo random number. */
ulNextRand = ( ulMultiplier * ulNextRand ) + ulIncrement;
return( ( int ) ( ulNextRand >> 16UL ) & 0x7fffUL );
}