Skip to content

Commit

Permalink
Merge pull request #895 from pennam/trng
Browse files Browse the repository at this point in the history
Enable (t)rng support for STM32H7 and NANO RP2040
  • Loading branch information
pennam committed Jun 28, 2024
2 parents 508d85e + 447062f commit 496ffbd
Show file tree
Hide file tree
Showing 2 changed files with 758 additions and 0 deletions.
33 changes: 33 additions & 0 deletions cores/arduino/WMath.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,36 @@

extern "C" {
#include "stdlib.h"
#include "hal/trng_api.h"
}
#if defined(ARDUINO_NANO_RP2040_CONNECT) || \
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);
}
Expand All @@ -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;
}

Expand All @@ -48,3 +79,5 @@ long random(long howsmall, long howbig)
long diff = howbig - howsmall;
return random(diff) + howsmall;
}

#undef MBED_TRNG_SUPPORT
Loading

0 comments on commit 496ffbd

Please sign in to comment.