diff --git a/cores/arduino/WMath.cpp b/cores/arduino/WMath.cpp index da8c03fa..83184d13 100644 --- a/cores/arduino/WMath.cpp +++ b/cores/arduino/WMath.cpp @@ -23,10 +23,47 @@ extern "C" { #include + #include "common_data.h" } +#if defined (ARDUINO_PORTENTA_C33) +#define SCE_TRNG_SUPPORT 1 +static long trng() +{ + uint32_t value[4]; + if (R_SCE_Open(&sce_ctrl, &sce_cfg) != FSP_SUCCESS) + return -1; + R_SCE_RandomNumberGenerate(value); + R_SCE_Close(&sce_ctrl); + return (long)value[0] >= 0 ? value[0] : -value[0]; +} +#endif + +#if defined(ARDUINO_UNOR4_WIFI) || defined(ARDUINO_UNOR4_MINIMA) +#define SCE_TRNG_SUPPORT 1 +extern "C" { + fsp_err_t HW_SCE_McuSpecificInit(void); + fsp_err_t HW_SCE_RNG_Read(uint32_t * OutData_Text); +} +static long trng() +{ + uint32_t value[4]; + if (HW_SCE_McuSpecificInit() != FSP_SUCCESS) + return -1; + HW_SCE_RNG_Read(value); + return (long)value[0] >= 0 ? value[0] : -value[0]; +} +#endif + +#if (SCE_TRNG_SUPPORT == 1) +static bool useTRNG = true; +#endif + void randomSeed(unsigned long seed) { +#if (SCE_TRNG_SUPPORT == 1) + useTRNG = false; +#endif if (seed != 0) { srand(seed); } @@ -37,6 +74,11 @@ long random(long howbig) if (howbig == 0) { return 0; } +#if (SCE_TRNG_SUPPORT == 1) + if (useTRNG == true) { + return trng() % howbig; + } +#endif return rand() % howbig; } @@ -48,3 +90,5 @@ long random(long howsmall, long howbig) long diff = howbig - howsmall; return random(diff) + howsmall; } + +#undef SCE_TRNG_SUPPORT