rng.c 964 Bytes
Newer Older
1
2
#include <string.h>

3
4
5
6
7
8
9
10
#include "stm32f4xx_hal.h"

#include "misc.h"
#include "mpconfig.h"
#include "qstr.h"
#include "obj.h"
#include "rng.h"

11
12
#if MICROPY_HW_ENABLE_RNG

13
14
/// \moduleref pyb

15
16
17
18
19
20
21
STATIC RNG_HandleTypeDef RNGHandle = {.Instance = NULL};

void rng_init0(void) {
    // reset the RNG handle
    memset(&RNGHandle, 0, sizeof(RNG_HandleTypeDef));
    RNGHandle.Instance = RNG;
}
22
23
24

void rng_init(void) {
    __RNG_CLK_ENABLE();
25
    HAL_RNG_Init(&RNGHandle);
26
27
}

28
uint32_t rng_get(void) {
29
30
31
32
    if (RNGHandle.State == HAL_RNG_STATE_RESET) {
        rng_init();
    }
    return HAL_RNG_GetRandomNumber(&RNGHandle);
33
34
}

35
36
/// \function rng()
/// Return a 30-bit hardware generated random number.
37
STATIC mp_obj_t pyb_rng_get(void) {
38
39
40
41
    if (RNGHandle.State == HAL_RNG_STATE_RESET) {
        rng_init();
    }
    return mp_obj_new_int(HAL_RNG_GetRandomNumber(&RNGHandle) >> 2);
42
43
44
}

MP_DEFINE_CONST_FUN_OBJ_0(pyb_rng_get_obj, pyb_rng_get);
45
46

#endif // MICROPY_HW_ENABLE_RNG