【GD32L233C-START评测】+猜猜下次哪个灯会亮
[复制链接]
GD32L233C 含有真随机数发生器模块(TRNG)能够通过连续模拟噪声生成一个32 位的随机数值。
操作步骤在手册里有详细说明,如下图
主函数
uint32_t random_data = 0, random_lastdata = 0;
uint8_t retry = 0;
/* configure systick */
systick_config();
/* turn on the oscillator */
rcu_osci_on(RCU_IRC48M);
if(ERROR == rcu_osci_stab_wait(RCU_IRC48M)){
while(1){
}
}
/* initilize the LEDs, USART and key */
gd_eval_led_init(LED1);
gd_eval_led_init(LED2);
gd_eval_led_init(LED3);
gd_eval_led_init(LED4);
gd_eval_com_init(EVAL_COM);
gd_eval_key_init(KEY_WAKEUP, KEY_MODE_GPIO);
/* print out the clock frequency of system, AHB, APB1 and APB2 */
printf("\r\nCK_SYS is %d", rcu_clock_freq_get(CK_SYS));
printf("\r\nCK_AHB is %d", rcu_clock_freq_get(CK_AHB));
printf("\r\nCK_APB1 is %d", rcu_clock_freq_get(CK_APB1));
printf("\r\nCK_APB2 is %d", rcu_clock_freq_get(CK_APB2));
/* show example introduce */
printf("============ Gigadevice TRNG poll mode demo ============ \r\n");
/* configure TRNG module */
while((ERROR == trng_configuration()) && retry < 3) {
printf("TRNG init fail \r\n");
printf("TRNG init retry \r\n");
retry++;
}
printf("TRNG init ok \r\n");
/* get the first random data */
random_lastdata = trng_get_true_random_data();
while(1) {
if(SET == gd_eval_key_state_get(KEY_WAKEUP)) {
delay_1ms(50);
if(SET == gd_eval_key_state_get(KEY_WAKEUP)) {
/* check wherther the random data is valid and get it */
if(SUCCESS == trng_ready_check()) {
random_data = trng_get_true_random_data();
if(random_data != random_lastdata) {
random_lastdata = random_data;
printf("Get random data: 0x%08x \r\n", random_data);
} else {
/* the random data is invalid */
printf("Error: Get the random data is same \r\n");
}
gd_eval_led_off(LED1);
gd_eval_led_off(LED2);
gd_eval_led_off(LED3);
gd_eval_led_off(LED4);
switch(random_data%4)
{
case 0:gd_eval_led_on(LED1);break;
case 1:gd_eval_led_on(LED2);break;
case 2:gd_eval_led_on(LED3);break;
case 3:gd_eval_led_on(LED4);break;
default:break;
}
}
}
while(RESET == gd_eval_key_state_get(KEY_WAKEUP)) {
}
}
}
随机数模块检查
uint32_t timeout = 0;
FlagStatus trng_flag = RESET;
ErrStatus reval = SUCCESS;
/* check wherther the random data is valid */
do {
timeout++;
trng_flag = trng_flag_get(TRNG_FLAG_DRDY);
} while((RESET == trng_flag) && (0xFFFF > timeout));
if(RESET == trng_flag) {
/* ready check timeout */
printf("Error: TRNG can't ready \r\n");
trng_flag = trng_flag_get(TRNG_FLAG_CECS);
printf("Clock error current status: %d \r\n", trng_flag);
trng_flag = trng_flag_get(TRNG_FLAG_SECS);
printf("Seed error current status: %d \r\n", trng_flag);
reval = ERROR;
}
/* return check status */
return reval;
随机数模块配置
ErrStatus reval = SUCCESS;
/* TRNG module clock enable */
rcu_periph_clock_enable(RCU_TRNG);
/* TRNG registers reset */
trng_disable();
trng_enable();
/* check TRNG work status */
reval = trng_ready_check();
return reval;
按下开发板上的按键K2(Wakeup),LED1-LED4将会随机电量一盏灯
|