Skip to content

Commit 45bf25a

Browse files
robert-hhdpgeorge
authored andcommitted
samd/moduos: Add uos.urandom() for SAMD51.
Based on the hardware RNG.
1 parent 15212ae commit 45bf25a

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

ports/samd/boards/mpconfig_samd51.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
#define MICROPY_PY_BUILTINS_COMPLEX (0)
66
#define MICROPY_PY_MATH (0)
77
#define MICROPY_PY_CMATH (0)
8+
#define MICROPY_PY_UOS_URANDOM (1)
9+
#define MICROPY_PY_URANDOM_SEED_INIT_FUNC (trng_random_u32())
10+
unsigned long trng_random_u32(void);
811

912
// Due to a limitation in the TC counter for us, the ticks period is 2**29
1013
#define MICROPY_PY_UTIME_TICKS_PERIOD (0x20000000)

ports/samd/moduos.c

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,46 @@
3434
#include "modmachine.h"
3535
#include "sam.h"
3636

37+
#if defined(MCU_SAMD51)
38+
static bool initialized = false;
39+
40+
STATIC void trng_start(void) {
41+
if (!initialized) {
42+
MCLK->APBCMASK.bit.TRNG_ = 1;
43+
REG_TRNG_CTRLA = TRNG_CTRLA_ENABLE;
44+
initialized = true;
45+
}
46+
}
47+
48+
uint32_t trng_random_u32(void) {
49+
trng_start();
50+
while ((REG_TRNG_INTFLAG & TRNG_INTFLAG_DATARDY) == 0) {
51+
}
52+
return REG_TRNG_DATA;
53+
}
54+
55+
#if MICROPY_PY_UOS_URANDOM
56+
STATIC mp_obj_t mp_uos_urandom(mp_obj_t num) {
57+
mp_int_t n = mp_obj_get_int(num);
58+
vstr_t vstr;
59+
vstr_init_len(&vstr, n);
60+
uint32_t rngval = 0;
61+
62+
trng_start();
63+
for (int i = 0; i < n; i++) {
64+
if ((i % 4) == 0) {
65+
rngval = trng_random_u32();
66+
}
67+
vstr.buf[i] = rngval & 0xff;
68+
rngval >>= 8;
69+
}
70+
return mp_obj_new_bytes_from_vstr(&vstr);
71+
}
72+
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_uos_urandom_obj, mp_uos_urandom);
73+
74+
#endif // MICROPY_PY_UOS_URANDOM
75+
#endif // defined(MCU_SAMD51)
76+
3777
#if MICROPY_PY_UOS_DUPTERM_BUILTIN_STREAM
3878
bool mp_uos_dupterm_is_builtin_stream(mp_const_obj_t stream) {
3979
const mp_obj_type_t *type = mp_obj_get_type(stream);

0 commit comments

Comments
 (0)