Skip to content

Instantly share code, notes, and snippets.

@Lukelectro
Created November 5, 2017 20:01
Show Gist options
  • Save Lukelectro/cca484ff1d3a4002493efc7bcd16d477 to your computer and use it in GitHub Desktop.
Save Lukelectro/cca484ff1d3a4002493efc7bcd16d477 to your computer and use it in GitHub Desktop.
Attempt at random number generation with noise from last bit of ADC read, for seeding pseudorandom generator. For STM32F103 board.
#define debug
void setup() {
// put your setup code here, to run once:
//analogReadResolution(12); // STM32F103, 12 bits adc resolution // Allwrong, this should work but doesn't. Fortunately, in contrast to documentation, a 12 bit result turns out te be the default on this board.
if(Serial);
}
void loop() {
// put your main code here, to run repeatedly:
#ifdef debug
//Serial.printf(F("Pitje: "), %d, BittenVoorPitten()); // waarom heeft die stm32 geen printf! Terwijl de IDE het wel een mooi kleurtje geeft.
Serial.println(BittenVoorPitten(), BIN);
#endif
Serial.println(BittenVoorPitten());// Random seed.
delay(1000);
}
long int BittenVoorPitten(){ // for use as random seed (ADC LSB noise on internal thermal input)
int temp, pitjes=0;
for(int i=0; i<16;i++){
//ADC_CR2 |= (1<<23); //enable internal temp sensor, ch16 (And VREF, ch 17), hmmz, doesn't work this way. Kinda frustrating...
ADC1->regs->CR2 |= (1<<23); //enable internal temp sensor, ch16 (And VREF, ch 17);
//(Undocumented?, found out by digging around .../sketchbook/hardware/Arduino_STM32-master/STM32F1/system/libmaple/include/libmaple/adc.h)
temp= analogRead(16); // ch 16 is internal temperature sensor. But heating the chip does not change the read value... So something goes wrong.
// enabling internal VREF and temp sensor did not help. (Despite this, the last bit is still noisy enough for this purpose... But it should not be on an external input...)
#ifdef debug
//Serial.printf(F("gelezen temperatuur"), %d, F(" binair:"), %b12, temp,temp);
Serial.print(F("gelezen temperatuur"));
Serial.print(temp);
Serial.print(F(" binair:"));
Serial.println(temp, BIN);
#endif
pitjes |= ((temp&1)<<i);
}
return pitjes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment