This sample prints a few words from the hardware random number generator with
rng_rand(), then draws a thousand more and counts how many repeat the one
before and how many of their bits are set: about 500 per mille, with no
repeats, from a good source.
The emulator has no generator: its driver returns a fixed word, so every word repeats.
pbl samples samples/drivers/rng
every board but sf32lb57_dpi_hdk
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <pbl/drivers/rng.h>
#include <pbl/kernel/compiler.h>
#define WORDS 4
#define STATS_WORDS 1000
int main(void) {
uint32_t val, prev = 0U;
unsigned int ones = 0U, repeats = 0U;
for (int i = 0; i < WORDS; i++) {
if (!rng_rand(&val)) {
fprintf(stderr, "rng: generation failed\n");
return -EIO;
}
printf("rng: 0x%08x\n", (unsigned int)val);
}
/* A good source sets about half of the bits, and does not repeat itself. */
for (int i = 0; i < STATS_WORDS; i++) {
if (!rng_rand(&val)) {
fprintf(stderr, "rng: generation failed\n");
return -EIO;
}
if (i > 0 && val == prev) {
repeats++;
}
ones += PBL_POPCOUNT(val);
prev = val;
}
printf("rng: %d words, %u repeated, %u per mille of the bits set\n", STATS_WORDS, repeats,
ones * 1000U / (STATS_WORDS * 32U));
printf("Sample done\n");
return 0;
}
rng: 0x[0-9a-f]+
rng: 0x[0-9a-f]+
rng: 0x[0-9a-f]+
rng: 0x[0-9a-f]+
rng: 1000 words, \d+ repeated, \d+ per mille of the bits set
Sample done
Generated from PebbleOS 9e782207f. This page is maintained in the pebbleos repository: docs/samples/drivers/rng.md.