完整的工程间附件,替换\STM32Cube_FW_H5_V1.2.0\Projects\NUCLEO-H533RE\Applications\ThreadX\Tx_Thread_Creation
这一篇继续体验rng随机数生成,随机数可用于aes生成iv等。
二.硬件驱动
添加驱动文件
stm32h5xx_hal_rng.c
stm32h5xx_hal_conf.h中取消注释
#define HAL_RNG_MODULE_ENABLED
MSP初始化 RNG
/**
* @brief RNG MSP Initialization
* This function configures the hardware resources used in this example
* @param hrng: RNG handle pointer
* @retval None
*/
void HAL_RNG_MspInit(RNG_HandleTypeDef* hrng)
{
RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
if(hrng->Instance==RNG)
{
/* USER CODE BEGIN RNG_MspInit 0 */
/* USER CODE END RNG_MspInit 0 */
/** Initializes the peripherals clock
*/
PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RNG;
PeriphClkInitStruct.RngClockSelection = RCC_RNGCLKSOURCE_HSI48;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
{
Error_Handler();
}
/* Peripheral clock enable */
__HAL_RCC_RNG_CLK_ENABLE();
/* RNG interrupt Init */
HAL_NVIC_SetPriority(RNG_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(RNG_IRQn);
/* USER CODE BEGIN RNG_MspInit 1 */
/* USER CODE END RNG_MspInit 1 */
}
}
/**
* @brief RNG MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param hrng: RNG handle pointer
* @retval None
*/
void HAL_RNG_MspDeInit(RNG_HandleTypeDef* hrng)
{
if(hrng->Instance==RNG)
{
/* USER CODE BEGIN RNG_MspDeInit 0 */
/* USER CODE END RNG_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_RNG_CLK_DISABLE();
/* RNG interrupt DeInit */
HAL_NVIC_DisableIRQ(RNG_IRQn);
/* USER CODE BEGIN RNG_MspDeInit 1 */
/* USER CODE END RNG_MspDeInit 1 */
}
}
RNG_HandleTypeDef hrng;
RNG初始化
hrng.Instance = RNG;
hrng.Init.ClockErrorDetection = RNG_CED_ENABLE;
if (HAL_RNG_Init(&hrng) != HAL_OK)
{
Error_Handler();
}
中断处理
extern RNG_HandleTypeDef hrng;
/**
* @brief This function handles RNG global interrupt.
*/
void RNG_IRQHandler(void)
{
/* USER CODE BEGIN RNG_IRQn 0 */
/* USER CODE END RNG_IRQn 0 */
HAL_RNG_IRQHandler(&hrng);
/* USER CODE BEGIN RNG_IRQn 1 */
/* USER CODE END RNG_IRQn 1 */
}
产生随机数
HAL_RNG_GenerateRandomNumber
三.测试
我们添加命令用于产生随机数,然后发送到PC,PC使用可视化工具画出曲线,查看曲线是否随机。
shell_func.c中
申明实现函数
static void rng_func(uint8_t* param);
新增命令用于计算
{ (uint8_t*)"rng", rng_func, (uint8_t*)"rng testtimes"}, "},
实现如下
static void rng_func(uint8_t* param)
{
uint32_t test_times;
if(sscanf((const char*)param,"%*s %d",&test_times) == 1)
{
hrng.Instance = RNG;
hrng.Init.ClockErrorDetection = RNG_CED_ENABLE;
if (HAL_RNG_Init(&hrng) != HAL_OK)
{
}
for(uint32_t i=0; i<test_times; i++)
{
uint32_t randnum;
HAL_RNG_GenerateRandomNumber(&hrng,&randnum);
tx_thread_sleep(10);
xprintf("/*%d*/\r\n",randnum);
}
if(HAL_RNG_DeInit(&hrng) != HAL_OK)
{
}
}
}
测试如下
输入rng 1000
查看曲线如下
用随机数发生器产生随机数,使得加密结果每次都不一样,增加破解难度,是最常用的一种手段,本文体验了STM32H5的随机数发生器,代码非常简单。
注意要使能HSI48的时钟。