1.测试环境
MDK V5.26.2.0
Nu-Link_Keil_Driver 3.07.7246r
ENV V1.2.0
Python V2.7.13
rt-thread-v4.0.4
2.测试任务
本次测试任务为新唐 NuMaker-M2354真随机数发生器TRNG模块
3.资源介绍
翻阅新唐M2354数据手册
4.代码
nu_rng.c
int32_t RNG_Random(uint32_t *pu32Buf, int32_t nWords)
{
int32_t i;
int32_t timeout = 0x10000;
/* Waiting for Busy */
while(CRPT->PRNG_CTL & CRPT_PRNG_CTL_BUSY_Msk) {}
if(nWords > 8)
nWords = 8;
/* Trig to generate seed 256 bits random number */
CRPT->PRNG_CTL = (6 << CRPT_PRNG_CTL_KEYSZ_Pos) | CRPT_PRNG_CTL_START_Msk;
while(CRPT->PRNG_CTL & CRPT_PRNG_CTL_BUSY_Msk)
{
if(timeout-- < 0)
return 0;
}
for(i = 0; i < nWords; i++)
{
pu32Buf[i] = CRPT->PRNG_KEY[i];
}
return nWords;
}
drv_trng.c
#define NU_CRYPTO_TRNG_NAME "nu_TRNG"
/* Private variables ------------------------------------------------------------*/
static struct rt_mutex s_TRNG_mutex;
static int s_i32TRNGEnable = 0;
static rt_uint32_t nu_trng_run(void)
{
uint32_t u32RNGValue;
rt_err_t result;
result = rt_mutex_take(&s_TRNG_mutex, RT_WAITING_FOREVER);
RT_ASSERT(result == RT_EOK);
RNG_Open();
if (RNG_Random(&u32RNGValue, 1) < 0)
{
//Failed, use software rand
u32RNGValue = rand();
}
result = rt_mutex_release(&s_TRNG_mutex);
RT_ASSERT(result == RT_EOK);
return u32RNGValue;
}
rt_err_t nu_trng_init(void)
{
rt_err_t result;
result = rt_mutex_init(&s_TRNG_mutex, NU_CRYPTO_TRNG_NAME, RT_IPC_FLAG_PRIO);
RT_ASSERT(result == RT_EOK);
s_i32TRNGEnable = 1;
SYS_ResetModule(TRNG_RST);
return RT_EOK;
}
void nu_trng_open(void)
{
#if defined(NU_PRNG_USE_SEED)
srand(NU_PRNG_SEED_VALUE);
#else
srand(rt_tick_get());
#endif
}
rt_uint32_t nu_trng_rand(struct hwcrypto_rng *ctx)
{
if (!s_i32TRNGEnable)
{
uint32_t u32RNGValue;
//use software rand
u32RNGValue = rand();
return u32RNGValue;
}
return nu_trng_run();
}
main.c
rt_uint32_t usr_trng;
int main(int argc, char **argv)
{
#if defined(RT_USING_PIN)
int counter = 100;
/* set LEDR pin mode to output */
// rt_pin_mode(LEDR, PIN_MODE_OUTPUT);
while (counter--)
{
// rt_pin_write(LEDR, PIN_HIGH);
// rt_thread_mdelay(500);
// rt_pin_write(LEDR, PIN_LOW);
rt_thread_mdelay(500);
usr_trng=nu_trng_rand();
}
#endif
return 0;
}
5.结果
6.心得
第一次用新唐的开发板,很感兴趣,RT-Thread提供的BSP很全面,功能很强大,基本上直接调用API就可以了,由于身边的工具不够,仅仅通过debug测试了一下TRNG,后面闲下来,再对其他模块测试分享出来。
原作者:lianghai