From 09d1d12656f128ba534f5860f44f8716c5bd3957 Mon Sep 17 00:00:00 2001 From: Charlie Birks Date: Sun, 5 Mar 2023 20:32:49 +0000 Subject: [PATCH] pico: use pico_rand for random API It's the closest we're getting to a hardware RNG. Saves ~2.5k RAM. (Requires pico-sdk 1.5.0) --- 32blit-pico/CMakeLists.txt | 2 +- 32blit-pico/main.cpp | 22 +++------------------- 2 files changed, 4 insertions(+), 20 deletions(-) diff --git a/32blit-pico/CMakeLists.txt b/32blit-pico/CMakeLists.txt index c52ce785d..b8e1d7fea 100644 --- a/32blit-pico/CMakeLists.txt +++ b/32blit-pico/CMakeLists.txt @@ -36,7 +36,7 @@ target_sources(BlitHalPico INTERFACE ${CMAKE_CURRENT_LIST_DIR}/usb_descriptors.c ) -target_link_libraries(BlitHalPico INTERFACE hardware_dma hardware_pio hardware_pwm hardware_spi pico_multicore pico_stdlib pico_unique_id tinyusb_device) +target_link_libraries(BlitHalPico INTERFACE hardware_dma hardware_pio hardware_pwm hardware_spi pico_multicore pico_stdlib pico_unique_id pico_rand tinyusb_device) target_include_directories(BlitHalPico INTERFACE ${CMAKE_CURRENT_LIST_DIR} # for tusb_config ${CMAKE_CURRENT_LIST_DIR}/../3rd-party/fatfs diff --git a/32blit-pico/main.cpp b/32blit-pico/main.cpp index ccd3e0711..867302419 100644 --- a/32blit-pico/main.cpp +++ b/32blit-pico/main.cpp @@ -1,10 +1,10 @@ -#include -#include +#include #include "hardware/structs/rosc.h" #include "hardware/vreg.h" #include "pico/binary_info.h" #include "pico/multicore.h" +#include "pico/rand.h" #include "pico/stdlib.h" #include "audio.hpp" @@ -26,24 +26,8 @@ static uint32_t now() { return to_ms_since_boot(get_absolute_time()); } -static uint32_t get_random_seed() { - uint32_t seed = 0; - - // use the hardware random bit to seed - for(int i = 0; i < 32; i++) { - seed <<= 1; - seed |= rosc_hw->randombit & 1; - sleep_us(1); // don't read too fast - } - - return seed; -} - static uint32_t random() { - static std::mt19937 random_generator(get_random_seed()); - static std::uniform_int_distribution random_distribution; - - return random_distribution(random_generator); + return get_rand_32(); } static void debug(const char *message) {