23 #include "TransistorNoiseSource.h"
120 #define SAMPLES_NUM 1024
123 #define SAMPLES_PCT(num) ((int)(((long)SAMPLES_NUM) * (num) / 100L))
127 #define NOISE_SPREAD (ADC_NUM / 8)
130 #define NOISE_NOT_CALIBRATING 0
131 #define NOISE_CALIBRATING 1
139 : threshold(ADC_NUM / 2)
141 , calState(NOISE_CALIBRATING)
145 digitalWrite(pin, LOW);
151 TransistorNoiseSource::~TransistorNoiseSource()
158 return calState != NOISE_NOT_CALIBRATING;
166 int value = analogRead(_pin);
167 if (value < minValue)
169 if (value > maxValue)
176 uint8_t bit = ((threshold - value) >> 15) & 1;
180 if (posn <
sizeof(buffer)) {
181 buffer[posn] = (buffer[posn] << 1) | bit;
196 if (++count < SAMPLES_NUM)
202 if ((maxValue - minValue) < NOISE_SPREAD) {
204 calState = NOISE_CALIBRATING;
205 threshold = ADC_NUM / 2;
211 if (ones >= SAMPLES_PCT(45) && ones <= SAMPLES_PCT(55)) {
212 if (posn >= (
sizeof(buffer) * 3 / 4)) {
217 output(buffer, posn, posn * 4);
220 calState = NOISE_NOT_CALIBRATING;
226 if (ones < SAMPLES_PCT(25) || ones > SAMPLES_PCT(75)) {
229 threshold -= (SAMPLES_PCT(50) - ones) / 8;
230 }
else if (ones < SAMPLES_PCT(50)) {
239 else if (threshold >= ADC_NUM)
240 threshold = ADC_NUM - 1;
242 calState = NOISE_CALIBRATING;
248 void TransistorNoiseSource::restart()
254 minValue = ADC_NUM - 1;
virtual void output(const uint8_t *data, size_t len, unsigned int credit)
Called from subclasses to output noise to the global random number pool.
TransistorNoiseSource(uint8_t pin)
Constructs a new transitor-based noise source handler.
bool calibrating() const
Determine if the noise source is still calibrating itself.
void stir()
Stirs entropy from this noise source into the global random number pool.