Good day! I decided to talk about a simple and interesting way to get honest random numbers on microcontrollers that do not have a hardware random number generator on board. It is enough that the microcontroller has an ADC and one free entry. Details under the cut.
The idea is not new and many people have come to mind. I implemented it in
one of my old projects on STM8S003F3, so code samples will be for this chip, although transferring the code to any other architecture is not difficult.
The bottom line is that when measuring voltage with an ADC, the lower bits of the result are most susceptible to noise. We use this fact to our advantage - we will take several measurements and record the low-order bit of the result (as the most “noisy”). Thus, by making 8 measurements you can get a completely random byte.
Worst measurement results as possible. Let's set the smallest sample time, and hang the microcontroller output, on which the ADC input is located, “in the air”, not pulling up anywhere and not connecting to anything. The more noise the better.
')
Initializing ADC:
CLK_PCKENR2 |= 0x08;
The function of receiving a random byte:
unsigned char GetRandom(void) { unsigned char i, result; result = 0; for (i = 0; i < 8; i++) { ADC_CR1 = MASK_ADC_CR1_ADON;
That is such a small trick. The code was restored from memory, so there may be errors - please write about them in the LAN.
I would be very pleased with the opinion of experienced people about this method of obtaining random numbers.