app: initialiaze random number generator

This commit is contained in:
King Kévin 2021-06-24 21:49:32 +02:00
parent 630945b27c
commit ae875daba7
1 changed files with 28 additions and 1 deletions

View File

@ -25,6 +25,7 @@
#include <libopencm3/stm32/desig.h> // design utilities
#include <libopencm3/stm32/flash.h> // flash utilities
#include <libopencm3/stm32/usart.h> // USART utilities for MP3 player
#include <libopencm3/stm32/adc.h> // ADC utilities for random seed
/* own libraries */
#include "global.h" // board definitions
@ -782,9 +783,35 @@ void main(void)
nvic_enable_irq(GPIO_NVIC_EXTI_IRQ(DOOR_PIN)); // enable interrupt
uint32_t door_sequence[4] = {0}; // duration of past door states, in RTC ticks, oldest first, updated every time the door is opened/closed
uint32_t door_timestamp = 0; // RTC timestamps when the door state has changed
puts("OK\n");
puts("setup RNG: ");
rcc_periph_clock_enable(RCC_ADC1); // enable clock for ADC peripheral
adc_power_off(ADC1); // ensure ADC is off for configuring
rcc_periph_reset_pulse(RST_ADC1); // reset configuration
rcc_set_adcpre(RCC_CFGR_ADCPRE_PCLK2_DIV2); // set clock
adc_set_dual_mode(ADC_CR1_DUALMOD_IND); // not sure what it does
adc_disable_scan_mode(ADC1); // we only do single conversion
adc_set_single_conversion_mode(ADC1); // ensure we do single conversion
adc_set_sample_time(ADC1, ADC_CHANNEL_TEMP, ADC_SMPR_SMP_1DOT5CYC); // we will read the temperature
adc_enable_external_trigger_regular(ADC1, ADC_CR2_EXTSEL_SWSTART); // conversion is triggered by software
adc_power_on(ADC1); // start ADC
adc_reset_calibration(ADC1); // reset calibration value
adc_calibrate(ADC1); // calibrate ADC
unsigned int seed = 1; // the seed we need to generate
uint8_t seed_rounds = 25; // get plenty of sample
while (seed_rounds--) { // go through all rounds
adc_start_conversion_regular(ADC1); // do conversion
while (!adc_eoc(ADC1)); // wait for conversion
const uint16_t temp = adc_read_regular(ADC1); // read temperature
if (temp > 2) {
seed *= temp; // calculate the seed
}
sleep_ms(10); // wait a bit for the temperature to change
}
srand(seed); // set the seed
printf("%u\n", seed);
// setup terminal
terminal_prefix = ""; // set default prefix
terminal_process = &process_command; // set central function to process commands