This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

Using the random number generator with SDK 15.3

I am trying to use RNG HAL  but I am not sure how to use it and there are (as far as I can tell) no examples. The only thing I need is generating random number. So I'm not using any cryptography, but just need simple random number.

I wrote the code like that:

nrf_rng_task_trigger(NRF_RNG_TASK_SET);
uint8_t value = nrf_rng_random_value_get();

But apparently I'm missing something. I have also added #define RNG_ENABLED 1 to sdk_config.h

Any suggestions what to do?

Thanks.

Parents Reply
  • You can use the nRF Thingy as the reference by using the nrf_drv_rng module.

    https://github.com/NordicSemiconductor/Nordic-Thingy52-FW

    static uint32_t random_vector_generate(uint8_t * p_buff, uint8_t size)
    {
        uint32_t err_code;
        uint8_t  bytes_available = 0;
    
        nrf_drv_rng_bytes_available(&bytes_available);
        uint8_t retries = 0;
        
        while (bytes_available < size)
        {
            retries++;
            NRF_LOG_WARNING("Too few random bytes available. Trying again \r\n");
            nrf_drv_rng_bytes_available(&bytes_available);
            nrf_delay_ms(5);
            
            if (retries > 5)    // Return after n attempts.
            {
                return NRF_ERROR_TIMEOUT;
            }
        }
        
        NRF_LOG_INFO("Available random bytes: %d \r\n", bytes_available);
    
        err_code = nrf_drv_rng_rand(p_buff, size);
        RETURN_IF_ERROR(err_code);
        
        NRF_LOG_INFO("Random value (hex): ");
        
        for (uint8_t i = 0; i < size; i++)
        {
            NRF_LOG_RAW_INFO("%02x", p_buff[i]);
        }
        
        NRF_LOG_RAW_INFO("\r\n");
    
        return NRF_SUCCESS;
    }

Children
Related