Randomness plays a vital role many embedded applications, from cryptographic security to gaming and simulations.
But did you know you can implement a hardware-based Pseudo-Random Number Generator (PRNG) directly on an 8-bit microcontroller using the Configurable Logic Block (CLB)?
In this post, we’ll explore how to create a PRNG that leverages the CLB and SPI peripherals. This hardware-driven approach achieves efficient and continuous random number generation with minimal CPU overhead.
What is a PRNG?
A Pseudo-Random Number Generator (PRNG) produces sequences of numbers that mimic true randomness, generated through deterministic algorithms These sequences are repeatable, making them ideal for resource-constrained environments where efficient and controlled randomness is essential for your design.
The first figure illustrates the logic required for the overall operation of the PRNG. The second figure highlights the logic needed for an 8-bit Left Feedback Shift Register, a key component responsible for generating the pseudo-random sequences.
Figure 1: Conceptual overview of PRNG implementation with LFSR, CLB, and SPI.
Figure 2: LFSR configuration block diagram for PRNG.
How It Works
The PRNG is implemented using:
- Linear Feedback Shift Register (LFSR): Generates pseudo-random sequences based on a feedback function determined by specific taps.
- SPI: Acts as a shift register to handle the output efficiently.
The PRNG is initialized with a non-zero seed value, ensuring continuous operation and preventing lock-up during execution.
Implementation Overview
Hardware Requirements
- Microcontroller PIC16F13145with CLB and SPI peripherals
- Microcontroller with CLB and SPI Peripherals (e.g., PIC16F13145)
MPLAB® Code Configurator (MCC) for configuration
Configuration Steps
- Configure the CLB: Set up the CLB to implement the logic required for the PRNG and the 8-bit LFSR submodule. l Refer to the diagrams above for guidance.Use SPI in Mode 1 to shift and observe the pseudo-random output.
- Assign a stable clock source (e.g., HFINTOSC) to drive the peripherals.
Code Example
The PRNG outputs verified pseudo-random numbers via SPI (SS, SDI, SCK) and UART, triggered by an onboard switch using MCC SPI APIs.
int main(void) {
SYSTEM_Initialize();
SPI_Open(CLIENT_CONFIG);
__delay_ms(100);
while (1) {
if (SWITCH_GetValue() == 0) {
if (SPI1_IsRXReady()) printf("\n\rRead byte: %x", SPI1_ByteRead());
}
}
}
Testing and Results
Validate the PRNG by observing the outputs on the SPI pins via UART or an oscilloscope. The generated sequences demonstrate consistent pseudo-random behavior, as shown below:
Figure 3: Sample PRNG output captured during testing.
Applications of CLB-Based PRNGs
- Cryptographic functions
- Data scrambling
- Gaming algorithms
- Simulations and modeling
By leveraging hardware-based logic, this approach reduces CPU workload and simplifies system design.
Learn More
Discover more about implementing PRNGs and other Configurable Logic Block examples: