diff --git a/cores/arduino/WMath.cpp b/cores/arduino/WMath.cpp index f4ce2b754..9e1c2103a 100644 --- a/cores/arduino/WMath.cpp +++ b/cores/arduino/WMath.cpp @@ -23,10 +23,36 @@ extern "C" { #include "stdlib.h" + #include "hal/trng_api.h" } +#if defined(ARDUINO_PORTENTA_H7_M7) || \ + defined(ARDUINO_NICLA_VISION) || \ + defined(ARDUINO_OPTA) || \ + defined(ARDUINO_GIGA) +#define MBED_TRNG_SUPPORT 1 +static long trng() +{ + trng_t trng_obj; + trng_init(&trng_obj); + long value; + size_t olen; + if (trng_get_bytes(&trng_obj, (uint8_t*)&value, sizeof(value), &olen) != 0) + return -1; + trng_free(&trng_obj); + return value >= 0 ? value : -value; +} +#endif + +#if (MBED_TRNG_SUPPORT == 1) +static bool useTRNG = true; +#endif + void randomSeed(unsigned long seed) { +#if (MBED_TRNG_SUPPORT == 1) + useTRNG = false; +#endif if (seed != 0) { srandom(seed); } @@ -37,6 +63,11 @@ long random(long howbig) if (howbig == 0) { return 0; } +#if (MBED_TRNG_SUPPORT == 1) + if (useTRNG == true) { + return trng() % howbig; + } +#endif return random() % howbig; } @@ -48,3 +79,5 @@ long random(long howsmall, long howbig) long diff = howbig - howsmall; return random(diff) + howsmall; } + +#undef MBED_TRNG_SUPPORT