]> oss.titaniummirror.com Git - rgblamp.git/commitdiff
Generate entropy with ADC reading floating pin
authorR. Steve McKown <rsmckown@gmail.com>
Thu, 8 Dec 2011 01:10:19 +0000 (18:10 -0700)
committerR. Steve McKown <rsmckown@gmail.com>
Thu, 8 Dec 2011 01:10:19 +0000 (18:10 -0700)
This entropy is then used in a call to srand() so that the color
sequence on power-up isn't the same each time.

adc_random.c [new file with mode: 0644]
adc_random.h [new file with mode: 0644]
main.c

diff --git a/adc_random.c b/adc_random.c
new file mode 100644 (file)
index 0000000..05450f4
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * File:   adc_random.c
+ *
+ * Generate a random 8-bit value by reading an unused (floating) IO pin.
+ * Pin 1, RA2 (AN2) is free in the current design.
+ */
+
+#include <htc.h>
+#include "timer.h"
+
+unsigned char adc_random()
+{
+    unsigned char save_ansela;
+    unsigned char save_trisa;
+    unsigned char accumulate = 0;
+
+    /* Turn on the FVR, configured for 1.024V to the ADC */
+    FVRCON = 0b10000001;
+    while (!FVRRDY); /* wait for ready signal */
+
+    /* Configure RA2 (AN2) for ADC input */
+    save_ansela = ANSELA;
+    ANSELA |= 4;
+    save_trisa = TRISA;
+    TRISA |= 4;
+    ADCON1 = 0b11110011; /* Right justified result, Frc clk, FVR/Vss refs */
+    ADCON0 = 0b00001001; /* Enable channel AN2, enable ADC */
+
+    /* Sample the ADC several times, accumulating the LSB of the result */
+    for (unsigned i = 0; i < 128; i++) {
+        timer_uwait(10); /* Sampling time */
+        ADGO = 1; /* Start the conversion */
+        while (ADGO); /* wait for completion */
+        accumulate += ADRESL;
+    }
+
+    /* Turn off ADC, FVR, and revert PORTA changes */
+    ADON = 0;
+    FVREN = 0;
+    TRISA = save_trisa;
+    ANSELA = save_ansela;
+
+    /* Return the result */
+    return accumulate;
+}
diff --git a/adc_random.h b/adc_random.h
new file mode 100644 (file)
index 0000000..7dc0dc7
--- /dev/null
@@ -0,0 +1,14 @@
+/*
+ * File:   adc_random.h
+ *
+ * Generate a random 8-bit value by reading an unused (floating) IO pin.
+ */
+
+
+#ifndef _ADC_RANDOM_H
+#define _ADC_RANDOM_H
+
+/* Return a random 8-bit value */
+unsigned char adc_random();
+
+#endif
diff --git a/main.c b/main.c
index 8f51cf26e926ab289e9713ddb08e74afa8226db5..765c75363717ba51d0da4a7d641e4f04f9930f60 100644 (file)
--- a/main.c
+++ b/main.c
@@ -32,6 +32,7 @@
 #include "buttons.h"
 #include "rgb.h"
 #include "timer.h"
+#include "adc_random.h"
 
 #define AUTO_OFF_COUNT          549316UL /* 5 hrs in 32.768 ms units */
 #define reset_steps()           do { incolor_steps = 1; fade_steps = 0; } \
@@ -88,7 +89,6 @@ int main(void)
     int fade_steps;
     unsigned long auto_off = 0;
 
-
     pic_init();
     unused_init();
     buttons_init();
@@ -96,6 +96,7 @@ int main(void)
     timer_init();
     dbgpin_init();
 
+    srand((adc_random() << 8) + adc_random());
     reset_steps();
     if (buttons_on())
       rgb_on();