Landtiger LPC1768 C BigLib 1
A self made, custom C library for the LandTiger board.
 
Loading...
Searching...
No Matches
prng.c
Go to the documentation of this file.
1#include "prng.h"
2#include "LPC17xx.h" // For accessing SysTick and system peripherals
3
4// Static variables to hold the current seed and state
6
7void PRNG_Set(u32 seed)
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}
27
29void PRNG_Release(void)
30{
31 // Stopping SysTick
32 SysTick->CTRL = 0;
33 prng_state = 0;
34}
35
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}
44
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
void PRNG_Release(void)
Releases the HW entropy sources used to seed the PRNG.
Definition prng.c:29
u32 PRNG_Range(u32 min, u32 max)
Generates a pseudo-random number in the given range, inclusive.
Definition prng.c:49
_PRIVATE u32 prng_state
Definition prng.c:5
void PRNG_Set(u32 seed)
Initializes the PRNG by seeding it with the given seed. Use PRNG_USE_AUTO_SEED to seed it automatical...
Definition prng.c:7
@ PRNG_USE_AUTO_SEED
PRNG automatically seeds itself using an hardware entropy source.
Definition prng.h:11
#define _PRIVATE
Definition types.h:37
uint32_t u32
Definition types.h:6