Skip to content

Commit 05bde25

Browse files
committed
Add random to ESP32-S2, fix it on STM32
1 parent 2529c0a commit 05bde25

File tree

3 files changed

+14
-4
lines changed

3 files changed

+14
-4
lines changed

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

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@
3030
#include "py/objtuple.h"
3131
#include "py/qstr.h"
3232

33+
#include "esp_system.h"
34+
3335
STATIC const qstr os_uname_info_fields[] = {
3436
MP_QSTR_sysname, MP_QSTR_nodename,
3537
MP_QSTR_release, MP_QSTR_version, MP_QSTR_machine
@@ -57,5 +59,15 @@ mp_obj_t common_hal_os_uname(void) {
5759
}
5860

5961
bool common_hal_os_urandom(uint8_t* buffer, uint32_t length) {
60-
return false;
62+
uint32_t i = 0;
63+
while (i < length) {
64+
uint32_t new_random = esp_random();
65+
for (int j = 0; j < 4 && i < length; j++) {
66+
buffer[i] = new_random & 0xff;
67+
i++;
68+
new_random >>= 8;
69+
}
70+
}
71+
72+
return true;
6173
}

ports/esp32s2/mpconfigport.mk

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ CIRCUITPY_COUNTIO = 0
2525

2626
# These modules are implemented in shared-module/ - they can be included in
2727
# any port once their prerequisites in common-hal are complete.
28-
CIRCUITPY_RANDOM = 0 # Requires OS
2928
CIRCUITPY_USB_MIDI = 0 # Requires USB
3029
CIRCUITPY_ULAB = 0 # No requirements, but takes extra flash
3130

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

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,10 @@ bool common_hal_os_urandom(uint8_t *buffer, uint32_t length) {
7777
uint32_t start = HAL_GetTick();
7878
//the HAL function has a timeout, but it isn't long enough, and isn't adjustable
7979
while(!(__HAL_RNG_GET_FLAG(&handle,RNG_FLAG_DRDY)) && ((HAL_GetTick() - start) < RNG_TIMEOUT));
80-
//
8180
if (HAL_RNG_GenerateRandomNumber(&handle, &temp) != HAL_OK) {
8281
mp_raise_ValueError(translate("Random number generation error"));
8382
}
84-
*buffer = (uint8_t)temp;
83+
buffer[i] = (uint8_t)temp;
8584
}
8685

8786
//shut down the peripheral

0 commit comments

Comments
 (0)