]> oss.titaniummirror.com Git - rgblamp.git/blobdiff - lfsr.c
Replace rand() with LFSR implementation
[rgblamp.git] / lfsr.c
diff --git a/lfsr.c b/lfsr.c
new file mode 100644 (file)
index 0000000..e2539d8
--- /dev/null
+++ b/lfsr.c
@@ -0,0 +1,38 @@
+/*
+ * File:   lfsr.c
+ *
+ * Linear Feedback Shift Register (random number generator)
+ */
+
+/**
+ * This is a small, fast and efficient software implementation of a 16-bit
+ * Linear Feedback Shift Register (LFSR).  It uses the Galois method to perform
+ * the exclusive OR operations in parallel for improved performance over the
+ * standard, or Fibonacci, method.  The algorithm also skips the exlusive or
+ * operations if it doesn't need to do them, though on this uC the branch may
+ * not generate a net performance increase over doing the exclusive or
+ * operations every time.
+ *
+ * After rng returns, RNGLO and RNGHI contain the updated 16-bit random number.
+ * RNGLO will contain a value $01-$FF, RNGHI will contain $00-$FF.
+ *
+ * @author R. Steve McKown <rsmckown@gmail.com>
+ */
+
+
+#include "lfsr.h"
+
+static unsigned lfsr_val = 0x1aa1;
+
+void lfsr_init(unsigned seed)
+{
+  /* The seed cannot be zero */
+  if (seed)
+    lfsr_val = seed;
+}
+
+unsigned lfsr_get()
+{
+  lfsr_val = (lfsr_val >> 1) ^ (-(lfsr_val & 1) & 0xd008);
+  return lfsr_val;
+}