Skip to content

Commit c229345

Browse files
committed
improve efficiency of stm32 random gen
1 parent 05bde25 commit c229345

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

ports/stm/common-hal/os/__init__.c

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,15 +72,20 @@ bool common_hal_os_urandom(uint8_t *buffer, uint32_t length) {
7272
if (HAL_RNG_Init(&handle) != HAL_OK) mp_raise_ValueError(translate("RNG Init Error"));
7373

7474
//Assign bytes
75-
for (uint i = 0; i < length; i++) {
76-
uint32_t temp;
75+
uint32_t i = 0;
76+
while (i < length) {
77+
uint32_t new_random;
7778
uint32_t start = HAL_GetTick();
7879
//the HAL function has a timeout, but it isn't long enough, and isn't adjustable
7980
while(!(__HAL_RNG_GET_FLAG(&handle,RNG_FLAG_DRDY)) && ((HAL_GetTick() - start) < RNG_TIMEOUT));
80-
if (HAL_RNG_GenerateRandomNumber(&handle, &temp) != HAL_OK) {
81+
if (HAL_RNG_GenerateRandomNumber(&handle, &new_random) != HAL_OK) {
8182
mp_raise_ValueError(translate("Random number generation error"));
8283
}
83-
buffer[i] = (uint8_t)temp;
84+
for (int j = 0; j < 4 && i < length; j++) {
85+
buffer[i] = new_random & 0xff;
86+
i++;
87+
new_random >>= 8;
88+
}
8489
}
8590

8691
//shut down the peripheral

0 commit comments

Comments
 (0)