-
Notifications
You must be signed in to change notification settings - Fork 0
/
HWRNG.cpp
51 lines (45 loc) · 1.52 KB
/
HWRNG.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "HWRNG.h"
#ifdef AVR
unsigned long HWRandom(void)
{
// 32 sample of LSB from internal temperature sensor. (only for Atmega 168A/P 328 and 32u4)
unsigned long X = 0;
while (X == 0x0 || X == 0xFFFFFFFF)
for (byte i = 0; i < 32; i++)
{
ADMUX |= 0xC8; // Set the internal reference and mux.
ADCSRA |= 0xC0; // Enable the ADC and start conversion
while (bitRead(ADCSRA,ADSC)); // Detect end-of-conversion
bitWrite (X, i, bitRead (ADCW, 0));
}
return X - 1;
}
unsigned long HWRandom(unsigned long Max)
{
// 32 sample of LSB from internal temperature sensor. (only for Atmega 168A/P 328 and 32u4)
unsigned long X = 0;
while (X == 0x0 || X == 0xFFFFFFFF)
for (byte i = 0; i < 32; i++)
{
ADMUX |= 0xC8; // Set the internal reference and mux.
ADCSRA |= 0xC0; // Enable the ADC and start conversion
while (bitRead(ADCSRA,ADSC)); // Detect end-of-conversion
bitWrite (X, i, bitRead (ADCW, 0));
}
return (X - 1) % Max;
}
unsigned long HWRandom(unsigned long Min, unsigned long Max)
{
// 32 sample of LSB from internal temperature sensor. (only for Atmega 168A/P 328 and 32u4)
unsigned long X = 0;
while (X == 0x0 || X == 0xFFFFFFFF)
for (byte i = 0; i < 32; i++)
{
ADMUX |= 0xC8; // Set the internal reference and mux.
ADCSRA |= 0xC0; // Enable the ADC and start conversion
while (bitRead(ADCSRA,ADSC)); // Detect end-of-conversion
bitWrite (X, i, bitRead (ADCW, 0));
}
return (X - 1) % (Max - Min) + Min;
}
#endif