0

nRF52840 Express RNG
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

nRF52840 Express RNG

by czuvich on Thu Jun 13, 2019 7:16 pm

Is there a way to generate a uint32_t random number on the nRF52840 Express?

czuvich
 
Posts: 108
Joined: Fri May 20, 2016 6:53 pm

Re: nRF52840 Express RNG

by hathach on Wed Jun 19, 2019 11:31 am

you can use hardware random generator with SD api
https://github.com/adafruit/Adafruit_nR ... soc.h#L489

You can check out noridc document for how to use, there is a example here
https://github.com/adafruit/Adafruit_nR ... o/random.c

note this hw rng can generate something like 64 byte random number, since you only need 4-byte number, a simple sd_rand_application_vector_get(&value, 4) should work.

hathach
 
Posts: 1006
Joined: Tue Apr 23, 2013 1:02 am

Re: nRF52840 Express RNG

by czuvich on Wed Jun 19, 2019 5:10 pm

Thanks! For anyone else wanting a full solution using SD. I found the code online at https://git.card10.badge.events.ccc.de/ ... odrandom.c

Code: Select all | TOGGLE FULL SIZE
static uint32_t machine_rng_generate_random_word(void) {
  uint32_t retval = 0;
  uint32_t status;
  do {
    status = sd_rand_application_vector_get((uint8_t *)&retval, 4); // Extract 4 bytes
  } while (status != 0);

  return retval;
}

static inline int rand30(void) {
  uint32_t val = machine_rng_generate_random_word();
  return (val & 0x3fffffff); // binary mask b00111111111111111111111111111111
}

static inline int randbelow(int n) {
  return rand30() % n;
}

czuvich
 
Posts: 108
Joined: Fri May 20, 2016 6:53 pm

Please be positive and constructive with your questions and comments.