]> oss.titaniummirror.com Git - rgblamp.git/blob - adc_random.c
Debounce for 64 ms instead of 32 ms
[rgblamp.git] / adc_random.c
1 /*
2 * File: adc_random.c
3 *
4 * Generate a random 8-bit value by reading an unused (floating) IO pin.
5 * Pin 1, RA2 (AN2) is free in the current design.
6 */
7
8 #include <htc.h>
9 #include "tmr.h"
10
11 unsigned char adc_random()
12 {
13 static bit save_ansa2;
14 static bit save_trisa2;
15 unsigned char accumulate = 0;
16
17 /* Turn on the FVR, configured for 1.024V to the ADC */
18 FVRCON = 0b10000001;
19 while (!FVRRDY); /* wait for ready signal */
20
21 /* Configure RA2 (AN2) for ADC input */
22 save_ansa2 = ANSA2;
23 ANSA2 = 1;
24 save_trisa2 = TRISA2;
25 TRISA2 = 1;
26 ADCON1 = 0b11110011; /* Right justified result, Frc clk, FVR/Vss refs */
27 ADCON0 = 0b00001001; /* Enable channel AN2, enable ADC */
28
29 /* Sample the ADC several times, accumulating the LSB of the result */
30 for (unsigned i = 0; i < 128; i++) {
31 tmr_uwait(10); /* Sampling time */
32 ADGO = 1; /* Start the conversion */
33 while (ADGO); /* wait for completion */
34 accumulate += ADRESL;
35 }
36
37 /* Turn off ADC, FVR, and revert PORTA changes */
38 ADON = 0;
39 FVREN = 0;
40 TRISA2 = save_trisa2;
41 ANSA2 = save_ansa2;
42
43 /* Return the result */
44 return accumulate;
45 }