---
title: "Random numbers"
canonical_url: https://developer.repebble.com/pebbleos/docs/samples/drivers/rng/
last_updated: 2026-11-17
sdk_version: 4.44
---
# Random numbers

Source: https://developer.repebble.com/pebbleos/docs/samples/drivers/rng/

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.

Run:

`pbl samples samples/drivers/rng`

Boards:

every board but sf32lb57\_dpi\_hdk

## Sources

src/main.c

```
#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 1000int 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;}
```

## Output

```
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](https://github.com/coredevices/pebbleos/commit/9e782207f53f8f1c02f7b13ea40cdc092d7bab3d). This page is maintained in the pebbleos repository: [docs/samples/drivers/rng.md](https://github.com/coredevices/pebbleos/blob/9e782207f53f8f1c02f7b13ea40cdc092d7bab3d/docs/samples/drivers/rng.md).
