Skip to content

Instantly share code, notes, and snippets.

@oskay
Created December 3, 2017 21:21
Show Gist options
  • Save oskay/13ae9350ea7cd29219353eccf8825df3 to your computer and use it in GitHub Desktop.
Save oskay/13ae9350ea7cd29219353eccf8825df3 to your computer and use it in GitHub Desktop.
/* "Random" seed generator for ATmega168P.
Application: An instrument needs to turn on a light and sound a buzzer a random time
_after being powered on_. Since power may not be on for a reliable amount of time,
we do not want to write to EEPROM. Must use environmental inputs to construct a
not-very-reproducible input that can be used as a random seed.
This is a fragment of code, and does not include all necessary
I/O setup or infrastructure
We use three environmental inputs: A floating input pin, a temperature sensor, and
a resistor midpoint (the voltage in the middle of a voltage divider from Vcc to Gnd)
as inputs to our ADC. We sum these values and use them as our seed.
*/
unsigned int ADoutTemp;
unsigned int RandTemp;
uint8_t i;
// Initialize outputs: No pull ups, and output pins are all high.
DDRD = _BV(5) | _BV(6) | _BV(7); // Output pins: D5, D6, D7.
PORTD = DDRD;
DDRB = 0; // PORT B is all input
DDRC = 0; // PORT C is all input
PORTB = DDRB;
PORTC = DDRC;
CLKPR = 0; // set clock to maximum
WDTCSR = 0x00; // disable watchdog timer
// ADC Setup
PRR &= ~(_BV(PRADC)); //Allow ADC to be powered up
ADMUX = 8; // Channel 8: Temperature sensor
// Enable ADC, prescale at 2.
ADCSRA = _BV(ADEN);
ADCSRA |= _BV(ADSC); // Start initial ADC cycle
while ((ADCSRA & _BV(ADSC)) != 0) // while ADC conversion has not finished
{
asm("nop;");
}
ADoutTemp = ADCW;
ADMUX = 3; // Channel 3 (resistor midpoint)
ADCSRA |= _BV(ADSC); // Start next ADC cycle
while ((ADCSRA & _BV(ADSC)) != 0) // while ADC conversion has not finished
{
asm("nop;");
}
ADoutTemp += ADCW;
ADMUX = 4; // Channel 4 (unconnected)
ADCSRA |= _BV(ADSC); // Start next ADC cycle
while ((ADCSRA & _BV(ADSC)) != 0) // while ADC conversion has not finished
{
asm("nop;");
}
ADoutTemp += ADCW;
srand(ADoutTemp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment