Fibonacci Linear Feedback Shift Register (Pseudo-Random Number Generator)
Dependents: SDP_K1_Rand FibonacciLFSR_LED_Demo
Revision 0:2038ff2b7de5, committed 2016-06-25
- Comitter:
- electromotivated
- Date:
- Sat Jun 25 03:19:45 2016 +0000
- Child:
- 1:a1207d543967
- Commit message:
- Fibonacci Linear Feedback Shift Register Pseudo-Random Number Generator; ;
Changed in this revision
| FibonacciLFSR.cpp | Show annotated file Show diff for this revision Revisions of this file |
| FibonacciLFSR.h | Show annotated file Show diff for this revision Revisions of this file |
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/FibonacciLFSR.cpp Sat Jun 25 03:19:45 2016 +0000
@@ -0,0 +1,31 @@
+#include "FibonacciLFSR.h"
+#include "mbed.h"
+
+FibonacciLFSR::FibonacciLFSR(LFSR_SIZE_t size){
+ this->size = size;
+ this->lfsr_period = (1 << size) - 1; // Number of random numbers
+ this->lfsr = 0x0001;
+}
+
+uint16_t FibonacciLFSR::getRandom(){
+ switch (size){
+ case LFSR_2:
+ feedback_bit = ((lfsr >> 1) ^ (lfsr >> 0)) & 0x01;
+ break;
+ case LFSR_4:
+ feedback_bit = ((lfsr >> 3) ^ (lfsr >> 2)) & 0x01;
+ break;
+ case LFSR_8:
+ feedback_bit = ((lfsr >> 7) ^ (lfsr >> 5) ^ (lfsr >> 4) ^ (lfsr >> 3)) & 0x01;
+ break;
+ case LFSR_16:
+ feedback_bit = ((lfsr >> 15) ^ (lfsr >> 14) ^ (lfsr >> 12) ^ (lfsr >> 3)) & 0x01;
+ break;
+ default:
+ break;
+ }
+
+ // Shift, add feedback, AND zero extra MSb's leaving only "size" number of bits representing lfsr
+ lfsr = ((lfsr << 1) | feedback_bit) & ((1 << size) - 1);
+ return lfsr;
+}
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/FibonacciLFSR.h Sat Jun 25 03:19:45 2016 +0000
@@ -0,0 +1,46 @@
+#ifndef FIBONACCI_LFSR
+#define FIBONACCI_LFSR
+
+/*
+ Library for Fibonacci Linear Feedback Shift Register pseudo-random number
+ generator. The uniqueness of the Fibonacci LFSR is that all permutations
+ (values) are explored except zero, ensuring at least one bit in the LFSR
+ is always HIGH.
+
+ Applications: Random Number Generation, LED Faux Candles, LED lighting
+ effects, etc.
+
+ References: (Press "Ctrl" and click link to open in browser)
+ https://en.wikipedia.org/wiki/Linear-feedback_shift_register
+
+ TODO: Consider making this class static
+*/
+
+#include "mbed.h"
+
+class FibonacciLFSR{
+ public:
+ typedef enum SIZE{
+ LFSR_2 = 2, LFSR_4 = 4,
+ LFSR_8 = 8, LFSR_16 = 16
+ }LFSR_SIZE_t;
+ /*
+ Constructor of Fibonacci Linear Feedback Shift Register Objects.
+ Preconditions: None
+ @param size Number of bits for LFSR
+ */
+ FibonacciLFSR(LFSR_SIZE_t size);
+
+ /*
+ Generate and return new random number
+ @return A new random value
+ */
+ uint16_t getRandom();
+
+ private:
+ LFSR_SIZE_t size; // The number of bits representing the LFSR
+ int lfsr_period; // Period of LFSR register (number of random values before repeating)
+ uint16_t lfsr;
+ uint16_t feedback_bit;
+};
+#endif
\ No newline at end of file