Landtiger LPC1768 C BigLib 1
A self made, custom C library for the LandTiger board.
 
Loading...
Searching...
No Matches
prng.h File Reference
#include "types.h"

Go to the source code of this file.

Enumerations

enum  PRNG_Config { PRNG_USE_AUTO_SEED }
 

Functions

void PRNG_Set (u32 seed)
 Initializes the PRNG by seeding it with the given seed. Use PRNG_USE_AUTO_SEED to seed it automatically using an HW entropy source.
 
void PRNG_Release (void)
 Releases the HW entropy sources used to seed the PRNG.
 
u32 PRNG_Next (void)
 Generates the next pseudo-random number.
 
u32 PRNG_Range (u32 min, u32 max)
 Generates a pseudo-random number in the given range, inclusive.
 

Enumeration Type Documentation

◆ PRNG_Config

Enumerator
PRNG_USE_AUTO_SEED 

PRNG automatically seeds itself using an hardware entropy source.

Definition at line 8 of file prng.h.

9{
PRNG_Config
Definition prng.h:9
@ PRNG_USE_AUTO_SEED
PRNG automatically seeds itself using an hardware entropy source.
Definition prng.h:11

Function Documentation

◆ PRNG_Next()

u32 PRNG_Next ( void  )

Generates the next pseudo-random number.

Returns
The PRN

Definition at line 38 of file prng.c.

39{
40 // A simple linear congruential generator (LCG) for pseudo-random numbers
41 prng_state = (1103515245 * prng_state + 12345) & 0x7FFFFFFF;
42 return prng_state;
43}
_PRIVATE u32 prng_state
Definition prng.c:5

◆ PRNG_Range()

u32 PRNG_Range ( u32  min,
u32  max 
)

Generates a pseudo-random number in the given range, inclusive.

Parameters
minLower bound
maxUpper bound
Returns
The PRN

Definition at line 49 of file prng.c.

50{
51 if (min > max)
52 {
53 // Swap min and max if inputs are invalid
54 u32 temp = min;
55 min = max;
56 max = temp;
57 }
58
59 u32 range = max - min + 1;
60 return (PRNG_Next() % range) + min;
61}
u32 PRNG_Next(void)
Generates the next pseudo-random number.
Definition prng.c:38
uint32_t u32
Definition types.h:6

◆ PRNG_Release()

void PRNG_Release ( void  )

Releases the HW entropy sources used to seed the PRNG.

Definition at line 29 of file prng.c.

30{
31 // Stopping SysTick
32 SysTick->CTRL = 0;
33 prng_state = 0;
34}

◆ PRNG_Set()

void PRNG_Set ( u32  seed)

Initializes the PRNG by seeding it with the given seed. Use PRNG_USE_AUTO_SEED to seed it automatically using an HW entropy source.

Parameters
seedThe seed to use.

Definition at line 7 of file prng.c.

8{
9 if (seed == (u32)PRNG_USE_AUTO_SEED)
10 {
11 // Starting SysTick if it's not already running
12 if (!(SysTick->CTRL & SysTick_CTRL_ENABLE_Msk))
13 {
14 SysTick->LOAD = 0xFFFFFF; // Set the maximum value for a 24-bit counter
15 SysTick->VAL = 0; // Reset the counter
16 SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_ENABLE_Msk; // Enable the counter
17 }
18
19 // Use SysTick counter as a hardware entropy source for automatic seeding
20 prng_state = SysTick->VAL ^ (SysTick->VAL << 16) ^ (SysTick->LOAD);
21 return;
22 }
23
24 // Use the provided seed
25 prng_state = seed;
26}